@askexenow/exe-os 0.8.40 → 0.8.42

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 (78) hide show
  1. package/dist/bin/backfill-conversations.js +805 -642
  2. package/dist/bin/backfill-responses.js +804 -641
  3. package/dist/bin/backfill-vectors.js +791 -634
  4. package/dist/bin/cleanup-stale-review-tasks.js +788 -631
  5. package/dist/bin/cli.js +1376 -659
  6. package/dist/bin/exe-agent.js +20 -1
  7. package/dist/bin/exe-assign.js +1503 -1343
  8. package/dist/bin/exe-boot.js +2549 -1784
  9. package/dist/bin/exe-call.js +39 -1
  10. package/dist/bin/exe-cloud.js +12 -2
  11. package/dist/bin/exe-dispatch.js +39 -2
  12. package/dist/bin/exe-doctor.js +791 -634
  13. package/dist/bin/exe-export-behaviors.js +792 -637
  14. package/dist/bin/exe-forget.js +145 -0
  15. package/dist/bin/exe-gateway.js +2501 -1846
  16. package/dist/bin/exe-heartbeat.js +147 -1
  17. package/dist/bin/exe-kill.js +795 -640
  18. package/dist/bin/exe-launch-agent.js +2168 -2008
  19. package/dist/bin/exe-link.js +44 -12
  20. package/dist/bin/exe-new-employee.js +6 -2
  21. package/dist/bin/exe-pending-messages.js +146 -1
  22. package/dist/bin/exe-pending-notifications.js +788 -631
  23. package/dist/bin/exe-pending-reviews.js +176 -1
  24. package/dist/bin/exe-rename.js +23 -0
  25. package/dist/bin/exe-review.js +490 -327
  26. package/dist/bin/exe-search.js +157 -4
  27. package/dist/bin/exe-session-cleanup.js +2487 -403
  28. package/dist/bin/exe-settings.js +2 -1
  29. package/dist/bin/exe-status.js +474 -317
  30. package/dist/bin/exe-team.js +474 -317
  31. package/dist/bin/git-sweep.js +2691 -151
  32. package/dist/bin/graph-backfill.js +794 -637
  33. package/dist/bin/graph-export.js +798 -641
  34. package/dist/bin/scan-tasks.js +2951 -44
  35. package/dist/bin/setup.js +50 -26
  36. package/dist/bin/shard-migrate.js +792 -637
  37. package/dist/bin/wiki-sync.js +794 -637
  38. package/dist/gateway/index.js +2542 -1887
  39. package/dist/hooks/bug-report-worker.js +2118 -576
  40. package/dist/hooks/commit-complete.js +2690 -150
  41. package/dist/hooks/error-recall.js +157 -4
  42. package/dist/hooks/ingest-worker.js +1455 -803
  43. package/dist/hooks/instructions-loaded.js +151 -0
  44. package/dist/hooks/notification.js +153 -2
  45. package/dist/hooks/post-compact.js +164 -0
  46. package/dist/hooks/pre-compact.js +3073 -101
  47. package/dist/hooks/pre-tool-use.js +151 -0
  48. package/dist/hooks/prompt-ingest-worker.js +1670 -1509
  49. package/dist/hooks/prompt-submit.js +2650 -1074
  50. package/dist/hooks/response-ingest-worker.js +154 -6
  51. package/dist/hooks/session-end.js +153 -2
  52. package/dist/hooks/session-start.js +157 -4
  53. package/dist/hooks/stop.js +151 -0
  54. package/dist/hooks/subagent-stop.js +155 -2
  55. package/dist/hooks/summary-worker.js +190 -21
  56. package/dist/index.js +326 -102
  57. package/dist/lib/cloud-sync.js +31 -10
  58. package/dist/lib/config.js +2 -0
  59. package/dist/lib/consolidation.js +69 -2
  60. package/dist/lib/database.js +19 -0
  61. package/dist/lib/device-registry.js +19 -0
  62. package/dist/lib/embedder.js +3 -1
  63. package/dist/lib/employee-templates.js +20 -1
  64. package/dist/lib/exe-daemon.js +285 -18
  65. package/dist/lib/hybrid-search.js +157 -4
  66. package/dist/lib/messaging.js +39 -2
  67. package/dist/lib/schedules.js +792 -637
  68. package/dist/lib/store.js +796 -636
  69. package/dist/lib/tasks.js +1485 -918
  70. package/dist/lib/tmux-routing.js +194 -10
  71. package/dist/mcp/server.js +1643 -924
  72. package/dist/mcp/tools/create-task.js +2283 -829
  73. package/dist/mcp/tools/list-tasks.js +2788 -159
  74. package/dist/mcp/tools/send-message.js +39 -2
  75. package/dist/mcp/tools/update-task.js +79 -0
  76. package/dist/runtime/index.js +280 -68
  77. package/dist/tui/App.js +1485 -645
  78. package/package.json +3 -2
@@ -23,312 +23,100 @@ var init_memory = __esm({
23
23
  }
24
24
  });
25
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, chmod as chmod2 } from "fs/promises";
43
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
44
- import path3 from "path";
45
- import os2 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 = path3.join(os2.homedir(), ".exe-os");
50
- const legacyDir = path3.join(os2.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
- }
26
+ // src/lib/db-retry.ts
27
+ function isBusyError(err) {
28
+ if (err instanceof Error) {
29
+ const msg = err.message.toLowerCase();
30
+ return msg.includes("sqlite_busy") || msg.includes("database is locked");
59
31
  }
60
- return newDir;
32
+ return false;
61
33
  }
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;
34
+ function delay(ms) {
35
+ return new Promise((resolve) => setTimeout(resolve, ms));
73
36
  }
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;
37
+ async function retryOnBusy(fn, label) {
38
+ let lastError;
39
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
40
+ try {
41
+ return await fn();
42
+ } catch (err) {
43
+ lastError = err;
44
+ if (!isBusyError(err) || attempt === MAX_RETRIES) {
45
+ throw err;
46
+ }
47
+ const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
48
+ const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
49
+ process.stderr.write(
50
+ `[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
51
+ `
52
+ );
53
+ await delay(backoff + jitter);
86
54
  }
87
55
  }
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
- function normalizeAutoUpdate(raw) {
108
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
109
- const userAU = raw.autoUpdate ?? {};
110
- raw.autoUpdate = { ...defaultAU, ...userAU };
56
+ throw lastError;
111
57
  }
