@askexenow/exe-os 0.9.7 → 0.9.9

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 (101) hide show
  1. package/dist/bin/backfill-conversations.js +953 -105
  2. package/dist/bin/backfill-responses.js +952 -104
  3. package/dist/bin/backfill-vectors.js +956 -108
  4. package/dist/bin/cleanup-stale-review-tasks.js +802 -58
  5. package/dist/bin/cli.js +2292 -1070
  6. package/dist/bin/exe-agent-config.js +157 -101
  7. package/dist/bin/exe-agent.js +55 -29
  8. package/dist/bin/exe-assign.js +940 -92
  9. package/dist/bin/exe-boot.js +1424 -442
  10. package/dist/bin/exe-call.js +240 -141
  11. package/dist/bin/exe-cloud.js +198 -70
  12. package/dist/bin/exe-dispatch.js +951 -192
  13. package/dist/bin/exe-doctor.js +791 -51
  14. package/dist/bin/exe-export-behaviors.js +790 -42
  15. package/dist/bin/exe-forget.js +771 -31
  16. package/dist/bin/exe-gateway.js +1592 -521
  17. package/dist/bin/exe-heartbeat.js +850 -109
  18. package/dist/bin/exe-kill.js +783 -35
  19. package/dist/bin/exe-launch-agent.js +1030 -107
  20. package/dist/bin/exe-link.js +916 -110
  21. package/dist/bin/exe-new-employee.js +526 -217
  22. package/dist/bin/exe-pending-messages.js +1046 -62
  23. package/dist/bin/exe-pending-notifications.js +1318 -111
  24. package/dist/bin/exe-pending-reviews.js +1040 -72
  25. package/dist/bin/exe-rename.js +772 -59
  26. package/dist/bin/exe-review.js +772 -32
  27. package/dist/bin/exe-search.js +982 -128
  28. package/dist/bin/exe-session-cleanup.js +1180 -306
  29. package/dist/bin/exe-settings.js +185 -105
  30. package/dist/bin/exe-start-codex.js +886 -132
  31. package/dist/bin/exe-start-opencode.js +873 -119
  32. package/dist/bin/exe-status.js +803 -59
  33. package/dist/bin/exe-team.js +772 -32
  34. package/dist/bin/git-sweep.js +1046 -223
  35. package/dist/bin/graph-backfill.js +779 -31
  36. package/dist/bin/graph-export.js +785 -37
  37. package/dist/bin/install.js +632 -200
  38. package/dist/bin/scan-tasks.js +1055 -232
  39. package/dist/bin/setup.js +1419 -320
  40. package/dist/bin/shard-migrate.js +783 -35
  41. package/dist/bin/update.js +138 -49
  42. package/dist/bin/wiki-sync.js +782 -34
  43. package/dist/gateway/index.js +1444 -449
  44. package/dist/hooks/bug-report-worker.js +1141 -269
  45. package/dist/hooks/codex-stop-task-finalizer.js +4678 -0
  46. package/dist/hooks/commit-complete.js +1044 -221
  47. package/dist/hooks/error-recall.js +989 -135
  48. package/dist/hooks/exe-heartbeat-hook.js +99 -75
  49. package/dist/hooks/ingest-worker.js +4176 -3226
  50. package/dist/hooks/ingest.js +920 -168
  51. package/dist/hooks/instructions-loaded.js +874 -70
  52. package/dist/hooks/notification.js +860 -56
  53. package/dist/hooks/post-compact.js +881 -73
  54. package/dist/hooks/pre-compact.js +1050 -227
  55. package/dist/hooks/pre-tool-use.js +1084 -159
  56. package/dist/hooks/prompt-ingest-worker.js +1089 -164
  57. package/dist/hooks/prompt-submit.js +1469 -515
  58. package/dist/hooks/response-ingest-worker.js +1104 -179
  59. package/dist/hooks/session-end.js +1085 -251
  60. package/dist/hooks/session-start.js +1241 -231
  61. package/dist/hooks/stop.js +935 -109
  62. package/dist/hooks/subagent-stop.js +881 -73
  63. package/dist/hooks/summary-worker.js +1323 -307
  64. package/dist/index.js +1449 -452
  65. package/dist/lib/agent-config.js +28 -6
  66. package/dist/lib/cloud-sync.js +909 -115
  67. package/dist/lib/config.js +30 -10
  68. package/dist/lib/consolidation.js +42 -9
  69. package/dist/lib/database.js +739 -33
  70. package/dist/lib/db-daemon-client.js +73 -19
  71. package/dist/lib/db.js +2359 -0
  72. package/dist/lib/device-registry.js +760 -47
  73. package/dist/lib/embedder.js +201 -73
  74. package/dist/lib/employee-templates.js +30 -4
  75. package/dist/lib/employees.js +290 -86
  76. package/dist/lib/exe-daemon-client.js +187 -83
  77. package/dist/lib/exe-daemon.js +1696 -616
  78. package/dist/lib/hybrid-search.js +982 -128
  79. package/dist/lib/identity.js +43 -13
  80. package/dist/lib/license.js +133 -48
  81. package/dist/lib/messaging.js +167 -80
  82. package/dist/lib/reminders.js +35 -5
  83. package/dist/lib/schedules.js +772 -32
  84. package/dist/lib/skill-learning.js +54 -7
  85. package/dist/lib/store.js +779 -31
  86. package/dist/lib/task-router.js +94 -73
  87. package/dist/lib/tasks.js +298 -225
  88. package/dist/lib/tmux-routing.js +246 -172
  89. package/dist/lib/token-spend.js +52 -14
  90. package/dist/mcp/server.js +2893 -850
  91. package/dist/mcp/tools/complete-reminder.js +35 -5
  92. package/dist/mcp/tools/create-reminder.js +35 -5
  93. package/dist/mcp/tools/create-task.js +507 -323
  94. package/dist/mcp/tools/deactivate-behavior.js +40 -10
  95. package/dist/mcp/tools/list-reminders.js +35 -5
  96. package/dist/mcp/tools/list-tasks.js +277 -104
  97. package/dist/mcp/tools/send-message.js +129 -56
  98. package/dist/mcp/tools/update-task.js +1864 -188
  99. package/dist/runtime/index.js +1083 -259
  100. package/dist/tui/App.js +1501 -434
  101. package/package.json +3 -2
