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