@askexenow/exe-os 0.8.0

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 (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -0
  3. package/dist/bin/backfill-responses.js +1912 -0
  4. package/dist/bin/backfill-vectors.js +1642 -0
  5. package/dist/bin/cleanup-stale-review-tasks.js +1339 -0
  6. package/dist/bin/cli.js +18800 -0
  7. package/dist/bin/exe-agent.js +1858 -0
  8. package/dist/bin/exe-assign.js +1957 -0
  9. package/dist/bin/exe-boot.js +6460 -0
  10. package/dist/bin/exe-call.js +197 -0
  11. package/dist/bin/exe-cloud.js +850 -0
  12. package/dist/bin/exe-dispatch.js +1146 -0
  13. package/dist/bin/exe-doctor.js +1657 -0
  14. package/dist/bin/exe-export-behaviors.js +1494 -0
  15. package/dist/bin/exe-forget.js +1627 -0
  16. package/dist/bin/exe-gateway.js +7732 -0
  17. package/dist/bin/exe-healthcheck.js +207 -0
  18. package/dist/bin/exe-heartbeat.js +1647 -0
  19. package/dist/bin/exe-kill.js +1479 -0
  20. package/dist/bin/exe-launch-agent.js +1704 -0
  21. package/dist/bin/exe-link.js +192 -0
  22. package/dist/bin/exe-new-employee.js +852 -0
  23. package/dist/bin/exe-pending-messages.js +1446 -0
  24. package/dist/bin/exe-pending-notifications.js +1321 -0
  25. package/dist/bin/exe-pending-reviews.js +1468 -0
  26. package/dist/bin/exe-repo-drift.js +95 -0
  27. package/dist/bin/exe-review.js +1590 -0
  28. package/dist/bin/exe-search.js +2651 -0
  29. package/dist/bin/exe-session-cleanup.js +3173 -0
  30. package/dist/bin/exe-settings.js +354 -0
  31. package/dist/bin/exe-status.js +1532 -0
  32. package/dist/bin/exe-team.js +1324 -0
  33. package/dist/bin/git-sweep.js +2185 -0
  34. package/dist/bin/graph-backfill.js +1968 -0
  35. package/dist/bin/graph-export.js +1604 -0
  36. package/dist/bin/install.js +656 -0
  37. package/dist/bin/list-providers.js +140 -0
  38. package/dist/bin/scan-tasks.js +1820 -0
  39. package/dist/bin/setup.js +951 -0
  40. package/dist/bin/shard-migrate.js +1494 -0
  41. package/dist/bin/update.js +95 -0
  42. package/dist/bin/wiki-sync.js +1514 -0
  43. package/dist/gateway/index.js +8848 -0
  44. package/dist/hooks/bug-report-worker.js +2743 -0
  45. package/dist/hooks/commit-complete.js +2108 -0
  46. package/dist/hooks/error-recall.js +2861 -0
  47. package/dist/hooks/exe-heartbeat-hook.js +232 -0
  48. package/dist/hooks/ingest-worker.js +4793 -0
  49. package/dist/hooks/ingest.js +684 -0
  50. package/dist/hooks/instructions-loaded.js +1880 -0
  51. package/dist/hooks/notification.js +1726 -0
  52. package/dist/hooks/post-compact.js +1751 -0
  53. package/dist/hooks/pre-compact.js +1746 -0
  54. package/dist/hooks/pre-tool-use.js +2191 -0
  55. package/dist/hooks/prompt-ingest-worker.js +2126 -0
  56. package/dist/hooks/prompt-submit.js +4693 -0
  57. package/dist/hooks/response-ingest-worker.js +1936 -0
  58. package/dist/hooks/session-end.js +1752 -0
  59. package/dist/hooks/session-start.js +2795 -0
  60. package/dist/hooks/stop.js +1835 -0
  61. package/dist/hooks/subagent-stop.js +1726 -0
  62. package/dist/hooks/summary-worker.js +2661 -0
  63. package/dist/index.js +11834 -0
  64. package/dist/lib/cloud-sync.js +495 -0
  65. package/dist/lib/config.js +222 -0
  66. package/dist/lib/consolidation.js +476 -0
  67. package/dist/lib/crypto.js +51 -0
  68. package/dist/lib/database.js +730 -0
  69. package/dist/lib/device-registry.js +900 -0
  70. package/dist/lib/embedder.js +632 -0
  71. package/dist/lib/employee-templates.js +543 -0
  72. package/dist/lib/employees.js +177 -0
  73. package/dist/lib/error-detector.js +156 -0
  74. package/dist/lib/exe-daemon-client.js +451 -0
  75. package/dist/lib/exe-daemon.js +8285 -0
  76. package/dist/lib/file-grep.js +199 -0
  77. package/dist/lib/hybrid-search.js +1819 -0
  78. package/dist/lib/identity-templates.js +320 -0
  79. package/dist/lib/identity.js +223 -0
  80. package/dist/lib/keychain.js +145 -0
  81. package/dist/lib/license.js +377 -0
  82. package/dist/lib/messaging.js +1376 -0
  83. package/dist/lib/reminders.js +63 -0
  84. package/dist/lib/schedules.js +1396 -0
  85. package/dist/lib/session-registry.js +52 -0
  86. package/dist/lib/skill-learning.js +477 -0
  87. package/dist/lib/status-brief.js +235 -0
  88. package/dist/lib/store.js +1551 -0
  89. package/dist/lib/task-router.js +62 -0
  90. package/dist/lib/tasks.js +2456 -0
  91. package/dist/lib/tmux-routing.js +2836 -0
  92. package/dist/lib/tmux-status.js +261 -0
  93. package/dist/lib/tmux-transport.js +83 -0
  94. package/dist/lib/transport.js +128 -0
  95. package/dist/lib/ws-auth.js +19 -0
  96. package/dist/lib/ws-client.js +160 -0
  97. package/dist/mcp/server.js +10538 -0
  98. package/dist/mcp/tools/complete-reminder.js +67 -0
  99. package/dist/mcp/tools/create-reminder.js +52 -0
  100. package/dist/mcp/tools/create-task.js +1853 -0
  101. package/dist/mcp/tools/deactivate-behavior.js +263 -0
  102. package/dist/mcp/tools/list-reminders.js +62 -0
  103. package/dist/mcp/tools/list-tasks.js +463 -0
  104. package/dist/mcp/tools/send-message.js +1382 -0
  105. package/dist/mcp/tools/update-task.js +1692 -0
  106. package/dist/runtime/index.js +6809 -0
  107. package/dist/tui/App.js +17479 -0
  108. package/package.json +104 -0
  109. package/src/commands/exe/assign.md +17 -0
  110. package/src/commands/exe/build-adv.md +381 -0
  111. package/src/commands/exe/call.md +133 -0
  112. package/src/commands/exe/cloud.md +17 -0
  113. package/src/commands/exe/employee-heartbeat.md +44 -0
  114. package/src/commands/exe/forget.md +15 -0
  115. package/src/commands/exe/heartbeat.md +92 -0
  116. package/src/commands/exe/intercom.md +81 -0
  117. package/src/commands/exe/kill.md +34 -0
  118. package/src/commands/exe/launch.md +52 -0
  119. package/src/commands/exe/link.md +17 -0
  120. package/src/commands/exe/logs.md +22 -0
  121. package/src/commands/exe/new-employee.md +12 -0
  122. package/src/commands/exe/review.md +14 -0
  123. package/src/commands/exe/schedule.md +108 -0
  124. package/src/commands/exe/search.md +13 -0
  125. package/src/commands/exe/sessions.md +25 -0
  126. package/src/commands/exe/settings.md +13 -0
  127. package/src/commands/exe/setup.md +171 -0
  128. package/src/commands/exe/status.md +15 -0
  129. package/src/commands/exe/team.md +11 -0
  130. package/src/commands/exe/update.md +11 -0
  131. package/src/commands/exe.md +181 -0
@@ -0,0 +1,2651 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
+ }) : x)(function(x) {
7
+ if (typeof require !== "undefined") return require.apply(this, arguments);
8
+ throw Error('Dynamic require of "' + x + '" is not supported');
9
+ });
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+
18
+ // src/types/memory.ts
19
+ var EMBEDDING_DIM;
20
+ var init_memory = __esm({
21
+ "src/types/memory.ts"() {
22
+ "use strict";
23
+ EMBEDDING_DIM = 1024;
24
+ }
25
+ });
26
+
27
+ // src/lib/config.ts
28
+ var config_exports = {};
29
+ __export(config_exports, {
30
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
31
+ CONFIG_PATH: () => CONFIG_PATH,
32
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
33
+ DB_PATH: () => DB_PATH,
34
+ EXE_AI_DIR: () => EXE_AI_DIR,
35
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
36
+ MODELS_DIR: () => MODELS_DIR,
37
+ loadConfig: () => loadConfig,
38
+ loadConfigFrom: () => loadConfigFrom,
39
+ loadConfigSync: () => loadConfigSync,
40
+ migrateConfig: () => migrateConfig,
41
+ saveConfig: () => saveConfig
42
+ });
43
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
44
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
45
+ import path2 from "path";
46
+ import os from "os";
47
+ function resolveDataDir() {
48
+ if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
49
+ if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
50
+ const newDir = path2.join(os.homedir(), ".exe-os");
51
+ const legacyDir = path2.join(os.homedir(), ".exe-mem");
52
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
53
+ try {
54
+ renameSync(legacyDir, newDir);
55
+ process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
56
+ `);
57
+ } catch {
58
+ return legacyDir;
59
+ }
60
+ }
61
+ return newDir;
62
+ }
63
+ function migrateLegacyConfig(raw) {
64
+ if ("r2" in raw) {
65
+ process.stderr.write(
66
+ "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
67
+ );
68
+ delete raw.r2;
69
+ }
70
+ if ("syncIntervalMs" in raw) {
71
+ delete raw.syncIntervalMs;
72
+ }
73
+ return raw;
74
+ }
75
+ function migrateConfig(raw) {
76
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
77
+ let currentVersion = fromVersion;
78
+ let migrated = false;
79
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
80
+ return { config: raw, migrated: false, fromVersion };
81
+ }
82
+ for (const migration of CONFIG_MIGRATIONS) {
83
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
84
+ raw = migration.migrate(raw);
85
+ currentVersion = migration.to;
86
+ migrated = true;
87
+ }
88
+ }
89
+ return { config: raw, migrated, fromVersion };
90
+ }
91
+ function normalizeScalingRoadmap(raw) {
92
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
93
+ const userRoadmap = raw.scalingRoadmap ?? {};
94
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
95
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
96
+ userAuto.enabled = raw.rerankerEnabled;
97
+ }
98
+ raw.scalingRoadmap = {
99
+ ...userRoadmap,
100
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
101
+ };
102
+ }
103
+ function normalizeSessionLifecycle(raw) {
104
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
105
+ const userSL = raw.sessionLifecycle ?? {};
106
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
107
+ }
108
+ async function loadConfig() {
109
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
110
+ await mkdir2(dir, { recursive: true });
111
+ const configPath = path2.join(dir, "config.json");
112
+ if (!existsSync2(configPath)) {
113
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
114
+ }
115
+ const raw = await readFile2(configPath, "utf-8");
116
+ try {
117
+ let parsed = JSON.parse(raw);
118
+ parsed = migrateLegacyConfig(parsed);
119
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
120
+ if (migrated) {
121
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
122
+ `);
123
+ try {
124
+ await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
125
+ } catch {
126
+ }
127
+ }
128
+ normalizeScalingRoadmap(migratedCfg);
129
+ normalizeSessionLifecycle(migratedCfg);
130
+ const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
131
+ if (config.dbPath.startsWith("~")) {
132
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
133
+ }
134
+ return config;
135
+ } catch {
136
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
137
+ }
138
+ }
139
+ function loadConfigSync() {
140
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
141
+ const configPath = path2.join(dir, "config.json");
142
+ if (!existsSync2(configPath)) {
143
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
144
+ }
145
+ try {
146
+ const raw = readFileSync(configPath, "utf-8");
147
+ let parsed = JSON.parse(raw);
148
+ parsed = migrateLegacyConfig(parsed);
149
+ const { config: migratedCfg } = migrateConfig(parsed);
150
+ normalizeScalingRoadmap(migratedCfg);
151
+ normalizeSessionLifecycle(migratedCfg);
152
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
153
+ } catch {
154
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
155
+ }
156
+ }
157
+ async function saveConfig(config) {
158
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
159
+ await mkdir2(dir, { recursive: true });
160
+ const configPath = path2.join(dir, "config.json");
161
+ await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
162
+ }
163
+ async function loadConfigFrom(configPath) {
164
+ const raw = await readFile2(configPath, "utf-8");
165
+ try {
166
+ let parsed = JSON.parse(raw);
167
+ parsed = migrateLegacyConfig(parsed);
168
+ const { config: migratedCfg } = migrateConfig(parsed);
169
+ normalizeScalingRoadmap(migratedCfg);
170
+ normalizeSessionLifecycle(migratedCfg);
171
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
172
+ } catch {
173
+ return { ...DEFAULT_CONFIG };
174
+ }
175
+ }
176
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
177
+ var init_config = __esm({
178
+ "src/lib/config.ts"() {
179
+ "use strict";
180
+ EXE_AI_DIR = resolveDataDir();
181
+ DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
182
+ MODELS_DIR = path2.join(EXE_AI_DIR, "models");
183
+ CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
184
+ LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
185
+ CURRENT_CONFIG_VERSION = 1;
186
+ DEFAULT_CONFIG = {
187
+ config_version: CURRENT_CONFIG_VERSION,
188
+ dbPath: DB_PATH,
189
+ modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
190
+ embeddingDim: 1024,
191
+ batchSize: 20,
192
+ flushIntervalMs: 1e4,
193
+ autoIngestion: true,
194
+ autoRetrieval: true,
195
+ searchMode: "hybrid",
196
+ hookSearchMode: "hybrid",
197
+ fileGrepEnabled: true,
198
+ splashEffect: true,
199
+ consolidationEnabled: true,
200
+ consolidationIntervalMs: 6 * 60 * 60 * 1e3,
201
+ consolidationModel: "claude-haiku-4-5-20251001",
202
+ consolidationMaxCallsPerRun: 20,
203
+ selfQueryRouter: true,
204
+ selfQueryModel: "claude-haiku-4-5-20251001",
205
+ rerankerEnabled: true,
206
+ scalingRoadmap: {
207
+ rerankerAutoTrigger: {
208
+ enabled: true,
209
+ broadQueryMinCardinality: 5e4,
210
+ fetchTopK: 150,
211
+ returnTopK: 5
212
+ }
213
+ },
214
+ graphRagEnabled: true,
215
+ wikiEnabled: false,
216
+ wikiUrl: "",
217
+ wikiApiKey: "",
218
+ wikiSyncIntervalMs: 30 * 60 * 1e3,
219
+ wikiWorkspaceMapping: {
220
+ exe: "Executive",
221
+ yoshi: "Engineering",
222
+ mari: "Marketing",
223
+ tom: "Engineering",
224
+ sasha: "Production"
225
+ },
226
+ wikiAutoUpdate: true,
227
+ wikiAutoUpdateThreshold: 0.5,
228
+ wikiAutoUpdateCreateNew: true,
229
+ skillLearning: true,
230
+ skillThreshold: 3,
231
+ skillModel: "claude-haiku-4-5-20251001",
232
+ exeHeartbeat: {
233
+ enabled: true,
234
+ intervalSeconds: 60,
235
+ staleInProgressThresholdHours: 2
236
+ },
237
+ sessionLifecycle: {
238
+ idleKillEnabled: true,
239
+ idleKillTicksRequired: 3,
240
+ idleKillIntercomAckWindowMs: 1e4,
241
+ maxAutoInstances: 10
242
+ }
243
+ };
244
+ CONFIG_MIGRATIONS = [
245
+ {
246
+ from: 0,
247
+ to: 1,
248
+ migrate: (cfg) => {
249
+ cfg.config_version = 1;
250
+ return cfg;
251
+ }
252
+ }
253
+ ];
254
+ }
255
+ });
256
+
257
+ // src/lib/shard-manager.ts
258
+ var shard_manager_exports = {};
259
+ __export(shard_manager_exports, {
260
+ disposeShards: () => disposeShards,
261
+ ensureShardSchema: () => ensureShardSchema,
262
+ getReadyShardClient: () => getReadyShardClient,
263
+ getShardClient: () => getShardClient,
264
+ getShardsDir: () => getShardsDir,
265
+ initShardManager: () => initShardManager,
266
+ isShardingEnabled: () => isShardingEnabled,
267
+ listShards: () => listShards,
268
+ shardExists: () => shardExists
269
+ });
270
+ import path3 from "path";
271
+ import { existsSync as existsSync3, mkdirSync } from "fs";
272
+ import { createClient as createClient2 } from "@libsql/client";
273
+ function initShardManager(encryptionKey) {
274
+ _encryptionKey = encryptionKey;
275
+ if (!existsSync3(SHARDS_DIR)) {
276
+ mkdirSync(SHARDS_DIR, { recursive: true });
277
+ }
278
+ _shardingEnabled = true;
279
+ }
280
+ function isShardingEnabled() {
281
+ return _shardingEnabled;
282
+ }
283
+ function getShardsDir() {
284
+ return SHARDS_DIR;
285
+ }
286
+ function getShardClient(projectName) {
287
+ if (!_encryptionKey) {
288
+ throw new Error("Shard manager not initialized. Call initShardManager() first.");
289
+ }
290
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
291
+ if (!safeName) {
292
+ throw new Error(`Invalid project name for shard: "${projectName}"`);
293
+ }
294
+ const cached = _shards.get(safeName);
295
+ if (cached) return cached;
296
+ const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
297
+ const client = createClient2({
298
+ url: `file:${dbPath}`,
299
+ encryptionKey: _encryptionKey
300
+ });
301
+ _shards.set(safeName, client);
302
+ return client;
303
+ }
304
+ function shardExists(projectName) {
305
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
306
+ return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
307
+ }
308
+ function listShards() {
309
+ if (!existsSync3(SHARDS_DIR)) return [];
310
+ const { readdirSync: readdirSync2 } = __require("fs");
311
+ return readdirSync2(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
312
+ }
313
+ async function ensureShardSchema(client) {
314
+ await client.execute("PRAGMA journal_mode = WAL");
315
+ await client.execute("PRAGMA busy_timeout = 5000");
316
+ try {
317
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
318
+ } catch {
319
+ }
320
+ await client.executeMultiple(`
321
+ CREATE TABLE IF NOT EXISTS memories (
322
+ id TEXT PRIMARY KEY,
323
+ agent_id TEXT NOT NULL,
324
+ agent_role TEXT NOT NULL,
325
+ session_id TEXT NOT NULL,
326
+ timestamp TEXT NOT NULL,
327
+ tool_name TEXT NOT NULL,
328
+ project_name TEXT NOT NULL,
329
+ has_error INTEGER NOT NULL DEFAULT 0,
330
+ raw_text TEXT NOT NULL,
331
+ vector F32_BLOB(1024),
332
+ version INTEGER NOT NULL DEFAULT 0
333
+ );
334
+
335
+ CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
336
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
337
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
338
+ `);
339
+ await client.executeMultiple(`
340
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
341
+ raw_text,
342
+ content='memories',
343
+ content_rowid='rowid'
344
+ );
345
+
346
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
347
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
348
+ END;
349
+
350
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
351
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
352
+ END;
353
+
354
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
355
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
356
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
357
+ END;
358
+ `);
359
+ for (const col of [
360
+ "ALTER TABLE memories ADD COLUMN task_id TEXT",
361
+ "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
362
+ "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
363
+ "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
364
+ "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
365
+ "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
366
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
367
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
368
+ "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
369
+ "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
370
+ // Wiki linkage columns (must match database.ts)
371
+ "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
372
+ "ALTER TABLE memories ADD COLUMN document_id TEXT",
373
+ "ALTER TABLE memories ADD COLUMN user_id TEXT",
374
+ "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
375
+ "ALTER TABLE memories ADD COLUMN page_number INTEGER"
376
+ ]) {
377
+ try {
378
+ await client.execute(col);
379
+ } catch {
380
+ }
381
+ }
382
+ try {
383
+ await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
384
+ } catch {
385
+ }
386
+ for (const idx of [
387
+ "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
388
+ "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
389
+ "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
390
+ ]) {
391
+ try {
392
+ await client.execute(idx);
393
+ } catch {
394
+ }
395
+ }
396
+ await client.executeMultiple(`
397
+ CREATE TABLE IF NOT EXISTS entities (
398
+ id TEXT PRIMARY KEY,
399
+ name TEXT NOT NULL,
400
+ type TEXT NOT NULL,
401
+ first_seen TEXT NOT NULL,
402
+ last_seen TEXT NOT NULL,
403
+ properties TEXT DEFAULT '{}',
404
+ UNIQUE(name, type)
405
+ );
406
+
407
+ CREATE TABLE IF NOT EXISTS relationships (
408
+ id TEXT PRIMARY KEY,
409
+ source_entity_id TEXT NOT NULL,
410
+ target_entity_id TEXT NOT NULL,
411
+ type TEXT NOT NULL,
412
+ weight REAL DEFAULT 1.0,
413
+ timestamp TEXT NOT NULL,
414
+ properties TEXT DEFAULT '{}',
415
+ UNIQUE(source_entity_id, target_entity_id, type)
416
+ );
417
+
418
+ CREATE TABLE IF NOT EXISTS entity_memories (
419
+ entity_id TEXT NOT NULL,
420
+ memory_id TEXT NOT NULL,
421
+ PRIMARY KEY (entity_id, memory_id)
422
+ );
423
+
424
+ CREATE TABLE IF NOT EXISTS relationship_memories (
425
+ relationship_id TEXT NOT NULL,
426
+ memory_id TEXT NOT NULL,
427
+ PRIMARY KEY (relationship_id, memory_id)
428
+ );
429
+
430
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
431
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
432
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
433
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
434
+ CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
435
+
436
+ CREATE TABLE IF NOT EXISTS hyperedges (
437
+ id TEXT PRIMARY KEY,
438
+ label TEXT NOT NULL,
439
+ relation TEXT NOT NULL,
440
+ confidence REAL DEFAULT 1.0,
441
+ timestamp TEXT NOT NULL
442
+ );
443
+
444
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
445
+ hyperedge_id TEXT NOT NULL,
446
+ entity_id TEXT NOT NULL,
447
+ PRIMARY KEY (hyperedge_id, entity_id)
448
+ );
449
+ `);
450
+ for (const col of [
451
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
452
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
453
+ ]) {
454
+ try {
455
+ await client.execute(col);
456
+ } catch {
457
+ }
458
+ }
459
+ }
460
+ async function getReadyShardClient(projectName) {
461
+ const client = getShardClient(projectName);
462
+ await ensureShardSchema(client);
463
+ return client;
464
+ }
465
+ function disposeShards() {
466
+ for (const [, client] of _shards) {
467
+ client.close();
468
+ }
469
+ _shards.clear();
470
+ _shardingEnabled = false;
471
+ _encryptionKey = null;
472
+ }
473
+ var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
474
+ var init_shard_manager = __esm({
475
+ "src/lib/shard-manager.ts"() {
476
+ "use strict";
477
+ init_config();
478
+ SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
479
+ _shards = /* @__PURE__ */ new Map();
480
+ _encryptionKey = null;
481
+ _shardingEnabled = false;
482
+ }
483
+ });
484
+
485
+ // src/lib/self-query-router.ts
486
+ var self_query_router_exports = {};
487
+ __export(self_query_router_exports, {
488
+ routeQuery: () => routeQuery
489
+ });
490
+ async function routeQuery(query, model = "claude-haiku-4-5-20251001") {
491
+ if (query.length < 10) {
492
+ return {
493
+ semanticQuery: query,
494
+ projectFilter: null,
495
+ roleFilter: null,
496
+ timeFilter: null,
497
+ isBroadQuery: false
498
+ };
499
+ }
500
+ try {
501
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
502
+ const client = new Anthropic();
503
+ const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
504
+ const response = await client.messages.create({
505
+ model,
506
+ max_tokens: 256,
507
+ system: `You are a search query router. Extract metadata filters from the user's memory search query. Today is ${now}. Convert relative time references (yesterday, last week) to ISO timestamps.`,
508
+ messages: [{ role: "user", content: query }],
509
+ tools: [EXTRACT_TOOL],
510
+ tool_choice: { type: "tool", name: "extract_search_filters" }
511
+ });
512
+ const toolBlock = response.content.find((b) => b.type === "tool_use");
513
+ if (toolBlock && toolBlock.type === "tool_use") {
514
+ const input = toolBlock.input;
515
+ return {
516
+ semanticQuery: input.semantic_query || query,
517
+ projectFilter: input.project_filter || null,
518
+ roleFilter: input.role_filter || null,
519
+ timeFilter: input.time_filter || null,
520
+ isBroadQuery: Boolean(input.is_broad_query)
521
+ };
522
+ }
523
+ } catch (err) {
524
+ process.stderr.write(
525
+ `[self-query-router] LLM extraction failed, using passthrough: ${err instanceof Error ? err.message : String(err)}
526
+ `
527
+ );
528
+ }
529
+ return {
530
+ semanticQuery: query,
531
+ projectFilter: null,
532
+ roleFilter: null,
533
+ timeFilter: null,
534
+ isBroadQuery: false
535
+ };
536
+ }
537
+ var EXTRACT_TOOL;
538
+ var init_self_query_router = __esm({
539
+ "src/lib/self-query-router.ts"() {
540
+ "use strict";
541
+ EXTRACT_TOOL = {
542
+ name: "extract_search_filters",
543
+ description: "Extract metadata filters from a memory search query to improve retrieval precision.",
544
+ input_schema: {
545
+ type: "object",
546
+ properties: {
547
+ semantic_query: {
548
+ type: "string",
549
+ description: "The core semantic meaning of the query, stripped of metadata references. This is used for embedding search."
550
+ },
551
+ project_filter: {
552
+ type: ["string", "null"],
553
+ description: "Project name if the query references a specific project (e.g., 'exe-os', 'exe-create'). Null if no project specified."
554
+ },
555
+ role_filter: {
556
+ type: ["string", "null"],
557
+ description: "Agent role if the query targets a specific role (e.g., 'CTO', 'CMO'). Null if no role specified."
558
+ },
559
+ time_filter: {
560
+ type: ["string", "null"],
561
+ description: "ISO 8601 timestamp lower bound if the query references a time period (e.g., 'last week', 'yesterday'). Null if no time reference."
562
+ },
563
+ is_broad_query: {
564
+ type: "boolean",
565
+ description: "True if the query is exploratory/broad (e.g., 'what has yoshi been working on', 'summarize recent activity'). False if targeted (e.g., 'how did we fix the auth bug')."
566
+ }
567
+ },
568
+ required: ["semantic_query", "project_filter", "role_filter", "time_filter", "is_broad_query"]
569
+ }
570
+ };
571
+ }
572
+ });
573
+
574
+ // src/lib/exe-daemon-client.ts
575
+ import net from "net";
576
+ import { spawn } from "child_process";
577
+ import { randomUUID } from "crypto";
578
+ import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
579
+ import path4 from "path";
580
+ import { fileURLToPath } from "url";
581
+ function handleData(chunk) {
582
+ _buffer += chunk.toString();
583
+ let newlineIdx;
584
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
585
+ const line = _buffer.slice(0, newlineIdx).trim();
586
+ _buffer = _buffer.slice(newlineIdx + 1);
587
+ if (!line) continue;
588
+ try {
589
+ const response = JSON.parse(line);
590
+ const entry = _pending.get(response.id);
591
+ if (entry) {
592
+ clearTimeout(entry.timer);
593
+ _pending.delete(response.id);
594
+ entry.resolve(response);
595
+ }
596
+ } catch {
597
+ }
598
+ }
599
+ }
600
+ function cleanupStaleFiles() {
601
+ if (existsSync4(PID_PATH)) {
602
+ try {
603
+ const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
604
+ if (pid > 0) {
605
+ try {
606
+ process.kill(pid, 0);
607
+ return;
608
+ } catch {
609
+ }
610
+ }
611
+ } catch {
612
+ }
613
+ try {
614
+ unlinkSync(PID_PATH);
615
+ } catch {
616
+ }
617
+ try {
618
+ unlinkSync(SOCKET_PATH);
619
+ } catch {
620
+ }
621
+ }
622
+ }
623
+ function findPackageRoot() {
624
+ let dir = path4.dirname(fileURLToPath(import.meta.url));
625
+ const { root } = path4.parse(dir);
626
+ while (dir !== root) {
627
+ if (existsSync4(path4.join(dir, "package.json"))) return dir;
628
+ dir = path4.dirname(dir);
629
+ }
630
+ return null;
631
+ }
632
+ function spawnDaemon() {
633
+ const pkgRoot = findPackageRoot();
634
+ if (!pkgRoot) {
635
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
636
+ return;
637
+ }
638
+ const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
639
+ if (!existsSync4(daemonPath)) {
640
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
641
+ `);
642
+ return;
643
+ }
644
+ const resolvedPath = daemonPath;
645
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
646
+ `);
647
+ const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
648
+ let stderrFd = "ignore";
649
+ try {
650
+ stderrFd = openSync(logPath, "a");
651
+ } catch {
652
+ }
653
+ const child = spawn(process.execPath, [resolvedPath], {
654
+ detached: true,
655
+ stdio: ["ignore", "ignore", stderrFd],
656
+ env: {
657
+ ...process.env,
658
+ EXE_DAEMON_SOCK: SOCKET_PATH,
659
+ EXE_DAEMON_PID: PID_PATH
660
+ }
661
+ });
662
+ child.unref();
663
+ if (typeof stderrFd === "number") {
664
+ try {
665
+ closeSync(stderrFd);
666
+ } catch {
667
+ }
668
+ }
669
+ }
670
+ function acquireSpawnLock() {
671
+ try {
672
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
673
+ closeSync(fd);
674
+ return true;
675
+ } catch {
676
+ try {
677
+ const stat = statSync(SPAWN_LOCK_PATH);
678
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
679
+ try {
680
+ unlinkSync(SPAWN_LOCK_PATH);
681
+ } catch {
682
+ }
683
+ try {
684
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
685
+ closeSync(fd);
686
+ return true;
687
+ } catch {
688
+ }
689
+ }
690
+ } catch {
691
+ }
692
+ return false;
693
+ }
694
+ }
695
+ function releaseSpawnLock() {
696
+ try {
697
+ unlinkSync(SPAWN_LOCK_PATH);
698
+ } catch {
699
+ }
700
+ }
701
+ function connectToSocket() {
702
+ return new Promise((resolve) => {
703
+ if (_socket && _connected) {
704
+ resolve(true);
705
+ return;
706
+ }
707
+ const socket = net.createConnection({ path: SOCKET_PATH });
708
+ const connectTimeout = setTimeout(() => {
709
+ socket.destroy();
710
+ resolve(false);
711
+ }, 2e3);
712
+ socket.on("connect", () => {
713
+ clearTimeout(connectTimeout);
714
+ _socket = socket;
715
+ _connected = true;
716
+ _buffer = "";
717
+ socket.on("data", handleData);
718
+ socket.on("close", () => {
719
+ _connected = false;
720
+ _socket = null;
721
+ for (const [id, entry] of _pending) {
722
+ clearTimeout(entry.timer);
723
+ _pending.delete(id);
724
+ entry.resolve({ error: "Connection closed" });
725
+ }
726
+ });
727
+ socket.on("error", () => {
728
+ _connected = false;
729
+ _socket = null;
730
+ });
731
+ resolve(true);
732
+ });
733
+ socket.on("error", () => {
734
+ clearTimeout(connectTimeout);
735
+ resolve(false);
736
+ });
737
+ });
738
+ }
739
+ async function connectEmbedDaemon() {
740
+ if (_socket && _connected) return true;
741
+ if (await connectToSocket()) return true;
742
+ if (acquireSpawnLock()) {
743
+ try {
744
+ cleanupStaleFiles();
745
+ spawnDaemon();
746
+ } finally {
747
+ releaseSpawnLock();
748
+ }
749
+ }
750
+ const start = Date.now();
751
+ let delay = 100;
752
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
753
+ await new Promise((r) => setTimeout(r, delay));
754
+ if (await connectToSocket()) return true;
755
+ delay = Math.min(delay * 2, 3e3);
756
+ }
757
+ return false;
758
+ }
759
+ function sendRequest(texts, priority) {
760
+ return new Promise((resolve) => {
761
+ if (!_socket || !_connected) {
762
+ resolve({ error: "Not connected" });
763
+ return;
764
+ }
765
+ const id = randomUUID();
766
+ const timer = setTimeout(() => {
767
+ _pending.delete(id);
768
+ resolve({ error: "Request timeout" });
769
+ }, REQUEST_TIMEOUT_MS);
770
+ _pending.set(id, { resolve, timer });
771
+ try {
772
+ _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
773
+ } catch {
774
+ clearTimeout(timer);
775
+ _pending.delete(id);
776
+ resolve({ error: "Write failed" });
777
+ }
778
+ });
779
+ }
780
+ async function pingDaemon() {
781
+ if (!_socket || !_connected) return null;
782
+ return new Promise((resolve) => {
783
+ const id = randomUUID();
784
+ const timer = setTimeout(() => {
785
+ _pending.delete(id);
786
+ resolve(null);
787
+ }, 5e3);
788
+ _pending.set(id, {
789
+ resolve: (data) => {
790
+ if (data.health) {
791
+ resolve(data.health);
792
+ } else {
793
+ resolve(null);
794
+ }
795
+ },
796
+ timer
797
+ });
798
+ try {
799
+ _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
800
+ } catch {
801
+ clearTimeout(timer);
802
+ _pending.delete(id);
803
+ resolve(null);
804
+ }
805
+ });
806
+ }
807
+ function killAndRespawnDaemon() {
808
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
809
+ if (existsSync4(PID_PATH)) {
810
+ try {
811
+ const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
812
+ if (pid > 0) {
813
+ try {
814
+ process.kill(pid, "SIGKILL");
815
+ } catch {
816
+ }
817
+ }
818
+ } catch {
819
+ }
820
+ }
821
+ if (_socket) {
822
+ _socket.destroy();
823
+ _socket = null;
824
+ }
825
+ _connected = false;
826
+ _buffer = "";
827
+ try {
828
+ unlinkSync(PID_PATH);
829
+ } catch {
830
+ }
831
+ try {
832
+ unlinkSync(SOCKET_PATH);
833
+ } catch {
834
+ }
835
+ spawnDaemon();
836
+ }
837
+ async function embedViaClient(text, priority = "high") {
838
+ if (!_connected && !await connectEmbedDaemon()) return null;
839
+ _requestCount++;
840
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
841
+ const health = await pingDaemon();
842
+ if (!health) {
843
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
844
+ `);
845
+ killAndRespawnDaemon();
846
+ const start = Date.now();
847
+ let delay = 200;
848
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
849
+ await new Promise((r) => setTimeout(r, delay));
850
+ if (await connectToSocket()) break;
851
+ delay = Math.min(delay * 2, 3e3);
852
+ }
853
+ if (!_connected) return null;
854
+ }
855
+ }
856
+ const result = await sendRequest([text], priority);
857
+ if (!result.error && result.vectors?.[0]) return result.vectors[0];
858
+ if (result.error) {
859
+ process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
860
+ `);
861
+ killAndRespawnDaemon();
862
+ const start = Date.now();
863
+ let delay = 200;
864
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
865
+ await new Promise((r) => setTimeout(r, delay));
866
+ if (await connectToSocket()) break;
867
+ delay = Math.min(delay * 2, 3e3);
868
+ }
869
+ if (!_connected) return null;
870
+ const retry = await sendRequest([text], priority);
871
+ if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
872
+ process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
873
+ `);
874
+ }
875
+ return null;
876
+ }
877
+ function disconnectClient() {
878
+ if (_socket) {
879
+ _socket.destroy();
880
+ _socket = null;
881
+ }
882
+ _connected = false;
883
+ _buffer = "";
884
+ for (const [id, entry] of _pending) {
885
+ clearTimeout(entry.timer);
886
+ _pending.delete(id);
887
+ entry.resolve({ error: "Client disconnected" });
888
+ }
889
+ }
890
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending;
891
+ var init_exe_daemon_client = __esm({
892
+ "src/lib/exe-daemon-client.ts"() {
893
+ "use strict";
894
+ init_config();
895
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
896
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
897
+ SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
898
+ SPAWN_LOCK_STALE_MS = 3e4;
899
+ CONNECT_TIMEOUT_MS = 15e3;
900
+ REQUEST_TIMEOUT_MS = 3e4;
901
+ _socket = null;
902
+ _connected = false;
903
+ _buffer = "";
904
+ _requestCount = 0;
905
+ HEALTH_CHECK_INTERVAL = 100;
906
+ _pending = /* @__PURE__ */ new Map();
907
+ }
908
+ });
909
+
910
+ // src/lib/embedder.ts
911
+ var embedder_exports = {};
912
+ __export(embedder_exports, {
913
+ disposeEmbedder: () => disposeEmbedder,
914
+ embed: () => embed,
915
+ embedDirect: () => embedDirect,
916
+ getEmbedder: () => getEmbedder
917
+ });
918
+ async function getEmbedder() {
919
+ const ok = await connectEmbedDaemon();
920
+ if (!ok) {
921
+ throw new Error(
922
+ "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
923
+ );
924
+ }
925
+ }
926
+ async function embed(text) {
927
+ const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
928
+ const vector = await embedViaClient(text, priority);
929
+ if (!vector) {
930
+ throw new Error(
931
+ "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
932
+ );
933
+ }
934
+ if (vector.length !== EMBEDDING_DIM) {
935
+ throw new Error(
936
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
937
+ );
938
+ }
939
+ return vector;
940
+ }
941
+ async function disposeEmbedder() {
942
+ disconnectClient();
943
+ }
944
+ async function embedDirect(text) {
945
+ const llamaCpp = await import("node-llama-cpp");
946
+ const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
947
+ const { existsSync: existsSync7 } = await import("fs");
948
+ const path8 = await import("path");
949
+ const modelPath = path8.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
950
+ if (!existsSync7(modelPath)) {
951
+ throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
952
+ }
953
+ const llama = await llamaCpp.getLlama();
954
+ const model = await llama.loadModel({ modelPath });
955
+ const context = await model.createEmbeddingContext();
956
+ try {
957
+ const embedding = await context.getEmbeddingFor(text);
958
+ const vector = Array.from(embedding.vector);
959
+ if (vector.length !== EMBEDDING_DIM) {
960
+ throw new Error(
961
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
962
+ );
963
+ }
964
+ return vector;
965
+ } finally {
966
+ await context.dispose();
967
+ await model.dispose();
968
+ }
969
+ }
970
+ var init_embedder = __esm({
971
+ "src/lib/embedder.ts"() {
972
+ "use strict";
973
+ init_memory();
974
+ init_exe_daemon_client();
975
+ }
976
+ });
977
+
978
+ // src/lib/project-name.ts
979
+ var project_name_exports = {};
980
+ __export(project_name_exports, {
981
+ _resetCache: () => _resetCache,
982
+ getProjectName: () => getProjectName
983
+ });
984
+ import { execSync } from "child_process";
985
+ import path5 from "path";
986
+ function getProjectName(cwd) {
987
+ const dir = cwd ?? process.cwd();
988
+ if (_cached && _cachedCwd === dir) return _cached;
989
+ try {
990
+ const repoRoot = execSync("git rev-parse --show-toplevel", {
991
+ cwd: dir,
992
+ encoding: "utf8",
993
+ timeout: 2e3,
994
+ stdio: ["pipe", "pipe", "pipe"]
995
+ }).trim();
996
+ _cached = path5.basename(repoRoot);
997
+ _cachedCwd = dir;
998
+ return _cached;
999
+ } catch {
1000
+ _cached = path5.basename(dir);
1001
+ _cachedCwd = dir;
1002
+ return _cached;
1003
+ }
1004
+ }
1005
+ function _resetCache() {
1006
+ _cached = null;
1007
+ _cachedCwd = null;
1008
+ }
1009
+ var _cached, _cachedCwd;
1010
+ var init_project_name = __esm({
1011
+ "src/lib/project-name.ts"() {
1012
+ "use strict";
1013
+ _cached = null;
1014
+ _cachedCwd = null;
1015
+ }
1016
+ });
1017
+
1018
+ // src/lib/file-grep.ts
1019
+ var file_grep_exports = {};
1020
+ __export(file_grep_exports, {
1021
+ grepProjectFiles: () => grepProjectFiles
1022
+ });
1023
+ import { execSync as execSync2 } from "child_process";
1024
+ import { readFileSync as readFileSync3, readdirSync, statSync as statSync2, existsSync as existsSync5 } from "fs";
1025
+ import path6 from "path";
1026
+ import crypto2 from "crypto";
1027
+ async function grepProjectFiles(query, projectRoot, options) {
1028
+ const maxResults = options?.maxResults ?? 10;
1029
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_-]/g, "")).filter((t) => t.length >= 3);
1030
+ if (terms.length === 0) return [];
1031
+ const pattern = terms.join("|");
1032
+ let hits;
1033
+ try {
1034
+ hits = grepWithRipgrep(pattern, projectRoot, options?.patterns);
1035
+ } catch {
1036
+ hits = grepWithNodeFs(pattern, projectRoot, options?.patterns);
1037
+ }
1038
+ hits.sort((a, b) => b.density - a.density);
1039
+ const topHits = hits.slice(0, maxResults);
1040
+ return topHits.map((hit) => {
1041
+ const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
1042
+ const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
1043
+ return {
1044
+ id: crypto2.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
1045
+ agent_id: "project",
1046
+ agent_role: "file",
1047
+ session_id: "file-grep",
1048
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1049
+ tool_name: "file_grep",
1050
+ project_name: path6.basename(projectRoot),
1051
+ has_error: false,
1052
+ raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
1053
+ vector: null,
1054
+ task_id: null
1055
+ };
1056
+ });
1057
+ }
1058
+ function getChunkContext(filePath, lineNumber) {
1059
+ try {
1060
+ const ext = filePath.split(".").pop()?.toLowerCase();
1061
+ if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
1062
+ const source = readFileSync3(filePath, "utf8");
1063
+ const lines = source.split("\n");
1064
+ for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
1065
+ const line = lines[i];
1066
+ const fnMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);
1067
+ if (fnMatch) return `function ${fnMatch[1]}`;
1068
+ const classMatch = line.match(/(?:export\s+)?class\s+(\w+)/);
1069
+ if (classMatch) return `class ${classMatch[1]}`;
1070
+ const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(/);
1071
+ if (arrowMatch) return `function ${arrowMatch[1]}`;
1072
+ }
1073
+ } catch {
1074
+ }
1075
+ return "";
1076
+ }
1077
+ function grepWithRipgrep(pattern, projectRoot, patterns) {
1078
+ const globs = (patterns ?? DEFAULT_PATTERNS).map((p) => `--glob '${p}'`).join(" ");
1079
+ const excludes = EXCLUDE_DIRS.map((d) => `--glob '!${d}'`).join(" ");
1080
+ const cmd = `rg -i -c --hidden '${pattern.replace(/'/g, "\\'")}' . ${globs} ${excludes} --max-filesize ${MAX_FILE_SIZE} 2>/dev/null || true`;
1081
+ const output = execSync2(cmd, {
1082
+ cwd: projectRoot,
1083
+ encoding: "utf8",
1084
+ timeout: 3e3,
1085
+ maxBuffer: 1024 * 1024
1086
+ });
1087
+ if (!output.trim()) return [];
1088
+ const hits = [];
1089
+ for (const line of output.trim().split("\n")) {
1090
+ const colonIdx = line.lastIndexOf(":");
1091
+ if (colonIdx === -1) continue;
1092
+ const filePath = line.slice(0, colonIdx);
1093
+ const matchCount = parseInt(line.slice(colonIdx + 1));
1094
+ if (isNaN(matchCount) || matchCount === 0) continue;
1095
+ try {
1096
+ const firstMatch = execSync2(
1097
+ `rg -i -n --hidden '${pattern.replace(/'/g, "\\'")}' '${filePath}' --max-count 1 2>/dev/null | head -1`,
1098
+ { cwd: projectRoot, encoding: "utf8", timeout: 1e3 }
1099
+ ).trim();
1100
+ const lineNum = parseInt(firstMatch.split(":")[0] ?? "1");
1101
+ const totalLines = execSync2(`wc -l < '${filePath}'`, {
1102
+ cwd: projectRoot,
1103
+ encoding: "utf8",
1104
+ timeout: 1e3
1105
+ }).trim();
1106
+ hits.push({
1107
+ filePath,
1108
+ lineNumber: isNaN(lineNum) ? 1 : lineNum,
1109
+ matchLine: firstMatch.slice(firstMatch.indexOf(":") + 1).slice(0, 200),
1110
+ matchCount,
1111
+ totalLines: parseInt(totalLines) || 1,
1112
+ density: matchCount / (parseInt(totalLines) || 1)
1113
+ });
1114
+ } catch {
1115
+ }
1116
+ }
1117
+ return hits;
1118
+ }
1119
+ function grepWithNodeFs(pattern, projectRoot, patterns) {
1120
+ const regex = new RegExp(pattern, "gi");
1121
+ const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
1122
+ const hits = [];
1123
+ for (const filePath of files.slice(0, MAX_FILES)) {
1124
+ const absPath = path6.join(projectRoot, filePath);
1125
+ try {
1126
+ const stat = statSync2(absPath);
1127
+ if (stat.size > MAX_FILE_SIZE) continue;
1128
+ const content = readFileSync3(absPath, "utf8");
1129
+ const lines = content.split("\n");
1130
+ const matches = content.match(regex);
1131
+ if (!matches || matches.length === 0) continue;
1132
+ const firstMatchIdx = lines.findIndex((l) => regex.test(l));
1133
+ regex.lastIndex = 0;
1134
+ hits.push({
1135
+ filePath,
1136
+ lineNumber: firstMatchIdx >= 0 ? firstMatchIdx + 1 : 1,
1137
+ matchLine: firstMatchIdx >= 0 ? lines[firstMatchIdx].slice(0, 200) : "",
1138
+ matchCount: matches.length,
1139
+ totalLines: lines.length,
1140
+ density: matches.length / lines.length
1141
+ });
1142
+ } catch {
1143
+ }
1144
+ }
1145
+ return hits;
1146
+ }
1147
+ function collectFiles(root, patterns) {
1148
+ const files = [];
1149
+ function walk(dir, relative) {
1150
+ if (files.length >= MAX_FILES) return;
1151
+ const basename = path6.basename(dir);
1152
+ if (EXCLUDE_DIRS.includes(basename)) return;
1153
+ try {
1154
+ const entries = readdirSync(dir, { withFileTypes: true });
1155
+ for (const entry of entries) {
1156
+ if (files.length >= MAX_FILES) return;
1157
+ const rel = path6.join(relative, entry.name);
1158
+ if (entry.isDirectory()) {
1159
+ walk(path6.join(dir, entry.name), rel);
1160
+ } else if (entry.isFile()) {
1161
+ for (const pat of patterns) {
1162
+ if (matchGlob(rel, pat)) {
1163
+ files.push(rel);
1164
+ break;
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ } catch {
1170
+ }
1171
+ }
1172
+ walk(root, "");
1173
+ return files;
1174
+ }
1175
+ function matchGlob(filePath, pattern) {
1176
+ if (!pattern.includes("*")) return filePath === pattern;
1177
+ const doubleStarMatch = pattern.match(/^(.+?)\/\*\*\/\*(\.\w+)$/);
1178
+ if (doubleStarMatch) {
1179
+ const dir = doubleStarMatch[1];
1180
+ const ext2 = doubleStarMatch[2];
1181
+ return filePath.startsWith(dir + "/") && filePath.endsWith(ext2);
1182
+ }
1183
+ if (pattern.startsWith("**/")) {
1184
+ const ext2 = pattern.slice(3).replace("*", "");
1185
+ return filePath.endsWith(ext2);
1186
+ }
1187
+ const slashIdx = pattern.lastIndexOf("/");
1188
+ if (slashIdx !== -1) {
1189
+ const dir = pattern.slice(0, slashIdx);
1190
+ const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
1191
+ const fileDir = path6.dirname(filePath);
1192
+ return fileDir === dir && filePath.endsWith(ext2);
1193
+ }
1194
+ const ext = pattern.replace("*", "");
1195
+ return filePath.endsWith(ext) && !filePath.includes("/");
1196
+ }
1197
+ function buildSnippet(hit, projectRoot) {
1198
+ try {
1199
+ const absPath = path6.join(projectRoot, hit.filePath);
1200
+ if (!existsSync5(absPath)) return hit.matchLine;
1201
+ const lines = readFileSync3(absPath, "utf8").split("\n");
1202
+ const start = Math.max(0, hit.lineNumber - 3);
1203
+ const end = Math.min(lines.length, hit.lineNumber + 2);
1204
+ return lines.slice(start, end).join("\n").slice(0, 500);
1205
+ } catch {
1206
+ return hit.matchLine;
1207
+ }
1208
+ }
1209
+ var DEFAULT_PATTERNS, EXCLUDE_DIRS, MAX_FILE_SIZE, MAX_FILES;
1210
+ var init_file_grep = __esm({
1211
+ "src/lib/file-grep.ts"() {
1212
+ "use strict";
1213
+ DEFAULT_PATTERNS = [
1214
+ ".planning/*.md",
1215
+ "exe/output/*.md",
1216
+ "README.md",
1217
+ "src/**/*.ts"
1218
+ ];
1219
+ EXCLUDE_DIRS = ["node_modules", "dist", ".git", "coverage", ".worktrees"];
1220
+ MAX_FILE_SIZE = 100 * 1024;
1221
+ MAX_FILES = 500;
1222
+ }
1223
+ });
1224
+
1225
+ // src/lib/reranker.ts
1226
+ var reranker_exports = {};
1227
+ __export(reranker_exports, {
1228
+ disposeReranker: () => disposeReranker,
1229
+ getRerankerModelPath: () => getRerankerModelPath,
1230
+ isRerankerAvailable: () => isRerankerAvailable,
1231
+ rerank: () => rerank,
1232
+ rerankWithScores: () => rerankWithScores
1233
+ });
1234
+ import path7 from "path";
1235
+ import { existsSync as existsSync6 } from "fs";
1236
+ function resetIdleTimer() {
1237
+ if (_idleTimer) clearTimeout(_idleTimer);
1238
+ _idleTimer = setTimeout(() => {
1239
+ void disposeReranker();
1240
+ }, IDLE_TIMEOUT_MS);
1241
+ if (_idleTimer && typeof _idleTimer === "object" && "unref" in _idleTimer) {
1242
+ _idleTimer.unref();
1243
+ }
1244
+ }
1245
+ function isRerankerAvailable() {
1246
+ return existsSync6(path7.join(MODELS_DIR, RERANKER_MODEL_FILE));
1247
+ }
1248
+ function getRerankerModelPath() {
1249
+ return path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1250
+ }
1251
+ async function ensureLoaded() {
1252
+ if (_rerankerContext) {
1253
+ resetIdleTimer();
1254
+ return;
1255
+ }
1256
+ const modelPath = path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1257
+ if (!existsSync6(modelPath)) {
1258
+ throw new Error(
1259
+ `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
1260
+ );
1261
+ }
1262
+ process.stderr.write("[reranker] Loading Jina Reranker v3...\n");
1263
+ const { getLlama } = await import("node-llama-cpp");
1264
+ const llama = await getLlama();
1265
+ _rerankerModel = await llama.loadModel({ modelPath });
1266
+ _rerankerContext = await _rerankerModel.createEmbeddingContext();
1267
+ process.stderr.write("[reranker] Jina Reranker v3 loaded.\n");
1268
+ resetIdleTimer();
1269
+ }
1270
+ async function disposeReranker() {
1271
+ if (_idleTimer) {
1272
+ clearTimeout(_idleTimer);
1273
+ _idleTimer = null;
1274
+ }
1275
+ if (_rerankerContext) {
1276
+ try {
1277
+ await _rerankerContext.dispose();
1278
+ } catch {
1279
+ }
1280
+ _rerankerContext = null;
1281
+ }
1282
+ if (_rerankerModel) {
1283
+ try {
1284
+ await _rerankerModel.dispose();
1285
+ } catch {
1286
+ }
1287
+ _rerankerModel = null;
1288
+ }
1289
+ process.stderr.write("[reranker] Unloaded (idle timeout).\n");
1290
+ }
1291
+ async function rerankWithScores(query, texts, topK) {
1292
+ if (texts.length === 0) return [];
1293
+ await ensureLoaded();
1294
+ const ctx = _rerankerContext;
1295
+ const scored = [];
1296
+ for (let i = 0; i < texts.length; i++) {
1297
+ const text = texts[i] ?? "";
1298
+ try {
1299
+ const input = `query: ${query} document: ${text.slice(0, 512)}`;
1300
+ const embedding = await ctx.getEmbeddingFor(input);
1301
+ const score = embedding.vector[0] ?? 0;
1302
+ scored.push({ text, score, index: i });
1303
+ } catch {
1304
+ scored.push({ text, score: -1, index: i });
1305
+ }
1306
+ }
1307
+ scored.sort((a, b) => b.score - a.score);
1308
+ return typeof topK === "number" ? scored.slice(0, topK) : scored;
1309
+ }
1310
+ async function rerank(query, candidates, topK = 5) {
1311
+ if (candidates.length === 0) return [];
1312
+ if (candidates.length <= topK) return candidates;
1313
+ const scored = await rerankWithScores(
1314
+ query,
1315
+ candidates.map((c) => c.raw_text),
1316
+ topK
1317
+ );
1318
+ return scored.map((s) => candidates[s.index]);
1319
+ }
1320
+ var RERANKER_MODEL_FILE, IDLE_TIMEOUT_MS, _rerankerContext, _rerankerModel, _idleTimer;
1321
+ var init_reranker = __esm({
1322
+ "src/lib/reranker.ts"() {
1323
+ "use strict";
1324
+ init_config();
1325
+ RERANKER_MODEL_FILE = "jina-reranker-v3-q4_k_m.gguf";
1326
+ IDLE_TIMEOUT_MS = 6e4;
1327
+ _rerankerContext = null;
1328
+ _rerankerModel = null;
1329
+ _idleTimer = null;
1330
+ }
1331
+ });
1332
+
1333
+ // src/lib/store.ts
1334
+ init_memory();
1335
+
1336
+ // src/lib/database.ts
1337
+ import { createClient } from "@libsql/client";
1338
+ var _client = null;
1339
+ var initTurso = initDatabase;
1340
+ async function initDatabase(config) {
1341
+ if (_client) {
1342
+ _client.close();
1343
+ _client = null;
1344
+ }
1345
+ const opts = {
1346
+ url: `file:${config.dbPath}`
1347
+ };
1348
+ if (config.encryptionKey) {
1349
+ opts.encryptionKey = config.encryptionKey;
1350
+ }
1351
+ _client = createClient(opts);
1352
+ }
1353
+ function getClient() {
1354
+ if (!_client) {
1355
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1356
+ }
1357
+ return _client;
1358
+ }
1359
+ async function ensureSchema() {
1360
+ const client = getClient();
1361
+ await client.execute("PRAGMA journal_mode = WAL");
1362
+ await client.execute("PRAGMA busy_timeout = 5000");
1363
+ try {
1364
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
1365
+ } catch {
1366
+ }
1367
+ await client.executeMultiple(`
1368
+ CREATE TABLE IF NOT EXISTS memories (
1369
+ id TEXT PRIMARY KEY,
1370
+ agent_id TEXT NOT NULL,
1371
+ agent_role TEXT NOT NULL,
1372
+ session_id TEXT NOT NULL,
1373
+ timestamp TEXT NOT NULL,
1374
+ tool_name TEXT NOT NULL,
1375
+ project_name TEXT NOT NULL,
1376
+ has_error INTEGER NOT NULL DEFAULT 0,
1377
+ raw_text TEXT NOT NULL,
1378
+ vector F32_BLOB(1024),
1379
+ version INTEGER NOT NULL DEFAULT 0
1380
+ );
1381
+
1382
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
1383
+ ON memories(agent_id);
1384
+
1385
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1386
+ ON memories(timestamp);
1387
+
1388
+ CREATE INDEX IF NOT EXISTS idx_memories_session
1389
+ ON memories(session_id);
1390
+
1391
+ CREATE INDEX IF NOT EXISTS idx_memories_project
1392
+ ON memories(project_name);
1393
+
1394
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
1395
+ ON memories(tool_name);
1396
+
1397
+ CREATE INDEX IF NOT EXISTS idx_memories_version
1398
+ ON memories(version);
1399
+
1400
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1401
+ ON memories(agent_id, project_name);
1402
+ `);
1403
+ await client.executeMultiple(`
1404
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1405
+ raw_text,
1406
+ content='memories',
1407
+ content_rowid='rowid'
1408
+ );
1409
+
1410
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1411
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1412
+ END;
1413
+
1414
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1415
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1416
+ END;
1417
+
1418
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1419
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1420
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1421
+ END;
1422
+ `);
1423
+ await client.executeMultiple(`
1424
+ CREATE TABLE IF NOT EXISTS sync_meta (
1425
+ key TEXT PRIMARY KEY,
1426
+ value TEXT NOT NULL
1427
+ );
1428
+ `);
1429
+ await client.executeMultiple(`
1430
+ CREATE TABLE IF NOT EXISTS tasks (
1431
+ id TEXT PRIMARY KEY,
1432
+ title TEXT NOT NULL,
1433
+ assigned_to TEXT NOT NULL,
1434
+ assigned_by TEXT NOT NULL,
1435
+ project_name TEXT NOT NULL,
1436
+ priority TEXT NOT NULL DEFAULT 'p1',
1437
+ status TEXT NOT NULL DEFAULT 'open',
1438
+ task_file TEXT,
1439
+ created_at TEXT NOT NULL,
1440
+ updated_at TEXT NOT NULL
1441
+ );
1442
+
1443
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1444
+ ON tasks(assigned_to, status);
1445
+ `);
1446
+ await client.executeMultiple(`
1447
+ CREATE TABLE IF NOT EXISTS behaviors (
1448
+ id TEXT PRIMARY KEY,
1449
+ agent_id TEXT NOT NULL,
1450
+ project_name TEXT,
1451
+ domain TEXT,
1452
+ content TEXT NOT NULL,
1453
+ active INTEGER NOT NULL DEFAULT 1,
1454
+ created_at TEXT NOT NULL,
1455
+ updated_at TEXT NOT NULL
1456
+ );
1457
+
1458
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1459
+ ON behaviors(agent_id, active);
1460
+ `);
1461
+ try {
1462
+ const existing = await client.execute({
1463
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
1464
+ args: []
1465
+ });
1466
+ if (Number(existing.rows[0]?.cnt) === 0) {
1467
+ await client.executeMultiple(`
1468
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1469
+ VALUES
1470
+ (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
1471
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1472
+ VALUES
1473
+ (hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
1474
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1475
+ VALUES
1476
+ (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
1477
+ `);
1478
+ }
1479
+ } catch {
1480
+ }
1481
+ try {
1482
+ await client.execute({
1483
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1484
+ args: []
1485
+ });
1486
+ } catch {
1487
+ }
1488
+ try {
1489
+ await client.execute({
1490
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1491
+ args: []
1492
+ });
1493
+ } catch {
1494
+ }
1495
+ try {
1496
+ await client.execute({
1497
+ sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
1498
+ args: []
1499
+ });
1500
+ } catch {
1501
+ }
1502
+ try {
1503
+ await client.execute({
1504
+ sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
1505
+ ON tasks(parent_task_id)
1506
+ WHERE parent_task_id IS NOT NULL`,
1507
+ args: []
1508
+ });
1509
+ } catch {
1510
+ }
1511
+ try {
1512
+ await client.execute({
1513
+ sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
1514
+ args: []
1515
+ });
1516
+ } catch {
1517
+ }
1518
+ try {
1519
+ await client.execute({
1520
+ sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
1521
+ args: []
1522
+ });
1523
+ } catch {
1524
+ }
1525
+ try {
1526
+ await client.execute({
1527
+ sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
1528
+ args: []
1529
+ });
1530
+ } catch {
1531
+ }
1532
+ try {
1533
+ await client.execute({
1534
+ sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
1535
+ args: []
1536
+ });
1537
+ } catch {
1538
+ }
1539
+ try {
1540
+ await client.execute({
1541
+ sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
1542
+ args: []
1543
+ });
1544
+ } catch {
1545
+ }
1546
+ try {
1547
+ await client.execute({
1548
+ sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
1549
+ args: []
1550
+ });
1551
+ } catch {
1552
+ }
1553
+ try {
1554
+ await client.execute({
1555
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1556
+ args: []
1557
+ });
1558
+ } catch {
1559
+ }
1560
+ try {
1561
+ await client.execute({
1562
+ sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
1563
+ args: []
1564
+ });
1565
+ } catch {
1566
+ }
1567
+ try {
1568
+ await client.execute({
1569
+ sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
1570
+ args: []
1571
+ });
1572
+ } catch {
1573
+ }
1574
+ await client.executeMultiple(`
1575
+ CREATE TABLE IF NOT EXISTS consolidations (
1576
+ id TEXT PRIMARY KEY,
1577
+ consolidated_memory_id TEXT NOT NULL,
1578
+ source_memory_id TEXT NOT NULL,
1579
+ created_at TEXT NOT NULL
1580
+ );
1581
+
1582
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
1583
+ ON consolidations(source_memory_id);
1584
+
1585
+ CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
1586
+ ON consolidations(consolidated_memory_id);
1587
+ `);
1588
+ await client.executeMultiple(`
1589
+ CREATE TABLE IF NOT EXISTS reminders (
1590
+ id TEXT PRIMARY KEY,
1591
+ text TEXT NOT NULL,
1592
+ created_at TEXT NOT NULL,
1593
+ due_date TEXT,
1594
+ completed_at TEXT
1595
+ );
1596
+ `);
1597
+ await client.executeMultiple(`
1598
+ CREATE TABLE IF NOT EXISTS notifications (
1599
+ id TEXT PRIMARY KEY,
1600
+ agent_id TEXT NOT NULL,
1601
+ agent_role TEXT NOT NULL,
1602
+ event TEXT NOT NULL,
1603
+ project TEXT NOT NULL,
1604
+ summary TEXT NOT NULL,
1605
+ task_file TEXT,
1606
+ read INTEGER NOT NULL DEFAULT 0,
1607
+ created_at TEXT NOT NULL
1608
+ );
1609
+
1610
+ CREATE INDEX IF NOT EXISTS idx_notifications_read
1611
+ ON notifications(read);
1612
+
1613
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent
1614
+ ON notifications(agent_id);
1615
+
1616
+ CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1617
+ ON notifications(task_file);
1618
+ `);
1619
+ await client.executeMultiple(`
1620
+ CREATE TABLE IF NOT EXISTS schedules (
1621
+ id TEXT PRIMARY KEY,
1622
+ cron TEXT NOT NULL,
1623
+ description TEXT NOT NULL,
1624
+ job_type TEXT NOT NULL DEFAULT 'report',
1625
+ prompt TEXT,
1626
+ assigned_to TEXT,
1627
+ project_name TEXT,
1628
+ active INTEGER NOT NULL DEFAULT 1,
1629
+ use_crontab INTEGER NOT NULL DEFAULT 0,
1630
+ created_at TEXT NOT NULL
1631
+ );
1632
+ `);
1633
+ await client.executeMultiple(`
1634
+ CREATE TABLE IF NOT EXISTS device_registry (
1635
+ device_id TEXT PRIMARY KEY,
1636
+ friendly_name TEXT NOT NULL,
1637
+ hostname TEXT NOT NULL,
1638
+ projects TEXT NOT NULL DEFAULT '[]',
1639
+ agents TEXT NOT NULL DEFAULT '[]',
1640
+ connected INTEGER DEFAULT 0,
1641
+ last_seen TEXT NOT NULL
1642
+ );
1643
+ `);
1644
+ await client.executeMultiple(`
1645
+ CREATE TABLE IF NOT EXISTS messages (
1646
+ id TEXT PRIMARY KEY,
1647
+ from_agent TEXT NOT NULL,
1648
+ from_device TEXT NOT NULL DEFAULT 'local',
1649
+ target_agent TEXT NOT NULL,
1650
+ target_project TEXT,
1651
+ target_device TEXT NOT NULL DEFAULT 'local',
1652
+ content TEXT NOT NULL,
1653
+ priority TEXT DEFAULT 'normal',
1654
+ status TEXT DEFAULT 'pending',
1655
+ server_seq INTEGER,
1656
+ retry_count INTEGER DEFAULT 0,
1657
+ created_at TEXT NOT NULL,
1658
+ delivered_at TEXT,
1659
+ processed_at TEXT,
1660
+ failed_at TEXT,
1661
+ failure_reason TEXT
1662
+ );
1663
+
1664
+ CREATE INDEX IF NOT EXISTS idx_messages_target
1665
+ ON messages(target_agent, status);
1666
+
1667
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
1668
+ ON messages(target_agent, from_agent, server_seq);
1669
+ `);
1670
+ try {
1671
+ await client.execute({
1672
+ sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
1673
+ args: []
1674
+ });
1675
+ await client.execute({
1676
+ sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1677
+ args: []
1678
+ });
1679
+ await client.execute({
1680
+ sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
1681
+ args: []
1682
+ });
1683
+ await client.execute({
1684
+ sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1685
+ args: []
1686
+ });
1687
+ } catch {
1688
+ }
1689
+ await client.executeMultiple(`
1690
+ CREATE TABLE IF NOT EXISTS trajectories (
1691
+ id TEXT PRIMARY KEY,
1692
+ task_id TEXT NOT NULL,
1693
+ agent_id TEXT NOT NULL,
1694
+ project_name TEXT NOT NULL,
1695
+ task_title TEXT NOT NULL,
1696
+ signature TEXT NOT NULL,
1697
+ signature_hash TEXT NOT NULL,
1698
+ tool_count INTEGER NOT NULL,
1699
+ skill_id TEXT,
1700
+ created_at TEXT NOT NULL
1701
+ );
1702
+
1703
+ CREATE INDEX IF NOT EXISTS idx_trajectories_hash
1704
+ ON trajectories(signature_hash);
1705
+
1706
+ CREATE INDEX IF NOT EXISTS idx_trajectories_agent
1707
+ ON trajectories(agent_id);
1708
+ `);
1709
+ try {
1710
+ await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
1711
+ } catch {
1712
+ }
1713
+ await client.executeMultiple(`
1714
+ CREATE TABLE IF NOT EXISTS consolidations (
1715
+ id TEXT PRIMARY KEY,
1716
+ consolidated_memory_id TEXT NOT NULL,
1717
+ source_memory_id TEXT NOT NULL,
1718
+ created_at TEXT NOT NULL
1719
+ );
1720
+
1721
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
1722
+ ON consolidations(source_memory_id);
1723
+ `);
1724
+ await client.executeMultiple(`
1725
+ CREATE TABLE IF NOT EXISTS audit_trail (
1726
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1727
+ timestamp TEXT NOT NULL,
1728
+ session_id TEXT NOT NULL,
1729
+ agent_id TEXT NOT NULL,
1730
+ tool TEXT NOT NULL,
1731
+ input TEXT,
1732
+ decision TEXT NOT NULL,
1733
+ reason TEXT,
1734
+ is_customer_facing INTEGER NOT NULL DEFAULT 0
1735
+ );
1736
+
1737
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
1738
+ ON audit_trail(agent_id, timestamp);
1739
+
1740
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_session
1741
+ ON audit_trail(session_id);
1742
+ `);
1743
+ try {
1744
+ await client.execute({
1745
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1746
+ args: []
1747
+ });
1748
+ } catch {
1749
+ }
1750
+ try {
1751
+ await client.execute({
1752
+ sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
1753
+ args: []
1754
+ });
1755
+ } catch {
1756
+ }
1757
+ try {
1758
+ await client.execute({
1759
+ sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
1760
+ args: []
1761
+ });
1762
+ } catch {
1763
+ }
1764
+ try {
1765
+ await client.execute({
1766
+ sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
1767
+ args: []
1768
+ });
1769
+ } catch {
1770
+ }
1771
+ try {
1772
+ await client.execute({
1773
+ sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
1774
+ args: []
1775
+ });
1776
+ } catch {
1777
+ }
1778
+ try {
1779
+ await client.execute({
1780
+ sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
1781
+ args: []
1782
+ });
1783
+ } catch {
1784
+ }
1785
+ try {
1786
+ await client.execute({
1787
+ sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
1788
+ args: []
1789
+ });
1790
+ } catch {
1791
+ }
1792
+ try {
1793
+ await client.execute({
1794
+ sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
1795
+ args: []
1796
+ });
1797
+ } catch {
1798
+ }
1799
+ for (const col of [
1800
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1801
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
1802
+ ]) {
1803
+ try {
1804
+ await client.execute(col);
1805
+ } catch {
1806
+ }
1807
+ }
1808
+ await client.executeMultiple(`
1809
+ CREATE TABLE IF NOT EXISTS entities (
1810
+ id TEXT PRIMARY KEY,
1811
+ name TEXT NOT NULL,
1812
+ type TEXT NOT NULL,
1813
+ first_seen TEXT NOT NULL,
1814
+ last_seen TEXT NOT NULL,
1815
+ properties TEXT DEFAULT '{}',
1816
+ UNIQUE(name, type)
1817
+ );
1818
+
1819
+ CREATE TABLE IF NOT EXISTS relationships (
1820
+ id TEXT PRIMARY KEY,
1821
+ source_entity_id TEXT NOT NULL,
1822
+ target_entity_id TEXT NOT NULL,
1823
+ type TEXT NOT NULL,
1824
+ weight REAL DEFAULT 1.0,
1825
+ timestamp TEXT NOT NULL,
1826
+ properties TEXT DEFAULT '{}',
1827
+ UNIQUE(source_entity_id, target_entity_id, type)
1828
+ );
1829
+
1830
+ CREATE TABLE IF NOT EXISTS entity_memories (
1831
+ entity_id TEXT NOT NULL,
1832
+ memory_id TEXT NOT NULL,
1833
+ PRIMARY KEY (entity_id, memory_id)
1834
+ );
1835
+
1836
+ CREATE TABLE IF NOT EXISTS relationship_memories (
1837
+ relationship_id TEXT NOT NULL,
1838
+ memory_id TEXT NOT NULL,
1839
+ PRIMARY KEY (relationship_id, memory_id)
1840
+ );
1841
+
1842
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1843
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1844
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1845
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1846
+
1847
+ CREATE TABLE IF NOT EXISTS hyperedges (
1848
+ id TEXT PRIMARY KEY,
1849
+ label TEXT NOT NULL,
1850
+ relation TEXT NOT NULL,
1851
+ confidence REAL DEFAULT 1.0,
1852
+ timestamp TEXT NOT NULL
1853
+ );
1854
+
1855
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1856
+ hyperedge_id TEXT NOT NULL,
1857
+ entity_id TEXT NOT NULL,
1858
+ PRIMARY KEY (hyperedge_id, entity_id)
1859
+ );
1860
+ `);
1861
+ await client.executeMultiple(`
1862
+ CREATE TABLE IF NOT EXISTS entity_aliases (
1863
+ alias TEXT NOT NULL PRIMARY KEY,
1864
+ canonical_entity_id TEXT NOT NULL
1865
+ );
1866
+ CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
1867
+ `);
1868
+ for (const col of [
1869
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1870
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1871
+ ]) {
1872
+ try {
1873
+ await client.execute(col);
1874
+ } catch {
1875
+ }
1876
+ }
1877
+ try {
1878
+ await client.execute(
1879
+ `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
1880
+ );
1881
+ } catch {
1882
+ }
1883
+ await client.executeMultiple(`
1884
+ CREATE TABLE IF NOT EXISTS identity (
1885
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1886
+ agent_id TEXT NOT NULL UNIQUE,
1887
+ content_hash TEXT NOT NULL,
1888
+ updated_at TEXT NOT NULL,
1889
+ updated_by TEXT NOT NULL
1890
+ );
1891
+
1892
+ CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
1893
+ `);
1894
+ await client.executeMultiple(`
1895
+ CREATE TABLE IF NOT EXISTS chat_history (
1896
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1897
+ session_id TEXT NOT NULL,
1898
+ role TEXT NOT NULL,
1899
+ content TEXT NOT NULL,
1900
+ tool_name TEXT,
1901
+ tool_id TEXT,
1902
+ is_error INTEGER NOT NULL DEFAULT 0,
1903
+ timestamp INTEGER NOT NULL
1904
+ );
1905
+
1906
+ CREATE INDEX IF NOT EXISTS idx_chat_history_session
1907
+ ON chat_history(session_id, id);
1908
+ `);
1909
+ await client.executeMultiple(`
1910
+ CREATE TABLE IF NOT EXISTS workspaces (
1911
+ id TEXT PRIMARY KEY,
1912
+ slug TEXT NOT NULL UNIQUE,
1913
+ name TEXT NOT NULL,
1914
+ owner_agent_id TEXT,
1915
+ created_at TEXT NOT NULL,
1916
+ metadata TEXT
1917
+ );
1918
+
1919
+ CREATE INDEX IF NOT EXISTS idx_workspaces_slug
1920
+ ON workspaces(slug);
1921
+ `);
1922
+ await client.executeMultiple(`
1923
+ CREATE TABLE IF NOT EXISTS documents (
1924
+ id TEXT PRIMARY KEY,
1925
+ workspace_id TEXT NOT NULL,
1926
+ filename TEXT NOT NULL,
1927
+ mime TEXT,
1928
+ source_type TEXT,
1929
+ user_id TEXT,
1930
+ uploaded_at TEXT NOT NULL,
1931
+ metadata TEXT,
1932
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
1933
+ );
1934
+
1935
+ CREATE INDEX IF NOT EXISTS idx_documents_workspace
1936
+ ON documents(workspace_id);
1937
+
1938
+ CREATE INDEX IF NOT EXISTS idx_documents_user
1939
+ ON documents(user_id);
1940
+ `);
1941
+ for (const column of [
1942
+ "workspace_id TEXT",
1943
+ "document_id TEXT",
1944
+ "user_id TEXT",
1945
+ "char_offset INTEGER",
1946
+ "page_number INTEGER"
1947
+ ]) {
1948
+ try {
1949
+ await client.execute({
1950
+ sql: `ALTER TABLE memories ADD COLUMN ${column}`,
1951
+ args: []
1952
+ });
1953
+ } catch {
1954
+ }
1955
+ }
1956
+ await client.executeMultiple(`
1957
+ CREATE INDEX IF NOT EXISTS idx_memories_workspace
1958
+ ON memories(workspace_id);
1959
+
1960
+ CREATE INDEX IF NOT EXISTS idx_memories_document
1961
+ ON memories(document_id);
1962
+
1963
+ CREATE INDEX IF NOT EXISTS idx_memories_user
1964
+ ON memories(user_id);
1965
+ `);
1966
+ await client.executeMultiple(`
1967
+ CREATE TABLE IF NOT EXISTS session_kills (
1968
+ id TEXT PRIMARY KEY,
1969
+ session_name TEXT NOT NULL,
1970
+ agent_id TEXT NOT NULL,
1971
+ killed_at TIMESTAMP NOT NULL,
1972
+ reason TEXT NOT NULL,
1973
+ ticks_idle INTEGER,
1974
+ estimated_tokens_saved INTEGER
1975
+ );
1976
+
1977
+ CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
1978
+ ON session_kills(killed_at);
1979
+
1980
+ CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1981
+ ON session_kills(agent_id);
1982
+ `);
1983
+ await client.executeMultiple(`
1984
+ CREATE TABLE IF NOT EXISTS conversations (
1985
+ id TEXT PRIMARY KEY,
1986
+ platform TEXT NOT NULL,
1987
+ external_id TEXT,
1988
+ sender_id TEXT NOT NULL,
1989
+ sender_name TEXT,
1990
+ sender_phone TEXT,
1991
+ sender_email TEXT,
1992
+ recipient_id TEXT,
1993
+ channel_id TEXT NOT NULL,
1994
+ thread_id TEXT,
1995
+ reply_to_id TEXT,
1996
+ content_text TEXT,
1997
+ content_media TEXT,
1998
+ content_metadata TEXT,
1999
+ agent_response TEXT,
2000
+ agent_name TEXT,
2001
+ timestamp TEXT NOT NULL,
2002
+ ingested_at TEXT NOT NULL
2003
+ );
2004
+
2005
+ CREATE INDEX IF NOT EXISTS idx_conversations_platform
2006
+ ON conversations(platform);
2007
+
2008
+ CREATE INDEX IF NOT EXISTS idx_conversations_sender
2009
+ ON conversations(sender_id);
2010
+
2011
+ CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
2012
+ ON conversations(timestamp);
2013
+
2014
+ CREATE INDEX IF NOT EXISTS idx_conversations_thread
2015
+ ON conversations(thread_id);
2016
+
2017
+ CREATE INDEX IF NOT EXISTS idx_conversations_channel
2018
+ ON conversations(channel_id);
2019
+ `);
2020
+ await client.executeMultiple(`
2021
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
2022
+ content_text,
2023
+ sender_name,
2024
+ agent_response,
2025
+ content='conversations',
2026
+ content_rowid='rowid'
2027
+ );
2028
+
2029
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
2030
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
2031
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
2032
+ END;
2033
+
2034
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
2035
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
2036
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
2037
+ END;
2038
+
2039
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
2040
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
2041
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
2042
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
2043
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
2044
+ END;
2045
+ `);
2046
+ }
2047
+
2048
+ // src/lib/keychain.ts
2049
+ import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
2050
+ import { existsSync } from "fs";
2051
+ import path from "path";
2052
+ import crypto from "crypto";
2053
+ var SERVICE = "exe-mem";
2054
+ var ACCOUNT = "master-key";
2055
+ function getKeyDir() {
2056
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(process.env.HOME ?? "/tmp", ".exe-os");
2057
+ }
2058
+ function getKeyPath() {
2059
+ return path.join(getKeyDir(), "master.key");
2060
+ }
2061
+ async function tryKeytar() {
2062
+ try {
2063
+ return await import("keytar");
2064
+ } catch {
2065
+ return null;
2066
+ }
2067
+ }
2068
+ async function getMasterKey() {
2069
+ const keytar = await tryKeytar();
2070
+ if (keytar) {
2071
+ try {
2072
+ const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2073
+ if (stored) {
2074
+ return Buffer.from(stored, "base64");
2075
+ }
2076
+ } catch {
2077
+ }
2078
+ }
2079
+ const keyPath = getKeyPath();
2080
+ if (!existsSync(keyPath)) {
2081
+ return null;
2082
+ }
2083
+ try {
2084
+ const content = await readFile(keyPath, "utf-8");
2085
+ return Buffer.from(content.trim(), "base64");
2086
+ } catch {
2087
+ return null;
2088
+ }
2089
+ }
2090
+
2091
+ // src/lib/store.ts
2092
+ init_config();
2093
+ var _pendingRecords = [];
2094
+ var _batchSize = 20;
2095
+ var _flushIntervalMs = 1e4;
2096
+ var _flushTimer = null;
2097
+ var _flushing = false;
2098
+ var _nextVersion = 1;
2099
+ async function initStore(options) {
2100
+ if (_flushTimer !== null) {
2101
+ clearInterval(_flushTimer);
2102
+ _flushTimer = null;
2103
+ }
2104
+ _pendingRecords = [];
2105
+ _flushing = false;
2106
+ _batchSize = options?.batchSize ?? 20;
2107
+ _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
2108
+ let dbPath = options?.dbPath;
2109
+ if (!dbPath) {
2110
+ const config = await loadConfig();
2111
+ dbPath = config.dbPath;
2112
+ }
2113
+ let masterKey = options?.masterKey ?? null;
2114
+ if (!masterKey) {
2115
+ masterKey = await getMasterKey();
2116
+ if (!masterKey) {
2117
+ throw new Error(
2118
+ "No encryption key found. Run /exe-setup to generate one."
2119
+ );
2120
+ }
2121
+ }
2122
+ const hexKey = masterKey.toString("hex");
2123
+ await initTurso({
2124
+ dbPath,
2125
+ encryptionKey: hexKey
2126
+ });
2127
+ await ensureSchema();
2128
+ try {
2129
+ const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
2130
+ initShardManager2(hexKey);
2131
+ } catch {
2132
+ }
2133
+ const client = getClient();
2134
+ const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
2135
+ _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
2136
+ }
2137
+ function buildWikiScopeFilter(options, columnPrefix) {
2138
+ const args = [];
2139
+ let clause = "";
2140
+ if (options?.workspaceId !== void 0) {
2141
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
2142
+ args.push(options.workspaceId);
2143
+ }
2144
+ if (options?.userId === void 0) {
2145
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
2146
+ } else if (options.userId === null) {
2147
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
2148
+ } else {
2149
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
2150
+ args.push(options.userId);
2151
+ }
2152
+ return { clause, args };
2153
+ }
2154
+ async function searchMemories(queryVector, agentId, options) {
2155
+ let client;
2156
+ try {
2157
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
2158
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
2159
+ client = await getReadyShardClient2(options.projectName);
2160
+ } else {
2161
+ client = getClient();
2162
+ }
2163
+ } catch {
2164
+ client = getClient();
2165
+ }
2166
+ const limit = options?.limit ?? 10;
2167
+ const statusFilter = options?.includeArchived ? "" : `
2168
+ AND COALESCE(status, 'active') = 'active'`;
2169
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
2170
+ tool_name, project_name,
2171
+ has_error, raw_text, vector, importance, status,
2172
+ confidence, last_accessed,
2173
+ workspace_id, document_id, user_id,
2174
+ char_offset, page_number
2175
+ FROM memories
2176
+ WHERE agent_id = ?
2177
+ AND vector IS NOT NULL${statusFilter}
2178
+ AND COALESCE(confidence, 0.7) >= 0.3`;
2179
+ const args = [agentId];
2180
+ const scope = buildWikiScopeFilter(options, "");
2181
+ sql += scope.clause;
2182
+ args.push(...scope.args);
2183
+ if (options?.projectName) {
2184
+ sql += ` AND project_name = ?`;
2185
+ args.push(options.projectName);
2186
+ }
2187
+ if (options?.toolName) {
2188
+ sql += ` AND tool_name = ?`;
2189
+ args.push(options.toolName);
2190
+ }
2191
+ if (options?.hasError !== void 0) {
2192
+ sql += ` AND has_error = ?`;
2193
+ args.push(options.hasError ? 1 : 0);
2194
+ }
2195
+ if (options?.since) {
2196
+ sql += ` AND timestamp >= ?`;
2197
+ args.push(options.since);
2198
+ }
2199
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
2200
+ args.push(vectorToBlob(queryVector));
2201
+ sql += ` LIMIT ?`;
2202
+ args.push(limit);
2203
+ const result = await client.execute({ sql, args });
2204
+ return result.rows.map((row) => ({
2205
+ id: row.id,
2206
+ agent_id: row.agent_id,
2207
+ agent_role: row.agent_role,
2208
+ session_id: row.session_id,
2209
+ timestamp: row.timestamp,
2210
+ tool_name: row.tool_name,
2211
+ project_name: row.project_name,
2212
+ has_error: row.has_error === 1,
2213
+ raw_text: row.raw_text,
2214
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
2215
+ importance: row.importance ?? 5,
2216
+ status: row.status ?? "active",
2217
+ confidence: row.confidence ?? 0.7,
2218
+ last_accessed: row.last_accessed ?? row.timestamp,
2219
+ workspace_id: row.workspace_id ?? null,
2220
+ document_id: row.document_id ?? null,
2221
+ user_id: row.user_id ?? null,
2222
+ char_offset: row.char_offset ?? null,
2223
+ page_number: row.page_number ?? null
2224
+ }));
2225
+ }
2226
+ async function attachDocumentMetadata(records) {
2227
+ const docIds = [
2228
+ ...new Set(
2229
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
2230
+ )
2231
+ ];
2232
+ if (docIds.length === 0) return records;
2233
+ try {
2234
+ const client = getClient();
2235
+ const placeholders = docIds.map(() => "?").join(",");
2236
+ const result = await client.execute({
2237
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
2238
+ FROM documents
2239
+ WHERE id IN (${placeholders})`,
2240
+ args: docIds
2241
+ });
2242
+ const byId = /* @__PURE__ */ new Map();
2243
+ for (const row of result.rows) {
2244
+ const id = row.id;
2245
+ byId.set(id, {
2246
+ document_id: id,
2247
+ filename: row.filename,
2248
+ mime: row.mime ?? null,
2249
+ source_type: row.source_type ?? null,
2250
+ uploaded_at: row.uploaded_at
2251
+ });
2252
+ }
2253
+ for (const record of records) {
2254
+ if (!record.document_id) continue;
2255
+ record.document_metadata = byId.get(record.document_id) ?? null;
2256
+ }
2257
+ } catch {
2258
+ }
2259
+ return records;
2260
+ }
2261
+ function vectorToBlob(vector) {
2262
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
2263
+ return JSON.stringify(Array.from(f32));
2264
+ }
2265
+
2266
+ // src/lib/hybrid-search.ts
2267
+ var RRF_K = 60;
2268
+ async function hybridSearch(queryText, agentId, options) {
2269
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2270
+ const config = await loadConfig2();
2271
+ if (config.searchMode === "fts") {
2272
+ return lightweightSearch(queryText, agentId, options);
2273
+ }
2274
+ const limit = options?.limit ?? 10;
2275
+ let effectiveQuery = queryText;
2276
+ let effectiveOptions = { ...options };
2277
+ let _isBroadQuery = false;
2278
+ if (config.selfQueryRouter && process.env.ANTHROPIC_API_KEY) {
2279
+ try {
2280
+ const { routeQuery: routeQuery2 } = await Promise.resolve().then(() => (init_self_query_router(), self_query_router_exports));
2281
+ const routed = await routeQuery2(queryText, config.selfQueryModel);
2282
+ effectiveQuery = routed.semanticQuery;
2283
+ _isBroadQuery = routed.isBroadQuery;
2284
+ if (routed.projectFilter && !effectiveOptions.projectName) {
2285
+ effectiveOptions.projectName = routed.projectFilter;
2286
+ }
2287
+ if (routed.timeFilter && !effectiveOptions.since) {
2288
+ effectiveOptions.since = routed.timeFilter;
2289
+ }
2290
+ } catch {
2291
+ }
2292
+ }
2293
+ const broadFetchTopK = config.scalingRoadmap?.rerankerAutoTrigger?.fetchTopK ?? 150;
2294
+ const fetchLimit = _isBroadQuery ? Math.max(limit * 5, broadFetchTopK) : Math.max(limit * 3, 30);
2295
+ const fetchOptions = { ...effectiveOptions, limit: fetchLimit, includeSource: false };
2296
+ let queryVector = null;
2297
+ try {
2298
+ const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
2299
+ queryVector = await embed2(effectiveQuery);
2300
+ } catch {
2301
+ process.stderr.write("[hybrid-search] Embed daemon unavailable \u2014 FTS-only mode\n");
2302
+ }
2303
+ let grepPromise = Promise.resolve([]);
2304
+ if (config.fileGrepEnabled !== false) {
2305
+ try {
2306
+ const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
2307
+ const projectRoot = process.cwd();
2308
+ const projectName = getProjectName2(projectRoot);
2309
+ if (projectName && projectName !== "tmp") {
2310
+ const { grepProjectFiles: grepProjectFiles2 } = await Promise.resolve().then(() => (init_file_grep(), file_grep_exports));
2311
+ grepPromise = grepProjectFiles2(effectiveQuery, projectRoot, {
2312
+ maxResults: 10
2313
+ }).catch(() => []);
2314
+ }
2315
+ } catch {
2316
+ }
2317
+ }
2318
+ const [ftsResults, vectorResults, grepResults] = await Promise.all([
2319
+ lightweightSearch(effectiveQuery, agentId, fetchOptions),
2320
+ queryVector ? searchMemories(queryVector, agentId, fetchOptions) : Promise.resolve([]),
2321
+ grepPromise
2322
+ ]);
2323
+ const lists = [];
2324
+ const weights = [];
2325
+ if (ftsResults.length > 0) {
2326
+ lists.push(ftsResults);
2327
+ weights.push(1);
2328
+ }
2329
+ if (vectorResults.length > 0) {
2330
+ lists.push(vectorResults);
2331
+ weights.push(1);
2332
+ }
2333
+ if (grepResults.length > 0) {
2334
+ lists.push(grepResults);
2335
+ weights.push(0.5);
2336
+ }
2337
+ if (lists.length === 0) return [];
2338
+ if (lists.length === 1 && !_isBroadQuery) return lists[0].slice(0, limit);
2339
+ const rrfLimit = _isBroadQuery ? Math.max(limit * 5, 150) : limit;
2340
+ const merged = lists.length === 1 ? lists[0].slice(0, rrfLimit) : rrfMergeMulti(lists, rrfLimit, RRF_K, weights);
2341
+ const auto = config.scalingRoadmap?.rerankerAutoTrigger ?? {
2342
+ enabled: config.rerankerEnabled ?? true,
2343
+ broadQueryMinCardinality: 5e4,
2344
+ fetchTopK: 150,
2345
+ returnTopK: 5
2346
+ };
2347
+ let rerankedAndBlended = null;
2348
+ if (_isBroadQuery && auto.enabled) {
2349
+ const cardinality = await estimateCardinality(agentId, effectiveOptions);
2350
+ if (cardinality > auto.broadQueryMinCardinality) {
2351
+ try {
2352
+ const { isRerankerAvailable: isRerankerAvailable2, rerank: rerank2 } = await Promise.resolve().then(() => (init_reranker(), reranker_exports));
2353
+ if (isRerankerAvailable2()) {
2354
+ const reranked = await rerank2(effectiveQuery, merged, auto.returnTopK);
2355
+ if (reranked.length > 0) {
2356
+ rerankedAndBlended = rrfMergeMulti(
2357
+ [reranked],
2358
+ auto.returnTopK,
2359
+ RRF_K
2360
+ );
2361
+ }
2362
+ }
2363
+ } catch {
2364
+ }
2365
+ }
2366
+ }
2367
+ const finalResults = (rerankedAndBlended ?? merged).slice(
2368
+ 0,
2369
+ rerankedAndBlended ? auto.returnTopK : limit
2370
+ );
2371
+ if (options?.includeSource && finalResults.length > 0) {
2372
+ await attachDocumentMetadata(finalResults);
2373
+ }
2374
+ if (finalResults.length > 0) {
2375
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2376
+ const ids = finalResults.map((r) => r.id);
2377
+ const placeholders = ids.map(() => "?").join(",");
2378
+ try {
2379
+ const client = getClient();
2380
+ void client.execute({
2381
+ sql: `UPDATE memories SET last_accessed = ? WHERE id IN (${placeholders})`,
2382
+ args: [now, ...ids]
2383
+ }).catch(() => {
2384
+ });
2385
+ } catch {
2386
+ }
2387
+ }
2388
+ return finalResults;
2389
+ }
2390
+ async function estimateCardinality(agentId, options) {
2391
+ const client = getClient();
2392
+ let sql = `SELECT COUNT(*) as cnt FROM memories
2393
+ WHERE agent_id = ?
2394
+ AND COALESCE(status, 'active') = 'active'
2395
+ AND COALESCE(confidence, 0.7) >= 0.3`;
2396
+ const args = [agentId];
2397
+ if (options?.projectName) {
2398
+ sql += ` AND project_name = ?`;
2399
+ args.push(options.projectName);
2400
+ }
2401
+ if (options?.toolName) {
2402
+ sql += ` AND tool_name = ?`;
2403
+ args.push(options.toolName);
2404
+ }
2405
+ if (options?.hasError !== void 0) {
2406
+ sql += ` AND has_error = ?`;
2407
+ args.push(options.hasError ? 1 : 0);
2408
+ }
2409
+ if (options?.since) {
2410
+ sql += ` AND timestamp >= ?`;
2411
+ args.push(options.since);
2412
+ }
2413
+ try {
2414
+ const result = await client.execute({ sql, args });
2415
+ return Number(result.rows[0]?.cnt) || 0;
2416
+ } catch {
2417
+ return 0;
2418
+ }
2419
+ }
2420
+ function recencyScore(timestamp) {
2421
+ const daysSince = (Date.now() - new Date(timestamp).getTime()) / (1e3 * 60 * 60 * 24);
2422
+ return 1 / (1 + daysSince * 0.01);
2423
+ }
2424
+ function normalizedImportance(importance) {
2425
+ return ((importance ?? 5) - 1) / 9;
2426
+ }
2427
+ function rrfMergeMulti(lists, limit, k = RRF_K, weights) {
2428
+ const scores = /* @__PURE__ */ new Map();
2429
+ for (let listIdx = 0; listIdx < lists.length; listIdx++) {
2430
+ const list = lists[listIdx];
2431
+ const weight = weights?.[listIdx] ?? 1;
2432
+ for (let i = 0; i < list.length; i++) {
2433
+ const rec = list[i];
2434
+ const entry = scores.get(rec.id) ?? { rrfScore: 0, record: rec };
2435
+ entry.rrfScore += weight * (1 / (k + i + 1));
2436
+ scores.set(rec.id, entry);
2437
+ }
2438
+ }
2439
+ const entries = Array.from(scores.values()).map((e) => {
2440
+ const recency = recencyScore(e.record.timestamp);
2441
+ const importance = normalizedImportance(e.record.importance);
2442
+ const confidence = e.record.confidence ?? 0.7;
2443
+ const finalScore = e.rrfScore * 0.35 + recency * 0.14 + importance * 0.21 + confidence * 0.3;
2444
+ return { score: finalScore, record: e.record };
2445
+ });
2446
+ return entries.sort((a, b) => b.score - a.score).slice(0, limit).map((e) => e.record);
2447
+ }
2448
+ async function lightweightSearch(queryText, agentId, options) {
2449
+ const client = getClient();
2450
+ const limit = options?.limit ?? 5;
2451
+ const terms = queryText.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_]/g, "")).filter((t) => t.length >= 3);
2452
+ if (terms.length === 0) {
2453
+ return recentRecords(agentId, options, limit);
2454
+ }
2455
+ const prefixTerms = terms.map((t) => `${t}*`);
2456
+ const useAnd = terms.length >= 3;
2457
+ const matchExpr = useAnd ? prefixTerms.join(" AND ") : prefixTerms.join(" OR ");
2458
+ const results = await ftsQuery(client, matchExpr, agentId, options, limit);
2459
+ if (useAnd && results.length < limit) {
2460
+ const orExpr = prefixTerms.join(" OR ");
2461
+ const orResults = await ftsQuery(client, orExpr, agentId, options, limit);
2462
+ const seen = new Set(results.map((r) => r.id));
2463
+ for (const r of orResults) {
2464
+ if (!seen.has(r.id) && results.length < limit) {
2465
+ results.push(r);
2466
+ seen.add(r.id);
2467
+ }
2468
+ }
2469
+ }
2470
+ if (options?.includeSource && results.length > 0) {
2471
+ await attachDocumentMetadata(results);
2472
+ }
2473
+ return results;
2474
+ }
2475
+ async function ftsQuery(client, matchExpr, agentId, options, limit) {
2476
+ const statusFilter = options?.includeArchived ? "" : `
2477
+ AND COALESCE(m.status, 'active') = 'active'`;
2478
+ let sql = `SELECT m.id, m.agent_id, m.agent_role, m.session_id, m.timestamp,
2479
+ m.tool_name, m.project_name,
2480
+ m.has_error, m.raw_text, m.vector, m.task_id,
2481
+ m.importance, m.status, m.confidence, m.last_accessed,
2482
+ m.workspace_id, m.document_id, m.user_id,
2483
+ m.char_offset, m.page_number
2484
+ FROM memories m
2485
+ JOIN memories_fts fts ON m.rowid = fts.rowid
2486
+ WHERE memories_fts MATCH ?
2487
+ AND m.agent_id = ?${statusFilter}
2488
+ AND COALESCE(m.confidence, 0.7) >= 0.3`;
2489
+ const args = [matchExpr, agentId];
2490
+ const scope = buildWikiScopeFilter(options, "m.");
2491
+ sql += scope.clause;
2492
+ args.push(...scope.args);
2493
+ if (options?.projectName) {
2494
+ sql += ` AND m.project_name = ?`;
2495
+ args.push(options.projectName);
2496
+ }
2497
+ if (options?.toolName) {
2498
+ sql += ` AND m.tool_name = ?`;
2499
+ args.push(options.toolName);
2500
+ }
2501
+ if (options?.hasError !== void 0) {
2502
+ sql += ` AND m.has_error = ?`;
2503
+ args.push(options.hasError ? 1 : 0);
2504
+ }
2505
+ if (options?.since) {
2506
+ sql += ` AND m.timestamp >= ?`;
2507
+ args.push(options.since);
2508
+ }
2509
+ sql += ` ORDER BY rank LIMIT ?`;
2510
+ args.push(limit);
2511
+ const result = await client.execute({ sql, args });
2512
+ return result.rows.map((row) => ({
2513
+ id: row.id,
2514
+ agent_id: row.agent_id,
2515
+ agent_role: row.agent_role,
2516
+ session_id: row.session_id,
2517
+ timestamp: row.timestamp,
2518
+ tool_name: row.tool_name,
2519
+ project_name: row.project_name,
2520
+ has_error: row.has_error === 1,
2521
+ raw_text: row.raw_text,
2522
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
2523
+ task_id: row.task_id ?? null,
2524
+ importance: row.importance ?? 5,
2525
+ status: row.status ?? "active",
2526
+ confidence: row.confidence ?? 0.7,
2527
+ last_accessed: row.last_accessed ?? row.timestamp,
2528
+ workspace_id: row.workspace_id ?? null,
2529
+ document_id: row.document_id ?? null,
2530
+ user_id: row.user_id ?? null,
2531
+ char_offset: row.char_offset ?? null,
2532
+ page_number: row.page_number ?? null
2533
+ }));
2534
+ }
2535
+ async function recentRecords(agentId, options, limit) {
2536
+ const client = getClient();
2537
+ const statusFilter = options?.includeArchived ? "" : `
2538
+ AND COALESCE(status, 'active') = 'active'`;
2539
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
2540
+ tool_name, project_name,
2541
+ has_error, raw_text, vector, task_id,
2542
+ importance, status, confidence, last_accessed,
2543
+ workspace_id, document_id, user_id,
2544
+ char_offset, page_number
2545
+ FROM memories
2546
+ WHERE agent_id = ?${statusFilter}
2547
+ AND COALESCE(confidence, 0.7) >= 0.3`;
2548
+ const args = [agentId];
2549
+ const scope = buildWikiScopeFilter(options, "");
2550
+ sql += scope.clause;
2551
+ args.push(...scope.args);
2552
+ if (options?.projectName) {
2553
+ sql += ` AND project_name = ?`;
2554
+ args.push(options.projectName);
2555
+ }
2556
+ if (options?.toolName) {
2557
+ sql += ` AND tool_name = ?`;
2558
+ args.push(options.toolName);
2559
+ }
2560
+ if (options?.hasError !== void 0) {
2561
+ sql += ` AND has_error = ?`;
2562
+ args.push(options.hasError ? 1 : 0);
2563
+ }
2564
+ if (options?.since) {
2565
+ sql += ` AND timestamp >= ?`;
2566
+ args.push(options.since);
2567
+ }
2568
+ sql += ` ORDER BY timestamp DESC LIMIT ?`;
2569
+ args.push(limit);
2570
+ const result = await client.execute({ sql, args });
2571
+ return result.rows.map((row) => ({
2572
+ id: row.id,
2573
+ agent_id: row.agent_id,
2574
+ agent_role: row.agent_role,
2575
+ session_id: row.session_id,
2576
+ timestamp: row.timestamp,
2577
+ tool_name: row.tool_name,
2578
+ project_name: row.project_name,
2579
+ has_error: row.has_error === 1,
2580
+ raw_text: row.raw_text,
2581
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
2582
+ task_id: row.task_id ?? null,
2583
+ importance: row.importance ?? 5,
2584
+ status: row.status ?? "active",
2585
+ confidence: row.confidence ?? 0.7,
2586
+ last_accessed: row.last_accessed ?? row.timestamp,
2587
+ workspace_id: row.workspace_id ?? null,
2588
+ document_id: row.document_id ?? null,
2589
+ user_id: row.user_id ?? null,
2590
+ char_offset: row.char_offset ?? null,
2591
+ page_number: row.page_number ?? null
2592
+ }));
2593
+ }
2594
+
2595
+ // src/bin/exe-search.ts
2596
+ init_config();
2597
+
2598
+ // src/lib/is-main.ts
2599
+ import { realpathSync } from "fs";
2600
+ import { fileURLToPath as fileURLToPath2 } from "url";
2601
+ function isMainModule(importMetaUrl) {
2602
+ if (process.argv[1] == null) return false;
2603
+ try {
2604
+ const scriptPath = realpathSync(process.argv[1]);
2605
+ const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
2606
+ return scriptPath === modulePath;
2607
+ } catch {
2608
+ return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
2609
+ }
2610
+ }
2611
+
2612
+ // src/bin/exe-search.ts
2613
+ async function main() {
2614
+ const query = process.argv.slice(2).join(" ");
2615
+ if (!query) {
2616
+ console.error('Usage: exe-search <query>\nExample: exe-search "auth bug JWT"');
2617
+ process.exit(1);
2618
+ }
2619
+ const agentId = process.env.AGENT_ID;
2620
+ if (!agentId) {
2621
+ console.error("No AGENT_ID set. Run this inside an employee session (/exe-call <name>).");
2622
+ process.exit(1);
2623
+ }
2624
+ await initStore();
2625
+ const config = await loadConfig();
2626
+ const search = config.searchMode === "hybrid" ? hybridSearch : lightweightSearch;
2627
+ const memories = await search(query, agentId, { limit: 10 });
2628
+ if (memories.length === 0) {
2629
+ console.log("No memories found.");
2630
+ return;
2631
+ }
2632
+ console.log(`Found ${memories.length} memories:
2633
+ `);
2634
+ for (const m of memories) {
2635
+ const errorTag = m.has_error ? " [ERROR]" : "";
2636
+ const text = m.raw_text.length > 300 ? m.raw_text.slice(0, 300) + "..." : m.raw_text;
2637
+ console.log(`[${m.timestamp}] ${m.tool_name} (${m.project_name})${errorTag}`);
2638
+ console.log(` ${text}`);
2639
+ console.log(` ID: ${m.id}`);
2640
+ console.log("");
2641
+ }
2642
+ }
2643
+ if (isMainModule(import.meta.url)) {
2644
+ main().catch((err) => {
2645
+ console.error(err instanceof Error ? err.message : String(err));
2646
+ process.exit(1);
2647
+ });
2648
+ }
2649
+ export {
2650
+ main
2651
+ };