@askexenow/exe-os 0.8.1 → 0.8.2

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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -1,481 +0,0 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
- var __esm = (fn, res) => function __init() {
3
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
- };
5
-
6
- // src/lib/config.ts
7
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
8
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
9
- import path2 from "path";
10
- import os from "os";
11
- function resolveDataDir() {
12
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
13
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
14
- const newDir = path2.join(os.homedir(), ".exe-os");
15
- const legacyDir = path2.join(os.homedir(), ".exe-mem");
16
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
17
- try {
18
- renameSync(legacyDir, newDir);
19
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
20
- `);
21
- } catch {
22
- return legacyDir;
23
- }
24
- }
25
- return newDir;
26
- }
27
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG;
28
- var init_config = __esm({
29
- "src/lib/config.ts"() {
30
- "use strict";
31
- EXE_AI_DIR = resolveDataDir();
32
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
33
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
34
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
35
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
36
- CURRENT_CONFIG_VERSION = 1;
37
- DEFAULT_CONFIG = {
38
- config_version: CURRENT_CONFIG_VERSION,
39
- dbPath: DB_PATH,
40
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
41
- embeddingDim: 1024,
42
- batchSize: 20,
43
- flushIntervalMs: 1e4,
44
- autoIngestion: true,
45
- autoRetrieval: true,
46
- searchMode: "hybrid",
47
- hookSearchMode: "hybrid",
48
- fileGrepEnabled: true,
49
- splashEffect: true,
50
- consolidationEnabled: true,
51
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
52
- consolidationModel: "claude-haiku-4-5-20251001",
53
- consolidationMaxCallsPerRun: 20,
54
- selfQueryRouter: true,
55
- selfQueryModel: "claude-haiku-4-5-20251001",
56
- rerankerEnabled: true,
57
- scalingRoadmap: {
58
- rerankerAutoTrigger: {
59
- enabled: true,
60
- broadQueryMinCardinality: 5e4,
61
- fetchTopK: 150,
62
- returnTopK: 5
63
- }
64
- },
65
- graphRagEnabled: true,
66
- wikiEnabled: false,
67
- wikiUrl: "",
68
- wikiApiKey: "",
69
- wikiSyncIntervalMs: 30 * 60 * 1e3,
70
- wikiWorkspaceMapping: {
71
- exe: "Executive",
72
- yoshi: "Engineering",
73
- mari: "Marketing",
74
- tom: "Engineering",
75
- sasha: "Production"
76
- },
77
- wikiAutoUpdate: true,
78
- wikiAutoUpdateThreshold: 0.5,
79
- wikiAutoUpdateCreateNew: true,
80
- skillLearning: true,
81
- skillThreshold: 3,
82
- skillModel: "claude-haiku-4-5-20251001",
83
- exeHeartbeat: {
84
- enabled: true,
85
- intervalSeconds: 60,
86
- staleInProgressThresholdHours: 2
87
- },
88
- sessionLifecycle: {
89
- idleKillEnabled: true,
90
- idleKillTicksRequired: 3,
91
- idleKillIntercomAckWindowMs: 1e4,
92
- maxAutoInstances: 10
93
- },
94
- autoUpdate: {
95
- checkOnBoot: true,
96
- autoInstall: false,
97
- checkIntervalMs: 24 * 60 * 60 * 1e3
98
- }
99
- };
100
- }
101
- });
102
-
103
- // src/lib/consolidation.ts
104
- import { randomUUID } from "crypto";
105
-
106
- // src/lib/database.ts
107
- import { createClient } from "@libsql/client";
108
-
109
- // src/lib/keychain.ts
110
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
111
- import { existsSync } from "fs";
112
- import path from "path";
113
- import crypto from "crypto";
114
-
115
- // src/lib/store.ts
116
- init_config();
117
- function vectorToBlob(vector) {
118
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
119
- return JSON.stringify(Array.from(f32));
120
- }
121
-
122
- // src/lib/consolidation.ts
123
- async function selectUnconsolidated(client, limit = 200) {
124
- const result = await client.execute({
125
- sql: `SELECT id, agent_id, project_name, tool_name, raw_text, timestamp
126
- FROM memories
127
- WHERE consolidated = 0
128
- AND timestamp >= datetime('now', '-7 days')
129
- ORDER BY timestamp DESC
130
- LIMIT ?`,
131
- args: [limit]
132
- });
133
- return result.rows.map((row) => ({
134
- id: row.id,
135
- agent_id: row.agent_id,
136
- project_name: row.project_name,
137
- tool_name: row.tool_name,
138
- raw_text: row.raw_text,
139
- timestamp: row.timestamp
140
- }));
141
- }
142
- function groupMemories(memories) {
143
- const byProject = /* @__PURE__ */ new Map();
144
- for (const mem of memories) {
145
- const key = `${mem.agent_id}::${mem.project_name}`;
146
- const list = byProject.get(key) ?? [];
147
- list.push(mem);
148
- byProject.set(key, list);
149
- }
150
- const clusters = [];
151
- for (const [key, projectMemories] of byProject) {
152
- const [agentId, projectName] = key.split("::");
153
- const byDay = /* @__PURE__ */ new Map();
154
- for (const mem of projectMemories) {
155
- const day = mem.timestamp.slice(0, 10);
156
- const list = byDay.get(day) ?? [];
157
- list.push(mem);
158
- byDay.set(day, list);
159
- }
160
- for (const [day, dayMemories] of byDay) {
161
- if (dayMemories.length <= 15) {
162
- clusters.push({
163
- agentId,
164
- projectName,
165
- dateRange: day,
166
- memories: dayMemories
167
- });
168
- } else {
169
- for (let i = 0; i < dayMemories.length; i += 12) {
170
- const chunk = dayMemories.slice(i, i + 12);
171
- clusters.push({
172
- agentId,
173
- projectName,
174
- dateRange: day,
175
- memories: chunk
176
- });
177
- }
178
- }
179
- }
180
- }
181
- return clusters;
182
- }
183
- function buildConsolidationPrompt(cluster) {
184
- const snippets = cluster.memories.map((m, i) => {
185
- const text = m.raw_text.length > 200 ? m.raw_text.slice(0, 200) + "..." : m.raw_text;
186
- return `${i + 1}. [${m.tool_name}] ${text}`;
187
- }).join("\n");
188
- return `You are reviewing a set of work memories from an AI coding agent.
189
- These are raw tool call records from ${cluster.dateRange}.
190
-
191
- Agent: ${cluster.agentId} | Project: ${cluster.projectName} | Date: ${cluster.dateRange}
192
-
193
- MEMORIES:
194
- ${snippets}
195
-
196
- Extract EXACTLY THREE types of insights:
197
-
198
- 1. KEY DECISIONS \u2014 choices that were made and why (at most 3)
199
- 2. RECURRING PATTERNS \u2014 actions or approaches that repeated (at most 3)
200
- 3. OPEN QUESTIONS \u2014 things that seem unresolved or risky (at most 2)
201
-
202
- Format each as a single sentence. Be specific \u2014 include file names,
203
- function names, and concrete details. Skip if no insight for a category.`;
204
- }
205
- async function consolidateCluster(cluster, model) {
206
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
207
- const client = new Anthropic();
208
- const prompt = buildConsolidationPrompt(cluster);
209
- const response = await client.messages.create({
210
- model,
211
- max_tokens: 300,
212
- messages: [{ role: "user", content: prompt }]
213
- });
214
- const textBlock = response.content.find((b) => b.type === "text");
215
- return textBlock?.text ?? "";
216
- }
217
- async function storeConsolidation(client, cluster, synthesisText, embedFn) {
218
- const consolidatedId = randomUUID();
219
- const now = (/* @__PURE__ */ new Date()).toISOString();
220
- const rawText = `CONSOLIDATION [${cluster.dateRange}, ${cluster.projectName}]:
221
-
222
- ${synthesisText}`;
223
- let vector = null;
224
- if (embedFn) {
225
- try {
226
- vector = await embedFn(rawText);
227
- } catch {
228
- }
229
- }
230
- const insertSql = vector ? `INSERT INTO memories
231
- (id, agent_id, agent_role, session_id, timestamp,
232
- tool_name, project_name, has_error, raw_text, vector, version, consolidated)
233
- VALUES (?, ?, 'consolidation', 'daemon-consolidation', ?, 'consolidation', ?, 0, ?, vector32(?), 0, 1)` : `INSERT INTO memories
234
- (id, agent_id, agent_role, session_id, timestamp,
235
- tool_name, project_name, has_error, raw_text, vector, version, consolidated)
236
- VALUES (?, ?, 'consolidation', 'daemon-consolidation', ?, 'consolidation', ?, 0, ?, NULL, 0, 1)`;
237
- const insertArgs = vector ? [consolidatedId, cluster.agentId, now, cluster.projectName, rawText, vectorToBlob(vector)] : [consolidatedId, cluster.agentId, now, cluster.projectName, rawText];
238
- await client.execute({ sql: insertSql, args: insertArgs });
239
- const sourceIds = cluster.memories.map((m) => m.id);
240
- const linkStmts = sourceIds.map((sourceId) => ({
241
- sql: `INSERT INTO consolidations (id, consolidated_memory_id, source_memory_id, created_at)
242
- VALUES (?, ?, ?, ?)`,
243
- args: [randomUUID(), consolidatedId, sourceId, now]
244
- }));
245
- const placeholders = sourceIds.map(() => "?").join(",");
246
- const markStmt = {
247
- sql: `UPDATE memories SET consolidated = 1 WHERE id IN (${placeholders})`,
248
- args: sourceIds
249
- };
250
- await client.batch([...linkStmts, markStmt], "write");
251
- return { consolidatedMemoryId: consolidatedId, sourceIds, rawText };
252
- }
253
- var WIKI_FETCH_TIMEOUT_MS = 1e4;
254
- async function pushToWiki(consolidation, config) {
255
- if (!config.wikiEnabled || !config.wikiAutoUpdate) {
256
- return { updated: false };
257
- }
258
- const apiUrl = config.wikiUrl || process.env.EXE_WIKI_API_URL;
259
- const apiKey = config.wikiApiKey || process.env.EXE_WIKI_API_KEY;
260
- if (!apiUrl || !apiKey) {
261
- return { updated: false };
262
- }
263
- const workspace = config.wikiWorkspaceMapping[consolidation.projectName] ?? consolidation.projectName;
264
- try {
265
- const listRes = await fetch(
266
- `${apiUrl}/v1/workspace/${encodeURIComponent(workspace)}/documents`,
267
- {
268
- headers: { Authorization: `Bearer ${apiKey}` },
269
- signal: AbortSignal.timeout(WIKI_FETCH_TIMEOUT_MS)
270
- }
271
- );
272
- if (!listRes.ok) {
273
- return { updated: false, error: `Workspace "${workspace}" not accessible (${listRes.status})` };
274
- }
275
- const listJson = await listRes.json();
276
- const docs = listJson.documents ?? listJson.localFiles?.items ?? [];
277
- const contentLines = consolidation.rawText.split("\n").filter((l) => l.trim() && !l.startsWith("CONSOLIDATION") && !l.match(/^[A-Z\s]+:$/)).join(" ");
278
- const keywords = contentLines.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((w) => w.length > 3);
279
- let bestMatch = null;
280
- for (const doc of docs) {
281
- if (!doc.id || !doc.title) continue;
282
- const titleWords = doc.title.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((w) => w.length > 3);
283
- if (titleWords.length === 0) continue;
284
- const matchCount = titleWords.filter(
285
- (tw) => keywords.some((k) => k.includes(tw) || tw.includes(k))
286
- ).length;
287
- const score = matchCount / titleWords.length;
288
- if (score > (bestMatch?.score ?? 0)) {
289
- bestMatch = { id: doc.id, title: doc.title, score };
290
- }
291
- }
292
- if (bestMatch && bestMatch.score >= config.wikiAutoUpdateThreshold) {
293
- const updateRes = await fetch(`${apiUrl}/v1/document/raw-text`, {
294
- method: "POST",
295
- headers: {
296
- "Content-Type": "application/json",
297
- Authorization: `Bearer ${apiKey}`
298
- },
299
- body: JSON.stringify({
300
- textContent: consolidation.rawText,
301
- metadata: { title: bestMatch.title, appendTo: bestMatch.id },
302
- workspaceSlugs: [workspace]
303
- }),
304
- signal: AbortSignal.timeout(WIKI_FETCH_TIMEOUT_MS)
305
- });
306
- if (updateRes.ok) {
307
- process.stderr.write(
308
- `[consolidation] Wiki auto-updated: ${workspace}/${bestMatch.title}
309
- `
310
- );
311
- return { updated: true, action: "updated", page: bestMatch.title };
312
- }
313
- return { updated: false, error: `Update failed (${updateRes.status})` };
314
- }
315
- if (config.wikiAutoUpdateCreateNew) {
316
- const title = `Consolidated Insights \u2014 ${consolidation.projectName} (${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)})`;
317
- const createRes = await fetch(`${apiUrl}/v1/document/raw-text`, {
318
- method: "POST",
319
- headers: {
320
- "Content-Type": "application/json",
321
- Authorization: `Bearer ${apiKey}`
322
- },
323
- body: JSON.stringify({
324
- textContent: consolidation.rawText,
325
- metadata: { title },
326
- workspaceSlugs: [workspace]
327
- }),
328
- signal: AbortSignal.timeout(WIKI_FETCH_TIMEOUT_MS)
329
- });
330
- if (createRes.ok) {
331
- process.stderr.write(
332
- `[consolidation] Wiki page created: ${workspace}/${title}
333
- `
334
- );
335
- return { updated: true, action: "created", page: title };
336
- }
337
- return { updated: false, error: `Create failed (${createRes.status})` };
338
- }
339
- return { updated: false };
340
- } catch (err) {
341
- const msg = err instanceof Error ? err.message : String(err);
342
- process.stderr.write(`[consolidation] Wiki push failed: ${msg}
343
- `);
344
- return { updated: false, error: msg };
345
- }
346
- }
347
- async function runConsolidation(client, options) {
348
- const memories = await selectUnconsolidated(client);
349
- if (memories.length < 20) {
350
- return { clustersProcessed: 0, memoriesConsolidated: 0 };
351
- }
352
- const clusters = groupMemories(memories);
353
- let clustersProcessed = 0;
354
- let memoriesConsolidated = 0;
355
- for (const cluster of clusters) {
356
- if (clustersProcessed >= options.maxCalls) break;
357
- if (cluster.memories.length < 3) continue;
358
- try {
359
- const isExe = cluster.agentId === "exe";
360
- if (isExe) {
361
- const synthesis = await consolidateCluster(cluster, options.model);
362
- if (!synthesis.trim()) continue;
363
- const result = await storeConsolidation(client, cluster, synthesis, options.embedFn);
364
- if (options.wikiConfig) {
365
- await pushToWiki(
366
- { ...result, projectName: cluster.projectName },
367
- options.wikiConfig
368
- ).catch((err) => {
369
- process.stderr.write(
370
- `[consolidation] Wiki push error (non-fatal): ${err instanceof Error ? err.message : String(err)}
371
- `
372
- );
373
- });
374
- }
375
- const sourceIds = result.sourceIds;
376
- if (sourceIds.length > 0) {
377
- const placeholders = sourceIds.map(() => "?").join(",");
378
- await client.execute({
379
- sql: `UPDATE memories SET status = 'archived' WHERE id IN (${placeholders})`,
380
- args: sourceIds
381
- });
382
- }
383
- } else {
384
- const dedupCount = await dedupCluster(client, cluster, options.embedFn);
385
- memoriesConsolidated += dedupCount;
386
- if (dedupCount === 0) continue;
387
- }
388
- clustersProcessed++;
389
- memoriesConsolidated += isExe ? cluster.memories.length : 0;
390
- } catch (err) {
391
- process.stderr.write(
392
- `[consolidation] Cluster failed (${cluster.projectName}/${cluster.dateRange}): ${err instanceof Error ? err.message : String(err)}
393
- `
394
- );
395
- }
396
- }
397
- return { clustersProcessed, memoriesConsolidated };
398
- }
399
- async function dedupCluster(client, cluster, embedFn) {
400
- if (!embedFn || cluster.memories.length < 2) return 0;
401
- const vectors = [];
402
- for (const mem of cluster.memories) {
403
- try {
404
- const v = await embedFn(mem.raw_text.slice(0, 500));
405
- vectors.push({ id: mem.id, vector: v });
406
- } catch {
407
- }
408
- }
409
- if (vectors.length < 2) return 0;
410
- const toArchive = /* @__PURE__ */ new Set();
411
- for (let i = 0; i < vectors.length; i++) {
412
- if (toArchive.has(vectors[i].id)) continue;
413
- for (let j = i + 1; j < vectors.length; j++) {
414
- if (toArchive.has(vectors[j].id)) continue;
415
- const sim = cosineSimilarity(vectors[i].vector, vectors[j].vector);
416
- if (sim > 0.95) {
417
- toArchive.add(vectors[j].id);
418
- }
419
- }
420
- }
421
- if (toArchive.size === 0) return 0;
422
- const ids = [...toArchive];
423
- const placeholders = ids.map(() => "?").join(",");
424
- await client.execute({
425
- sql: `UPDATE memories SET status = 'archived', consolidated = 1 WHERE id IN (${placeholders})`,
426
- args: ids
427
- });
428
- const survivors = vectors.filter((v) => !toArchive.has(v.id)).map((v) => v.id);
429
- if (survivors.length > 0) {
430
- const survivorPlaceholders = survivors.map(() => "?").join(",");
431
- await client.execute({
432
- sql: `UPDATE memories SET confidence = MIN(1.0, COALESCE(confidence, 0.7) + 0.1) WHERE id IN (${survivorPlaceholders})`,
433
- args: survivors
434
- });
435
- }
436
- return ids.length;
437
- }
438
- function cosineSimilarity(a, b) {
439
- let dot = 0, normA = 0, normB = 0;
440
- for (let i = 0; i < a.length; i++) {
441
- dot += a[i] * b[i];
442
- normA += a[i] * a[i];
443
- normB += b[i] * b[i];
444
- }
445
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
446
- return denom === 0 ? 0 : dot / denom;
447
- }
448
- async function isUserIdle(client, idleMinutes = 30) {
449
- const result = await client.execute({
450
- sql: `SELECT MAX(timestamp) as last_activity
451
- FROM memories
452
- WHERE tool_name != 'consolidation'
453
- AND timestamp >= datetime('now', '-1 day')`,
454
- args: []
455
- });
456
- const lastActivity = result.rows[0]?.last_activity;
457
- if (!lastActivity) return true;
458
- const lastMs = new Date(lastActivity).getTime();
459
- const now = Date.now();
460
- return now - lastMs >= idleMinutes * 60 * 1e3;
461
- }
462
- async function countUnconsolidated(client) {
463
- const result = await client.execute({
464
- sql: `SELECT COUNT(*) as cnt FROM memories
465
- WHERE consolidated = 0
466
- AND timestamp >= datetime('now', '-7 days')`,
467
- args: []
468
- });
469
- return Number(result.rows[0]?.cnt ?? 0);
470
- }
471
- export {
472
- buildConsolidationPrompt,
473
- consolidateCluster,
474
- countUnconsolidated,
475
- groupMemories,
476
- isUserIdle,
477
- pushToWiki,
478
- runConsolidation,
479
- selectUnconsolidated,
480
- storeConsolidation
481
- };
@@ -1,51 +0,0 @@
1
- // src/lib/crypto.ts
2
- import crypto from "crypto";
3
- var ALGORITHM = "aes-256-gcm";
4
- var IV_LENGTH = 12;
5
- var TAG_LENGTH = 16;
6
- var SYNC_HKDF_INFO = "exe-mem-sync-v2";
7
- var _syncKey = null;
8
- function initSyncCrypto(masterKey) {
9
- if (masterKey.length !== 32) {
10
- throw new Error(`Master key must be 32 bytes, got ${masterKey.length}`);
11
- }
12
- _syncKey = Buffer.from(
13
- crypto.hkdfSync("sha256", masterKey, "", SYNC_HKDF_INFO, 32)
14
- );
15
- }
16
- function isSyncCryptoInitialized() {
17
- return _syncKey !== null;
18
- }
19
- function requireSyncKey() {
20
- if (!_syncKey) {
21
- throw new Error("Sync crypto not initialized. Call initSyncCrypto(masterKey) first.");
22
- }
23
- return _syncKey;
24
- }
25
- function encryptSyncBlob(data) {
26
- const key = requireSyncKey();
27
- const iv = crypto.randomBytes(IV_LENGTH);
28
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
29
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
30
- const tag = cipher.getAuthTag();
31
- return Buffer.concat([iv, encrypted, tag]).toString("base64");
32
- }
33
- function decryptSyncBlob(ciphertext) {
34
- const key = requireSyncKey();
35
- const combined = Buffer.from(ciphertext, "base64");
36
- if (combined.length < IV_LENGTH + TAG_LENGTH) {
37
- throw new Error("Sync blob too short to contain IV + tag");
38
- }
39
- const iv = combined.subarray(0, IV_LENGTH);
40
- const tag = combined.subarray(combined.length - TAG_LENGTH);
41
- const encrypted = combined.subarray(IV_LENGTH, combined.length - TAG_LENGTH);
42
- const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
43
- decipher.setAuthTag(tag);
44
- return Buffer.concat([decipher.update(encrypted), decipher.final()]);
45
- }
46
- export {
47
- decryptSyncBlob,
48
- encryptSyncBlob,
49
- initSyncCrypto,
50
- isSyncCryptoInitialized
51
- };