@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,1819 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // src/types/memory.ts
18
+ var EMBEDDING_DIM;
19
+ var init_memory = __esm({
20
+ "src/types/memory.ts"() {
21
+ "use strict";
22
+ EMBEDDING_DIM = 1024;
23
+ }
24
+ });
25
+
26
+ // src/lib/config.ts
27
+ var config_exports = {};
28
+ __export(config_exports, {
29
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
30
+ CONFIG_PATH: () => CONFIG_PATH,
31
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
32
+ DB_PATH: () => DB_PATH,
33
+ EXE_AI_DIR: () => EXE_AI_DIR,
34
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
35
+ MODELS_DIR: () => MODELS_DIR,
36
+ loadConfig: () => loadConfig,
37
+ loadConfigFrom: () => loadConfigFrom,
38
+ loadConfigSync: () => loadConfigSync,
39
+ migrateConfig: () => migrateConfig,
40
+ saveConfig: () => saveConfig
41
+ });
42
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
43
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
44
+ import path2 from "path";
45
+ import os from "os";
46
+ function resolveDataDir() {
47
+ if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
48
+ if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
49
+ const newDir = path2.join(os.homedir(), ".exe-os");
50
+ const legacyDir = path2.join(os.homedir(), ".exe-mem");
51
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
52
+ try {
53
+ renameSync(legacyDir, newDir);
54
+ process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
55
+ `);
56
+ } catch {
57
+ return legacyDir;
58
+ }
59
+ }
60
+ return newDir;
61
+ }
62
+ function migrateLegacyConfig(raw) {
63
+ if ("r2" in raw) {
64
+ process.stderr.write(
65
+ "[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"
66
+ );
67
+ delete raw.r2;
68
+ }
69
+ if ("syncIntervalMs" in raw) {
70
+ delete raw.syncIntervalMs;
71
+ }
72
+ return raw;
73
+ }
74
+ function migrateConfig(raw) {
75
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
76
+ let currentVersion = fromVersion;
77
+ let migrated = false;
78
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
79
+ return { config: raw, migrated: false, fromVersion };
80
+ }
81
+ for (const migration of CONFIG_MIGRATIONS) {
82
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
83
+ raw = migration.migrate(raw);
84
+ currentVersion = migration.to;
85
+ migrated = true;
86
+ }
87
+ }
88
+ return { config: raw, migrated, fromVersion };
89
+ }
90
+ function normalizeScalingRoadmap(raw) {
91
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
92
+ const userRoadmap = raw.scalingRoadmap ?? {};
93
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
94
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
95
+ userAuto.enabled = raw.rerankerEnabled;
96
+ }
97
+ raw.scalingRoadmap = {
98
+ ...userRoadmap,
99
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
100
+ };
101
+ }
102
+ function normalizeSessionLifecycle(raw) {
103
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
104
+ const userSL = raw.sessionLifecycle ?? {};
105
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
106
+ }
107
+ async function loadConfig() {
108
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
109
+ await mkdir2(dir, { recursive: true });
110
+ const configPath = path2.join(dir, "config.json");
111
+ if (!existsSync2(configPath)) {
112
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
113
+ }
114
+ const raw = await readFile2(configPath, "utf-8");
115
+ try {
116
+ let parsed = JSON.parse(raw);
117
+ parsed = migrateLegacyConfig(parsed);
118
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
119
+ if (migrated) {
120
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
121
+ `);
122
+ try {
123
+ await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
124
+ } catch {
125
+ }
126
+ }
127
+ normalizeScalingRoadmap(migratedCfg);
128
+ normalizeSessionLifecycle(migratedCfg);
129
+ const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
130
+ if (config.dbPath.startsWith("~")) {
131
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
132
+ }
133
+ return config;
134
+ } catch {
135
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
136
+ }
137
+ }
138
+ function loadConfigSync() {
139
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
140
+ const configPath = path2.join(dir, "config.json");
141
+ if (!existsSync2(configPath)) {
142
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
143
+ }
144
+ try {
145
+ const raw = readFileSync(configPath, "utf-8");
146
+ let parsed = JSON.parse(raw);
147
+ parsed = migrateLegacyConfig(parsed);
148
+ const { config: migratedCfg } = migrateConfig(parsed);
149
+ normalizeScalingRoadmap(migratedCfg);
150
+ normalizeSessionLifecycle(migratedCfg);
151
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
152
+ } catch {
153
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
154
+ }
155
+ }
156
+ async function saveConfig(config) {
157
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
158
+ await mkdir2(dir, { recursive: true });
159
+ const configPath = path2.join(dir, "config.json");
160
+ await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
161
+ }
162
+ async function loadConfigFrom(configPath) {
163
+ const raw = await readFile2(configPath, "utf-8");
164
+ try {
165
+ let parsed = JSON.parse(raw);
166
+ parsed = migrateLegacyConfig(parsed);
167
+ const { config: migratedCfg } = migrateConfig(parsed);
168
+ normalizeScalingRoadmap(migratedCfg);
169
+ normalizeSessionLifecycle(migratedCfg);
170
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
171
+ } catch {
172
+ return { ...DEFAULT_CONFIG };
173
+ }
174
+ }
175
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
176
+ var init_config = __esm({
177
+ "src/lib/config.ts"() {
178
+ "use strict";
179
+ EXE_AI_DIR = resolveDataDir();
180
+ DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
181
+ MODELS_DIR = path2.join(EXE_AI_DIR, "models");
182
+ CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
183
+ LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
184
+ CURRENT_CONFIG_VERSION = 1;
185
+ DEFAULT_CONFIG = {
186
+ config_version: CURRENT_CONFIG_VERSION,
187
+ dbPath: DB_PATH,
188
+ modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
189
+ embeddingDim: 1024,
190
+ batchSize: 20,
191
+ flushIntervalMs: 1e4,
192
+ autoIngestion: true,
193
+ autoRetrieval: true,
194
+ searchMode: "hybrid",
195
+ hookSearchMode: "hybrid",
196
+ fileGrepEnabled: true,
197
+ splashEffect: true,
198
+ consolidationEnabled: true,
199
+ consolidationIntervalMs: 6 * 60 * 60 * 1e3,
200
+ consolidationModel: "claude-haiku-4-5-20251001",
201
+ consolidationMaxCallsPerRun: 20,
202
+ selfQueryRouter: true,
203
+ selfQueryModel: "claude-haiku-4-5-20251001",
204
+ rerankerEnabled: true,
205
+ scalingRoadmap: {
206
+ rerankerAutoTrigger: {
207
+ enabled: true,
208
+ broadQueryMinCardinality: 5e4,
209
+ fetchTopK: 150,
210
+ returnTopK: 5
211
+ }
212
+ },
213
+ graphRagEnabled: true,
214
+ wikiEnabled: false,
215
+ wikiUrl: "",
216
+ wikiApiKey: "",
217
+ wikiSyncIntervalMs: 30 * 60 * 1e3,
218
+ wikiWorkspaceMapping: {
219
+ exe: "Executive",
220
+ yoshi: "Engineering",
221
+ mari: "Marketing",
222
+ tom: "Engineering",
223
+ sasha: "Production"
224
+ },
225
+ wikiAutoUpdate: true,
226
+ wikiAutoUpdateThreshold: 0.5,
227
+ wikiAutoUpdateCreateNew: true,
228
+ skillLearning: true,
229
+ skillThreshold: 3,
230
+ skillModel: "claude-haiku-4-5-20251001",
231
+ exeHeartbeat: {
232
+ enabled: true,
233
+ intervalSeconds: 60,
234
+ staleInProgressThresholdHours: 2
235
+ },
236
+ sessionLifecycle: {
237
+ idleKillEnabled: true,
238
+ idleKillTicksRequired: 3,
239
+ idleKillIntercomAckWindowMs: 1e4,
240
+ maxAutoInstances: 10
241
+ }
242
+ };
243
+ CONFIG_MIGRATIONS = [
244
+ {
245
+ from: 0,
246
+ to: 1,
247
+ migrate: (cfg) => {
248
+ cfg.config_version = 1;
249
+ return cfg;
250
+ }
251
+ }
252
+ ];
253
+ }
254
+ });
255
+
256
+ // src/lib/shard-manager.ts
257
+ var shard_manager_exports = {};
258
+ __export(shard_manager_exports, {
259
+ disposeShards: () => disposeShards,
260
+ ensureShardSchema: () => ensureShardSchema,
261
+ getReadyShardClient: () => getReadyShardClient,
262
+ getShardClient: () => getShardClient,
263
+ getShardsDir: () => getShardsDir,
264
+ initShardManager: () => initShardManager,
265
+ isShardingEnabled: () => isShardingEnabled,
266
+ listShards: () => listShards,
267
+ shardExists: () => shardExists
268
+ });
269
+ import path3 from "path";
270
+ import { existsSync as existsSync3, mkdirSync } from "fs";
271
+ import { createClient as createClient2 } from "@libsql/client";
272
+ function initShardManager(encryptionKey) {
273
+ _encryptionKey = encryptionKey;
274
+ if (!existsSync3(SHARDS_DIR)) {
275
+ mkdirSync(SHARDS_DIR, { recursive: true });
276
+ }
277
+ _shardingEnabled = true;
278
+ }
279
+ function isShardingEnabled() {
280
+ return _shardingEnabled;
281
+ }
282
+ function getShardsDir() {
283
+ return SHARDS_DIR;
284
+ }
285
+ function getShardClient(projectName) {
286
+ if (!_encryptionKey) {
287
+ throw new Error("Shard manager not initialized. Call initShardManager() first.");
288
+ }
289
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
290
+ if (!safeName) {
291
+ throw new Error(`Invalid project name for shard: "${projectName}"`);
292
+ }
293
+ const cached = _shards.get(safeName);
294
+ if (cached) return cached;
295
+ const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
296
+ const client = createClient2({
297
+ url: `file:${dbPath}`,
298
+ encryptionKey: _encryptionKey
299
+ });
300
+ _shards.set(safeName, client);
301
+ return client;
302
+ }
303
+ function shardExists(projectName) {
304
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
305
+ return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
306
+ }
307
+ function listShards() {
308
+ if (!existsSync3(SHARDS_DIR)) return [];
309
+ const { readdirSync: readdirSync2 } = __require("fs");
310
+ return readdirSync2(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
311
+ }
312
+ async function ensureShardSchema(client) {
313
+ await client.execute("PRAGMA journal_mode = WAL");
314
+ await client.execute("PRAGMA busy_timeout = 5000");
315
+ try {
316
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
317
+ } catch {
318
+ }
319
+ await client.executeMultiple(`
320
+ CREATE TABLE IF NOT EXISTS memories (
321
+ id TEXT PRIMARY KEY,
322
+ agent_id TEXT NOT NULL,
323
+ agent_role TEXT NOT NULL,
324
+ session_id TEXT NOT NULL,
325
+ timestamp TEXT NOT NULL,
326
+ tool_name TEXT NOT NULL,
327
+ project_name TEXT NOT NULL,
328
+ has_error INTEGER NOT NULL DEFAULT 0,
329
+ raw_text TEXT NOT NULL,
330
+ vector F32_BLOB(1024),
331
+ version INTEGER NOT NULL DEFAULT 0
332
+ );
333
+
334
+ CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
335
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
336
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
337
+ `);
338
+ await client.executeMultiple(`
339
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
340
+ raw_text,
341
+ content='memories',
342
+ content_rowid='rowid'
343
+ );
344
+
345
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
346
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
347
+ END;
348
+
349
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
350
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
351
+ END;
352
+
353
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
354
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
355
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
356
+ END;
357
+ `);
358
+ for (const col of [
359
+ "ALTER TABLE memories ADD COLUMN task_id TEXT",
360
+ "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
361
+ "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
362
+ "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
363
+ "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
364
+ "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
365
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
366
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
367
+ "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
368
+ "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
369
+ // Wiki linkage columns (must match database.ts)
370
+ "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
371
+ "ALTER TABLE memories ADD COLUMN document_id TEXT",
372
+ "ALTER TABLE memories ADD COLUMN user_id TEXT",
373
+ "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
374
+ "ALTER TABLE memories ADD COLUMN page_number INTEGER"
375
+ ]) {
376
+ try {
377
+ await client.execute(col);
378
+ } catch {
379
+ }
380
+ }
381
+ try {
382
+ await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
383
+ } catch {
384
+ }
385
+ for (const idx of [
386
+ "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
387
+ "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
388
+ "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
389
+ ]) {
390
+ try {
391
+ await client.execute(idx);
392
+ } catch {
393
+ }
394
+ }
395
+ await client.executeMultiple(`
396
+ CREATE TABLE IF NOT EXISTS entities (
397
+ id TEXT PRIMARY KEY,
398
+ name TEXT NOT NULL,
399
+ type TEXT NOT NULL,
400
+ first_seen TEXT NOT NULL,
401
+ last_seen TEXT NOT NULL,
402
+ properties TEXT DEFAULT '{}',
403
+ UNIQUE(name, type)
404
+ );
405
+
406
+ CREATE TABLE IF NOT EXISTS relationships (
407
+ id TEXT PRIMARY KEY,
408
+ source_entity_id TEXT NOT NULL,
409
+ target_entity_id TEXT NOT NULL,
410
+ type TEXT NOT NULL,
411
+ weight REAL DEFAULT 1.0,
412
+ timestamp TEXT NOT NULL,
413
+ properties TEXT DEFAULT '{}',
414
+ UNIQUE(source_entity_id, target_entity_id, type)
415
+ );
416
+
417
+ CREATE TABLE IF NOT EXISTS entity_memories (
418
+ entity_id TEXT NOT NULL,
419
+ memory_id TEXT NOT NULL,
420
+ PRIMARY KEY (entity_id, memory_id)
421
+ );
422
+
423
+ CREATE TABLE IF NOT EXISTS relationship_memories (
424
+ relationship_id TEXT NOT NULL,
425
+ memory_id TEXT NOT NULL,
426
+ PRIMARY KEY (relationship_id, memory_id)
427
+ );
428
+
429
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
430
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
431
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
432
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
433
+ CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
434
+
435
+ CREATE TABLE IF NOT EXISTS hyperedges (
436
+ id TEXT PRIMARY KEY,
437
+ label TEXT NOT NULL,
438
+ relation TEXT NOT NULL,
439
+ confidence REAL DEFAULT 1.0,
440
+ timestamp TEXT NOT NULL
441
+ );
442
+
443
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
444
+ hyperedge_id TEXT NOT NULL,
445
+ entity_id TEXT NOT NULL,
446
+ PRIMARY KEY (hyperedge_id, entity_id)
447
+ );
448
+ `);
449
+ for (const col of [
450
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
451
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
452
+ ]) {
453
+ try {
454
+ await client.execute(col);
455
+ } catch {
456
+ }
457
+ }
458
+ }
459
+ async function getReadyShardClient(projectName) {
460
+ const client = getShardClient(projectName);
461
+ await ensureShardSchema(client);
462
+ return client;
463
+ }
464
+ function disposeShards() {
465
+ for (const [, client] of _shards) {
466
+ client.close();
467
+ }
468
+ _shards.clear();
469
+ _shardingEnabled = false;
470
+ _encryptionKey = null;
471
+ }
472
+ var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
473
+ var init_shard_manager = __esm({
474
+ "src/lib/shard-manager.ts"() {
475
+ "use strict";
476
+ init_config();
477
+ SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
478
+ _shards = /* @__PURE__ */ new Map();
479
+ _encryptionKey = null;
480
+ _shardingEnabled = false;
481
+ }
482
+ });
483
+
484
+ // src/lib/self-query-router.ts
485
+ var self_query_router_exports = {};
486
+ __export(self_query_router_exports, {
487
+ routeQuery: () => routeQuery
488
+ });
489
+ async function routeQuery(query, model = "claude-haiku-4-5-20251001") {
490
+ if (query.length < 10) {
491
+ return {
492
+ semanticQuery: query,
493
+ projectFilter: null,
494
+ roleFilter: null,
495
+ timeFilter: null,
496
+ isBroadQuery: false
497
+ };
498
+ }
499
+ try {
500
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
501
+ const client = new Anthropic();
502
+ const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
503
+ const response = await client.messages.create({
504
+ model,
505
+ max_tokens: 256,
506
+ 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.`,
507
+ messages: [{ role: "user", content: query }],
508
+ tools: [EXTRACT_TOOL],
509
+ tool_choice: { type: "tool", name: "extract_search_filters" }
510
+ });
511
+ const toolBlock = response.content.find((b) => b.type === "tool_use");
512
+ if (toolBlock && toolBlock.type === "tool_use") {
513
+ const input = toolBlock.input;
514
+ return {
515
+ semanticQuery: input.semantic_query || query,
516
+ projectFilter: input.project_filter || null,
517
+ roleFilter: input.role_filter || null,
518
+ timeFilter: input.time_filter || null,
519
+ isBroadQuery: Boolean(input.is_broad_query)
520
+ };
521
+ }
522
+ } catch (err) {
523
+ process.stderr.write(
524
+ `[self-query-router] LLM extraction failed, using passthrough: ${err instanceof Error ? err.message : String(err)}
525
+ `
526
+ );
527
+ }
528
+ return {
529
+ semanticQuery: query,
530
+ projectFilter: null,
531
+ roleFilter: null,
532
+ timeFilter: null,
533
+ isBroadQuery: false
534
+ };
535
+ }
536
+ var EXTRACT_TOOL;
537
+ var init_self_query_router = __esm({
538
+ "src/lib/self-query-router.ts"() {
539
+ "use strict";
540
+ EXTRACT_TOOL = {
541
+ name: "extract_search_filters",
542
+ description: "Extract metadata filters from a memory search query to improve retrieval precision.",
543
+ input_schema: {
544
+ type: "object",
545
+ properties: {
546
+ semantic_query: {
547
+ type: "string",
548
+ description: "The core semantic meaning of the query, stripped of metadata references. This is used for embedding search."
549
+ },
550
+ project_filter: {
551
+ type: ["string", "null"],
552
+ description: "Project name if the query references a specific project (e.g., 'exe-os', 'exe-create'). Null if no project specified."
553
+ },
554
+ role_filter: {
555
+ type: ["string", "null"],
556
+ description: "Agent role if the query targets a specific role (e.g., 'CTO', 'CMO'). Null if no role specified."
557
+ },
558
+ time_filter: {
559
+ type: ["string", "null"],
560
+ description: "ISO 8601 timestamp lower bound if the query references a time period (e.g., 'last week', 'yesterday'). Null if no time reference."
561
+ },
562
+ is_broad_query: {
563
+ type: "boolean",
564
+ 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')."
565
+ }
566
+ },
567
+ required: ["semantic_query", "project_filter", "role_filter", "time_filter", "is_broad_query"]
568
+ }
569
+ };
570
+ }
571
+ });
572
+
573
+ // src/lib/exe-daemon-client.ts
574
+ import net from "net";
575
+ import { spawn } from "child_process";
576
+ import { randomUUID } from "crypto";
577
+ import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
578
+ import path4 from "path";
579
+ import { fileURLToPath } from "url";
580
+ function handleData(chunk) {
581
+ _buffer += chunk.toString();
582
+ let newlineIdx;
583
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
584
+ const line = _buffer.slice(0, newlineIdx).trim();
585
+ _buffer = _buffer.slice(newlineIdx + 1);
586
+ if (!line) continue;
587
+ try {
588
+ const response = JSON.parse(line);
589
+ const entry = _pending.get(response.id);
590
+ if (entry) {
591
+ clearTimeout(entry.timer);
592
+ _pending.delete(response.id);
593
+ entry.resolve(response);
594
+ }
595
+ } catch {
596
+ }
597
+ }
598
+ }
599
+ function cleanupStaleFiles() {
600
+ if (existsSync4(PID_PATH)) {
601
+ try {
602
+ const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
603
+ if (pid > 0) {
604
+ try {
605
+ process.kill(pid, 0);
606
+ return;
607
+ } catch {
608
+ }
609
+ }
610
+ } catch {
611
+ }
612
+ try {
613
+ unlinkSync(PID_PATH);
614
+ } catch {
615
+ }
616
+ try {
617
+ unlinkSync(SOCKET_PATH);
618
+ } catch {
619
+ }
620
+ }
621
+ }
622
+ function findPackageRoot() {
623
+ let dir = path4.dirname(fileURLToPath(import.meta.url));
624
+ const { root } = path4.parse(dir);
625
+ while (dir !== root) {
626
+ if (existsSync4(path4.join(dir, "package.json"))) return dir;
627
+ dir = path4.dirname(dir);
628
+ }
629
+ return null;
630
+ }
631
+ function spawnDaemon() {
632
+ const pkgRoot = findPackageRoot();
633
+ if (!pkgRoot) {
634
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
635
+ return;
636
+ }
637
+ const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
638
+ if (!existsSync4(daemonPath)) {
639
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
640
+ `);
641
+ return;
642
+ }
643
+ const resolvedPath = daemonPath;
644
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
645
+ `);
646
+ const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
647
+ let stderrFd = "ignore";
648
+ try {
649
+ stderrFd = openSync(logPath, "a");
650
+ } catch {
651
+ }
652
+ const child = spawn(process.execPath, [resolvedPath], {
653
+ detached: true,
654
+ stdio: ["ignore", "ignore", stderrFd],
655
+ env: {
656
+ ...process.env,
657
+ EXE_DAEMON_SOCK: SOCKET_PATH,
658
+ EXE_DAEMON_PID: PID_PATH
659
+ }
660
+ });
661
+ child.unref();
662
+ if (typeof stderrFd === "number") {
663
+ try {
664
+ closeSync(stderrFd);
665
+ } catch {
666
+ }
667
+ }
668
+ }
669
+ function acquireSpawnLock() {
670
+ try {
671
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
672
+ closeSync(fd);
673
+ return true;
674
+ } catch {
675
+ try {
676
+ const stat = statSync(SPAWN_LOCK_PATH);
677
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
678
+ try {
679
+ unlinkSync(SPAWN_LOCK_PATH);
680
+ } catch {
681
+ }
682
+ try {
683
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
684
+ closeSync(fd);
685
+ return true;
686
+ } catch {
687
+ }
688
+ }
689
+ } catch {
690
+ }
691
+ return false;
692
+ }
693
+ }
694
+ function releaseSpawnLock() {
695
+ try {
696
+ unlinkSync(SPAWN_LOCK_PATH);
697
+ } catch {
698
+ }
699
+ }
700
+ function connectToSocket() {
701
+ return new Promise((resolve) => {
702
+ if (_socket && _connected) {
703
+ resolve(true);
704
+ return;
705
+ }
706
+ const socket = net.createConnection({ path: SOCKET_PATH });
707
+ const connectTimeout = setTimeout(() => {
708
+ socket.destroy();
709
+ resolve(false);
710
+ }, 2e3);
711
+ socket.on("connect", () => {
712
+ clearTimeout(connectTimeout);
713
+ _socket = socket;
714
+ _connected = true;
715
+ _buffer = "";
716
+ socket.on("data", handleData);
717
+ socket.on("close", () => {
718
+ _connected = false;
719
+ _socket = null;
720
+ for (const [id, entry] of _pending) {
721
+ clearTimeout(entry.timer);
722
+ _pending.delete(id);
723
+ entry.resolve({ error: "Connection closed" });
724
+ }
725
+ });
726
+ socket.on("error", () => {
727
+ _connected = false;
728
+ _socket = null;
729
+ });
730
+ resolve(true);
731
+ });
732
+ socket.on("error", () => {
733
+ clearTimeout(connectTimeout);
734
+ resolve(false);
735
+ });
736
+ });
737
+ }
738
+ async function connectEmbedDaemon() {
739
+ if (_socket && _connected) return true;
740
+ if (await connectToSocket()) return true;
741
+ if (acquireSpawnLock()) {
742
+ try {
743
+ cleanupStaleFiles();
744
+ spawnDaemon();
745
+ } finally {
746
+ releaseSpawnLock();
747
+ }
748
+ }
749
+ const start = Date.now();
750
+ let delay = 100;
751
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
752
+ await new Promise((r) => setTimeout(r, delay));
753
+ if (await connectToSocket()) return true;
754
+ delay = Math.min(delay * 2, 3e3);
755
+ }
756
+ return false;
757
+ }
758
+ function sendRequest(texts, priority) {
759
+ return new Promise((resolve) => {
760
+ if (!_socket || !_connected) {
761
+ resolve({ error: "Not connected" });
762
+ return;
763
+ }
764
+ const id = randomUUID();
765
+ const timer = setTimeout(() => {
766
+ _pending.delete(id);
767
+ resolve({ error: "Request timeout" });
768
+ }, REQUEST_TIMEOUT_MS);
769
+ _pending.set(id, { resolve, timer });
770
+ try {
771
+ _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
772
+ } catch {
773
+ clearTimeout(timer);
774
+ _pending.delete(id);
775
+ resolve({ error: "Write failed" });
776
+ }
777
+ });
778
+ }
779
+ async function pingDaemon() {
780
+ if (!_socket || !_connected) return null;
781
+ return new Promise((resolve) => {
782
+ const id = randomUUID();
783
+ const timer = setTimeout(() => {
784
+ _pending.delete(id);
785
+ resolve(null);
786
+ }, 5e3);
787
+ _pending.set(id, {
788
+ resolve: (data) => {
789
+ if (data.health) {
790
+ resolve(data.health);
791
+ } else {
792
+ resolve(null);
793
+ }
794
+ },
795
+ timer
796
+ });
797
+ try {
798
+ _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
799
+ } catch {
800
+ clearTimeout(timer);
801
+ _pending.delete(id);
802
+ resolve(null);
803
+ }
804
+ });
805
+ }
806
+ function killAndRespawnDaemon() {
807
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
808
+ if (existsSync4(PID_PATH)) {
809
+ try {
810
+ const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
811
+ if (pid > 0) {
812
+ try {
813
+ process.kill(pid, "SIGKILL");
814
+ } catch {
815
+ }
816
+ }
817
+ } catch {
818
+ }
819
+ }
820
+ if (_socket) {
821
+ _socket.destroy();
822
+ _socket = null;
823
+ }
824
+ _connected = false;
825
+ _buffer = "";
826
+ try {
827
+ unlinkSync(PID_PATH);
828
+ } catch {
829
+ }
830
+ try {
831
+ unlinkSync(SOCKET_PATH);
832
+ } catch {
833
+ }
834
+ spawnDaemon();
835
+ }
836
+ async function embedViaClient(text, priority = "high") {
837
+ if (!_connected && !await connectEmbedDaemon()) return null;
838
+ _requestCount++;
839
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
840
+ const health = await pingDaemon();
841
+ if (!health) {
842
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
843
+ `);
844
+ killAndRespawnDaemon();
845
+ const start = Date.now();
846
+ let delay = 200;
847
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
848
+ await new Promise((r) => setTimeout(r, delay));
849
+ if (await connectToSocket()) break;
850
+ delay = Math.min(delay * 2, 3e3);
851
+ }
852
+ if (!_connected) return null;
853
+ }
854
+ }
855
+ const result = await sendRequest([text], priority);
856
+ if (!result.error && result.vectors?.[0]) return result.vectors[0];
857
+ if (result.error) {
858
+ process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
859
+ `);
860
+ killAndRespawnDaemon();
861
+ const start = Date.now();
862
+ let delay = 200;
863
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
864
+ await new Promise((r) => setTimeout(r, delay));
865
+ if (await connectToSocket()) break;
866
+ delay = Math.min(delay * 2, 3e3);
867
+ }
868
+ if (!_connected) return null;
869
+ const retry = await sendRequest([text], priority);
870
+ if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
871
+ process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
872
+ `);
873
+ }
874
+ return null;
875
+ }
876
+ function disconnectClient() {
877
+ if (_socket) {
878
+ _socket.destroy();
879
+ _socket = null;
880
+ }
881
+ _connected = false;
882
+ _buffer = "";
883
+ for (const [id, entry] of _pending) {
884
+ clearTimeout(entry.timer);
885
+ _pending.delete(id);
886
+ entry.resolve({ error: "Client disconnected" });
887
+ }
888
+ }
889
+ 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;
890
+ var init_exe_daemon_client = __esm({
891
+ "src/lib/exe-daemon-client.ts"() {
892
+ "use strict";
893
+ init_config();
894
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
895
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
896
+ SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
897
+ SPAWN_LOCK_STALE_MS = 3e4;
898
+ CONNECT_TIMEOUT_MS = 15e3;
899
+ REQUEST_TIMEOUT_MS = 3e4;
900
+ _socket = null;
901
+ _connected = false;
902
+ _buffer = "";
903
+ _requestCount = 0;
904
+ HEALTH_CHECK_INTERVAL = 100;
905
+ _pending = /* @__PURE__ */ new Map();
906
+ }
907
+ });
908
+
909
+ // src/lib/embedder.ts
910
+ var embedder_exports = {};
911
+ __export(embedder_exports, {
912
+ disposeEmbedder: () => disposeEmbedder,
913
+ embed: () => embed,
914
+ embedDirect: () => embedDirect,
915
+ getEmbedder: () => getEmbedder
916
+ });
917
+ async function getEmbedder() {
918
+ const ok = await connectEmbedDaemon();
919
+ if (!ok) {
920
+ throw new Error(
921
+ "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
922
+ );
923
+ }
924
+ }
925
+ async function embed(text) {
926
+ const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
927
+ const vector = await embedViaClient(text, priority);
928
+ if (!vector) {
929
+ throw new Error(
930
+ "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
931
+ );
932
+ }
933
+ if (vector.length !== EMBEDDING_DIM) {
934
+ throw new Error(
935
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
936
+ );
937
+ }
938
+ return vector;
939
+ }
940
+ async function disposeEmbedder() {
941
+ disconnectClient();
942
+ }
943
+ async function embedDirect(text) {
944
+ const llamaCpp = await import("node-llama-cpp");
945
+ const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
946
+ const { existsSync: existsSync7 } = await import("fs");
947
+ const path8 = await import("path");
948
+ const modelPath = path8.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
949
+ if (!existsSync7(modelPath)) {
950
+ throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
951
+ }
952
+ const llama = await llamaCpp.getLlama();
953
+ const model = await llama.loadModel({ modelPath });
954
+ const context = await model.createEmbeddingContext();
955
+ try {
956
+ const embedding = await context.getEmbeddingFor(text);
957
+ const vector = Array.from(embedding.vector);
958
+ if (vector.length !== EMBEDDING_DIM) {
959
+ throw new Error(
960
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
961
+ );
962
+ }
963
+ return vector;
964
+ } finally {
965
+ await context.dispose();
966
+ await model.dispose();
967
+ }
968
+ }
969
+ var init_embedder = __esm({
970
+ "src/lib/embedder.ts"() {
971
+ "use strict";
972
+ init_memory();
973
+ init_exe_daemon_client();
974
+ }
975
+ });
976
+
977
+ // src/lib/project-name.ts
978
+ var project_name_exports = {};
979
+ __export(project_name_exports, {
980
+ _resetCache: () => _resetCache,
981
+ getProjectName: () => getProjectName
982
+ });
983
+ import { execSync } from "child_process";
984
+ import path5 from "path";
985
+ function getProjectName(cwd) {
986
+ const dir = cwd ?? process.cwd();
987
+ if (_cached && _cachedCwd === dir) return _cached;
988
+ try {
989
+ const repoRoot = execSync("git rev-parse --show-toplevel", {
990
+ cwd: dir,
991
+ encoding: "utf8",
992
+ timeout: 2e3,
993
+ stdio: ["pipe", "pipe", "pipe"]
994
+ }).trim();
995
+ _cached = path5.basename(repoRoot);
996
+ _cachedCwd = dir;
997
+ return _cached;
998
+ } catch {
999
+ _cached = path5.basename(dir);
1000
+ _cachedCwd = dir;
1001
+ return _cached;
1002
+ }
1003
+ }
1004
+ function _resetCache() {
1005
+ _cached = null;
1006
+ _cachedCwd = null;
1007
+ }
1008
+ var _cached, _cachedCwd;
1009
+ var init_project_name = __esm({
1010
+ "src/lib/project-name.ts"() {
1011
+ "use strict";
1012
+ _cached = null;
1013
+ _cachedCwd = null;
1014
+ }
1015
+ });
1016
+
1017
+ // src/lib/file-grep.ts
1018
+ var file_grep_exports = {};
1019
+ __export(file_grep_exports, {
1020
+ grepProjectFiles: () => grepProjectFiles
1021
+ });
1022
+ import { execSync as execSync2 } from "child_process";
1023
+ import { readFileSync as readFileSync3, readdirSync, statSync as statSync2, existsSync as existsSync5 } from "fs";
1024
+ import path6 from "path";
1025
+ import crypto2 from "crypto";
1026
+ async function grepProjectFiles(query, projectRoot, options) {
1027
+ const maxResults = options?.maxResults ?? 10;
1028
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_-]/g, "")).filter((t) => t.length >= 3);
1029
+ if (terms.length === 0) return [];
1030
+ const pattern = terms.join("|");
1031
+ let hits;
1032
+ try {
1033
+ hits = grepWithRipgrep(pattern, projectRoot, options?.patterns);
1034
+ } catch {
1035
+ hits = grepWithNodeFs(pattern, projectRoot, options?.patterns);
1036
+ }
1037
+ hits.sort((a, b) => b.density - a.density);
1038
+ const topHits = hits.slice(0, maxResults);
1039
+ return topHits.map((hit) => {
1040
+ const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
1041
+ const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
1042
+ return {
1043
+ id: crypto2.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
1044
+ agent_id: "project",
1045
+ agent_role: "file",
1046
+ session_id: "file-grep",
1047
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1048
+ tool_name: "file_grep",
1049
+ project_name: path6.basename(projectRoot),
1050
+ has_error: false,
1051
+ raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
1052
+ vector: null,
1053
+ task_id: null
1054
+ };
1055
+ });
1056
+ }
1057
+ function getChunkContext(filePath, lineNumber) {
1058
+ try {
1059
+ const ext = filePath.split(".").pop()?.toLowerCase();
1060
+ if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
1061
+ const source = readFileSync3(filePath, "utf8");
1062
+ const lines = source.split("\n");
1063
+ for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
1064
+ const line = lines[i];
1065
+ const fnMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);
1066
+ if (fnMatch) return `function ${fnMatch[1]}`;
1067
+ const classMatch = line.match(/(?:export\s+)?class\s+(\w+)/);
1068
+ if (classMatch) return `class ${classMatch[1]}`;
1069
+ const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(/);
1070
+ if (arrowMatch) return `function ${arrowMatch[1]}`;
1071
+ }
1072
+ } catch {
1073
+ }
1074
+ return "";
1075
+ }
1076
+ function grepWithRipgrep(pattern, projectRoot, patterns) {
1077
+ const globs = (patterns ?? DEFAULT_PATTERNS).map((p) => `--glob '${p}'`).join(" ");
1078
+ const excludes = EXCLUDE_DIRS.map((d) => `--glob '!${d}'`).join(" ");
1079
+ const cmd = `rg -i -c --hidden '${pattern.replace(/'/g, "\\'")}' . ${globs} ${excludes} --max-filesize ${MAX_FILE_SIZE} 2>/dev/null || true`;
1080
+ const output = execSync2(cmd, {
1081
+ cwd: projectRoot,
1082
+ encoding: "utf8",
1083
+ timeout: 3e3,
1084
+ maxBuffer: 1024 * 1024
1085
+ });
1086
+ if (!output.trim()) return [];
1087
+ const hits = [];
1088
+ for (const line of output.trim().split("\n")) {
1089
+ const colonIdx = line.lastIndexOf(":");
1090
+ if (colonIdx === -1) continue;
1091
+ const filePath = line.slice(0, colonIdx);
1092
+ const matchCount = parseInt(line.slice(colonIdx + 1));
1093
+ if (isNaN(matchCount) || matchCount === 0) continue;
1094
+ try {
1095
+ const firstMatch = execSync2(
1096
+ `rg -i -n --hidden '${pattern.replace(/'/g, "\\'")}' '${filePath}' --max-count 1 2>/dev/null | head -1`,
1097
+ { cwd: projectRoot, encoding: "utf8", timeout: 1e3 }
1098
+ ).trim();
1099
+ const lineNum = parseInt(firstMatch.split(":")[0] ?? "1");
1100
+ const totalLines = execSync2(`wc -l < '${filePath}'`, {
1101
+ cwd: projectRoot,
1102
+ encoding: "utf8",
1103
+ timeout: 1e3
1104
+ }).trim();
1105
+ hits.push({
1106
+ filePath,
1107
+ lineNumber: isNaN(lineNum) ? 1 : lineNum,
1108
+ matchLine: firstMatch.slice(firstMatch.indexOf(":") + 1).slice(0, 200),
1109
+ matchCount,
1110
+ totalLines: parseInt(totalLines) || 1,
1111
+ density: matchCount / (parseInt(totalLines) || 1)
1112
+ });
1113
+ } catch {
1114
+ }
1115
+ }
1116
+ return hits;
1117
+ }
1118
+ function grepWithNodeFs(pattern, projectRoot, patterns) {
1119
+ const regex = new RegExp(pattern, "gi");
1120
+ const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
1121
+ const hits = [];
1122
+ for (const filePath of files.slice(0, MAX_FILES)) {
1123
+ const absPath = path6.join(projectRoot, filePath);
1124
+ try {
1125
+ const stat = statSync2(absPath);
1126
+ if (stat.size > MAX_FILE_SIZE) continue;
1127
+ const content = readFileSync3(absPath, "utf8");
1128
+ const lines = content.split("\n");
1129
+ const matches = content.match(regex);
1130
+ if (!matches || matches.length === 0) continue;
1131
+ const firstMatchIdx = lines.findIndex((l) => regex.test(l));
1132
+ regex.lastIndex = 0;
1133
+ hits.push({
1134
+ filePath,
1135
+ lineNumber: firstMatchIdx >= 0 ? firstMatchIdx + 1 : 1,
1136
+ matchLine: firstMatchIdx >= 0 ? lines[firstMatchIdx].slice(0, 200) : "",
1137
+ matchCount: matches.length,
1138
+ totalLines: lines.length,
1139
+ density: matches.length / lines.length
1140
+ });
1141
+ } catch {
1142
+ }
1143
+ }
1144
+ return hits;
1145
+ }
1146
+ function collectFiles(root, patterns) {
1147
+ const files = [];
1148
+ function walk(dir, relative) {
1149
+ if (files.length >= MAX_FILES) return;
1150
+ const basename = path6.basename(dir);
1151
+ if (EXCLUDE_DIRS.includes(basename)) return;
1152
+ try {
1153
+ const entries = readdirSync(dir, { withFileTypes: true });
1154
+ for (const entry of entries) {
1155
+ if (files.length >= MAX_FILES) return;
1156
+ const rel = path6.join(relative, entry.name);
1157
+ if (entry.isDirectory()) {
1158
+ walk(path6.join(dir, entry.name), rel);
1159
+ } else if (entry.isFile()) {
1160
+ for (const pat of patterns) {
1161
+ if (matchGlob(rel, pat)) {
1162
+ files.push(rel);
1163
+ break;
1164
+ }
1165
+ }
1166
+ }
1167
+ }
1168
+ } catch {
1169
+ }
1170
+ }
1171
+ walk(root, "");
1172
+ return files;
1173
+ }
1174
+ function matchGlob(filePath, pattern) {
1175
+ if (!pattern.includes("*")) return filePath === pattern;
1176
+ const doubleStarMatch = pattern.match(/^(.+?)\/\*\*\/\*(\.\w+)$/);
1177
+ if (doubleStarMatch) {
1178
+ const dir = doubleStarMatch[1];
1179
+ const ext2 = doubleStarMatch[2];
1180
+ return filePath.startsWith(dir + "/") && filePath.endsWith(ext2);
1181
+ }
1182
+ if (pattern.startsWith("**/")) {
1183
+ const ext2 = pattern.slice(3).replace("*", "");
1184
+ return filePath.endsWith(ext2);
1185
+ }
1186
+ const slashIdx = pattern.lastIndexOf("/");
1187
+ if (slashIdx !== -1) {
1188
+ const dir = pattern.slice(0, slashIdx);
1189
+ const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
1190
+ const fileDir = path6.dirname(filePath);
1191
+ return fileDir === dir && filePath.endsWith(ext2);
1192
+ }
1193
+ const ext = pattern.replace("*", "");
1194
+ return filePath.endsWith(ext) && !filePath.includes("/");
1195
+ }
1196
+ function buildSnippet(hit, projectRoot) {
1197
+ try {
1198
+ const absPath = path6.join(projectRoot, hit.filePath);
1199
+ if (!existsSync5(absPath)) return hit.matchLine;
1200
+ const lines = readFileSync3(absPath, "utf8").split("\n");
1201
+ const start = Math.max(0, hit.lineNumber - 3);
1202
+ const end = Math.min(lines.length, hit.lineNumber + 2);
1203
+ return lines.slice(start, end).join("\n").slice(0, 500);
1204
+ } catch {
1205
+ return hit.matchLine;
1206
+ }
1207
+ }
1208
+ var DEFAULT_PATTERNS, EXCLUDE_DIRS, MAX_FILE_SIZE, MAX_FILES;
1209
+ var init_file_grep = __esm({
1210
+ "src/lib/file-grep.ts"() {
1211
+ "use strict";
1212
+ DEFAULT_PATTERNS = [
1213
+ ".planning/*.md",
1214
+ "exe/output/*.md",
1215
+ "README.md",
1216
+ "src/**/*.ts"
1217
+ ];
1218
+ EXCLUDE_DIRS = ["node_modules", "dist", ".git", "coverage", ".worktrees"];
1219
+ MAX_FILE_SIZE = 100 * 1024;
1220
+ MAX_FILES = 500;
1221
+ }
1222
+ });
1223
+
1224
+ // src/lib/reranker.ts
1225
+ var reranker_exports = {};
1226
+ __export(reranker_exports, {
1227
+ disposeReranker: () => disposeReranker,
1228
+ getRerankerModelPath: () => getRerankerModelPath,
1229
+ isRerankerAvailable: () => isRerankerAvailable,
1230
+ rerank: () => rerank,
1231
+ rerankWithScores: () => rerankWithScores
1232
+ });
1233
+ import path7 from "path";
1234
+ import { existsSync as existsSync6 } from "fs";
1235
+ function resetIdleTimer() {
1236
+ if (_idleTimer) clearTimeout(_idleTimer);
1237
+ _idleTimer = setTimeout(() => {
1238
+ void disposeReranker();
1239
+ }, IDLE_TIMEOUT_MS);
1240
+ if (_idleTimer && typeof _idleTimer === "object" && "unref" in _idleTimer) {
1241
+ _idleTimer.unref();
1242
+ }
1243
+ }
1244
+ function isRerankerAvailable() {
1245
+ return existsSync6(path7.join(MODELS_DIR, RERANKER_MODEL_FILE));
1246
+ }
1247
+ function getRerankerModelPath() {
1248
+ return path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1249
+ }
1250
+ async function ensureLoaded() {
1251
+ if (_rerankerContext) {
1252
+ resetIdleTimer();
1253
+ return;
1254
+ }
1255
+ const modelPath = path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
1256
+ if (!existsSync6(modelPath)) {
1257
+ throw new Error(
1258
+ `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
1259
+ );
1260
+ }
1261
+ process.stderr.write("[reranker] Loading Jina Reranker v3...\n");
1262
+ const { getLlama } = await import("node-llama-cpp");
1263
+ const llama = await getLlama();
1264
+ _rerankerModel = await llama.loadModel({ modelPath });
1265
+ _rerankerContext = await _rerankerModel.createEmbeddingContext();
1266
+ process.stderr.write("[reranker] Jina Reranker v3 loaded.\n");
1267
+ resetIdleTimer();
1268
+ }
1269
+ async function disposeReranker() {
1270
+ if (_idleTimer) {
1271
+ clearTimeout(_idleTimer);
1272
+ _idleTimer = null;
1273
+ }
1274
+ if (_rerankerContext) {
1275
+ try {
1276
+ await _rerankerContext.dispose();
1277
+ } catch {
1278
+ }
1279
+ _rerankerContext = null;
1280
+ }
1281
+ if (_rerankerModel) {
1282
+ try {
1283
+ await _rerankerModel.dispose();
1284
+ } catch {
1285
+ }
1286
+ _rerankerModel = null;
1287
+ }
1288
+ process.stderr.write("[reranker] Unloaded (idle timeout).\n");
1289
+ }
1290
+ async function rerankWithScores(query, texts, topK) {
1291
+ if (texts.length === 0) return [];
1292
+ await ensureLoaded();
1293
+ const ctx = _rerankerContext;
1294
+ const scored = [];
1295
+ for (let i = 0; i < texts.length; i++) {
1296
+ const text = texts[i] ?? "";
1297
+ try {
1298
+ const input = `query: ${query} document: ${text.slice(0, 512)}`;
1299
+ const embedding = await ctx.getEmbeddingFor(input);
1300
+ const score = embedding.vector[0] ?? 0;
1301
+ scored.push({ text, score, index: i });
1302
+ } catch {
1303
+ scored.push({ text, score: -1, index: i });
1304
+ }
1305
+ }
1306
+ scored.sort((a, b) => b.score - a.score);
1307
+ return typeof topK === "number" ? scored.slice(0, topK) : scored;
1308
+ }
1309
+ async function rerank(query, candidates, topK = 5) {
1310
+ if (candidates.length === 0) return [];
1311
+ if (candidates.length <= topK) return candidates;
1312
+ const scored = await rerankWithScores(
1313
+ query,
1314
+ candidates.map((c) => c.raw_text),
1315
+ topK
1316
+ );
1317
+ return scored.map((s) => candidates[s.index]);
1318
+ }
1319
+ var RERANKER_MODEL_FILE, IDLE_TIMEOUT_MS, _rerankerContext, _rerankerModel, _idleTimer;
1320
+ var init_reranker = __esm({
1321
+ "src/lib/reranker.ts"() {
1322
+ "use strict";
1323
+ init_config();
1324
+ RERANKER_MODEL_FILE = "jina-reranker-v3-q4_k_m.gguf";
1325
+ IDLE_TIMEOUT_MS = 6e4;
1326
+ _rerankerContext = null;
1327
+ _rerankerModel = null;
1328
+ _idleTimer = null;
1329
+ }
1330
+ });
1331
+
1332
+ // src/lib/store.ts
1333
+ init_memory();
1334
+
1335
+ // src/lib/database.ts
1336
+ import { createClient } from "@libsql/client";
1337
+ var _client = null;
1338
+ function getClient() {
1339
+ if (!_client) {
1340
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1341
+ }
1342
+ return _client;
1343
+ }
1344
+
1345
+ // src/lib/keychain.ts
1346
+ import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
1347
+ import { existsSync } from "fs";
1348
+ import path from "path";
1349
+ import crypto from "crypto";
1350
+
1351
+ // src/lib/store.ts
1352
+ init_config();
1353
+ function buildWikiScopeFilter(options, columnPrefix) {
1354
+ const args = [];
1355
+ let clause = "";
1356
+ if (options?.workspaceId !== void 0) {
1357
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
1358
+ args.push(options.workspaceId);
1359
+ }
1360
+ if (options?.userId === void 0) {
1361
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
1362
+ } else if (options.userId === null) {
1363
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
1364
+ } else {
1365
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
1366
+ args.push(options.userId);
1367
+ }
1368
+ return { clause, args };
1369
+ }
1370
+ async function searchMemories(queryVector, agentId, options) {
1371
+ let client;
1372
+ try {
1373
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1374
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
1375
+ client = await getReadyShardClient2(options.projectName);
1376
+ } else {
1377
+ client = getClient();
1378
+ }
1379
+ } catch {
1380
+ client = getClient();
1381
+ }
1382
+ const limit = options?.limit ?? 10;
1383
+ const statusFilter = options?.includeArchived ? "" : `
1384
+ AND COALESCE(status, 'active') = 'active'`;
1385
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
1386
+ tool_name, project_name,
1387
+ has_error, raw_text, vector, importance, status,
1388
+ confidence, last_accessed,
1389
+ workspace_id, document_id, user_id,
1390
+ char_offset, page_number
1391
+ FROM memories
1392
+ WHERE agent_id = ?
1393
+ AND vector IS NOT NULL${statusFilter}
1394
+ AND COALESCE(confidence, 0.7) >= 0.3`;
1395
+ const args = [agentId];
1396
+ const scope = buildWikiScopeFilter(options, "");
1397
+ sql += scope.clause;
1398
+ args.push(...scope.args);
1399
+ if (options?.projectName) {
1400
+ sql += ` AND project_name = ?`;
1401
+ args.push(options.projectName);
1402
+ }
1403
+ if (options?.toolName) {
1404
+ sql += ` AND tool_name = ?`;
1405
+ args.push(options.toolName);
1406
+ }
1407
+ if (options?.hasError !== void 0) {
1408
+ sql += ` AND has_error = ?`;
1409
+ args.push(options.hasError ? 1 : 0);
1410
+ }
1411
+ if (options?.since) {
1412
+ sql += ` AND timestamp >= ?`;
1413
+ args.push(options.since);
1414
+ }
1415
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
1416
+ args.push(vectorToBlob(queryVector));
1417
+ sql += ` LIMIT ?`;
1418
+ args.push(limit);
1419
+ const result = await client.execute({ sql, args });
1420
+ return result.rows.map((row) => ({
1421
+ id: row.id,
1422
+ agent_id: row.agent_id,
1423
+ agent_role: row.agent_role,
1424
+ session_id: row.session_id,
1425
+ timestamp: row.timestamp,
1426
+ tool_name: row.tool_name,
1427
+ project_name: row.project_name,
1428
+ has_error: row.has_error === 1,
1429
+ raw_text: row.raw_text,
1430
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
1431
+ importance: row.importance ?? 5,
1432
+ status: row.status ?? "active",
1433
+ confidence: row.confidence ?? 0.7,
1434
+ last_accessed: row.last_accessed ?? row.timestamp,
1435
+ workspace_id: row.workspace_id ?? null,
1436
+ document_id: row.document_id ?? null,
1437
+ user_id: row.user_id ?? null,
1438
+ char_offset: row.char_offset ?? null,
1439
+ page_number: row.page_number ?? null
1440
+ }));
1441
+ }
1442
+ async function attachDocumentMetadata(records) {
1443
+ const docIds = [
1444
+ ...new Set(
1445
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
1446
+ )
1447
+ ];
1448
+ if (docIds.length === 0) return records;
1449
+ try {
1450
+ const client = getClient();
1451
+ const placeholders = docIds.map(() => "?").join(",");
1452
+ const result = await client.execute({
1453
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
1454
+ FROM documents
1455
+ WHERE id IN (${placeholders})`,
1456
+ args: docIds
1457
+ });
1458
+ const byId = /* @__PURE__ */ new Map();
1459
+ for (const row of result.rows) {
1460
+ const id = row.id;
1461
+ byId.set(id, {
1462
+ document_id: id,
1463
+ filename: row.filename,
1464
+ mime: row.mime ?? null,
1465
+ source_type: row.source_type ?? null,
1466
+ uploaded_at: row.uploaded_at
1467
+ });
1468
+ }
1469
+ for (const record of records) {
1470
+ if (!record.document_id) continue;
1471
+ record.document_metadata = byId.get(record.document_id) ?? null;
1472
+ }
1473
+ } catch {
1474
+ }
1475
+ return records;
1476
+ }
1477
+ function vectorToBlob(vector) {
1478
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
1479
+ return JSON.stringify(Array.from(f32));
1480
+ }
1481
+
1482
+ // src/lib/hybrid-search.ts
1483
+ var RRF_K = 60;
1484
+ async function hybridSearch(queryText, agentId, options) {
1485
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1486
+ const config = await loadConfig2();
1487
+ if (config.searchMode === "fts") {
1488
+ return lightweightSearch(queryText, agentId, options);
1489
+ }
1490
+ const limit = options?.limit ?? 10;
1491
+ let effectiveQuery = queryText;
1492
+ let effectiveOptions = { ...options };
1493
+ let _isBroadQuery = false;
1494
+ if (config.selfQueryRouter && process.env.ANTHROPIC_API_KEY) {
1495
+ try {
1496
+ const { routeQuery: routeQuery2 } = await Promise.resolve().then(() => (init_self_query_router(), self_query_router_exports));
1497
+ const routed = await routeQuery2(queryText, config.selfQueryModel);
1498
+ effectiveQuery = routed.semanticQuery;
1499
+ _isBroadQuery = routed.isBroadQuery;
1500
+ if (routed.projectFilter && !effectiveOptions.projectName) {
1501
+ effectiveOptions.projectName = routed.projectFilter;
1502
+ }
1503
+ if (routed.timeFilter && !effectiveOptions.since) {
1504
+ effectiveOptions.since = routed.timeFilter;
1505
+ }
1506
+ } catch {
1507
+ }
1508
+ }
1509
+ const broadFetchTopK = config.scalingRoadmap?.rerankerAutoTrigger?.fetchTopK ?? 150;
1510
+ const fetchLimit = _isBroadQuery ? Math.max(limit * 5, broadFetchTopK) : Math.max(limit * 3, 30);
1511
+ const fetchOptions = { ...effectiveOptions, limit: fetchLimit, includeSource: false };
1512
+ let queryVector = null;
1513
+ try {
1514
+ const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
1515
+ queryVector = await embed2(effectiveQuery);
1516
+ } catch {
1517
+ process.stderr.write("[hybrid-search] Embed daemon unavailable \u2014 FTS-only mode\n");
1518
+ }
1519
+ let grepPromise = Promise.resolve([]);
1520
+ if (config.fileGrepEnabled !== false) {
1521
+ try {
1522
+ const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
1523
+ const projectRoot = process.cwd();
1524
+ const projectName = getProjectName2(projectRoot);
1525
+ if (projectName && projectName !== "tmp") {
1526
+ const { grepProjectFiles: grepProjectFiles2 } = await Promise.resolve().then(() => (init_file_grep(), file_grep_exports));
1527
+ grepPromise = grepProjectFiles2(effectiveQuery, projectRoot, {
1528
+ maxResults: 10
1529
+ }).catch(() => []);
1530
+ }
1531
+ } catch {
1532
+ }
1533
+ }
1534
+ const [ftsResults, vectorResults, grepResults] = await Promise.all([
1535
+ lightweightSearch(effectiveQuery, agentId, fetchOptions),
1536
+ queryVector ? searchMemories(queryVector, agentId, fetchOptions) : Promise.resolve([]),
1537
+ grepPromise
1538
+ ]);
1539
+ const lists = [];
1540
+ const weights = [];
1541
+ if (ftsResults.length > 0) {
1542
+ lists.push(ftsResults);
1543
+ weights.push(1);
1544
+ }
1545
+ if (vectorResults.length > 0) {
1546
+ lists.push(vectorResults);
1547
+ weights.push(1);
1548
+ }
1549
+ if (grepResults.length > 0) {
1550
+ lists.push(grepResults);
1551
+ weights.push(0.5);
1552
+ }
1553
+ if (lists.length === 0) return [];
1554
+ if (lists.length === 1 && !_isBroadQuery) return lists[0].slice(0, limit);
1555
+ const rrfLimit = _isBroadQuery ? Math.max(limit * 5, 150) : limit;
1556
+ const merged = lists.length === 1 ? lists[0].slice(0, rrfLimit) : rrfMergeMulti(lists, rrfLimit, RRF_K, weights);
1557
+ const auto = config.scalingRoadmap?.rerankerAutoTrigger ?? {
1558
+ enabled: config.rerankerEnabled ?? true,
1559
+ broadQueryMinCardinality: 5e4,
1560
+ fetchTopK: 150,
1561
+ returnTopK: 5
1562
+ };
1563
+ let rerankedAndBlended = null;
1564
+ if (_isBroadQuery && auto.enabled) {
1565
+ const cardinality = await estimateCardinality(agentId, effectiveOptions);
1566
+ if (cardinality > auto.broadQueryMinCardinality) {
1567
+ try {
1568
+ const { isRerankerAvailable: isRerankerAvailable2, rerank: rerank2 } = await Promise.resolve().then(() => (init_reranker(), reranker_exports));
1569
+ if (isRerankerAvailable2()) {
1570
+ const reranked = await rerank2(effectiveQuery, merged, auto.returnTopK);
1571
+ if (reranked.length > 0) {
1572
+ rerankedAndBlended = rrfMergeMulti(
1573
+ [reranked],
1574
+ auto.returnTopK,
1575
+ RRF_K
1576
+ );
1577
+ }
1578
+ }
1579
+ } catch {
1580
+ }
1581
+ }
1582
+ }
1583
+ const finalResults = (rerankedAndBlended ?? merged).slice(
1584
+ 0,
1585
+ rerankedAndBlended ? auto.returnTopK : limit
1586
+ );
1587
+ if (options?.includeSource && finalResults.length > 0) {
1588
+ await attachDocumentMetadata(finalResults);
1589
+ }
1590
+ if (finalResults.length > 0) {
1591
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1592
+ const ids = finalResults.map((r) => r.id);
1593
+ const placeholders = ids.map(() => "?").join(",");
1594
+ try {
1595
+ const client = getClient();
1596
+ void client.execute({
1597
+ sql: `UPDATE memories SET last_accessed = ? WHERE id IN (${placeholders})`,
1598
+ args: [now, ...ids]
1599
+ }).catch(() => {
1600
+ });
1601
+ } catch {
1602
+ }
1603
+ }
1604
+ return finalResults;
1605
+ }
1606
+ async function estimateCardinality(agentId, options) {
1607
+ const client = getClient();
1608
+ let sql = `SELECT COUNT(*) as cnt FROM memories
1609
+ WHERE agent_id = ?
1610
+ AND COALESCE(status, 'active') = 'active'
1611
+ AND COALESCE(confidence, 0.7) >= 0.3`;
1612
+ const args = [agentId];
1613
+ if (options?.projectName) {
1614
+ sql += ` AND project_name = ?`;
1615
+ args.push(options.projectName);
1616
+ }
1617
+ if (options?.toolName) {
1618
+ sql += ` AND tool_name = ?`;
1619
+ args.push(options.toolName);
1620
+ }
1621
+ if (options?.hasError !== void 0) {
1622
+ sql += ` AND has_error = ?`;
1623
+ args.push(options.hasError ? 1 : 0);
1624
+ }
1625
+ if (options?.since) {
1626
+ sql += ` AND timestamp >= ?`;
1627
+ args.push(options.since);
1628
+ }
1629
+ try {
1630
+ const result = await client.execute({ sql, args });
1631
+ return Number(result.rows[0]?.cnt) || 0;
1632
+ } catch {
1633
+ return 0;
1634
+ }
1635
+ }
1636
+ function rrfMerge(listA, listB, limit, k = RRF_K) {
1637
+ return rrfMergeMulti([listA, listB], limit, k);
1638
+ }
1639
+ function recencyScore(timestamp) {
1640
+ const daysSince = (Date.now() - new Date(timestamp).getTime()) / (1e3 * 60 * 60 * 24);
1641
+ return 1 / (1 + daysSince * 0.01);
1642
+ }
1643
+ function normalizedImportance(importance) {
1644
+ return ((importance ?? 5) - 1) / 9;
1645
+ }
1646
+ function rrfMergeMulti(lists, limit, k = RRF_K, weights) {
1647
+ const scores = /* @__PURE__ */ new Map();
1648
+ for (let listIdx = 0; listIdx < lists.length; listIdx++) {
1649
+ const list = lists[listIdx];
1650
+ const weight = weights?.[listIdx] ?? 1;
1651
+ for (let i = 0; i < list.length; i++) {
1652
+ const rec = list[i];
1653
+ const entry = scores.get(rec.id) ?? { rrfScore: 0, record: rec };
1654
+ entry.rrfScore += weight * (1 / (k + i + 1));
1655
+ scores.set(rec.id, entry);
1656
+ }
1657
+ }
1658
+ const entries = Array.from(scores.values()).map((e) => {
1659
+ const recency = recencyScore(e.record.timestamp);
1660
+ const importance = normalizedImportance(e.record.importance);
1661
+ const confidence = e.record.confidence ?? 0.7;
1662
+ const finalScore = e.rrfScore * 0.35 + recency * 0.14 + importance * 0.21 + confidence * 0.3;
1663
+ return { score: finalScore, record: e.record };
1664
+ });
1665
+ return entries.sort((a, b) => b.score - a.score).slice(0, limit).map((e) => e.record);
1666
+ }
1667
+ async function lightweightSearch(queryText, agentId, options) {
1668
+ const client = getClient();
1669
+ const limit = options?.limit ?? 5;
1670
+ const terms = queryText.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_]/g, "")).filter((t) => t.length >= 3);
1671
+ if (terms.length === 0) {
1672
+ return recentRecords(agentId, options, limit);
1673
+ }
1674
+ const prefixTerms = terms.map((t) => `${t}*`);
1675
+ const useAnd = terms.length >= 3;
1676
+ const matchExpr = useAnd ? prefixTerms.join(" AND ") : prefixTerms.join(" OR ");
1677
+ const results = await ftsQuery(client, matchExpr, agentId, options, limit);
1678
+ if (useAnd && results.length < limit) {
1679
+ const orExpr = prefixTerms.join(" OR ");
1680
+ const orResults = await ftsQuery(client, orExpr, agentId, options, limit);
1681
+ const seen = new Set(results.map((r) => r.id));
1682
+ for (const r of orResults) {
1683
+ if (!seen.has(r.id) && results.length < limit) {
1684
+ results.push(r);
1685
+ seen.add(r.id);
1686
+ }
1687
+ }
1688
+ }
1689
+ if (options?.includeSource && results.length > 0) {
1690
+ await attachDocumentMetadata(results);
1691
+ }
1692
+ return results;
1693
+ }
1694
+ async function ftsQuery(client, matchExpr, agentId, options, limit) {
1695
+ const statusFilter = options?.includeArchived ? "" : `
1696
+ AND COALESCE(m.status, 'active') = 'active'`;
1697
+ let sql = `SELECT m.id, m.agent_id, m.agent_role, m.session_id, m.timestamp,
1698
+ m.tool_name, m.project_name,
1699
+ m.has_error, m.raw_text, m.vector, m.task_id,
1700
+ m.importance, m.status, m.confidence, m.last_accessed,
1701
+ m.workspace_id, m.document_id, m.user_id,
1702
+ m.char_offset, m.page_number
1703
+ FROM memories m
1704
+ JOIN memories_fts fts ON m.rowid = fts.rowid
1705
+ WHERE memories_fts MATCH ?
1706
+ AND m.agent_id = ?${statusFilter}
1707
+ AND COALESCE(m.confidence, 0.7) >= 0.3`;
1708
+ const args = [matchExpr, agentId];
1709
+ const scope = buildWikiScopeFilter(options, "m.");
1710
+ sql += scope.clause;
1711
+ args.push(...scope.args);
1712
+ if (options?.projectName) {
1713
+ sql += ` AND m.project_name = ?`;
1714
+ args.push(options.projectName);
1715
+ }
1716
+ if (options?.toolName) {
1717
+ sql += ` AND m.tool_name = ?`;
1718
+ args.push(options.toolName);
1719
+ }
1720
+ if (options?.hasError !== void 0) {
1721
+ sql += ` AND m.has_error = ?`;
1722
+ args.push(options.hasError ? 1 : 0);
1723
+ }
1724
+ if (options?.since) {
1725
+ sql += ` AND m.timestamp >= ?`;
1726
+ args.push(options.since);
1727
+ }
1728
+ sql += ` ORDER BY rank LIMIT ?`;
1729
+ args.push(limit);
1730
+ const result = await client.execute({ sql, args });
1731
+ return result.rows.map((row) => ({
1732
+ id: row.id,
1733
+ agent_id: row.agent_id,
1734
+ agent_role: row.agent_role,
1735
+ session_id: row.session_id,
1736
+ timestamp: row.timestamp,
1737
+ tool_name: row.tool_name,
1738
+ project_name: row.project_name,
1739
+ has_error: row.has_error === 1,
1740
+ raw_text: row.raw_text,
1741
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
1742
+ task_id: row.task_id ?? null,
1743
+ importance: row.importance ?? 5,
1744
+ status: row.status ?? "active",
1745
+ confidence: row.confidence ?? 0.7,
1746
+ last_accessed: row.last_accessed ?? row.timestamp,
1747
+ workspace_id: row.workspace_id ?? null,
1748
+ document_id: row.document_id ?? null,
1749
+ user_id: row.user_id ?? null,
1750
+ char_offset: row.char_offset ?? null,
1751
+ page_number: row.page_number ?? null
1752
+ }));
1753
+ }
1754
+ async function recentRecords(agentId, options, limit) {
1755
+ const client = getClient();
1756
+ const statusFilter = options?.includeArchived ? "" : `
1757
+ AND COALESCE(status, 'active') = 'active'`;
1758
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
1759
+ tool_name, project_name,
1760
+ has_error, raw_text, vector, task_id,
1761
+ importance, status, confidence, last_accessed,
1762
+ workspace_id, document_id, user_id,
1763
+ char_offset, page_number
1764
+ FROM memories
1765
+ WHERE agent_id = ?${statusFilter}
1766
+ AND COALESCE(confidence, 0.7) >= 0.3`;
1767
+ const args = [agentId];
1768
+ const scope = buildWikiScopeFilter(options, "");
1769
+ sql += scope.clause;
1770
+ args.push(...scope.args);
1771
+ if (options?.projectName) {
1772
+ sql += ` AND project_name = ?`;
1773
+ args.push(options.projectName);
1774
+ }
1775
+ if (options?.toolName) {
1776
+ sql += ` AND tool_name = ?`;
1777
+ args.push(options.toolName);
1778
+ }
1779
+ if (options?.hasError !== void 0) {
1780
+ sql += ` AND has_error = ?`;
1781
+ args.push(options.hasError ? 1 : 0);
1782
+ }
1783
+ if (options?.since) {
1784
+ sql += ` AND timestamp >= ?`;
1785
+ args.push(options.since);
1786
+ }
1787
+ sql += ` ORDER BY timestamp DESC LIMIT ?`;
1788
+ args.push(limit);
1789
+ const result = await client.execute({ sql, args });
1790
+ return result.rows.map((row) => ({
1791
+ id: row.id,
1792
+ agent_id: row.agent_id,
1793
+ agent_role: row.agent_role,
1794
+ session_id: row.session_id,
1795
+ timestamp: row.timestamp,
1796
+ tool_name: row.tool_name,
1797
+ project_name: row.project_name,
1798
+ has_error: row.has_error === 1,
1799
+ raw_text: row.raw_text,
1800
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
1801
+ task_id: row.task_id ?? null,
1802
+ importance: row.importance ?? 5,
1803
+ status: row.status ?? "active",
1804
+ confidence: row.confidence ?? 0.7,
1805
+ last_accessed: row.last_accessed ?? row.timestamp,
1806
+ workspace_id: row.workspace_id ?? null,
1807
+ document_id: row.document_id ?? null,
1808
+ user_id: row.user_id ?? null,
1809
+ char_offset: row.char_offset ?? null,
1810
+ page_number: row.page_number ?? null
1811
+ }));
1812
+ }
1813
+ export {
1814
+ estimateCardinality,
1815
+ hybridSearch,
1816
+ lightweightSearch,
1817
+ rrfMerge,
1818
+ rrfMergeMulti
1819
+ };