@askexenow/exe-os 0.8.0 → 0.8.1

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