112
- async function loadConfig() {
113
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
114
- await mkdir2(dir, { recursive: true });
115
- const configPath = path3.join(dir, "config.json");
116
- if (!existsSync2(configPath)) {
117
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
118
- }
119
- const raw = await readFile2(configPath, "utf-8");
120
- try {
121
- let parsed = JSON.parse(raw);
122
- parsed = migrateLegacyConfig(parsed);
123
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
124
- if (migrated) {
125
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
126
- `);
127
- try {
128
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
129
- } catch {
58
+ function wrapWithRetry(client) {
59
+ return new Proxy(client, {
60
+ get(target, prop, receiver) {
61
+ if (prop === "execute") {
62
+ return (sql) => retryOnBusy(() => target.execute(sql), "execute");
130
63
  }
64
+ if (prop === "batch") {
65
+ return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
66
+ }
67
+ return Reflect.get(target, prop, receiver);
131
68
  }
132
- normalizeScalingRoadmap(migratedCfg);
133
- normalizeSessionLifecycle(migratedCfg);
134
- normalizeAutoUpdate(migratedCfg);
135
- const config = { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
136
- if (config.dbPath.startsWith("~")) {
137
- config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
138
- }
139
- return config;
140
- } catch {
141
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
142
- }
69
+ });
143
70
  }
144
- function loadConfigSync() {
145
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
146
- const configPath = path3.join(dir, "config.json");
147
- if (!existsSync2(configPath)) {
148
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
71
+ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
72
+ var init_db_retry = __esm({
73
+ "src/lib/db-retry.ts"() {
74
+ "use strict";
75
+ MAX_RETRIES = 3;
76
+ BASE_DELAY_MS = 200;
77
+ MAX_JITTER_MS = 300;
149
78
  }
150
- try {
151
- const raw = readFileSync(configPath, "utf-8");
152
- let parsed = JSON.parse(raw);
153
- parsed = migrateLegacyConfig(parsed);
154
- const { config: migratedCfg } = migrateConfig(parsed);
155
- normalizeScalingRoadmap(migratedCfg);
156
- normalizeSessionLifecycle(migratedCfg);
157
- normalizeAutoUpdate(migratedCfg);
158
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
159
- } catch {
160
- return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
79
+ });
80
+
81
+ // src/lib/database.ts
82
+ import { createClient } from "@libsql/client";
83
+ async function initDatabase(config) {
84
+ if (_client) {
85
+ _client.close();
86
+ _client = null;
87
+ _resilientClient = null;
88
+ }
89
+ const opts = {
90
+ url: `file:${config.dbPath}`
91
+ };
92
+ if (config.encryptionKey) {
93
+ opts.encryptionKey = config.encryptionKey;
161
94
  }
95
+ _client = createClient(opts);
96
+ _resilientClient = wrapWithRetry(_client);
162
97
  }
163
- async function saveConfig(config) {
164
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
165
- await mkdir2(dir, { recursive: true });
166
- const configPath = path3.join(dir, "config.json");
167
- await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
168
- if (config.cloud?.apiKey) {
169
- await chmod2(configPath, 384);
98
+ function isInitialized() {
99
+ return _client !== null;
100
+ }
101
+ function getClient() {
102
+ if (!_resilientClient) {
103
+ throw new Error("Database client not initialized. Call initDatabase() first.");
170
104
  }
105
+ return _resilientClient;
171
106
  }
172
- async function loadConfigFrom(configPath) {
173
- const raw = await readFile2(configPath, "utf-8");
107
+ function getRawClient() {
108
+ if (!_client) {
109
+ throw new Error("Database client not initialized. Call initDatabase() first.");
110
+ }
111
+ return _client;
112
+ }
113
+ async function ensureSchema() {
114
+ const client = getRawClient();
115
+ await client.execute("PRAGMA journal_mode = WAL");
116
+ await client.execute("PRAGMA busy_timeout = 30000");
117
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
174
118
  try {
175
- let parsed = JSON.parse(raw);
176
- parsed = migrateLegacyConfig(parsed);
177
- const { config: migratedCfg } = migrateConfig(parsed);
178
- normalizeScalingRoadmap(migratedCfg);
179
- normalizeSessionLifecycle(migratedCfg);
180
- normalizeAutoUpdate(migratedCfg);
181
- return { ...DEFAULT_CONFIG, ...migratedCfg };
182
- } catch {
183
- return { ...DEFAULT_CONFIG };
184
- }
185
- }
186
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
187
- var init_config = __esm({
188
- "src/lib/config.ts"() {
189
- "use strict";
190
- EXE_AI_DIR = resolveDataDir();
191
- DB_PATH = path3.join(EXE_AI_DIR, "memories.db");
192
- MODELS_DIR = path3.join(EXE_AI_DIR, "models");
193
- CONFIG_PATH = path3.join(EXE_AI_DIR, "config.json");
194
- LEGACY_LANCE_PATH = path3.join(EXE_AI_DIR, "local.lance");
195
- CURRENT_CONFIG_VERSION = 1;
196
- DEFAULT_CONFIG = {
197
- config_version: CURRENT_CONFIG_VERSION,
198
- dbPath: DB_PATH,
199
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
200
- embeddingDim: 1024,
201
- batchSize: 20,
202
- flushIntervalMs: 1e4,
203
- autoIngestion: true,
204
- autoRetrieval: true,
205
- searchMode: "hybrid",
206
- hookSearchMode: "hybrid",
207
- fileGrepEnabled: true,
208
- splashEffect: true,
209
- consolidationEnabled: true,
210
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
211
- consolidationModel: "claude-haiku-4-5-20251001",
212
- consolidationMaxCallsPerRun: 20,
213
- selfQueryRouter: true,
214
- selfQueryModel: "claude-haiku-4-5-20251001",
215
- rerankerEnabled: true,
216
- scalingRoadmap: {
217
- rerankerAutoTrigger: {
218
- enabled: true,
219
- broadQueryMinCardinality: 5e4,
220
- fetchTopK: 150,
221
- returnTopK: 5
222
- }
223
- },
224
- graphRagEnabled: true,
225
- wikiEnabled: false,
226
- wikiUrl: "",
227
- wikiApiKey: "",
228
- wikiSyncIntervalMs: 30 * 60 * 1e3,
229
- wikiWorkspaceMapping: {
230
- exe: "Executive",
231
- yoshi: "Engineering",
232
- mari: "Marketing",
233
- tom: "Engineering",
234
- sasha: "Production"
235
- },
236
- wikiAutoUpdate: true,
237
- wikiAutoUpdateThreshold: 0.5,
238
- wikiAutoUpdateCreateNew: true,
239
- skillLearning: true,
240
- skillThreshold: 3,
241
- skillModel: "claude-haiku-4-5-20251001",
242
- exeHeartbeat: {
243
- enabled: true,
244
- intervalSeconds: 60,
245
- staleInProgressThresholdHours: 2
246
- },
247
- sessionLifecycle: {
248
- idleKillEnabled: true,
249
- idleKillTicksRequired: 3,
250
- idleKillIntercomAckWindowMs: 1e4,
251
- maxAutoInstances: 10
252
- },
253
- autoUpdate: {
254
- checkOnBoot: true,
255
- autoInstall: false,
256
- checkIntervalMs: 24 * 60 * 60 * 1e3
257
- }
258
- };
259
- CONFIG_MIGRATIONS = [
260
- {
261
- from: 0,
262
- to: 1,
263
- migrate: (cfg) => {
264
- cfg.config_version = 1;
265
- return cfg;
266
- }
267
- }
268
- ];
269
- }
270
- });
271
-
272
- // src/lib/shard-manager.ts
273
- var shard_manager_exports = {};
274
- __export(shard_manager_exports, {
275
- disposeShards: () => disposeShards,
276
- ensureShardSchema: () => ensureShardSchema,
277
- getReadyShardClient: () => getReadyShardClient,
278
- getShardClient: () => getShardClient,
279
- getShardsDir: () => getShardsDir,
280
- initShardManager: () => initShardManager,
281
- isShardingEnabled: () => isShardingEnabled,
282
- listShards: () => listShards,
283
- shardExists: () => shardExists
284
- });
285
- import path4 from "path";
286
- import { existsSync as existsSync3, mkdirSync, readdirSync } from "fs";
287
- import { createClient as createClient2 } from "@libsql/client";
288
- function initShardManager(encryptionKey) {
289
- _encryptionKey = encryptionKey;
290
- if (!existsSync3(SHARDS_DIR)) {
291
- mkdirSync(SHARDS_DIR, { recursive: true });
292
- }
293
- _shardingEnabled = true;
294
- }
295
- function isShardingEnabled() {
296
- return _shardingEnabled;
297
- }
298
- function getShardsDir() {
299
- return SHARDS_DIR;
300
- }
301
- function getShardClient(projectName) {
302
- if (!_encryptionKey) {
303
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
304
- }
305
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
306
- if (!safeName) {
307
- throw new Error(`Invalid project name for shard: "${projectName}"`);
308
- }
309
- const cached = _shards.get(safeName);
310
- if (cached) return cached;
311
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
312
- const client = createClient2({
313
- url: `file:${dbPath}`,
314
- encryptionKey: _encryptionKey
315
- });
316
- _shards.set(safeName, client);
317
- return client;
318
- }
319
- function shardExists(projectName) {
320
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
321
- return existsSync3(path4.join(SHARDS_DIR, `${safeName}.db`));
322
- }
323
- function listShards() {
324
- if (!existsSync3(SHARDS_DIR)) return [];
325
- return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
326
- }
327
- async function ensureShardSchema(client) {
328
- await client.execute("PRAGMA journal_mode = WAL");
329
- await client.execute("PRAGMA busy_timeout = 30000");
330
- try {
331
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
119
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
332
120
  } catch {
333
121
  }
334
122
  await client.executeMultiple(`
@@ -346,9 +134,26 @@ async function ensureShardSchema(client) {
346
134
  version INTEGER NOT NULL DEFAULT 0
347
135
  );
348
136
 
349
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
350
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
351
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
137
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
138
+ ON memories(agent_id);
139
+
140
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
141
+ ON memories(timestamp);
142
+
143
+ CREATE INDEX IF NOT EXISTS idx_memories_session
144
+ ON memories(session_id);
145
+
146
+ CREATE INDEX IF NOT EXISTS idx_memories_project
147
+ ON memories(project_name);
148
+
149
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
150
+ ON memories(tool_name);
151
+
152
+ CREATE INDEX IF NOT EXISTS idx_memories_version
153
+ ON memories(version);
154
+
155
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
156
+ ON memories(agent_id, project_name);
352
157
  `);
353
158
  await client.executeMultiple(`
354
159
  CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
@@ -370,1153 +175,1161 @@ async function ensureShardSchema(client) {
370
175
  INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
371
176
  END;
372
177
  `);
373
- for (const col of [
374
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
375
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
376
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
377
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
378
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
379
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
380
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
381
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
382
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
383
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
384
- // Wiki linkage columns (must match database.ts)
385
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
386
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
387
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
388
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
389
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
390
- // Source provenance columns (must match database.ts)
391
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
392
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
393
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
394
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
395
- ]) {
396
- try {
397
- await client.execute(col);
398
- } catch {
178
+ await client.executeMultiple(`
179
+ CREATE TABLE IF NOT EXISTS sync_meta (
180
+ key TEXT PRIMARY KEY,
181
+ value TEXT NOT NULL
182
+ );
183
+ `);
184
+ await client.executeMultiple(`
185
+ CREATE TABLE IF NOT EXISTS tasks (
186
+ id TEXT PRIMARY KEY,
187
+ title TEXT NOT NULL,
188
+ assigned_to TEXT NOT NULL,
189
+ assigned_by TEXT NOT NULL,
190
+ project_name TEXT NOT NULL,
191
+ priority TEXT NOT NULL DEFAULT 'p1',
192
+ status TEXT NOT NULL DEFAULT 'open',
193
+ task_file TEXT,
194
+ created_at TEXT NOT NULL,
195
+ updated_at TEXT NOT NULL
196
+ );
197
+
198
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
199
+ ON tasks(assigned_to, status);
200
+ `);
201
+ await client.executeMultiple(`
202
+ CREATE TABLE IF NOT EXISTS behaviors (
203
+ id TEXT PRIMARY KEY,
204
+ agent_id TEXT NOT NULL,
205
+ project_name TEXT,
206
+ domain TEXT,
207
+ content TEXT NOT NULL,
208
+ active INTEGER NOT NULL DEFAULT 1,
209
+ created_at TEXT NOT NULL,
210
+ updated_at TEXT NOT NULL
211
+ );
212
+
213
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
214
+ ON behaviors(agent_id, active);
215
+ `);
216
+ try {
217
+ const existing = await client.execute({
218
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
219
+ args: []
220
+ });
221
+ if (Number(existing.rows[0]?.cnt) === 0) {
222
+ await client.executeMultiple(`
223
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
224
+ VALUES
225
+ (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');
226
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
227
+ VALUES
228
+ (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');
229
+ INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
230
+ VALUES
231
+ (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');
232
+ `);
399
233
  }
234
+ } catch {
400
235
  }
401
- for (const idx of [
402
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
403
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
404
- ]) {
405
- try {
406
- await client.execute(idx);
407
- } catch {
408
- }
236
+ try {
237
+ await client.execute({
238
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
239
+ args: []
240
+ });
241
+ } catch {
409
242
  }
410
243
  try {
411
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
244
+ await client.execute({
245
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
246
+ args: []
247
+ });
412
248
  } catch {
413
249
  }
414
- for (const idx of [
415
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
416
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
417
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
418
- ]) {
419
- try {
420
- await client.execute(idx);
421
- } catch {
422
- }
250
+ try {
251
+ await client.execute({
252
+ sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
253
+ args: []
254
+ });
255
+ } catch {
423
256
  }
424
- await client.executeMultiple(`
425
- CREATE TABLE IF NOT EXISTS entities (
426
- id TEXT PRIMARY KEY,
427
- name TEXT NOT NULL,
428
- type TEXT NOT NULL,
429
- first_seen TEXT NOT NULL,
430
- last_seen TEXT NOT NULL,
431
- properties TEXT DEFAULT '{}',
432
- UNIQUE(name, type)
433
- );
434
-
435
- CREATE TABLE IF NOT EXISTS relationships (
436
- id TEXT PRIMARY KEY,
437
- source_entity_id TEXT NOT NULL,
438
- target_entity_id TEXT NOT NULL,
439
- type TEXT NOT NULL,
440
- weight REAL DEFAULT 1.0,
441
- timestamp TEXT NOT NULL,
442
- properties TEXT DEFAULT '{}',
443
- UNIQUE(source_entity_id, target_entity_id, type)
444
- );
445
-
446
- CREATE TABLE IF NOT EXISTS entity_memories (
447
- entity_id TEXT NOT NULL,
448
- memory_id TEXT NOT NULL,
449
- PRIMARY KEY (entity_id, memory_id)
450
- );
451
-
452
- CREATE TABLE IF NOT EXISTS relationship_memories (
453
- relationship_id TEXT NOT NULL,
454
- memory_id TEXT NOT NULL,
455
- PRIMARY KEY (relationship_id, memory_id)
456
- );
457
-
458
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
459
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
460
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
461
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
462
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
463
-
464
- CREATE TABLE IF NOT EXISTS hyperedges (
465
- id TEXT PRIMARY KEY,
466
- label TEXT NOT NULL,
467
- relation TEXT NOT NULL,
468
- confidence REAL DEFAULT 1.0,
469
- timestamp TEXT NOT NULL
470
- );
471
-
472
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
473
- hyperedge_id TEXT NOT NULL,
474
- entity_id TEXT NOT NULL,
475
- PRIMARY KEY (hyperedge_id, entity_id)
476
- );
477
- `);
478
- for (const col of [
479
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
480
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
481
- ]) {
482
- try {
483
- await client.execute(col);
484
- } catch {
485
- }
486
- }
487
- }
488
- async function getReadyShardClient(projectName) {
489
- const client = getShardClient(projectName);
490
- await ensureShardSchema(client);
491
- return client;
492
- }
493
- function disposeShards() {
494
- for (const [, client] of _shards) {
495
- client.close();
496
- }
497
- _shards.clear();
498
- _shardingEnabled = false;
499
- _encryptionKey = null;
500
- }
501
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
502
- var init_shard_manager = __esm({
503
- "src/lib/shard-manager.ts"() {
504
- "use strict";
505
- init_config();
506
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
507
- _shards = /* @__PURE__ */ new Map();
508
- _encryptionKey = null;
509
- _shardingEnabled = false;
257
+ try {
258
+ await client.execute({
259
+ sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
260
+ ON tasks(parent_task_id)
261
+ WHERE parent_task_id IS NOT NULL`,
262
+ args: []
263
+ });
264
+ } catch {
510
265
  }
511
- });
512
-
513
- // src/lib/exe-daemon-client.ts
514
- import net from "net";
515
- import { spawn } from "child_process";
516
- import { randomUUID as randomUUID2 } from "crypto";
517
- import { existsSync as existsSync7, unlinkSync, readFileSync as readFileSync5, openSync, closeSync, statSync } from "fs";
518
- import path8 from "path";
519
- import { fileURLToPath } from "url";
520
- function handleData(chunk) {
521
- _buffer += chunk.toString();
522
- if (_buffer.length > MAX_BUFFER) {
523
- _buffer = "";
524
- return;
266
+ try {
267
+ await client.execute({
268
+ sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
269
+ args: []
270
+ });
271
+ } catch {
525
272
  }
526
- let newlineIdx;
527
- while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
528
- const line = _buffer.slice(0, newlineIdx).trim();
529
- _buffer = _buffer.slice(newlineIdx + 1);
530
- if (!line) continue;
531
- try {
532
- const response = JSON.parse(line);
533
- const entry = _pending.get(response.id);
534
- if (entry) {
535
- clearTimeout(entry.timer);
536
- _pending.delete(response.id);
537
- entry.resolve(response);
538
- }
539
- } catch {
540
- }
273
+ try {
274
+ await client.execute({
275
+ sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
276
+ args: []
277
+ });
278
+ } catch {
541
279
  }
542
- }
543
- function cleanupStaleFiles() {
544
- if (existsSync7(PID_PATH)) {
545
- try {
546
- const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
547
- if (pid > 0) {
548
- try {
549
- process.kill(pid, 0);
550
- return;
551
- } catch {
552
- }
553
- }
554
- } catch {
555
- }
556
- try {
557
- unlinkSync(PID_PATH);
558
- } catch {
559
- }
560
- try {
561
- unlinkSync(SOCKET_PATH);
562
- } catch {
563
- }
280
+ try {
281
+ await client.execute({
282
+ sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
283
+ args: []
284
+ });
285
+ } catch {
564
286
  }
565
- }
566
- function findPackageRoot() {
567
- let dir = path8.dirname(fileURLToPath(import.meta.url));
568
- const { root } = path8.parse(dir);
569
- while (dir !== root) {
570
- if (existsSync7(path8.join(dir, "package.json"))) return dir;
571
- dir = path8.dirname(dir);
287
+ try {
288
+ await client.execute({
289
+ sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
290
+ args: []
291
+ });
292
+ } catch {
572
293
  }
573
- return null;
574
- }
575
- function spawnDaemon() {
576
- const pkgRoot = findPackageRoot();
577
- if (!pkgRoot) {
578
- process.stderr.write("[exed-client] WARN: cannot find package root\n");
579
- return;
294
+ try {
295
+ await client.execute({
296
+ sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
297
+ args: []
298
+ });
299
+ } catch {
580
300
  }
581
- const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
582
- if (!existsSync7(daemonPath)) {
583
- process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
584
- `);
585
- return;
301
+ try {
302
+ await client.execute({
303
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
304
+ args: []
305
+ });
306
+ } catch {
586
307
  }
587
- const resolvedPath = daemonPath;
588
- process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
589
- `);
590
- const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
591
- let stderrFd = "ignore";
592
308
  try {
593
- stderrFd = openSync(logPath, "a");
309
+ await client.execute({
310
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
311
+ args: []
312
+ });
594
313
  } catch {
595
314
  }
596
- const child = spawn(process.execPath, [resolvedPath], {
597
- detached: true,
598
- stdio: ["ignore", "ignore", stderrFd],
599
- env: {
600
- ...process.env,
601
- EXE_DAEMON_SOCK: SOCKET_PATH,
602
- EXE_DAEMON_PID: PID_PATH
603
- }
604
- });
605
- child.unref();
606
- if (typeof stderrFd === "number") {
607
- try {
608
- closeSync(stderrFd);
609
- } catch {
610
- }
315
+ try {
316
+ await client.execute({
317
+ sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
318
+ args: []
319
+ });
320
+ } catch {
611
321
  }
612
- }
613
- function acquireSpawnLock() {
614
322
  try {
615
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
616
- closeSync(fd);
617
- return true;
323
+ await client.execute({
324
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
325
+ args: []
326
+ });
618
327
  } catch {
619
- try {
620
- const stat = statSync(SPAWN_LOCK_PATH);
621
- if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
622
- try {
623
- unlinkSync(SPAWN_LOCK_PATH);
624
- } catch {
625
- }
626
- try {
627
- const fd = openSync(SPAWN_LOCK_PATH, "wx");
628
- closeSync(fd);
629
- return true;
630
- } catch {
631
- }
632
- }
633
- } catch {
634
- }
635
- return false;
636
328
  }
637
- }
638
- function releaseSpawnLock() {
639
329
  try {
640
- unlinkSync(SPAWN_LOCK_PATH);
330
+ await client.execute({
331
+ sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
332
+ args: []
333
+ });
641
334
  } catch {
642
335
  }
643
- }
644
- function connectToSocket() {
645
- return new Promise((resolve) => {
646
- if (_socket && _connected) {
647
- resolve(true);
648
- return;
649
- }
650
- const socket = net.createConnection({ path: SOCKET_PATH });
651
- const connectTimeout = setTimeout(() => {
652
- socket.destroy();
653
- resolve(false);
654
- }, 2e3);
655
- socket.on("connect", () => {
656
- clearTimeout(connectTimeout);
657
- _socket = socket;
658
- _connected = true;
659
- _buffer = "";
660
- socket.on("data", handleData);
661
- socket.on("close", () => {
662
- _connected = false;
663
- _socket = null;
664
- for (const [id, entry] of _pending) {
665
- clearTimeout(entry.timer);
666
- _pending.delete(id);
667
- entry.resolve({ error: "Connection closed" });
668
- }
669
- });
670
- socket.on("error", () => {
671
- _connected = false;
672
- _socket = null;
673
- });
674
- resolve(true);
675
- });
676
- socket.on("error", () => {
677
- clearTimeout(connectTimeout);
678
- resolve(false);
679
- });
680
- });
681
- }
682
- async function connectEmbedDaemon() {
683
- if (_socket && _connected) return true;
684
- if (await connectToSocket()) return true;
685
- if (acquireSpawnLock()) {
686
- try {
687
- cleanupStaleFiles();
688
- spawnDaemon();
689
- } finally {
690
- releaseSpawnLock();
691
- }
692
- }
693
- const start = Date.now();
694
- let delay2 = 100;
695
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
696
- await new Promise((r) => setTimeout(r, delay2));
697
- if (await connectToSocket()) return true;
698
- delay2 = Math.min(delay2 * 2, 3e3);
699
- }
700
- return false;
701
- }
702
- function sendRequest(texts, priority) {
703
- return new Promise((resolve) => {
704
- if (!_socket || !_connected) {
705
- resolve({ error: "Not connected" });
706
- return;
707
- }
708
- const id = randomUUID2();
709
- const timer = setTimeout(() => {
710
- _pending.delete(id);
711
- resolve({ error: "Request timeout" });
712
- }, REQUEST_TIMEOUT_MS);
713
- _pending.set(id, { resolve, timer });
714
- try {
715
- _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
716
- } catch {
717
- clearTimeout(timer);
718
- _pending.delete(id);
719
- resolve({ error: "Write failed" });
720
- }
721
- });
722
- }
723
- async function pingDaemon() {
724
- if (!_socket || !_connected) return null;
725
- return new Promise((resolve) => {
726
- const id = randomUUID2();
727
- const timer = setTimeout(() => {
728
- _pending.delete(id);
729
- resolve(null);
730
- }, 5e3);
731
- _pending.set(id, {
732
- resolve: (data) => {
733
- if (data.health) {
734
- resolve(data.health);
735
- } else {
736
- resolve(null);
737
- }
738
- },
739
- timer
740
- });
741
- try {
742
- _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
743
- } catch {
744
- clearTimeout(timer);
745
- _pending.delete(id);
746
- resolve(null);
747
- }
748
- });
749
- }
750
- function killAndRespawnDaemon() {
751
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
752
- if (existsSync7(PID_PATH)) {
753
- try {
754
- const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
755
- if (pid > 0) {
756
- try {
757
- process.kill(pid, "SIGKILL");
758
- } catch {
759
- }
760
- }
761
- } catch {
762
- }
763
- }
764
- if (_socket) {
765
- _socket.destroy();
766
- _socket = null;
767
- }
768
- _connected = false;
769
- _buffer = "";
770
- try {
771
- unlinkSync(PID_PATH);
772
- } catch {
773
- }
774
- try {
775
- unlinkSync(SOCKET_PATH);
776
- } catch {
777
- }
778
- spawnDaemon();
779
- }
780
- async function embedViaClient(text, priority = "high") {
781
- if (!_connected && !await connectEmbedDaemon()) return null;
782
- _requestCount++;
783
- if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
784
- const health = await pingDaemon();
785
- if (!health) {
786
- process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
787
- `);
788
- killAndRespawnDaemon();
789
- const start = Date.now();
790
- let delay2 = 200;
791
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
792
- await new Promise((r) => setTimeout(r, delay2));
793
- if (await connectToSocket()) break;
794
- delay2 = Math.min(delay2 * 2, 3e3);
795
- }
796
- if (!_connected) return null;
797
- }
798
- }
799
- const result = await sendRequest([text], priority);
800
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
801
- if (result.error) {
802
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
803
- `);
804
- killAndRespawnDaemon();
805
- const start = Date.now();
806
- let delay2 = 200;
807
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
808
- await new Promise((r) => setTimeout(r, delay2));
809
- if (await connectToSocket()) break;
810
- delay2 = Math.min(delay2 * 2, 3e3);
811
- }
812
- if (!_connected) return null;
813
- const retry = await sendRequest([text], priority);
814
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
815
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
816
- `);
817
- }
818
- return null;
819
- }
820
- function disconnectClient() {
821
- if (_socket) {
822
- _socket.destroy();
823
- _socket = null;
824
- }
825
- _connected = false;
826
- _buffer = "";
827
- for (const [id, entry] of _pending) {
828
- clearTimeout(entry.timer);
829
- _pending.delete(id);
830
- entry.resolve({ error: "Client disconnected" });
831
- }
832
- }
833
- 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, MAX_BUFFER;
834
- var init_exe_daemon_client = __esm({
835
- "src/lib/exe-daemon-client.ts"() {
836
- "use strict";
837
- init_config();
838
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
839
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
840
- SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
841
- SPAWN_LOCK_STALE_MS = 3e4;
842
- CONNECT_TIMEOUT_MS = 15e3;
843
- REQUEST_TIMEOUT_MS = 3e4;
844
- _socket = null;
845
- _connected = false;
846
- _buffer = "";
847
- _requestCount = 0;
848
- HEALTH_CHECK_INTERVAL = 100;
849
- _pending = /* @__PURE__ */ new Map();
850
- MAX_BUFFER = 1e7;
851
- }
852
- });
853
-
854
- // src/lib/embedder.ts
855
- var embedder_exports = {};
856
- __export(embedder_exports, {
857
- disposeEmbedder: () => disposeEmbedder,
858
- embed: () => embed,
859
- embedDirect: () => embedDirect,
860
- getEmbedder: () => getEmbedder
861
- });
862
- async function getEmbedder() {
863
- const ok = await connectEmbedDaemon();
864
- if (!ok) {
865
- throw new Error(
866
- "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
867
- );
868
- }
869
- }
870
- async function embed(text) {
871
- const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
872
- const vector = await embedViaClient(text, priority);
873
- if (!vector) {
874
- throw new Error(
875
- "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
876
- );
877
- }
878
- if (vector.length !== EMBEDDING_DIM) {
879
- throw new Error(
880
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
881
- );
882
- }
883
- return vector;
884
- }
885
- async function disposeEmbedder() {
886
- disconnectClient();
887
- }
888
- async function embedDirect(text) {
889
- const llamaCpp = await import("node-llama-cpp");
890
- const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
891
- const { existsSync: existsSync8 } = await import("fs");
892
- const path10 = await import("path");
893
- const modelPath = path10.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
894
- if (!existsSync8(modelPath)) {
895
- throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
896
- }
897
- const llama = await llamaCpp.getLlama();
898
- const model = await llama.loadModel({ modelPath });
899
- const context = await model.createEmbeddingContext();
900
- try {
901
- const embedding = await context.getEmbeddingFor(text);
902
- const vector = Array.from(embedding.vector);
903
- if (vector.length !== EMBEDDING_DIM) {
904
- throw new Error(
905
- `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
906
- );
907
- }
908
- return vector;
909
- } finally {
910
- await context.dispose();
911
- await model.dispose();
912
- }
913
- }
914
- var init_embedder = __esm({
915
- "src/lib/embedder.ts"() {
916
- "use strict";
917
- init_memory();
918
- init_exe_daemon_client();
919
- }
920
- });
921
-
922
- // src/adapters/claude/hooks/prompt-ingest-worker.ts
923
- import crypto2 from "crypto";
924
- import { writeFileSync as writeFileSync2 } from "fs";
925
- import path9 from "path";
926
-
927
- // src/lib/project-name.ts
928
- import { execSync } from "child_process";
929
- import path from "path";
930
- var _cached = null;
931
- var _cachedCwd = null;
932
- function getProjectName(cwd) {
933
- const dir = cwd ?? process.cwd();
934
- if (_cached && _cachedCwd === dir) return _cached;
935
- try {
936
- let repoRoot;
937
- try {
938
- const gitCommonDir = execSync("git rev-parse --path-format=absolute --git-common-dir", {
939
- cwd: dir,
940
- encoding: "utf8",
941
- timeout: 2e3,
942
- stdio: ["pipe", "pipe", "pipe"]
943
- }).trim();
944
- repoRoot = path.dirname(gitCommonDir);
945
- } catch {
946
- repoRoot = execSync("git rev-parse --show-toplevel", {
947
- cwd: dir,
948
- encoding: "utf8",
949
- timeout: 2e3,
950
- stdio: ["pipe", "pipe", "pipe"]
951
- }).trim();
952
- }
953
- _cached = path.basename(repoRoot);
954
- _cachedCwd = dir;
955
- return _cached;
956
- } catch {
957
- _cached = path.basename(dir);
958
- _cachedCwd = dir;
959
- return _cached;
960
- }
961
- }
962
-
963
- // src/lib/store.ts
964
- init_memory();
965
-
966
- // src/lib/database.ts
967
- import { createClient } from "@libsql/client";
968
-
969
- // src/lib/db-retry.ts
970
- var MAX_RETRIES = 3;
971
- var BASE_DELAY_MS = 200;
972
- var MAX_JITTER_MS = 300;
973
- function isBusyError(err) {
974
- if (err instanceof Error) {
975
- const msg = err.message.toLowerCase();
976
- return msg.includes("sqlite_busy") || msg.includes("database is locked");
977
- }
978
- return false;
979
- }
980
- function delay(ms) {
981
- return new Promise((resolve) => setTimeout(resolve, ms));
982
- }
983
- async function retryOnBusy(fn, label) {
984
- let lastError;
985
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
986
- try {
987
- return await fn();
988
- } catch (err) {
989
- lastError = err;
990
- if (!isBusyError(err) || attempt === MAX_RETRIES) {
991
- throw err;
992
- }
993
- const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
994
- const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
995
- process.stderr.write(
996
- `[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
997
- `
998
- );
999
- await delay(backoff + jitter);
1000
- }
1001
- }
1002
- throw lastError;
1003
- }
1004
- function wrapWithRetry(client) {
1005
- return new Proxy(client, {
1006
- get(target, prop, receiver) {
1007
- if (prop === "execute") {
1008
- return (sql) => retryOnBusy(() => target.execute(sql), "execute");
1009
- }
1010
- if (prop === "batch") {
1011
- return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
1012
- }
1013
- return Reflect.get(target, prop, receiver);
1014
- }
1015
- });
1016
- }
1017
-
1018
- // src/lib/database.ts
1019
- var _client = null;
1020
- var _resilientClient = null;
1021
- var initTurso = initDatabase;
1022
- async function initDatabase(config) {
1023
- if (_client) {
1024
- _client.close();
1025
- _client = null;
1026
- _resilientClient = null;
1027
- }
1028
- const opts = {
1029
- url: `file:${config.dbPath}`
1030
- };
1031
- if (config.encryptionKey) {
1032
- opts.encryptionKey = config.encryptionKey;
1033
- }
1034
- _client = createClient(opts);
1035
- _resilientClient = wrapWithRetry(_client);
1036
- }
1037
- function isInitialized() {
1038
- return _client !== null;
1039
- }
1040
- function getClient() {
1041
- if (!_resilientClient) {
1042
- throw new Error("Database client not initialized. Call initDatabase() first.");
1043
- }
1044
- return _resilientClient;
1045
- }
1046
- function getRawClient() {
1047
- if (!_client) {
1048
- throw new Error("Database client not initialized. Call initDatabase() first.");
1049
- }
1050
- return _client;
1051
- }
1052
- async function ensureSchema() {
1053
- const client = getRawClient();
1054
- await client.execute("PRAGMA journal_mode = WAL");
1055
- await client.execute("PRAGMA busy_timeout = 30000");
1056
- await client.execute("PRAGMA wal_autocheckpoint = 1000");
1057
- try {
1058
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1059
- } catch {
1060
- }
1061
- await client.executeMultiple(`
1062
- CREATE TABLE IF NOT EXISTS memories (
1063
- id TEXT PRIMARY KEY,
1064
- agent_id TEXT NOT NULL,
1065
- agent_role TEXT NOT NULL,
1066
- session_id TEXT NOT NULL,
1067
- timestamp TEXT NOT NULL,
1068
- tool_name TEXT NOT NULL,
1069
- project_name TEXT NOT NULL,
1070
- has_error INTEGER NOT NULL DEFAULT 0,
1071
- raw_text TEXT NOT NULL,
1072
- vector F32_BLOB(1024),
1073
- version INTEGER NOT NULL DEFAULT 0
1074
- );
1075
-
1076
- CREATE INDEX IF NOT EXISTS idx_memories_agent
1077
- ON memories(agent_id);
1078
-
1079
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1080
- ON memories(timestamp);
1081
-
1082
- CREATE INDEX IF NOT EXISTS idx_memories_session
1083
- ON memories(session_id);
1084
-
1085
- CREATE INDEX IF NOT EXISTS idx_memories_project
1086
- ON memories(project_name);
1087
-
1088
- CREATE INDEX IF NOT EXISTS idx_memories_tool
1089
- ON memories(tool_name);
1090
-
1091
- CREATE INDEX IF NOT EXISTS idx_memories_version
1092
- ON memories(version);
1093
-
1094
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1095
- ON memories(agent_id, project_name);
1096
- `);
1097
- await client.executeMultiple(`
1098
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1099
- raw_text,
1100
- content='memories',
1101
- content_rowid='rowid'
1102
- );
1103
-
1104
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1105
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1106
- END;
1107
-
1108
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1109
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1110
- END;
1111
-
1112
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1113
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1114
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1115
- END;
1116
- `);
1117
- await client.executeMultiple(`
1118
- CREATE TABLE IF NOT EXISTS sync_meta (
1119
- key TEXT PRIMARY KEY,
1120
- value TEXT NOT NULL
1121
- );
1122
- `);
1123
- await client.executeMultiple(`
1124
- CREATE TABLE IF NOT EXISTS tasks (
1125
- id TEXT PRIMARY KEY,
1126
- title TEXT NOT NULL,
1127
- assigned_to TEXT NOT NULL,
1128
- assigned_by TEXT NOT NULL,
1129
- project_name TEXT NOT NULL,
1130
- priority TEXT NOT NULL DEFAULT 'p1',
1131
- status TEXT NOT NULL DEFAULT 'open',
1132
- task_file TEXT,
1133
- created_at TEXT NOT NULL,
1134
- updated_at TEXT NOT NULL
1135
- );
1136
-
1137
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1138
- ON tasks(assigned_to, status);
1139
- `);
1140
- await client.executeMultiple(`
1141
- CREATE TABLE IF NOT EXISTS behaviors (
1142
- id TEXT PRIMARY KEY,
1143
- agent_id TEXT NOT NULL,
1144
- project_name TEXT,
1145
- domain TEXT,
1146
- content TEXT NOT NULL,
1147
- active INTEGER NOT NULL DEFAULT 1,
1148
- created_at TEXT NOT NULL,
1149
- updated_at TEXT NOT NULL
1150
- );
1151
-
1152
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1153
- ON behaviors(agent_id, active);
1154
- `);
1155
336
  try {
1156
- const existing = await client.execute({
1157
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
337
+ await client.execute({
338
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1158
339
  args: []
1159
340
  });
1160
- if (Number(existing.rows[0]?.cnt) === 0) {
1161
- await client.executeMultiple(`
1162
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1163
- VALUES
1164
- (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');
1165
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1166
- VALUES
1167
- (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');
1168
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1169
- VALUES
1170
- (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');
1171
- `);
1172
- }
1173
341
  } catch {
1174
342
  }
1175
343
  try {
1176
344
  await client.execute({
1177
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
345
+ sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
1178
346
  args: []
1179
347
  });
1180
348
  } catch {
1181
349
  }
1182
350
  try {
1183
351
  await client.execute({
1184
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
352
+ sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
1185
353
  args: []
1186
354
  });
1187
355
  } catch {
1188
356
  }
357
+ await client.executeMultiple(`
358
+ CREATE TABLE IF NOT EXISTS consolidations (
359
+ id TEXT PRIMARY KEY,
360
+ consolidated_memory_id TEXT NOT NULL,
361
+ source_memory_id TEXT NOT NULL,
362
+ created_at TEXT NOT NULL
363
+ );
364
+
365
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
366
+ ON consolidations(source_memory_id);
367
+
368
+ CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
369
+ ON consolidations(consolidated_memory_id);
370
+ `);
371
+ await client.executeMultiple(`
372
+ CREATE TABLE IF NOT EXISTS reminders (
373
+ id TEXT PRIMARY KEY,
374
+ text TEXT NOT NULL,
375
+ created_at TEXT NOT NULL,
376
+ due_date TEXT,
377
+ completed_at TEXT
378
+ );
379
+ `);
380
+ await client.executeMultiple(`
381
+ CREATE TABLE IF NOT EXISTS notifications (
382
+ id TEXT PRIMARY KEY,
383
+ agent_id TEXT NOT NULL,
384
+ agent_role TEXT NOT NULL,
385
+ event TEXT NOT NULL,
386
+ project TEXT NOT NULL,
387
+ summary TEXT NOT NULL,
388
+ task_file TEXT,
389
+ read INTEGER NOT NULL DEFAULT 0,
390
+ created_at TEXT NOT NULL
391
+ );
392
+
393
+ CREATE INDEX IF NOT EXISTS idx_notifications_read
394
+ ON notifications(read);
395
+
396
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent
397
+ ON notifications(agent_id);
398
+
399
+ CREATE INDEX IF NOT EXISTS idx_notifications_task_file
400
+ ON notifications(task_file);
401
+ `);
402
+ await client.executeMultiple(`
403
+ CREATE TABLE IF NOT EXISTS schedules (
404
+ id TEXT PRIMARY KEY,
405
+ cron TEXT NOT NULL,
406
+ description TEXT NOT NULL,
407
+ job_type TEXT NOT NULL DEFAULT 'report',
408
+ prompt TEXT,
409
+ assigned_to TEXT,
410
+ project_name TEXT,
411
+ active INTEGER NOT NULL DEFAULT 1,
412
+ use_crontab INTEGER NOT NULL DEFAULT 0,
413
+ created_at TEXT NOT NULL
414
+ );
415
+ `);
416
+ await client.executeMultiple(`
417
+ CREATE TABLE IF NOT EXISTS device_registry (
418
+ device_id TEXT PRIMARY KEY,
419
+ friendly_name TEXT NOT NULL,
420
+ hostname TEXT NOT NULL,
421
+ projects TEXT NOT NULL DEFAULT '[]',
422
+ agents TEXT NOT NULL DEFAULT '[]',
423
+ connected INTEGER DEFAULT 0,
424
+ last_seen TEXT NOT NULL
425
+ );
426
+ `);
427
+ await client.executeMultiple(`
428
+ CREATE TABLE IF NOT EXISTS messages (
429
+ id TEXT PRIMARY KEY,
430
+ from_agent TEXT NOT NULL,
431
+ from_device TEXT NOT NULL DEFAULT 'local',
432
+ target_agent TEXT NOT NULL,
433
+ target_project TEXT,
434
+ target_device TEXT NOT NULL DEFAULT 'local',
435
+ content TEXT NOT NULL,
436
+ priority TEXT DEFAULT 'normal',
437
+ status TEXT DEFAULT 'pending',
438
+ server_seq INTEGER,
439
+ retry_count INTEGER DEFAULT 0,
440
+ created_at TEXT NOT NULL,
441
+ delivered_at TEXT,
442
+ processed_at TEXT,
443
+ failed_at TEXT,
444
+ failure_reason TEXT
445
+ );
446
+
447
+ CREATE INDEX IF NOT EXISTS idx_messages_target
448
+ ON messages(target_agent, status);
449
+
450
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
451
+ ON messages(target_agent, from_agent, server_seq);
452
+ `);
1189
453
  try {
1190
454
  await client.execute({
1191
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
455
+ sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
1192
456
  args: []
1193
457
  });
1194
- } catch {
1195
- }
1196
- try {
1197
458
  await client.execute({
1198
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
1199
- ON tasks(parent_task_id)
1200
- WHERE parent_task_id IS NOT NULL`,
459
+ sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1201
460
  args: []
1202
461
  });
1203
- } catch {
1204
- }
1205
- try {
1206
462
  await client.execute({
1207
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
463
+ sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
1208
464
  args: []
1209
465
  });
1210
- } catch {
1211
- }
1212
- try {
1213
466
  await client.execute({
1214
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
467
+ sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1215
468
  args: []
1216
469
  });
1217
470
  } catch {
1218
471
  }
472
+ await client.executeMultiple(`
473
+ CREATE TABLE IF NOT EXISTS trajectories (
474
+ id TEXT PRIMARY KEY,
475
+ task_id TEXT NOT NULL,
476
+ agent_id TEXT NOT NULL,
477
+ project_name TEXT NOT NULL,
478
+ task_title TEXT NOT NULL,
479
+ signature TEXT NOT NULL,
480
+ signature_hash TEXT NOT NULL,
481
+ tool_count INTEGER NOT NULL,
482
+ skill_id TEXT,
483
+ created_at TEXT NOT NULL
484
+ );
485
+
486
+ CREATE INDEX IF NOT EXISTS idx_trajectories_hash
487
+ ON trajectories(signature_hash);
488
+
489
+ CREATE INDEX IF NOT EXISTS idx_trajectories_agent
490
+ ON trajectories(agent_id);
491
+ `);
1219
492
  try {
1220
- await client.execute({
1221
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
1222
- args: []
1223
- });
493
+ await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
1224
494
  } catch {
1225
495
  }
496
+ await client.executeMultiple(`
497
+ CREATE TABLE IF NOT EXISTS consolidations (
498
+ id TEXT PRIMARY KEY,
499
+ consolidated_memory_id TEXT NOT NULL,
500
+ source_memory_id TEXT NOT NULL,
501
+ created_at TEXT NOT NULL
502
+ );
503
+
504
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
505
+ ON consolidations(source_memory_id);
506
+ `);
507
+ await client.executeMultiple(`
508
+ CREATE TABLE IF NOT EXISTS audit_trail (
509
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
510
+ timestamp TEXT NOT NULL,
511
+ session_id TEXT NOT NULL,
512
+ agent_id TEXT NOT NULL,
513
+ tool TEXT NOT NULL,
514
+ input TEXT,
515
+ decision TEXT NOT NULL,
516
+ reason TEXT,
517
+ is_customer_facing INTEGER NOT NULL DEFAULT 0
518
+ );
519
+
520
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
521
+ ON audit_trail(agent_id, timestamp);
522
+
523
+ CREATE INDEX IF NOT EXISTS idx_audit_trail_session
524
+ ON audit_trail(session_id);
525
+ `);
1226
526
  try {
1227
527
  await client.execute({
1228
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
528
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1229
529
  args: []
1230
530
  });
1231
531
  } catch {
1232
532
  }
1233
533
  try {
1234
534
  await client.execute({
1235
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
535
+ sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
1236
536
  args: []
1237
537
  });
1238
538
  } catch {
1239
539
  }
1240
540
  try {
1241
541
  await client.execute({
1242
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
542
+ sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
1243
543
  args: []
1244
544
  });
1245
545
  } catch {
1246
546
  }
1247
547
  try {
1248
548
  await client.execute({
1249
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
549
+ sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
1250
550
  args: []
1251
551
  });
1252
552
  } catch {
1253
553
  }
1254
554
  try {
1255
555
  await client.execute({
1256
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
556
+ sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
1257
557
  args: []
1258
558
  });
1259
559
  } catch {
1260
560
  }
1261
561
  try {
1262
562
  await client.execute({
1263
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
563
+ sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
1264
564
  args: []
1265
565
  });
1266
566
  } catch {
1267
567
  }
1268
568
  try {
1269
569
  await client.execute({
1270
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
570
+ sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
1271
571
  args: []
1272
572
  });
1273
573
  } catch {
1274
574
  }
1275
575
  try {
1276
576
  await client.execute({
1277
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
577
+ sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
1278
578
  args: []
1279
579
  });
1280
580
  } catch {
1281
581
  }
582
+ for (const col of [
583
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
584
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
585
+ ]) {
586
+ try {
587
+ await client.execute(col);
588
+ } catch {
589
+ }
590
+ }
591
+ await client.executeMultiple(`
592
+ CREATE TABLE IF NOT EXISTS entities (
593
+ id TEXT PRIMARY KEY,
594
+ name TEXT NOT NULL,
595
+ type TEXT NOT NULL,
596
+ first_seen TEXT NOT NULL,
597
+ last_seen TEXT NOT NULL,
598
+ properties TEXT DEFAULT '{}',
599
+ UNIQUE(name, type)
600
+ );
601
+
602
+ CREATE TABLE IF NOT EXISTS relationships (
603
+ id TEXT PRIMARY KEY,
604
+ source_entity_id TEXT NOT NULL,
605
+ target_entity_id TEXT NOT NULL,
606
+ type TEXT NOT NULL,
607
+ weight REAL DEFAULT 1.0,
608
+ timestamp TEXT NOT NULL,
609
+ properties TEXT DEFAULT '{}',
610
+ UNIQUE(source_entity_id, target_entity_id, type)
611
+ );
612
+
613
+ CREATE TABLE IF NOT EXISTS entity_memories (
614
+ entity_id TEXT NOT NULL,
615
+ memory_id TEXT NOT NULL,
616
+ PRIMARY KEY (entity_id, memory_id)
617
+ );
618
+
619
+ CREATE TABLE IF NOT EXISTS relationship_memories (
620
+ relationship_id TEXT NOT NULL,
621
+ memory_id TEXT NOT NULL,
622
+ PRIMARY KEY (relationship_id, memory_id)
623
+ );
624
+
625
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
626
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
627
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
628
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
629
+
630
+ CREATE TABLE IF NOT EXISTS hyperedges (
631
+ id TEXT PRIMARY KEY,
632
+ label TEXT NOT NULL,
633
+ relation TEXT NOT NULL,
634
+ confidence REAL DEFAULT 1.0,
635
+ timestamp TEXT NOT NULL
636
+ );
637
+
638
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
639
+ hyperedge_id TEXT NOT NULL,
640
+ entity_id TEXT NOT NULL,
641
+ PRIMARY KEY (hyperedge_id, entity_id)
642
+ );
643
+ `);
644
+ await client.executeMultiple(`
645
+ CREATE TABLE IF NOT EXISTS entity_aliases (
646
+ alias TEXT NOT NULL PRIMARY KEY,
647
+ canonical_entity_id TEXT NOT NULL
648
+ );
649
+ CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
650
+ `);
651
+ for (const col of [
652
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
653
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
654
+ ]) {
655
+ try {
656
+ await client.execute(col);
657
+ } catch {
658
+ }
659
+ }
1282
660
  try {
1283
- await client.execute({
1284
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
1285
- args: []
1286
- });
661
+ await client.execute(
662
+ `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
663
+ );
1287
664
  } catch {
1288
665
  }
1289
666
  await client.executeMultiple(`
1290
- CREATE TABLE IF NOT EXISTS consolidations (
1291
- id TEXT PRIMARY KEY,
1292
- consolidated_memory_id TEXT NOT NULL,
1293
- source_memory_id TEXT NOT NULL,
1294
- created_at TEXT NOT NULL
667
+ CREATE TABLE IF NOT EXISTS identity (
668
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
669
+ agent_id TEXT NOT NULL UNIQUE,
670
+ content_hash TEXT NOT NULL,
671
+ updated_at TEXT NOT NULL,
672
+ updated_by TEXT NOT NULL
1295
673
  );
1296
674
 
1297
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
1298
- ON consolidations(source_memory_id);
1299
-
1300
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
1301
- ON consolidations(consolidated_memory_id);
675
+ CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
1302
676
  `);
1303
677
  await client.executeMultiple(`
1304
- CREATE TABLE IF NOT EXISTS reminders (
1305
- id TEXT PRIMARY KEY,
1306
- text TEXT NOT NULL,
1307
- created_at TEXT NOT NULL,
1308
- due_date TEXT,
1309
- completed_at TEXT
678
+ CREATE TABLE IF NOT EXISTS chat_history (
679
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
680
+ session_id TEXT NOT NULL,
681
+ role TEXT NOT NULL,
682
+ content TEXT NOT NULL,
683
+ tool_name TEXT,
684
+ tool_id TEXT,
685
+ is_error INTEGER NOT NULL DEFAULT 0,
686
+ timestamp INTEGER NOT NULL
1310
687
  );
688
+
689
+ CREATE INDEX IF NOT EXISTS idx_chat_history_session
690
+ ON chat_history(session_id, id);
1311
691
  `);
1312
692
  await client.executeMultiple(`
1313
- CREATE TABLE IF NOT EXISTS notifications (
1314
- id TEXT PRIMARY KEY,
1315
- agent_id TEXT NOT NULL,
1316
- agent_role TEXT NOT NULL,
1317
- event TEXT NOT NULL,
1318
- project TEXT NOT NULL,
1319
- summary TEXT NOT NULL,
1320
- task_file TEXT,
1321
- read INTEGER NOT NULL DEFAULT 0,
1322
- created_at TEXT NOT NULL
693
+ CREATE TABLE IF NOT EXISTS workspaces (
694
+ id TEXT PRIMARY KEY,
695
+ slug TEXT NOT NULL UNIQUE,
696
+ name TEXT NOT NULL,
697
+ owner_agent_id TEXT,
698
+ created_at TEXT NOT NULL,
699
+ metadata TEXT
1323
700
  );
1324
701
 
1325
- CREATE INDEX IF NOT EXISTS idx_notifications_read
1326
- ON notifications(read);
1327
-
1328
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
1329
- ON notifications(agent_id);
1330
-
1331
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1332
- ON notifications(task_file);
702
+ CREATE INDEX IF NOT EXISTS idx_workspaces_slug
703
+ ON workspaces(slug);
1333
704
  `);
1334
705
  await client.executeMultiple(`
1335
- CREATE TABLE IF NOT EXISTS schedules (
706
+ CREATE TABLE IF NOT EXISTS documents (
1336
707
  id TEXT PRIMARY KEY,
1337
- cron TEXT NOT NULL,
1338
- description TEXT NOT NULL,
1339
- job_type TEXT NOT NULL DEFAULT 'report',
1340
- prompt TEXT,
1341
- assigned_to TEXT,
1342
- project_name TEXT,
1343
- active INTEGER NOT NULL DEFAULT 1,
1344
- use_crontab INTEGER NOT NULL DEFAULT 0,
1345
- created_at TEXT NOT NULL
708
+ workspace_id TEXT NOT NULL,
709
+ filename TEXT NOT NULL,
710
+ mime TEXT,
711
+ source_type TEXT,
712
+ user_id TEXT,
713
+ uploaded_at TEXT NOT NULL,
714
+ metadata TEXT,
715
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
1346
716
  );
717
+
718
+ CREATE INDEX IF NOT EXISTS idx_documents_workspace
719
+ ON documents(workspace_id);
720
+
721
+ CREATE INDEX IF NOT EXISTS idx_documents_user
722
+ ON documents(user_id);
1347
723
  `);
724
+ for (const column of [
725
+ "workspace_id TEXT",
726
+ "document_id TEXT",
727
+ "user_id TEXT",
728
+ "char_offset INTEGER",
729
+ "page_number INTEGER"
730
+ ]) {
731
+ try {
732
+ await client.execute({
733
+ sql: `ALTER TABLE memories ADD COLUMN ${column}`,
734
+ args: []
735
+ });
736
+ } catch {
737
+ }
738
+ }
739
+ for (const col of [
740
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
741
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
742
+ ]) {
743
+ try {
744
+ await client.execute(col);
745
+ } catch {
746
+ }
747
+ }
1348
748
  await client.executeMultiple(`
1349
- CREATE TABLE IF NOT EXISTS device_registry (
1350
- device_id TEXT PRIMARY KEY,
1351
- friendly_name TEXT NOT NULL,
1352
- hostname TEXT NOT NULL,
1353
- projects TEXT NOT NULL DEFAULT '[]',
1354
- agents TEXT NOT NULL DEFAULT '[]',
1355
- connected INTEGER DEFAULT 0,
1356
- last_seen TEXT NOT NULL
749
+ CREATE INDEX IF NOT EXISTS idx_memories_workspace
750
+ ON memories(workspace_id);
751
+
752
+ CREATE INDEX IF NOT EXISTS idx_memories_document
753
+ ON memories(document_id);
754
+
755
+ CREATE INDEX IF NOT EXISTS idx_memories_user
756
+ ON memories(user_id);
757
+ `);
758
+ await client.executeMultiple(`
759
+ CREATE TABLE IF NOT EXISTS session_kills (
760
+ id TEXT PRIMARY KEY,
761
+ session_name TEXT NOT NULL,
762
+ agent_id TEXT NOT NULL,
763
+ killed_at TIMESTAMP NOT NULL,
764
+ reason TEXT NOT NULL,
765
+ ticks_idle INTEGER,
766
+ estimated_tokens_saved INTEGER
1357
767
  );
768
+
769
+ CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
770
+ ON session_kills(killed_at);
771
+
772
+ CREATE INDEX IF NOT EXISTS idx_session_kills_agent
773
+ ON session_kills(agent_id);
774
+ `);
775
+ await client.execute(`
776
+ CREATE TABLE IF NOT EXISTS global_procedures (
777
+ id TEXT PRIMARY KEY,
778
+ title TEXT NOT NULL,
779
+ content TEXT NOT NULL,
780
+ priority TEXT NOT NULL DEFAULT 'p0',
781
+ domain TEXT,
782
+ active INTEGER NOT NULL DEFAULT 1,
783
+ created_at TEXT NOT NULL,
784
+ updated_at TEXT NOT NULL
785
+ )
1358
786
  `);
1359
787
  await client.executeMultiple(`
1360
- CREATE TABLE IF NOT EXISTS messages (
788
+ CREATE TABLE IF NOT EXISTS conversations (
1361
789
  id TEXT PRIMARY KEY,
1362
- from_agent TEXT NOT NULL,
1363
- from_device TEXT NOT NULL DEFAULT 'local',
1364
- target_agent TEXT NOT NULL,
1365
- target_project TEXT,
1366
- target_device TEXT NOT NULL DEFAULT 'local',
1367
- content TEXT NOT NULL,
1368
- priority TEXT DEFAULT 'normal',
1369
- status TEXT DEFAULT 'pending',
1370
- server_seq INTEGER,
1371
- retry_count INTEGER DEFAULT 0,
1372
- created_at TEXT NOT NULL,
1373
- delivered_at TEXT,
1374
- processed_at TEXT,
1375
- failed_at TEXT,
1376
- failure_reason TEXT
790
+ platform TEXT NOT NULL,
791
+ external_id TEXT,
792
+ sender_id TEXT NOT NULL,
793
+ sender_name TEXT,
794
+ sender_phone TEXT,
795
+ sender_email TEXT,
796
+ recipient_id TEXT,
797
+ channel_id TEXT NOT NULL,
798
+ thread_id TEXT,
799
+ reply_to_id TEXT,
800
+ content_text TEXT,
801
+ content_media TEXT,
802
+ content_metadata TEXT,
803
+ agent_response TEXT,
804
+ agent_name TEXT,
805
+ timestamp TEXT NOT NULL,
806
+ ingested_at TEXT NOT NULL
807
+ );
808
+
809
+ CREATE INDEX IF NOT EXISTS idx_conversations_platform
810
+ ON conversations(platform);
811
+
812
+ CREATE INDEX IF NOT EXISTS idx_conversations_sender
813
+ ON conversations(sender_id);
814
+
815
+ CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
816
+ ON conversations(timestamp);
817
+
818
+ CREATE INDEX IF NOT EXISTS idx_conversations_thread
819
+ ON conversations(thread_id);
820
+
821
+ CREATE INDEX IF NOT EXISTS idx_conversations_channel
822
+ ON conversations(channel_id);
823
+ `);
824
+ try {
825
+ await client.execute({
826
+ sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
827
+ args: []
828
+ });
829
+ } catch {
830
+ }
831
+ try {
832
+ await client.execute({
833
+ sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
834
+ args: []
835
+ });
836
+ } catch {
837
+ }
838
+ try {
839
+ await client.execute({
840
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
841
+ args: []
842
+ });
843
+ } catch {
844
+ }
845
+ try {
846
+ await client.execute({
847
+ sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
848
+ args: []
849
+ });
850
+ } catch {
851
+ }
852
+ await client.executeMultiple(`
853
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
854
+ content_text,
855
+ sender_name,
856
+ agent_response,
857
+ content='conversations',
858
+ content_rowid='rowid'
1377
859
  );
1378
860
 
1379
- CREATE INDEX IF NOT EXISTS idx_messages_target
1380
- ON messages(target_agent, status);
861
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
862
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
863
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
864
+ END;
1381
865
 
1382
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
1383
- ON messages(target_agent, from_agent, server_seq);
866
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
867
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
868
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
869
+ END;
870
+
871
+ CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
872
+ INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
873
+ VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
874
+ INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
875
+ VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
876
+ END;
1384
877
  `);
1385
878
  try {
1386
879
  await client.execute({
1387
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
880
+ sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
1388
881
  args: []
1389
882
  });
883
+ } catch {
884
+ }
885
+ try {
886
+ await client.execute(
887
+ `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
888
+ );
889
+ } catch {
890
+ }
891
+ try {
1390
892
  await client.execute({
1391
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
893
+ sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
1392
894
  args: []
1393
895
  });
1394
896
  await client.execute({
1395
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
897
+ sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
1396
898
  args: []
1397
899
  });
900
+ } catch {
901
+ }
902
+ try {
1398
903
  await client.execute({
1399
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
904
+ sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
1400
905
  args: []
1401
906
  });
1402
907
  } catch {
1403
908
  }
1404
- await client.executeMultiple(`
1405
- CREATE TABLE IF NOT EXISTS trajectories (
1406
- id TEXT PRIMARY KEY,
1407
- task_id TEXT NOT NULL,
1408
- agent_id TEXT NOT NULL,
1409
- project_name TEXT NOT NULL,
1410
- task_title TEXT NOT NULL,
1411
- signature TEXT NOT NULL,
1412
- signature_hash TEXT NOT NULL,
1413
- tool_count INTEGER NOT NULL,
1414
- skill_id TEXT,
1415
- created_at TEXT NOT NULL
1416
- );
1417
-
1418
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
1419
- ON trajectories(signature_hash);
909
+ try {
910
+ await client.execute(
911
+ `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
912
+ );
913
+ } catch {
914
+ }
915
+ for (const col of [
916
+ "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
917
+ "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
918
+ ]) {
919
+ try {
920
+ await client.execute(col);
921
+ } catch {
922
+ }
923
+ }
924
+ }
925
+ var _client, _resilientClient, initTurso;
926
+ var init_database = __esm({
927
+ "src/lib/database.ts"() {
928
+ "use strict";
929
+ init_db_retry();
930
+ _client = null;
931
+ _resilientClient = null;
932
+ initTurso = initDatabase;
933
+ }
934
+ });
935
+
936
+ // src/lib/config.ts
937
+ var config_exports = {};
938
+ __export(config_exports, {
939
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
940
+ CONFIG_PATH: () => CONFIG_PATH,
941
+ COO_AGENT_NAME: () => COO_AGENT_NAME,
942
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
943
+ DB_PATH: () => DB_PATH,
944
+ EXE_AI_DIR: () => EXE_AI_DIR,
945
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
946
+ MODELS_DIR: () => MODELS_DIR,
947
+ loadConfig: () => loadConfig,
948
+ loadConfigFrom: () => loadConfigFrom,
949
+ loadConfigSync: () => loadConfigSync,
950
+ migrateConfig: () => migrateConfig,
951
+ saveConfig: () => saveConfig
952
+ });
953
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
954
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
955
+ import path3 from "path";
956
+ import os2 from "os";
957
+ function resolveDataDir() {
958
+ if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
959
+ if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
960
+ const newDir = path3.join(os2.homedir(), ".exe-os");
961
+ const legacyDir = path3.join(os2.homedir(), ".exe-mem");
962
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
963
+ try {
964
+ renameSync(legacyDir, newDir);
965
+ process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
966
+ `);
967
+ } catch {
968
+ return legacyDir;
969
+ }
970
+ }
971
+ return newDir;
972
+ }
973
+ function migrateLegacyConfig(raw) {
974
+ if ("r2" in raw) {
975
+ process.stderr.write(
976
+ "[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"
977
+ );
978
+ delete raw.r2;
979
+ }
980
+ if ("syncIntervalMs" in raw) {
981
+ delete raw.syncIntervalMs;
982
+ }
983
+ return raw;
984
+ }
985
+ function migrateConfig(raw) {
986
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
987
+ let currentVersion = fromVersion;
988
+ let migrated = false;
989
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
990
+ return { config: raw, migrated: false, fromVersion };
991
+ }
992
+ for (const migration of CONFIG_MIGRATIONS) {
993
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
994
+ raw = migration.migrate(raw);
995
+ currentVersion = migration.to;
996
+ migrated = true;
997
+ }
998
+ }
999
+ return { config: raw, migrated, fromVersion };
1000
+ }
1001
+ function normalizeScalingRoadmap(raw) {
1002
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
1003
+ const userRoadmap = raw.scalingRoadmap ?? {};
1004
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
1005
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
1006
+ userAuto.enabled = raw.rerankerEnabled;
1007
+ }
1008
+ raw.scalingRoadmap = {
1009
+ ...userRoadmap,
1010
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
1011
+ };
1012
+ }
1013
+ function normalizeSessionLifecycle(raw) {
1014
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
1015
+ const userSL = raw.sessionLifecycle ?? {};
1016
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
1017
+ }
1018
+ function normalizeAutoUpdate(raw) {
1019
+ const defaultAU = DEFAULT_CONFIG.autoUpdate;
1020
+ const userAU = raw.autoUpdate ?? {};
1021
+ raw.autoUpdate = { ...defaultAU, ...userAU };
1022
+ }
1023
+ async function loadConfig() {
1024
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1025
+ await mkdir2(dir, { recursive: true });
1026
+ const configPath = path3.join(dir, "config.json");
1027
+ if (!existsSync2(configPath)) {
1028
+ return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
1029
+ }
1030
+ const raw = await readFile2(configPath, "utf-8");
1031
+ try {
1032
+ let parsed = JSON.parse(raw);
1033
+ parsed = migrateLegacyConfig(parsed);
1034
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
1035
+ if (migrated) {
1036
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
1037
+ `);
1038
+ try {
1039
+ await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
1040
+ } catch {
1041
+ }
1042
+ }
1043
+ normalizeScalingRoadmap(migratedCfg);
1044
+ normalizeSessionLifecycle(migratedCfg);
1045
+ normalizeAutoUpdate(migratedCfg);
1046
+ const config = { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
1047
+ if (config.dbPath.startsWith("~")) {
1048
+ config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
1049
+ }
1050
+ return config;
1051
+ } catch {
1052
+ return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
1053
+ }
1054
+ }
1055
+ function loadConfigSync() {
1056
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1057
+ const configPath = path3.join(dir, "config.json");
1058
+ if (!existsSync2(configPath)) {
1059
+ return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
1060
+ }
1061
+ try {
1062
+ const raw = readFileSync(configPath, "utf-8");
1063
+ let parsed = JSON.parse(raw);
1064
+ parsed = migrateLegacyConfig(parsed);
1065
+ const { config: migratedCfg } = migrateConfig(parsed);
1066
+ normalizeScalingRoadmap(migratedCfg);
1067
+ normalizeSessionLifecycle(migratedCfg);
1068
+ normalizeAutoUpdate(migratedCfg);
1069
+ return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
1070
+ } catch {
1071
+ return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
1072
+ }
1073
+ }
1074
+ async function saveConfig(config) {
1075
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1076
+ await mkdir2(dir, { recursive: true });
1077
+ const configPath = path3.join(dir, "config.json");
1078
+ await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
1079
+ if (config.cloud?.apiKey) {
1080
+ await chmod2(configPath, 384);
1081
+ }
1082
+ }
1083
+ async function loadConfigFrom(configPath) {
1084
+ const raw = await readFile2(configPath, "utf-8");
1085
+ try {
1086
+ let parsed = JSON.parse(raw);
1087
+ parsed = migrateLegacyConfig(parsed);
1088
+ const { config: migratedCfg } = migrateConfig(parsed);
1089
+ normalizeScalingRoadmap(migratedCfg);
1090
+ normalizeSessionLifecycle(migratedCfg);
1091
+ normalizeAutoUpdate(migratedCfg);
1092
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
1093
+ } catch {
1094
+ return { ...DEFAULT_CONFIG };
1095
+ }
1096
+ }
1097
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, COO_AGENT_NAME, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
1098
+ var init_config = __esm({
1099
+ "src/lib/config.ts"() {
1100
+ "use strict";
1101
+ EXE_AI_DIR = resolveDataDir();
1102
+ DB_PATH = path3.join(EXE_AI_DIR, "memories.db");
1103
+ MODELS_DIR = path3.join(EXE_AI_DIR, "models");
1104
+ CONFIG_PATH = path3.join(EXE_AI_DIR, "config.json");
1105
+ COO_AGENT_NAME = "exe";
1106
+ LEGACY_LANCE_PATH = path3.join(EXE_AI_DIR, "local.lance");
1107
+ CURRENT_CONFIG_VERSION = 1;
1108
+ DEFAULT_CONFIG = {
1109
+ config_version: CURRENT_CONFIG_VERSION,
1110
+ dbPath: DB_PATH,
1111
+ modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
1112
+ embeddingDim: 1024,
1113
+ batchSize: 20,
1114
+ flushIntervalMs: 1e4,
1115
+ autoIngestion: true,
1116
+ autoRetrieval: true,
1117
+ searchMode: "hybrid",
1118
+ hookSearchMode: "hybrid",
1119
+ fileGrepEnabled: true,
1120
+ splashEffect: true,
1121
+ consolidationEnabled: true,
1122
+ consolidationIntervalMs: 6 * 60 * 60 * 1e3,
1123
+ consolidationModel: "claude-haiku-4-5-20251001",
1124
+ consolidationMaxCallsPerRun: 20,
1125
+ selfQueryRouter: true,
1126
+ selfQueryModel: "claude-haiku-4-5-20251001",
1127
+ rerankerEnabled: true,
1128
+ scalingRoadmap: {
1129
+ rerankerAutoTrigger: {
1130
+ enabled: true,
1131
+ broadQueryMinCardinality: 5e4,
1132
+ fetchTopK: 150,
1133
+ returnTopK: 5
1134
+ }
1135
+ },
1136
+ graphRagEnabled: true,
1137
+ wikiEnabled: false,
1138
+ wikiUrl: "",
1139
+ wikiApiKey: "",
1140
+ wikiSyncIntervalMs: 30 * 60 * 1e3,
1141
+ wikiWorkspaceMapping: {
1142
+ exe: "Executive",
1143
+ yoshi: "Engineering",
1144
+ mari: "Marketing",
1145
+ tom: "Engineering",
1146
+ sasha: "Production"
1147
+ },
1148
+ wikiAutoUpdate: true,
1149
+ wikiAutoUpdateThreshold: 0.5,
1150
+ wikiAutoUpdateCreateNew: true,
1151
+ skillLearning: true,
1152
+ skillThreshold: 3,
1153
+ skillModel: "claude-haiku-4-5-20251001",
1154
+ exeHeartbeat: {
1155
+ enabled: true,
1156
+ intervalSeconds: 60,
1157
+ staleInProgressThresholdHours: 2
1158
+ },
1159
+ sessionLifecycle: {
1160
+ idleKillEnabled: true,
1161
+ idleKillTicksRequired: 3,
1162
+ idleKillIntercomAckWindowMs: 1e4,
1163
+ maxAutoInstances: 10
1164
+ },
1165
+ autoUpdate: {
1166
+ checkOnBoot: true,
1167
+ autoInstall: false,
1168
+ checkIntervalMs: 24 * 60 * 60 * 1e3
1169
+ }
1170
+ };
1171
+ CONFIG_MIGRATIONS = [
1172
+ {
1173
+ from: 0,
1174
+ to: 1,
1175
+ migrate: (cfg) => {
1176
+ cfg.config_version = 1;
1177
+ return cfg;
1178
+ }
1179
+ }
1180
+ ];
1181
+ }
1182
+ });
1420
1183
 
1421
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
1422
- ON trajectories(agent_id);
1423
- `);
1184
+ // src/lib/shard-manager.ts
1185
+ var shard_manager_exports = {};
1186
+ __export(shard_manager_exports, {
1187
+ disposeShards: () => disposeShards,
1188
+ ensureShardSchema: () => ensureShardSchema,
1189
+ getReadyShardClient: () => getReadyShardClient,
1190
+ getShardClient: () => getShardClient,
1191
+ getShardsDir: () => getShardsDir,
1192
+ initShardManager: () => initShardManager,
1193
+ isShardingEnabled: () => isShardingEnabled,
1194
+ listShards: () => listShards,
1195
+ shardExists: () => shardExists
1196
+ });
1197
+ import path4 from "path";
1198
+ import { existsSync as existsSync3, mkdirSync, readdirSync } from "fs";
1199
+ import { createClient as createClient2 } from "@libsql/client";
1200
+ function initShardManager(encryptionKey) {
1201
+ _encryptionKey = encryptionKey;
1202
+ if (!existsSync3(SHARDS_DIR)) {
1203
+ mkdirSync(SHARDS_DIR, { recursive: true });
1204
+ }
1205
+ _shardingEnabled = true;
1206
+ }
1207
+ function isShardingEnabled() {
1208
+ return _shardingEnabled;
1209
+ }
1210
+ function getShardsDir() {
1211
+ return SHARDS_DIR;
1212
+ }
1213
+ function getShardClient(projectName) {
1214
+ if (!_encryptionKey) {
1215
+ throw new Error("Shard manager not initialized. Call initShardManager() first.");
1216
+ }
1217
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1218
+ if (!safeName) {
1219
+ throw new Error(`Invalid project name for shard: "${projectName}"`);
1220
+ }
1221
+ const cached = _shards.get(safeName);
1222
+ if (cached) return cached;
1223
+ const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1224
+ const client = createClient2({
1225
+ url: `file:${dbPath}`,
1226
+ encryptionKey: _encryptionKey
1227
+ });
1228
+ _shards.set(safeName, client);
1229
+ return client;
1230
+ }
1231
+ function shardExists(projectName) {
1232
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1233
+ return existsSync3(path4.join(SHARDS_DIR, `${safeName}.db`));
1234
+ }
1235
+ function listShards() {
1236
+ if (!existsSync3(SHARDS_DIR)) return [];
1237
+ return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1238
+ }
1239
+ async function ensureShardSchema(client) {
1240
+ await client.execute("PRAGMA journal_mode = WAL");
1241
+ await client.execute("PRAGMA busy_timeout = 30000");
1424
1242
  try {
1425
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
1243
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
1426
1244
  } catch {
1427
1245
  }
1428
1246
  await client.executeMultiple(`
1429
- CREATE TABLE IF NOT EXISTS consolidations (
1430
- id TEXT PRIMARY KEY,
1431
- consolidated_memory_id TEXT NOT NULL,
1432
- source_memory_id TEXT NOT NULL,
1433
- created_at TEXT NOT NULL
1247
+ CREATE TABLE IF NOT EXISTS memories (
1248
+ id TEXT PRIMARY KEY,
1249
+ agent_id TEXT NOT NULL,
1250
+ agent_role TEXT NOT NULL,
1251
+ session_id TEXT NOT NULL,
1252
+ timestamp TEXT NOT NULL,
1253
+ tool_name TEXT NOT NULL,
1254
+ project_name TEXT NOT NULL,
1255
+ has_error INTEGER NOT NULL DEFAULT 0,
1256
+ raw_text TEXT NOT NULL,
1257
+ vector F32_BLOB(1024),
1258
+ version INTEGER NOT NULL DEFAULT 0
1434
1259
  );
1435
1260
 
1436
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
1437
- ON consolidations(source_memory_id);
1261
+ CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
1262
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
1263
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
1438
1264
  `);
1439
1265
  await client.executeMultiple(`
1440
- CREATE TABLE IF NOT EXISTS audit_trail (
1441
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1442
- timestamp TEXT NOT NULL,
1443
- session_id TEXT NOT NULL,
1444
- agent_id TEXT NOT NULL,
1445
- tool TEXT NOT NULL,
1446
- input TEXT,
1447
- decision TEXT NOT NULL,
1448
- reason TEXT,
1449
- is_customer_facing INTEGER NOT NULL DEFAULT 0
1266
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1267
+ raw_text,
1268
+ content='memories',
1269
+ content_rowid='rowid'
1450
1270
  );
1451
1271
 
1452
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
1453
- ON audit_trail(agent_id, timestamp);
1272
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1273
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1274
+ END;
1454
1275
 
1455
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
1456
- ON audit_trail(session_id);
1276
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1277
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1278
+ END;
1279
+
1280
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1281
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1282
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1283
+ END;
1457
1284
  `);
1458
- try {
1459
- await client.execute({
1460
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1461
- args: []
1462
- });
1463
- } catch {
1464
- }
1465
- try {
1466
- await client.execute({
1467
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
1468
- args: []
1469
- });
1470
- } catch {
1471
- }
1472
- try {
1473
- await client.execute({
1474
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
1475
- args: []
1476
- });
1477
- } catch {
1478
- }
1479
- try {
1480
- await client.execute({
1481
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
1482
- args: []
1483
- });
1484
- } catch {
1485
- }
1486
- try {
1487
- await client.execute({
1488
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
1489
- args: []
1490
- });
1491
- } catch {
1492
- }
1493
- try {
1494
- await client.execute({
1495
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
1496
- args: []
1497
- });
1498
- } catch {
1285
+ for (const col of [
1286
+ "ALTER TABLE memories ADD COLUMN task_id TEXT",
1287
+ "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
1288
+ "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1289
+ "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1290
+ "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
1291
+ "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
1292
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1293
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
1294
+ "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
1295
+ "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
1296
+ // Wiki linkage columns (must match database.ts)
1297
+ "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
1298
+ "ALTER TABLE memories ADD COLUMN document_id TEXT",
1299
+ "ALTER TABLE memories ADD COLUMN user_id TEXT",
1300
+ "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
1301
+ "ALTER TABLE memories ADD COLUMN page_number INTEGER",
1302
+ // Source provenance columns (must match database.ts)
1303
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
1304
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1305
+ "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1306
+ "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1307
+ ]) {
1308
+ try {
1309
+ await client.execute(col);
1310
+ } catch {
1311
+ }
1499
1312
  }
1500
- try {
1501
- await client.execute({
1502
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
1503
- args: []
1504
- });
1505
- } catch {
1313
+ for (const idx of [
1314
+ "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
1315
+ "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
1316
+ ]) {
1317
+ try {
1318
+ await client.execute(idx);
1319
+ } catch {
1320
+ }
1506
1321
  }
1507
1322
  try {
1508
- await client.execute({
1509
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
1510
- args: []
1511
- });
1323
+ await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
1512
1324
  } catch {
1513
1325
  }
1514
- for (const col of [
1515
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1516
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
1326
+ for (const idx of [
1327
+ "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
1328
+ "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
1329
+ "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
1517
1330
  ]) {
1518
1331
  try {
1519
- await client.execute(col);
1332
+ await client.execute(idx);
1520
1333
  } catch {
1521
1334
  }
1522
1335
  }
@@ -1558,6 +1371,7 @@ async function ensureSchema() {
1558
1371
  CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1559
1372
  CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1560
1373
  CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1374
+ CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
1561
1375
 
1562
1376
  CREATE TABLE IF NOT EXISTS hyperedges (
1563
1377
  id TEXT PRIMARY KEY,
@@ -1573,276 +1387,560 @@ async function ensureSchema() {
1573
1387
  PRIMARY KEY (hyperedge_id, entity_id)
1574
1388
  );
1575
1389
  `);
1576
- await client.executeMultiple(`
1577
- CREATE TABLE IF NOT EXISTS entity_aliases (
1578
- alias TEXT NOT NULL PRIMARY KEY,
1579
- canonical_entity_id TEXT NOT NULL
1580
- );
1581
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
1582
- `);
1583
1390
  for (const col of [
1584
1391
  "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1585
1392
  "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1586
1393
  ]) {
1587
1394
  try {
1588
- await client.execute(col);
1589
- } catch {
1395
+ await client.execute(col);
1396
+ } catch {
1397
+ }
1398
+ }
1399
+ }
1400
+ async function getReadyShardClient(projectName) {
1401
+ const client = getShardClient(projectName);
1402
+ await ensureShardSchema(client);
1403
+ return client;
1404
+ }
1405
+ function disposeShards() {
1406
+ for (const [, client] of _shards) {
1407
+ client.close();
1408
+ }
1409
+ _shards.clear();
1410
+ _shardingEnabled = false;
1411
+ _encryptionKey = null;
1412
+ }
1413
+ var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
1414
+ var init_shard_manager = __esm({
1415
+ "src/lib/shard-manager.ts"() {
1416
+ "use strict";
1417
+ init_config();
1418
+ SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
1419
+ _shards = /* @__PURE__ */ new Map();
1420
+ _encryptionKey = null;
1421
+ _shardingEnabled = false;
1422
+ }
1423
+ });
1424
+
1425
+ // src/lib/global-procedures.ts
1426
+ var global_procedures_exports = {};
1427
+ __export(global_procedures_exports, {
1428
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
1429
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
1430
+ loadGlobalProcedures: () => loadGlobalProcedures,
1431
+ storeGlobalProcedure: () => storeGlobalProcedure
1432
+ });
1433
+ import { randomUUID } from "crypto";
1434
+ async function loadGlobalProcedures() {
1435
+ const client = getClient();
1436
+ const result = await client.execute({
1437
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
1438
+ args: []
1439
+ });
1440
+ const procedures = result.rows;
1441
+ if (procedures.length > 0) {
1442
+ _cache = procedures.map((p) => `### ${p.title}
1443
+ ${p.content}`).join("\n\n");
1444
+ } else {
1445
+ _cache = "";
1446
+ }
1447
+ _cacheLoaded = true;
1448
+ return procedures;
1449
+ }
1450
+ function getGlobalProceduresBlock() {
1451
+ if (!_cacheLoaded) return "";
1452
+ if (!_cache) return "";
1453
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
1454
+
1455
+ ${_cache}
1456
+ `;
1457
+ }
1458
+ async function storeGlobalProcedure(input) {
1459
+ const id = randomUUID();
1460
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1461
+ const client = getClient();
1462
+ await client.execute({
1463
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
1464
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
1465
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
1466
+ });
1467
+ await loadGlobalProcedures();
1468
+ return id;
1469
+ }
1470
+ async function deactivateGlobalProcedure(id) {
1471
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1472
+ const client = getClient();
1473
+ const result = await client.execute({
1474
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
1475
+ args: [now, id]
1476
+ });
1477
+ await loadGlobalProcedures();
1478
+ return result.rowsAffected > 0;
1479
+ }
1480
+ var _cache, _cacheLoaded;
1481
+ var init_global_procedures = __esm({
1482
+ "src/lib/global-procedures.ts"() {
1483
+ "use strict";
1484
+ init_database();
1485
+ _cache = "";
1486
+ _cacheLoaded = false;
1487
+ }
1488
+ });
1489
+
1490
+ // src/lib/exe-daemon-client.ts
1491
+ import net from "net";
1492
+ import { spawn } from "child_process";
1493
+ import { randomUUID as randomUUID3 } from "crypto";
1494
+ import { existsSync as existsSync7, unlinkSync, readFileSync as readFileSync5, openSync, closeSync, statSync } from "fs";
1495
+ import path8 from "path";
1496
+ import { fileURLToPath } from "url";
1497
+ function handleData(chunk) {
1498
+ _buffer += chunk.toString();
1499
+ if (_buffer.length > MAX_BUFFER) {
1500
+ _buffer = "";
1501
+ return;
1502
+ }
1503
+ let newlineIdx;
1504
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1505
+ const line = _buffer.slice(0, newlineIdx).trim();
1506
+ _buffer = _buffer.slice(newlineIdx + 1);
1507
+ if (!line) continue;
1508
+ try {
1509
+ const response = JSON.parse(line);
1510
+ const entry = _pending.get(response.id);
1511
+ if (entry) {
1512
+ clearTimeout(entry.timer);
1513
+ _pending.delete(response.id);
1514
+ entry.resolve(response);
1515
+ }
1516
+ } catch {
1517
+ }
1518
+ }
1519
+ }
1520
+ function cleanupStaleFiles() {
1521
+ if (existsSync7(PID_PATH)) {
1522
+ try {
1523
+ const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
1524
+ if (pid > 0) {
1525
+ try {
1526
+ process.kill(pid, 0);
1527
+ return;
1528
+ } catch {
1529
+ }
1530
+ }
1531
+ } catch {
1532
+ }
1533
+ try {
1534
+ unlinkSync(PID_PATH);
1535
+ } catch {
1536
+ }
1537
+ try {
1538
+ unlinkSync(SOCKET_PATH);
1539
+ } catch {
1540
+ }
1541
+ }
1542
+ }
1543
+ function findPackageRoot() {
1544
+ let dir = path8.dirname(fileURLToPath(import.meta.url));
1545
+ const { root } = path8.parse(dir);
1546
+ while (dir !== root) {
1547
+ if (existsSync7(path8.join(dir, "package.json"))) return dir;
1548
+ dir = path8.dirname(dir);
1549
+ }
1550
+ return null;
1551
+ }
1552
+ function spawnDaemon() {
1553
+ const pkgRoot = findPackageRoot();
1554
+ if (!pkgRoot) {
1555
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1556
+ return;
1557
+ }
1558
+ const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1559
+ if (!existsSync7(daemonPath)) {
1560
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1561
+ `);
1562
+ return;
1563
+ }
1564
+ const resolvedPath = daemonPath;
1565
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1566
+ `);
1567
+ const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
1568
+ let stderrFd = "ignore";
1569
+ try {
1570
+ stderrFd = openSync(logPath, "a");
1571
+ } catch {
1572
+ }
1573
+ const child = spawn(process.execPath, [resolvedPath], {
1574
+ detached: true,
1575
+ stdio: ["ignore", "ignore", stderrFd],
1576
+ env: {
1577
+ ...process.env,
1578
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1579
+ EXE_DAEMON_PID: PID_PATH
1580
+ }
1581
+ });
1582
+ child.unref();
1583
+ if (typeof stderrFd === "number") {
1584
+ try {
1585
+ closeSync(stderrFd);
1586
+ } catch {
1587
+ }
1588
+ }
1589
+ }
1590
+ function acquireSpawnLock() {
1591
+ try {
1592
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1593
+ closeSync(fd);
1594
+ return true;
1595
+ } catch {
1596
+ try {
1597
+ const stat = statSync(SPAWN_LOCK_PATH);
1598
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1599
+ try {
1600
+ unlinkSync(SPAWN_LOCK_PATH);
1601
+ } catch {
1602
+ }
1603
+ try {
1604
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1605
+ closeSync(fd);
1606
+ return true;
1607
+ } catch {
1608
+ }
1609
+ }
1610
+ } catch {
1611
+ }
1612
+ return false;
1613
+ }
1614
+ }
1615
+ function releaseSpawnLock() {
1616
+ try {
1617
+ unlinkSync(SPAWN_LOCK_PATH);
1618
+ } catch {
1619
+ }
1620
+ }
1621
+ function connectToSocket() {
1622
+ return new Promise((resolve) => {
1623
+ if (_socket && _connected) {
1624
+ resolve(true);
1625
+ return;
1626
+ }
1627
+ const socket = net.createConnection({ path: SOCKET_PATH });
1628
+ const connectTimeout = setTimeout(() => {
1629
+ socket.destroy();
1630
+ resolve(false);
1631
+ }, 2e3);
1632
+ socket.on("connect", () => {
1633
+ clearTimeout(connectTimeout);
1634
+ _socket = socket;
1635
+ _connected = true;
1636
+ _buffer = "";
1637
+ socket.on("data", handleData);
1638
+ socket.on("close", () => {
1639
+ _connected = false;
1640
+ _socket = null;
1641
+ for (const [id, entry] of _pending) {
1642
+ clearTimeout(entry.timer);
1643
+ _pending.delete(id);
1644
+ entry.resolve({ error: "Connection closed" });
1645
+ }
1646
+ });
1647
+ socket.on("error", () => {
1648
+ _connected = false;
1649
+ _socket = null;
1650
+ });
1651
+ resolve(true);
1652
+ });
1653
+ socket.on("error", () => {
1654
+ clearTimeout(connectTimeout);
1655
+ resolve(false);
1656
+ });
1657
+ });
1658
+ }
1659
+ async function connectEmbedDaemon() {
1660
+ if (_socket && _connected) return true;
1661
+ if (await connectToSocket()) return true;
1662
+ if (acquireSpawnLock()) {
1663
+ try {
1664
+ cleanupStaleFiles();
1665
+ spawnDaemon();
1666
+ } finally {
1667
+ releaseSpawnLock();
1590
1668
  }
1591
1669
  }
1592
- try {
1593
- await client.execute(
1594
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
1595
- );
1596
- } catch {
1670
+ const start = Date.now();
1671
+ let delay2 = 100;
1672
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1673
+ await new Promise((r) => setTimeout(r, delay2));
1674
+ if (await connectToSocket()) return true;
1675
+ delay2 = Math.min(delay2 * 2, 3e3);
1597
1676
  }
1598
- await client.executeMultiple(`
1599
- CREATE TABLE IF NOT EXISTS identity (
1600
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1601
- agent_id TEXT NOT NULL UNIQUE,
1602
- content_hash TEXT NOT NULL,
1603
- updated_at TEXT NOT NULL,
1604
- updated_by TEXT NOT NULL
1605
- );
1606
-
1607
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
1608
- `);
1609
- await client.executeMultiple(`
1610
- CREATE TABLE IF NOT EXISTS chat_history (
1611
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1612
- session_id TEXT NOT NULL,
1613
- role TEXT NOT NULL,
1614
- content TEXT NOT NULL,
1615
- tool_name TEXT,
1616
- tool_id TEXT,
1617
- is_error INTEGER NOT NULL DEFAULT 0,
1618
- timestamp INTEGER NOT NULL
1619
- );
1620
-
1621
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
1622
- ON chat_history(session_id, id);
1623
- `);
1624
- await client.executeMultiple(`
1625
- CREATE TABLE IF NOT EXISTS workspaces (
1626
- id TEXT PRIMARY KEY,
1627
- slug TEXT NOT NULL UNIQUE,
1628
- name TEXT NOT NULL,
1629
- owner_agent_id TEXT,
1630
- created_at TEXT NOT NULL,
1631
- metadata TEXT
1632
- );
1633
-
1634
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
1635
- ON workspaces(slug);
1636
- `);
1637
- await client.executeMultiple(`
1638
- CREATE TABLE IF NOT EXISTS documents (
1639
- id TEXT PRIMARY KEY,
1640
- workspace_id TEXT NOT NULL,
1641
- filename TEXT NOT NULL,
1642
- mime TEXT,
1643
- source_type TEXT,
1644
- user_id TEXT,
1645
- uploaded_at TEXT NOT NULL,
1646
- metadata TEXT,
1647
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
1648
- );
1649
-
1650
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
1651
- ON documents(workspace_id);
1652
-
1653
- CREATE INDEX IF NOT EXISTS idx_documents_user
1654
- ON documents(user_id);
1655
- `);
1656
- for (const column of [
1657
- "workspace_id TEXT",
1658
- "document_id TEXT",
1659
- "user_id TEXT",
1660
- "char_offset INTEGER",
1661
- "page_number INTEGER"
1662
- ]) {
1677
+ return false;
1678
+ }
1679
+ function sendRequest(texts, priority) {
1680
+ return new Promise((resolve) => {
1681
+ if (!_socket || !_connected) {
1682
+ resolve({ error: "Not connected" });
1683
+ return;
1684
+ }
1685
+ const id = randomUUID3();
1686
+ const timer = setTimeout(() => {
1687
+ _pending.delete(id);
1688
+ resolve({ error: "Request timeout" });
1689
+ }, REQUEST_TIMEOUT_MS);
1690
+ _pending.set(id, { resolve, timer });
1663
1691
  try {
1664
- await client.execute({
1665
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
1666
- args: []
1667
- });
1692
+ _socket.write(JSON.stringify({ id, texts, priority }) + "\n");
1668
1693
  } catch {
1694
+ clearTimeout(timer);
1695
+ _pending.delete(id);
1696
+ resolve({ error: "Write failed" });
1669
1697
  }
1670
- }
1671
- for (const col of [
1672
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
1673
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
1674
- ]) {
1698
+ });
1699
+ }
1700
+ async function pingDaemon() {
1701
+ if (!_socket || !_connected) return null;
1702
+ return new Promise((resolve) => {
1703
+ const id = randomUUID3();
1704
+ const timer = setTimeout(() => {
1705
+ _pending.delete(id);
1706
+ resolve(null);
1707
+ }, 5e3);
1708
+ _pending.set(id, {
1709
+ resolve: (data) => {
1710
+ if (data.health) {
1711
+ resolve(data.health);
1712
+ } else {
1713
+ resolve(null);
1714
+ }
1715
+ },
1716
+ timer
1717
+ });
1675
1718
  try {
1676
- await client.execute(col);
1719
+ _socket.write(JSON.stringify({ id, type: "health" }) + "\n");
1720
+ } catch {
1721
+ clearTimeout(timer);
1722
+ _pending.delete(id);
1723
+ resolve(null);
1724
+ }
1725
+ });
1726
+ }
1727
+ function killAndRespawnDaemon() {
1728
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1729
+ if (existsSync7(PID_PATH)) {
1730
+ try {
1731
+ const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
1732
+ if (pid > 0) {
1733
+ try {
1734
+ process.kill(pid, "SIGKILL");
1735
+ } catch {
1736
+ }
1737
+ }
1677
1738
  } catch {
1678
1739
  }
1679
1740
  }
1680
- await client.executeMultiple(`
1681
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
1682
- ON memories(workspace_id);
1683
-
1684
- CREATE INDEX IF NOT EXISTS idx_memories_document
1685
- ON memories(document_id);
1686
-
1687
- CREATE INDEX IF NOT EXISTS idx_memories_user
1688
- ON memories(user_id);
1689
- `);
1690
- await client.executeMultiple(`
1691
- CREATE TABLE IF NOT EXISTS session_kills (
1692
- id TEXT PRIMARY KEY,
1693
- session_name TEXT NOT NULL,
1694
- agent_id TEXT NOT NULL,
1695
- killed_at TIMESTAMP NOT NULL,
1696
- reason TEXT NOT NULL,
1697
- ticks_idle INTEGER,
1698
- estimated_tokens_saved INTEGER
1699
- );
1700
-
1701
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
1702
- ON session_kills(killed_at);
1703
-
1704
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1705
- ON session_kills(agent_id);
1706
- `);
1707
- await client.executeMultiple(`
1708
- CREATE TABLE IF NOT EXISTS conversations (
1709
- id TEXT PRIMARY KEY,
1710
- platform TEXT NOT NULL,
1711
- external_id TEXT,
1712
- sender_id TEXT NOT NULL,
1713
- sender_name TEXT,
1714
- sender_phone TEXT,
1715
- sender_email TEXT,
1716
- recipient_id TEXT,
1717
- channel_id TEXT NOT NULL,
1718
- thread_id TEXT,
1719
- reply_to_id TEXT,
1720
- content_text TEXT,
1721
- content_media TEXT,
1722
- content_metadata TEXT,
1723
- agent_response TEXT,
1724
- agent_name TEXT,
1725
- timestamp TEXT NOT NULL,
1726
- ingested_at TEXT NOT NULL
1727
- );
1728
-
1729
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
1730
- ON conversations(platform);
1731
-
1732
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
1733
- ON conversations(sender_id);
1734
-
1735
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
1736
- ON conversations(timestamp);
1737
-
1738
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
1739
- ON conversations(thread_id);
1740
-
1741
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
1742
- ON conversations(channel_id);
1743
- `);
1741
+ if (_socket) {
1742
+ _socket.destroy();
1743
+ _socket = null;
1744
+ }
1745
+ _connected = false;
1746
+ _buffer = "";
1744
1747
  try {
1745
- await client.execute({
1746
- sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
1747
- args: []
1748
- });
1748
+ unlinkSync(PID_PATH);
1749
1749
  } catch {
1750
1750
  }
1751
- try {
1752
- await client.execute({
1753
- sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
1754
- args: []
1755
- });
1756
- } catch {
1751
+ try {
1752
+ unlinkSync(SOCKET_PATH);
1753
+ } catch {
1754
+ }
1755
+ spawnDaemon();
1756
+ }
1757
+ async function embedViaClient(text, priority = "high") {
1758
+ if (!_connected && !await connectEmbedDaemon()) return null;
1759
+ _requestCount++;
1760
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1761
+ const health = await pingDaemon();
1762
+ if (!health) {
1763
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1764
+ `);
1765
+ killAndRespawnDaemon();
1766
+ const start = Date.now();
1767
+ let delay2 = 200;
1768
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1769
+ await new Promise((r) => setTimeout(r, delay2));
1770
+ if (await connectToSocket()) break;
1771
+ delay2 = Math.min(delay2 * 2, 3e3);
1772
+ }
1773
+ if (!_connected) return null;
1774
+ }
1775
+ }
1776
+ const result = await sendRequest([text], priority);
1777
+ if (!result.error && result.vectors?.[0]) return result.vectors[0];
1778
+ if (result.error) {
1779
+ process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
1780
+ `);
1781
+ killAndRespawnDaemon();
1782
+ const start = Date.now();
1783
+ let delay2 = 200;
1784
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1785
+ await new Promise((r) => setTimeout(r, delay2));
1786
+ if (await connectToSocket()) break;
1787
+ delay2 = Math.min(delay2 * 2, 3e3);
1788
+ }
1789
+ if (!_connected) return null;
1790
+ const retry = await sendRequest([text], priority);
1791
+ if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
1792
+ process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
1793
+ `);
1757
1794
  }
1758
- try {
1759
- await client.execute({
1760
- sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
1761
- args: []
1762
- });
1763
- } catch {
1795
+ return null;
1796
+ }
1797
+ function disconnectClient() {
1798
+ if (_socket) {
1799
+ _socket.destroy();
1800
+ _socket = null;
1764
1801
  }
1765
- try {
1766
- await client.execute({
1767
- sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
1768
- args: []
1769
- });
1770
- } catch {
1802
+ _connected = false;
1803
+ _buffer = "";
1804
+ for (const [id, entry] of _pending) {
1805
+ clearTimeout(entry.timer);
1806
+ _pending.delete(id);
1807
+ entry.resolve({ error: "Client disconnected" });
1771
1808
  }
1772
- await client.executeMultiple(`
1773
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
1774
- content_text,
1775
- sender_name,
1776
- agent_response,
1777
- content='conversations',
1778
- content_rowid='rowid'
1779
- );
1780
-
1781
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
1782
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1783
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1784
- END;
1785
-
1786
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
1787
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1788
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1789
- END;
1809
+ }
1810
+ 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, MAX_BUFFER;
1811
+ var init_exe_daemon_client = __esm({
1812
+ "src/lib/exe-daemon-client.ts"() {
1813
+ "use strict";
1814
+ init_config();
1815
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
1816
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
1817
+ SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
1818
+ SPAWN_LOCK_STALE_MS = 3e4;
1819
+ CONNECT_TIMEOUT_MS = 15e3;
1820
+ REQUEST_TIMEOUT_MS = 3e4;
1821
+ _socket = null;
1822
+ _connected = false;
1823
+ _buffer = "";
1824
+ _requestCount = 0;
1825
+ HEALTH_CHECK_INTERVAL = 100;
1826
+ _pending = /* @__PURE__ */ new Map();
1827
+ MAX_BUFFER = 1e7;
1828
+ }
1829
+ });
1790
1830
 
1791
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
1792
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
1793
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
1794
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
1795
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
1796
- END;
1797
- `);
1798
- try {
1799
- await client.execute({
1800
- sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
1801
- args: []
1802
- });
1803
- } catch {
1831
+ // src/lib/embedder.ts
1832
+ var embedder_exports = {};
1833
+ __export(embedder_exports, {
1834
+ disposeEmbedder: () => disposeEmbedder,
1835
+ embed: () => embed,
1836
+ embedDirect: () => embedDirect,
1837
+ getEmbedder: () => getEmbedder
1838
+ });
1839
+ async function getEmbedder() {
1840
+ const ok = await connectEmbedDaemon();
1841
+ if (!ok) {
1842
+ throw new Error(
1843
+ "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
1844
+ );
1804
1845
  }
1805
- try {
1806
- await client.execute(
1807
- `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
1846
+ }
1847
+ async function embed(text) {
1848
+ const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
1849
+ const vector = await embedViaClient(text, priority);
1850
+ if (!vector) {
1851
+ throw new Error(
1852
+ "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
1808
1853
  );
1809
- } catch {
1810
1854
  }
1811
- try {
1812
- await client.execute({
1813
- sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
1814
- args: []
1815
- });
1816
- await client.execute({
1817
- sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
1818
- args: []
1819
- });
1820
- } catch {
1855
+ if (vector.length !== EMBEDDING_DIM) {
1856
+ throw new Error(
1857
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
1858
+ );
1821
1859
  }
1822
- try {
1823
- await client.execute({
1824
- sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
1825
- args: []
1826
- });
1827
- } catch {
1860
+ return vector;
1861
+ }
1862
+ async function disposeEmbedder() {
1863
+ disconnectClient();
1864
+ }
1865
+ async function embedDirect(text) {
1866
+ const llamaCpp = await import("node-llama-cpp");
1867
+ const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1868
+ const { existsSync: existsSync8 } = await import("fs");
1869
+ const path10 = await import("path");
1870
+ const modelPath = path10.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
1871
+ if (!existsSync8(modelPath)) {
1872
+ throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
1828
1873
  }
1874
+ const llama = await llamaCpp.getLlama();
1875
+ const model = await llama.loadModel({ modelPath });
1876
+ const context = await model.createEmbeddingContext();
1829
1877
  try {
1830
- await client.execute(
1831
- `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
1832
- );
1833
- } catch {
1878
+ const embedding = await context.getEmbeddingFor(text);
1879
+ const vector = Array.from(embedding.vector);
1880
+ if (vector.length !== EMBEDDING_DIM) {
1881
+ throw new Error(
1882
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
1883
+ );
1884
+ }
1885
+ return vector;
1886
+ } finally {
1887
+ await context.dispose();
1888
+ await model.dispose();
1834
1889
  }
1835
- for (const col of [
1836
- "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
1837
- "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
1838
- ]) {
1890
+ }
1891
+ var init_embedder = __esm({
1892
+ "src/lib/embedder.ts"() {
1893
+ "use strict";
1894
+ init_memory();
1895
+ init_exe_daemon_client();
1896
+ }
1897
+ });
1898
+
1899
+ // src/adapters/claude/hooks/prompt-ingest-worker.ts
1900
+ import crypto2 from "crypto";
1901
+ import { writeFileSync as writeFileSync2 } from "fs";
1902
+ import path9 from "path";
1903
+
1904
+ // src/lib/project-name.ts
1905
+ import { execSync } from "child_process";
1906
+ import path from "path";
1907
+ var _cached = null;
1908
+ var _cachedCwd = null;
1909
+ function getProjectName(cwd) {
1910
+ const dir = cwd ?? process.cwd();
1911
+ if (_cached && _cachedCwd === dir) return _cached;
1912
+ try {
1913
+ let repoRoot;
1839
1914
  try {
1840
- await client.execute(col);
1915
+ const gitCommonDir = execSync("git rev-parse --path-format=absolute --git-common-dir", {
1916
+ cwd: dir,
1917
+ encoding: "utf8",
1918
+ timeout: 2e3,
1919
+ stdio: ["pipe", "pipe", "pipe"]
1920
+ }).trim();
1921
+ repoRoot = path.dirname(gitCommonDir);
1841
1922
  } catch {
1923
+ repoRoot = execSync("git rev-parse --show-toplevel", {
1924
+ cwd: dir,
1925
+ encoding: "utf8",
1926
+ timeout: 2e3,
1927
+ stdio: ["pipe", "pipe", "pipe"]
1928
+ }).trim();
1842
1929
  }
1930
+ _cached = path.basename(repoRoot);
1931
+ _cachedCwd = dir;
1932
+ return _cached;
1933
+ } catch {
1934
+ _cached = path.basename(dir);
1935
+ _cachedCwd = dir;
1936
+ return _cached;
1843
1937
  }
1844
1938
  }
1845
1939
 
1940
+ // src/lib/store.ts
1941
+ init_memory();
1942
+ init_database();
1943
+
1846
1944
  // src/lib/keychain.ts
1847
1945
  import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
1848
1946
  import { existsSync } from "fs";
@@ -1889,6 +1987,57 @@ async function getMasterKey() {
1889
1987
 
1890
1988
  // src/lib/store.ts
1891
1989
  init_config();
1990
+
1991
+ // src/lib/state-bus.ts
1992
+ var StateBus = class {
1993
+ handlers = /* @__PURE__ */ new Map();
1994
+ globalHandlers = /* @__PURE__ */ new Set();
1995
+ /** Emit an event to all subscribers */
1996
+ emit(event) {
1997
+ const typeHandlers = this.handlers.get(event.type);
1998
+ if (typeHandlers) {
1999
+ for (const handler of typeHandlers) {
2000
+ try {
2001
+ handler(event);
2002
+ } catch {
2003
+ }
2004
+ }
2005
+ }
2006
+ for (const handler of this.globalHandlers) {
2007
+ try {
2008
+ handler(event);
2009
+ } catch {
2010
+ }
2011
+ }
2012
+ }
2013
+ /** Subscribe to a specific event type */
2014
+ on(type, handler) {
2015
+ if (!this.handlers.has(type)) {
2016
+ this.handlers.set(type, /* @__PURE__ */ new Set());
2017
+ }
2018
+ this.handlers.get(type).add(handler);
2019
+ }
2020
+ /** Subscribe to ALL events */
2021
+ onAny(handler) {
2022
+ this.globalHandlers.add(handler);
2023
+ }
2024
+ /** Unsubscribe from a specific event type */
2025
+ off(type, handler) {
2026
+ this.handlers.get(type)?.delete(handler);
2027
+ }
2028
+ /** Unsubscribe from ALL events */
2029
+ offAny(handler) {
2030
+ this.globalHandlers.delete(handler);
2031
+ }
2032
+ /** Remove all listeners */
2033
+ clear() {
2034
+ this.handlers.clear();
2035
+ this.globalHandlers.clear();
2036
+ }
2037
+ };
2038
+ var orgBus = new StateBus();
2039
+
2040
+ // src/lib/store.ts
1892
2041
  var INIT_MAX_RETRIES = 3;
1893
2042
  var INIT_RETRY_DELAY_MS = 1e3;
1894
2043
  function isBusyError2(err) {
@@ -1959,6 +2108,11 @@ async function initStore(options) {
1959
2108
  "version-query"
1960
2109
  );
1961
2110
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
2111
+ try {
2112
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
2113
+ await loadGlobalProcedures2();
2114
+ } catch {
2115
+ }
1962
2116
  }
1963
2117
  function classifyTier(record) {
1964
2118
  if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
@@ -2000,6 +2154,12 @@ async function writeMemory(record) {
2000
2154
  supersedes_id: record.supersedes_id ?? null
2001
2155
  };
2002
2156
  _pendingRecords.push(dbRow);
2157
+ orgBus.emit({
2158
+ type: "memory_stored",
2159
+ agentId: record.agent_id,
2160
+ project: record.project_name,
2161
+ timestamp: record.timestamp
2162
+ });
2003
2163
  const MAX_PENDING = 1e3;
2004
2164
  if (_pendingRecords.length > MAX_PENDING) {
2005
2165
  const dropped = _pendingRecords.length - MAX_PENDING;
@@ -2155,6 +2315,7 @@ function vectorToBlob(vector) {
2155
2315
  }
2156
2316
 
2157
2317
  // src/lib/plan-limits.ts
2318
+ init_database();
2158
2319
  import { readFileSync as readFileSync4, existsSync as existsSync6 } from "fs";
2159
2320
  import path7 from "path";
2160
2321
 
@@ -2169,7 +2330,7 @@ var EMPLOYEES_PATH = path5.join(EXE_AI_DIR, "exe-employees.json");
2169
2330
  // src/lib/license.ts
2170
2331
  init_config();
2171
2332
  import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
2172
- import { randomUUID } from "crypto";
2333
+ import { randomUUID as randomUUID2 } from "crypto";
2173
2334
  import path6 from "path";
2174
2335
  import { jwtVerify, importSPKI } from "jose";
2175
2336
  var LICENSE_PATH = path6.join(EXE_AI_DIR, "license.key");
@@ -2222,7 +2383,7 @@ function loadDeviceId() {
2222
2383
  }
2223
2384
  } catch {
2224
2385
  }
2225
- const id = randomUUID();
2386
+ const id = randomUUID2();
2226
2387
  mkdirSync2(EXE_AI_DIR, { recursive: true });
2227
2388
  writeFileSync(DEVICE_ID_PATH, id, "utf8");
2228
2389
  return id;