@@ -64,9 +64,34 @@ var init_db_retry = __esm({
64
64
  }
65
65
  });
66
66
 
67
+ // src/lib/secure-files.ts
68
+ import { chmodSync, existsSync, mkdirSync } from "fs";
69
+ import { chmod, mkdir } from "fs/promises";
70
+ async function ensurePrivateDir(dirPath) {
71
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
72
+ try {
73
+ await chmod(dirPath, PRIVATE_DIR_MODE);
74
+ } catch {
75
+ }
76
+ }
77
+ async function enforcePrivateFile(filePath) {
78
+ try {
79
+ await chmod(filePath, PRIVATE_FILE_MODE);
80
+ } catch {
81
+ }
82
+ }
83
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
84
+ var init_secure_files = __esm({
85
+ "src/lib/secure-files.ts"() {
86
+ "use strict";
87
+ PRIVATE_DIR_MODE = 448;
88
+ PRIVATE_FILE_MODE = 384;
89
+ }
90
+ });
91
+
67
92
  // src/lib/config.ts
68
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
69
- import { readFileSync, existsSync, renameSync } from "fs";
93
+ import { readFile, writeFile } from "fs/promises";
94
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
70
95
  import path from "path";
71
96
  import os from "os";
72
97
  function resolveDataDir() {
@@ -74,7 +99,7 @@ function resolveDataDir() {
74
99
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
75
100
  const newDir = path.join(os.homedir(), ".exe-os");
76
101
  const legacyDir = path.join(os.homedir(), ".exe-mem");
77
- if (!existsSync(newDir) && existsSync(legacyDir)) {
102
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
78
103
  try {
79
104
  renameSync(legacyDir, newDir);
80
105
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -137,9 +162,9 @@ function normalizeAutoUpdate(raw) {
137
162
  }
138
163
  async function loadConfig() {
139
164
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
140
- await mkdir(dir, { recursive: true });
165
+ await ensurePrivateDir(dir);
141
166
  const configPath = path.join(dir, "config.json");
142
- if (!existsSync(configPath)) {
167
+ if (!existsSync2(configPath)) {
143
168
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
144
169
  }
145
170
  const raw = await readFile(configPath, "utf-8");
@@ -152,6 +177,7 @@ async function loadConfig() {
152
177
  `);
153
178
  try {
154
179
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
180
+ await enforcePrivateFile(configPath);
155
181
  } catch {
156
182
  }
157
183
  }
@@ -171,6 +197,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
171
197
  var init_config = __esm({
172
198
  "src/lib/config.ts"() {
173
199
  "use strict";
200
+ init_secure_files();
174
201
  EXE_AI_DIR = resolveDataDir();
175
202
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
176
203
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -249,7 +276,7 @@ var init_config = __esm({
249
276
 
250
277
  // src/lib/employees.ts
251
278
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
252
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
279
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
253
280
  import { execSync } from "child_process";
254
281
  import path2 from "path";
255
282
  import os2 from "os";
@@ -266,14 +293,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
266
293
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
267
294
  }
268
295
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
269
- if (!existsSync2(employeesPath)) return [];
296
+ if (!existsSync3(employeesPath)) return [];
270
297
  try {
271
298
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
272
299
  } catch {
273
300
  return [];
274
301
  }
275
302
  }
276
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
303
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
277
304
  var init_employees = __esm({
278
305
  "src/lib/employees.ts"() {
279
306
  "use strict";
@@ -281,12 +308,609 @@ var init_employees = __esm({
281
308
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
282
309
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
283
310
  COORDINATOR_ROLE = "COO";
311
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
312
+ }
313
+ });
314
+
315
+ // src/lib/database-adapter.ts
316
+ import os3 from "os";
317
+ import path3 from "path";
318
+ import { createRequire } from "module";
319
+ import { pathToFileURL } from "url";
320
+ function quotedIdentifier(identifier) {
321
+ return `"${identifier.replace(/"/g, '""')}"`;
322
+ }
323
+ function unqualifiedTableName(name) {
324
+ const raw = name.trim().replace(/^"|"$/g, "");
325
+ const parts = raw.split(".");
326
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
327
+ }
328
+ function stripTrailingSemicolon(sql) {
329
+ return sql.trim().replace(/;+\s*$/u, "");
330
+ }
331
+ function appendClause(sql, clause) {
332
+ const trimmed = stripTrailingSemicolon(sql);
333
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
334
+ if (!returningMatch) {
335
+ return `${trimmed}${clause}`;
336
+ }
337
+ const idx = returningMatch.index;
338
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
339
+ }
340
+ function normalizeStatement(stmt) {
341
+ if (typeof stmt === "string") {
342
+ return { kind: "positional", sql: stmt, args: [] };
343
+ }
344
+ const sql = stmt.sql;
345
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
346
+ return { kind: "positional", sql, args: stmt.args ?? [] };
347
+ }
348
+ return { kind: "named", sql, args: stmt.args };
349
+ }
350
+ function rewriteBooleanLiterals(sql) {
351
+ let out = sql;
352
+ for (const column of BOOLEAN_COLUMN_NAMES) {
353
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
354
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
355
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
356
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
357
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
358
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
359
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
360
+ }
361
+ return out;
362
+ }
363
+ function rewriteInsertOrIgnore(sql) {
364
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
365
+ return sql;
366
+ }
367
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
368
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
369
+ }
370
+ function rewriteInsertOrReplace(sql) {
371
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
372
+ if (!match) {
373
+ return sql;
374
+ }
375
+ const rawTable = match[1];
376
+ const rawColumns = match[2];
377
+ const remainder = match[3];
378
+ const tableName = unqualifiedTableName(rawTable);
379
+ const conflictKeys = UPSERT_KEYS[tableName];
380
+ if (!conflictKeys?.length) {
381
+ return sql;
382
+ }
383
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
384
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
385
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
386
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
387
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
388
+ }
389
+ function rewriteSql(sql) {
390
+ let out = sql;
391
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
392
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
393
+ out = rewriteBooleanLiterals(out);
394
+ out = rewriteInsertOrReplace(out);
395
+ out = rewriteInsertOrIgnore(out);
396
+ return stripTrailingSemicolon(out);
397
+ }
398
+ function toBoolean(value) {
399
+ if (value === null || value === void 0) return value;
400
+ if (typeof value === "boolean") return value;
401
+ if (typeof value === "number") return value !== 0;
402
+ if (typeof value === "bigint") return value !== 0n;
403
+ if (typeof value === "string") {
404
+ const normalized = value.trim().toLowerCase();
405
+ if (normalized === "0" || normalized === "false") return false;
406
+ if (normalized === "1" || normalized === "true") return true;
407
+ }
408
+ return Boolean(value);
409
+ }
410
+ function countQuestionMarks(sql, end) {
411
+ let count = 0;
412
+ let inSingle = false;
413
+ let inDouble = false;
414
+ let inLineComment = false;
415
+ let inBlockComment = false;
416
+ for (let i = 0; i < end; i++) {
417
+ const ch = sql[i];
418
+ const next = sql[i + 1];
419
+ if (inLineComment) {
420
+ if (ch === "\n") inLineComment = false;
421
+ continue;
422
+ }
423
+ if (inBlockComment) {
424
+ if (ch === "*" && next === "/") {
425
+ inBlockComment = false;
426
+ i += 1;
427
+ }
428
+ continue;
429
+ }
430
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
431
+ inLineComment = true;
432
+ i += 1;
433
+ continue;
434
+ }
435
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
436
+ inBlockComment = true;
437
+ i += 1;
438
+ continue;
439
+ }
440
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
441
+ inSingle = !inSingle;
442
+ continue;
443
+ }
444
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
445
+ inDouble = !inDouble;
446
+ continue;
447
+ }
448
+ if (!inSingle && !inDouble && ch === "?") {
449
+ count += 1;
450
+ }
451
+ }
452
+ return count;
453
+ }
454
+ function findBooleanPlaceholderIndexes(sql) {
455
+ const indexes = /* @__PURE__ */ new Set();
456
+ for (const column of BOOLEAN_COLUMN_NAMES) {
457
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
458
+ for (const match of sql.matchAll(pattern)) {
459
+ const matchText = match[0];
460
+ const qIndex = match.index + matchText.lastIndexOf("?");
461
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
462
+ }
463
+ }
464
+ return indexes;
465
+ }
466
+ function coerceInsertBooleanArgs(sql, args) {
467
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
468
+ if (!match) return;
469
+ const rawTable = match[1];
470
+ const rawColumns = match[2];
471
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
472
+ if (!boolColumns?.size) return;
473
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
474
+ for (const [index, column] of columns.entries()) {
475
+ if (boolColumns.has(column) && index < args.length) {
476
+ args[index] = toBoolean(args[index]);
477
+ }
478
+ }
479
+ }
480
+ function coerceUpdateBooleanArgs(sql, args) {
481
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
482
+ if (!match) return;
483
+ const rawTable = match[1];
484
+ const setClause = match[2];
485
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
486
+ if (!boolColumns?.size) return;
487
+ const assignments = setClause.split(",");
488
+ let placeholderIndex = 0;
489
+ for (const assignment of assignments) {
490
+ if (!assignment.includes("?")) continue;
491
+ placeholderIndex += 1;
492
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
493
+ if (colMatch && boolColumns.has(colMatch[1])) {
494
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
495
+ }
496
+ }
497
+ }
498
+ function coerceBooleanArgs(sql, args) {
499
+ const nextArgs = [...args];
500
+ coerceInsertBooleanArgs(sql, nextArgs);
501
+ coerceUpdateBooleanArgs(sql, nextArgs);
502
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
503
+ for (const index of placeholderIndexes) {
504
+ if (index > 0 && index <= nextArgs.length) {
505
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
506
+ }
507
+ }
508
+ return nextArgs;
509
+ }
510
+ function convertQuestionMarksToDollarParams(sql) {
511
+ let out = "";
512
+ let placeholder = 0;
513
+ let inSingle = false;
514
+ let inDouble = false;
515
+ let inLineComment = false;
516
+ let inBlockComment = false;
517
+ for (let i = 0; i < sql.length; i++) {
518
+ const ch = sql[i];
519
+ const next = sql[i + 1];
520
+ if (inLineComment) {
521
+ out += ch;
522
+ if (ch === "\n") inLineComment = false;
523
+ continue;
524
+ }
525
+ if (inBlockComment) {
526
+ out += ch;
527
+ if (ch === "*" && next === "/") {
528
+ out += next;
529
+ inBlockComment = false;
530
+ i += 1;
531
+ }
532
+ continue;
533
+ }
534
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
535
+ out += ch + next;
536
+ inLineComment = true;
537
+ i += 1;
538
+ continue;
539
+ }
540
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
541
+ out += ch + next;
542
+ inBlockComment = true;
543
+ i += 1;
544
+ continue;
545
+ }
546
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
547
+ inSingle = !inSingle;
548
+ out += ch;
549
+ continue;
550
+ }
551
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
552
+ inDouble = !inDouble;
553
+ out += ch;
554
+ continue;
555
+ }
556
+ if (!inSingle && !inDouble && ch === "?") {
557
+ placeholder += 1;
558
+ out += `$${placeholder}`;
559
+ continue;
560
+ }
561
+ out += ch;
562
+ }
563
+ return out;
564
+ }
565
+ function translateStatementForPostgres(stmt) {
566
+ const normalized = normalizeStatement(stmt);
567
+ if (normalized.kind === "named") {
568
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
569
+ }
570
+ const rewrittenSql = rewriteSql(normalized.sql);
571
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
572
+ return {
573
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
574
+ args: coercedArgs
575
+ };
576
+ }
577
+ function shouldBypassPostgres(stmt) {
578
+ const normalized = normalizeStatement(stmt);
579
+ if (normalized.kind === "named") {
580
+ return true;
581
+ }
582
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
583
+ }
584
+ function shouldFallbackOnError(error) {
585
+ const message = error instanceof Error ? error.message : String(error);
586
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
587
+ }
588
+ function isReadQuery(sql) {
589
+ const trimmed = sql.trimStart();
590
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
591
+ }
592
+ function buildRow(row, columns) {
593
+ const values = columns.map((column) => row[column]);
594
+ return Object.assign(values, row);
595
+ }
596
+ function buildResultSet(rows, rowsAffected = 0) {
597
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
598
+ const resultRows = rows.map((row) => buildRow(row, columns));
599
+ return {
600
+ columns,
601
+ columnTypes: columns.map(() => ""),
602
+ rows: resultRows,
603
+ rowsAffected,
604
+ lastInsertRowid: void 0,
605
+ toJSON() {
606
+ return {
607
+ columns,
608
+ columnTypes: columns.map(() => ""),
609
+ rows,
610
+ rowsAffected,
611
+ lastInsertRowid: void 0
612
+ };
613
+ }
614
+ };
615
+ }
616
+ async function loadPrismaClient() {
617
+ if (!prismaClientPromise) {
618
+ prismaClientPromise = (async () => {
619
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
620
+ if (explicitPath) {
621
+ const module2 = await import(pathToFileURL(explicitPath).href);
622
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
623
+ if (!PrismaClient2) {
624
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
625
+ }
626
+ return new PrismaClient2();
627
+ }
628
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
629
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
630
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
631
+ const module = await import(pathToFileURL(prismaEntry).href);
632
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
633
+ if (!PrismaClient) {
634
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
635
+ }
636
+ return new PrismaClient();
637
+ })();
638
+ }
639
+ return prismaClientPromise;
640
+ }
641
+ async function ensureCompatibilityViews(prisma) {
642
+ if (!compatibilityBootstrapPromise) {
643
+ compatibilityBootstrapPromise = (async () => {
644
+ for (const mapping of VIEW_MAPPINGS) {
645
+ const relation = mapping.source.replace(/"/g, "");
646
+ const rows = await prisma.$queryRawUnsafe(
647
+ "SELECT to_regclass($1) AS regclass",
648
+ relation
649
+ );
650
+ if (!rows[0]?.regclass) {
651
+ continue;
652
+ }
653
+ await prisma.$executeRawUnsafe(
654
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
655
+ );
656
+ }
657
+ })();
658
+ }
659
+ return compatibilityBootstrapPromise;
660
+ }
661
+ async function executeOnPrisma(executor, stmt) {
662
+ const translated = translateStatementForPostgres(stmt);
663
+ if (isReadQuery(translated.sql)) {
664
+ const rows = await executor.$queryRawUnsafe(
665
+ translated.sql,
666
+ ...translated.args
667
+ );
668
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
669
+ }
670
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
671
+ return buildResultSet([], rowsAffected);
672
+ }
673
+ function splitSqlStatements(sql) {
674
+ const parts = [];
675
+ let current = "";
676
+ let inSingle = false;
677
+ let inDouble = false;
678
+ let inLineComment = false;
679
+ let inBlockComment = false;
680
+ for (let i = 0; i < sql.length; i++) {
681
+ const ch = sql[i];
682
+ const next = sql[i + 1];
683
+ if (inLineComment) {
684
+ current += ch;
685
+ if (ch === "\n") inLineComment = false;
686
+ continue;
687
+ }
688
+ if (inBlockComment) {
689
+ current += ch;
690
+ if (ch === "*" && next === "/") {
691
+ current += next;
692
+ inBlockComment = false;
693
+ i += 1;
694
+ }
695
+ continue;
696
+ }
697
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
698
+ current += ch + next;
699
+ inLineComment = true;
700
+ i += 1;
701
+ continue;
702
+ }
703
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
704
+ current += ch + next;
705
+ inBlockComment = true;
706
+ i += 1;
707
+ continue;
708
+ }
709
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
710
+ inSingle = !inSingle;
711
+ current += ch;
712
+ continue;
713
+ }
714
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
715
+ inDouble = !inDouble;
716
+ current += ch;
717
+ continue;
718
+ }
719
+ if (!inSingle && !inDouble && ch === ";") {
720
+ if (current.trim()) {
721
+ parts.push(current.trim());
722
+ }
723
+ current = "";
724
+ continue;
725
+ }
726
+ current += ch;
727
+ }
728
+ if (current.trim()) {
729
+ parts.push(current.trim());
730
+ }
731
+ return parts;
732
+ }
733
+ async function createPrismaDbAdapter(fallbackClient) {
734
+ const prisma = await loadPrismaClient();
735
+ await ensureCompatibilityViews(prisma);
736
+ let closed = false;
737
+ let adapter;
738
+ const fallbackExecute = async (stmt, error) => {
739
+ if (!fallbackClient) {
740
+ if (error) throw error;
741
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
742
+ }
743
+ if (error) {
744
+ process.stderr.write(
745
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
746
+ `
747
+ );
748
+ }
749
+ return fallbackClient.execute(stmt);
750
+ };
751
+ adapter = {
752
+ async execute(stmt) {
753
+ if (shouldBypassPostgres(stmt)) {
754
+ return fallbackExecute(stmt);
755
+ }
756
+ try {
757
+ return await executeOnPrisma(prisma, stmt);
758
+ } catch (error) {
759
+ if (shouldFallbackOnError(error)) {
760
+ return fallbackExecute(stmt, error);
761
+ }
762
+ throw error;
763
+ }
764
+ },
765
+ async batch(stmts, mode) {
766
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
767
+ if (!fallbackClient) {
768
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
769
+ }
770
+ return fallbackClient.batch(stmts, mode);
771
+ }
772
+ try {
773
+ if (prisma.$transaction) {
774
+ return await prisma.$transaction(async (tx) => {
775
+ const results2 = [];
776
+ for (const stmt of stmts) {
777
+ results2.push(await executeOnPrisma(tx, stmt));
778
+ }
779
+ return results2;
780
+ });
781
+ }
782
+ const results = [];
783
+ for (const stmt of stmts) {
784
+ results.push(await executeOnPrisma(prisma, stmt));
785
+ }
786
+ return results;
787
+ } catch (error) {
788
+ if (fallbackClient && shouldFallbackOnError(error)) {
789
+ process.stderr.write(
790
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
791
+ `
792
+ );
793
+ return fallbackClient.batch(stmts, mode);
794
+ }
795
+ throw error;
796
+ }
797
+ },
798
+ async migrate(stmts) {
799
+ if (fallbackClient) {
800
+ return fallbackClient.migrate(stmts);
801
+ }
802
+ return adapter.batch(stmts, "deferred");
803
+ },
804
+ async transaction(mode) {
805
+ if (!fallbackClient) {
806
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
807
+ }
808
+ return fallbackClient.transaction(mode);
809
+ },
810
+ async executeMultiple(sql) {
811
+ if (fallbackClient && shouldBypassPostgres(sql)) {
812
+ return fallbackClient.executeMultiple(sql);
813
+ }
814
+ for (const statement of splitSqlStatements(sql)) {
815
+ await adapter.execute(statement);
816
+ }
817
+ },
818
+ async sync() {
819
+ if (fallbackClient) {
820
+ return fallbackClient.sync();
821
+ }
822
+ return { frame_no: 0, frames_synced: 0 };
823
+ },
824
+ close() {
825
+ closed = true;
826
+ prismaClientPromise = null;
827
+ compatibilityBootstrapPromise = null;
828
+ void prisma.$disconnect?.();
829
+ },
830
+ get closed() {
831
+ return closed;
832
+ },
833
+ get protocol() {
834
+ return "prisma-postgres";
835
+ }
836
+ };
837
+ return adapter;
838
+ }
839
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
840
+ var init_database_adapter = __esm({
841
+ "src/lib/database-adapter.ts"() {
842
+ "use strict";
843
+ VIEW_MAPPINGS = [
844
+ { view: "memories", source: "memory.memory_records" },
845
+ { view: "tasks", source: "memory.tasks" },
846
+ { view: "behaviors", source: "memory.behaviors" },
847
+ { view: "entities", source: "memory.entities" },
848
+ { view: "relationships", source: "memory.relationships" },
849
+ { view: "entity_memories", source: "memory.entity_memories" },
850
+ { view: "entity_aliases", source: "memory.entity_aliases" },
851
+ { view: "notifications", source: "memory.notifications" },
852
+ { view: "messages", source: "memory.messages" },
853
+ { view: "users", source: "wiki.users" },
854
+ { view: "workspaces", source: "wiki.workspaces" },
855
+ { view: "workspace_users", source: "wiki.workspace_users" },
856
+ { view: "documents", source: "wiki.workspace_documents" },
857
+ { view: "chats", source: "wiki.workspace_chats" }
858
+ ];
859
+ UPSERT_KEYS = {
860
+ memories: ["id"],
861
+ tasks: ["id"],
862
+ behaviors: ["id"],
863
+ entities: ["id"],
864
+ relationships: ["id"],
865
+ entity_aliases: ["alias"],
866
+ notifications: ["id"],
867
+ messages: ["id"],
868
+ users: ["id"],
869
+ workspaces: ["id"],
870
+ workspace_users: ["id"],
871
+ documents: ["id"],
872
+ chats: ["id"]
873
+ };
874
+ BOOLEAN_COLUMNS_BY_TABLE = {
875
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
876
+ behaviors: /* @__PURE__ */ new Set(["active"]),
877
+ notifications: /* @__PURE__ */ new Set(["read"]),
878
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
879
+ };
880
+ BOOLEAN_COLUMN_NAMES = new Set(
881
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
882
+ );
883
+ IMMEDIATE_FALLBACK_PATTERNS = [
884
+ /\bPRAGMA\b/i,
885
+ /\bsqlite_master\b/i,
886
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
887
+ /\bMATCH\b/i,
888
+ /\bvector_distance_cos\s*\(/i,
889
+ /\bjson_extract\s*\(/i,
890
+ /\bjulianday\s*\(/i,
891
+ /\bstrftime\s*\(/i,
892
+ /\blast_insert_rowid\s*\(/i
893
+ ];
894
+ prismaClientPromise = null;
895
+ compatibilityBootstrapPromise = null;
284
896
  }
285
897
  });
286
898
 
287
899
  // src/lib/database.ts
288
900
  import { createClient } from "@libsql/client";
289
901
  async function initDatabase(config) {
902
+ if (_walCheckpointTimer) {
903
+ clearInterval(_walCheckpointTimer);
904
+ _walCheckpointTimer = null;
905
+ }
906
+ if (_daemonClient) {
907
+ _daemonClient.close();
908
+ _daemonClient = null;
909
+ }
910
+ if (_adapterClient && _adapterClient !== _resilientClient) {
911
+ _adapterClient.close();
912
+ }
913
+ _adapterClient = null;
290
914
  if (_client) {
291
915
  _client.close();
292
916
  _client = null;
@@ -300,6 +924,7 @@ async function initDatabase(config) {
300
924
  }
301
925
  _client = createClient(opts);
302
926
  _resilientClient = wrapWithRetry(_client);
927
+ _adapterClient = _resilientClient;
303
928
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
304
929
  });
305
930
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -310,11 +935,17 @@ async function initDatabase(config) {
310
935
  });
311
936
  }, 3e4);
312
937
  _walCheckpointTimer.unref();
938
+ if (process.env.DATABASE_URL) {
939
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
940
+ }
313
941
  }
314
942
  function getClient() {
315
- if (!_resilientClient) {
943
+ if (!_adapterClient) {
316
944
  throw new Error("Database client not initialized. Call initDatabase() first.");
317
945
  }
946
+ if (process.env.DATABASE_URL) {
947
+ return _adapterClient;
948
+ }
318
949
  if (process.env.EXE_IS_DAEMON === "1") {
319
950
  return _resilientClient;
320
951
  }
@@ -607,6 +1238,7 @@ async function ensureSchema() {
607
1238
  project TEXT NOT NULL,
608
1239
  summary TEXT NOT NULL,
609
1240
  task_file TEXT,
1241
+ session_scope TEXT,
610
1242
  read INTEGER NOT NULL DEFAULT 0,
611
1243
  created_at TEXT NOT NULL
612
1244
  );
@@ -615,7 +1247,7 @@ async function ensureSchema() {
615
1247
  ON notifications(read);
616
1248
 
617
1249
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
618
- ON notifications(agent_id);
1250
+ ON notifications(agent_id, session_scope);
619
1251
 
620
1252
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
621
1253
  ON notifications(task_file);
@@ -653,6 +1285,7 @@ async function ensureSchema() {
653
1285
  target_agent TEXT NOT NULL,
654
1286
  target_project TEXT,
655
1287
  target_device TEXT NOT NULL DEFAULT 'local',
1288
+ session_scope TEXT,
656
1289
  content TEXT NOT NULL,
657
1290
  priority TEXT DEFAULT 'normal',
658
1291
  status TEXT DEFAULT 'pending',
@@ -666,10 +1299,31 @@ async function ensureSchema() {
666
1299
  );
667
1300
 
668
1301
  CREATE INDEX IF NOT EXISTS idx_messages_target
669
- ON messages(target_agent, status);
1302
+ ON messages(target_agent, session_scope, status);
670
1303
 
671
1304
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
672
- ON messages(target_agent, from_agent, server_seq);
1305
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1306
+ `);
1307
+ try {
1308
+ await client.execute({
1309
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1310
+ args: []
1311
+ });
1312
+ } catch {
1313
+ }
1314
+ try {
1315
+ await client.execute({
1316
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1317
+ args: []
1318
+ });
1319
+ } catch {
1320
+ }
1321
+ await client.executeMultiple(`
1322
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1323
+ ON notifications(agent_id, session_scope, read, created_at);
1324
+
1325
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1326
+ ON messages(target_agent, session_scope, status, created_at);
673
1327
  `);
674
1328
  try {
675
1329
  await client.execute({
@@ -1253,28 +1907,45 @@ async function ensureSchema() {
1253
1907
  } catch {
1254
1908
  }
1255
1909
  }
1910
+ try {
1911
+ await client.execute({
1912
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1913
+ args: []
1914
+ });
1915
+ } catch {
1916
+ }
1256
1917
  }
1257
1918
  async function disposeDatabase() {
1919
+ if (_walCheckpointTimer) {
1920
+ clearInterval(_walCheckpointTimer);
1921
+ _walCheckpointTimer = null;
1922
+ }
1258
1923
  if (_daemonClient) {
1259
1924
  _daemonClient.close();
1260
1925
  _daemonClient = null;
1261
1926
  }
1927
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1928
+ _adapterClient.close();
1929
+ }
1930
+ _adapterClient = null;
1262
1931
  if (_client) {
1263
1932
  _client.close();
1264
1933
  _client = null;
1265
1934
  _resilientClient = null;
1266
1935
  }
1267
1936
  }
1268
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
1937
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1269
1938
  var init_database = __esm({
1270
1939
  "src/lib/database.ts"() {
1271
1940
  "use strict";
1272
1941
  init_db_retry();
1273
1942
  init_employees();
1943
+ init_database_adapter();
1274
1944
  _client = null;
1275
1945
  _resilientClient = null;
1276
1946
  _walCheckpointTimer = null;
1277
1947
  _daemonClient = null;
1948
+ _adapterClient = null;
1278
1949
  initTurso = initDatabase;
1279
1950
  disposeTurso = disposeDatabase;
1280
1951
  }
@@ -1285,6 +1956,7 @@ var shard_manager_exports = {};
1285
1956
  __export(shard_manager_exports, {
1286
1957
  disposeShards: () => disposeShards,
1287
1958
  ensureShardSchema: () => ensureShardSchema,
1959
+ getOpenShardCount: () => getOpenShardCount,
1288
1960
  getReadyShardClient: () => getReadyShardClient,
1289
1961
  getShardClient: () => getShardClient,
1290
1962
  getShardsDir: () => getShardsDir,
@@ -1293,15 +1965,18 @@ __export(shard_manager_exports, {
1293
1965
  listShards: () => listShards,
1294
1966
  shardExists: () => shardExists
1295
1967
  });
1296
- import path4 from "path";
1297
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1968
+ import path5 from "path";
1969
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1298
1970
  import { createClient as createClient2 } from "@libsql/client";
1299
1971
  function initShardManager(encryptionKey) {
1300
1972
  _encryptionKey = encryptionKey;
1301
- if (!existsSync4(SHARDS_DIR)) {
1302
- mkdirSync(SHARDS_DIR, { recursive: true });
1973
+ if (!existsSync5(SHARDS_DIR)) {
1974
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1303
1975
  }
1304
1976
  _shardingEnabled = true;
1977
+ if (_evictionTimer) clearInterval(_evictionTimer);
1978
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
1979
+ _evictionTimer.unref();
1305
1980
  }
1306
1981
  function isShardingEnabled() {
1307
1982
  return _shardingEnabled;
@@ -1318,21 +1993,28 @@ function getShardClient(projectName) {
1318
1993
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1319
1994
  }
1320
1995
  const cached = _shards.get(safeName);
1321
- if (cached) return cached;
1322
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1996
+ if (cached) {
1997
+ _shardLastAccess.set(safeName, Date.now());
1998
+ return cached;
1999
+ }
2000
+ while (_shards.size >= MAX_OPEN_SHARDS) {
2001
+ evictLRU();
2002
+ }
2003
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1323
2004
  const client = createClient2({
1324
2005
  url: `file:${dbPath}`,
1325
2006
  encryptionKey: _encryptionKey
1326
2007
  });
1327
2008
  _shards.set(safeName, client);
2009
+ _shardLastAccess.set(safeName, Date.now());
1328
2010
  return client;
1329
2011
  }
1330
2012
  function shardExists(projectName) {
1331
2013
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1332
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2014
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1333
2015
  }
1334
2016
  function listShards() {
1335
- if (!existsSync4(SHARDS_DIR)) return [];
2017
+ if (!existsSync5(SHARDS_DIR)) return [];
1336
2018
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1337
2019
  }
1338
2020
  async function ensureShardSchema(client) {
@@ -1384,6 +2066,8 @@ async function ensureShardSchema(client) {
1384
2066
  for (const col of [
1385
2067
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1386
2068
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2069
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2070
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1387
2071
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1388
2072
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1389
2073
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1406,7 +2090,23 @@ async function ensureShardSchema(client) {
1406
2090
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1407
2091
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1408
2092
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1409
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2093
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2094
+ // Metadata enrichment columns (must match database.ts)
2095
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2096
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2097
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2098
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2099
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2100
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2101
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2102
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2103
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2104
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2105
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2106
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2107
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2108
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2109
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1410
2110
  ]) {
1411
2111
  try {
1412
2112
  await client.execute(col);
@@ -1505,21 +2205,69 @@ async function getReadyShardClient(projectName) {
1505
2205
  await ensureShardSchema(client);
1506
2206
  return client;
1507
2207
  }
2208
+ function evictLRU() {
2209
+ let oldest = null;
2210
+ let oldestTime = Infinity;
2211
+ for (const [name, time] of _shardLastAccess) {
2212
+ if (time < oldestTime) {
2213
+ oldestTime = time;
2214
+ oldest = name;
2215
+ }
2216
+ }
2217
+ if (oldest) {
2218
+ const client = _shards.get(oldest);
2219
+ if (client) {
2220
+ client.close();
2221
+ }
2222
+ _shards.delete(oldest);
2223
+ _shardLastAccess.delete(oldest);
2224
+ }
2225
+ }
2226
+ function evictIdleShards() {
2227
+ const now = Date.now();
2228
+ const toEvict = [];
2229
+ for (const [name, lastAccess] of _shardLastAccess) {
2230
+ if (now - lastAccess > SHARD_IDLE_MS) {
2231
+ toEvict.push(name);
2232
+ }
2233
+ }
2234
+ for (const name of toEvict) {
2235
+ const client = _shards.get(name);
2236
+ if (client) {
2237
+ client.close();
2238
+ }
2239
+ _shards.delete(name);
2240
+ _shardLastAccess.delete(name);
2241
+ }
2242
+ }
2243
+ function getOpenShardCount() {
2244
+ return _shards.size;
2245
+ }
1508
2246
  function disposeShards() {
2247
+ if (_evictionTimer) {
2248
+ clearInterval(_evictionTimer);
2249
+ _evictionTimer = null;
2250
+ }
1509
2251
  for (const [, client] of _shards) {
1510
2252
  client.close();
1511
2253
  }
1512
2254
  _shards.clear();
2255
+ _shardLastAccess.clear();
1513
2256
  _shardingEnabled = false;
1514
2257
  _encryptionKey = null;
1515
2258
  }
1516
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2259
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1517
2260
  var init_shard_manager = __esm({
1518
2261
  "src/lib/shard-manager.ts"() {
1519
2262
  "use strict";
1520
2263
  init_config();
1521
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2264
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2265
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2266
+ MAX_OPEN_SHARDS = 10;
2267
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1522
2268
  _shards = /* @__PURE__ */ new Map();
2269
+ _shardLastAccess = /* @__PURE__ */ new Map();
2270
+ _evictionTimer = null;
1523
2271
  _encryptionKey = null;
1524
2272
  _shardingEnabled = false;
1525
2273
  }
@@ -1718,16 +2466,16 @@ init_database();
1718
2466
 
1719
2467
  // src/lib/keychain.ts
1720
2468
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1721
- import { existsSync as existsSync3 } from "fs";
1722
- import path3 from "path";
1723
- import os3 from "os";
2469
+ import { existsSync as existsSync4 } from "fs";
2470
+ import path4 from "path";
2471
+ import os4 from "os";
1724
2472
  var SERVICE = "exe-mem";
1725
2473
  var ACCOUNT = "master-key";
1726
2474
  function getKeyDir() {
1727
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2475
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1728
2476
  }
1729
2477
  function getKeyPath() {
1730
- return path3.join(getKeyDir(), "master.key");
2478
+ return path4.join(getKeyDir(), "master.key");
1731
2479
  }
1732
2480
  async function tryKeytar() {
1733
2481
  try {
@@ -1748,9 +2496,9 @@ async function getMasterKey() {
1748
2496
  }
1749
2497
  }
1750
2498
  const keyPath = getKeyPath();
1751
- if (!existsSync3(keyPath)) {
2499
+ if (!existsSync4(keyPath)) {
1752
2500
  process.stderr.write(
1753
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2501
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1754
2502
  `
1755
2503
  );
1756
2504
  return null;
@@ -2064,8 +2812,8 @@ function vectorToBlob(vector) {
2064
2812
  init_database();
2065
2813
 
2066
2814
  // src/lib/wiki-sync.ts
2067
- async function wikiRequest(config, path5, method = "GET", body) {
2068
- const url = `${config.wikiUrl}/api/v1${path5}`;
2815
+ async function wikiRequest(config, path6, method = "GET", body) {
2816
+ const url = `${config.wikiUrl}/api/v1${path6}`;
2069
2817
  const headers = {
2070
2818
  "Authorization": `Bearer ${config.wikiApiKey}`,
2071
2819
  "Content-Type": "application/json"
@@ -2077,7 +2825,7 @@ async function wikiRequest(config, path5, method = "GET", body) {
2077
2825
  signal: AbortSignal.timeout(3e4)
2078
2826
  });
2079
2827
  if (!response.ok) {
2080
- throw new Error(`Wiki API ${method} ${path5}: ${response.status} ${response.statusText}`);
2828
+ throw new Error(`Wiki API ${method} ${path6}: ${response.status} ${response.statusText}`);
2081
2829
  }
2082
2830
  return response.json();
2083
2831
  }