@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
@@ -71,9 +71,34 @@ var init_db_retry = __esm({
71
71
  }
72
72
  });
73
73
 
74
+ // src/lib/secure-files.ts
75
+ import { chmodSync, existsSync, mkdirSync } from "fs";
76
+ import { chmod, mkdir } from "fs/promises";
77
+ async function ensurePrivateDir(dirPath) {
78
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
79
+ try {
80
+ await chmod(dirPath, PRIVATE_DIR_MODE);
81
+ } catch {
82
+ }
83
+ }
84
+ async function enforcePrivateFile(filePath) {
85
+ try {
86
+ await chmod(filePath, PRIVATE_FILE_MODE);
87
+ } catch {
88
+ }
89
+ }
90
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
91
+ var init_secure_files = __esm({
92
+ "src/lib/secure-files.ts"() {
93
+ "use strict";
94
+ PRIVATE_DIR_MODE = 448;
95
+ PRIVATE_FILE_MODE = 384;
96
+ }
97
+ });
98
+
74
99
  // src/lib/config.ts
75
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
76
- import { readFileSync, existsSync, renameSync } from "fs";
100
+ import { readFile, writeFile } from "fs/promises";
101
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
77
102
  import path from "path";
78
103
  import os from "os";
79
104
  function resolveDataDir() {
@@ -81,7 +106,7 @@ function resolveDataDir() {
81
106
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
82
107
  const newDir = path.join(os.homedir(), ".exe-os");
83
108
  const legacyDir = path.join(os.homedir(), ".exe-mem");
84
- if (!existsSync(newDir) && existsSync(legacyDir)) {
109
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
85
110
  try {
86
111
  renameSync(legacyDir, newDir);
87
112
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -144,9 +169,9 @@ function normalizeAutoUpdate(raw) {
144
169
  }
145
170
  async function loadConfig() {
146
171
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
147
- await mkdir(dir, { recursive: true });
172
+ await ensurePrivateDir(dir);
148
173
  const configPath = path.join(dir, "config.json");
149
- if (!existsSync(configPath)) {
174
+ if (!existsSync2(configPath)) {
150
175
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
151
176
  }
152
177
  const raw = await readFile(configPath, "utf-8");
@@ -159,6 +184,7 @@ async function loadConfig() {
159
184
  `);
160
185
  try {
161
186
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
187
+ await enforcePrivateFile(configPath);
162
188
  } catch {
163
189
  }
164
190
  }
@@ -178,6 +204,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
178
204
  var init_config = __esm({
179
205
  "src/lib/config.ts"() {
180
206
  "use strict";
207
+ init_secure_files();
181
208
  EXE_AI_DIR = resolveDataDir();
182
209
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
183
210
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -256,7 +283,7 @@ var init_config = __esm({
256
283
 
257
284
  // src/lib/employees.ts
258
285
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
259
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
286
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
260
287
  import { execSync } from "child_process";
261
288
  import path2 from "path";
262
289
  import os2 from "os";
@@ -273,14 +300,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
273
300
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
274
301
  }
275
302
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
276
- if (!existsSync2(employeesPath)) return [];
303
+ if (!existsSync3(employeesPath)) return [];
277
304
  try {
278
305
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
279
306
  } catch {
280
307
  return [];
281
308
  }
282
309
  }
283
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
310
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
284
311
  var init_employees = __esm({
285
312
  "src/lib/employees.ts"() {
286
313
  "use strict";
@@ -288,12 +315,609 @@ var init_employees = __esm({
288
315
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
289
316
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
290
317
  COORDINATOR_ROLE = "COO";
318
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
319
+ }
320
+ });
321
+
322
+ // src/lib/database-adapter.ts
323
+ import os3 from "os";
324
+ import path3 from "path";
325
+ import { createRequire } from "module";
326
+ import { pathToFileURL } from "url";
327
+ function quotedIdentifier(identifier) {
328
+ return `"${identifier.replace(/"/g, '""')}"`;
329
+ }
330
+ function unqualifiedTableName(name) {
331
+ const raw = name.trim().replace(/^"|"$/g, "");
332
+ const parts = raw.split(".");
333
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
334
+ }
335
+ function stripTrailingSemicolon(sql) {
336
+ return sql.trim().replace(/;+\s*$/u, "");
337
+ }
338
+ function appendClause(sql, clause) {
339
+ const trimmed = stripTrailingSemicolon(sql);
340
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
341
+ if (!returningMatch) {
342
+ return `${trimmed}${clause}`;
343
+ }
344
+ const idx = returningMatch.index;
345
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
346
+ }
347
+ function normalizeStatement(stmt) {
348
+ if (typeof stmt === "string") {
349
+ return { kind: "positional", sql: stmt, args: [] };
350
+ }
351
+ const sql = stmt.sql;
352
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
353
+ return { kind: "positional", sql, args: stmt.args ?? [] };
354
+ }
355
+ return { kind: "named", sql, args: stmt.args };
356
+ }
357
+ function rewriteBooleanLiterals(sql) {
358
+ let out = sql;
359
+ for (const column of BOOLEAN_COLUMN_NAMES) {
360
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
361
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
362
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
363
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
364
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
365
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
366
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
367
+ }
368
+ return out;
369
+ }
370
+ function rewriteInsertOrIgnore(sql) {
371
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
372
+ return sql;
373
+ }
374
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
375
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
376
+ }
377
+ function rewriteInsertOrReplace(sql) {
378
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
379
+ if (!match) {
380
+ return sql;
381
+ }
382
+ const rawTable = match[1];
383
+ const rawColumns = match[2];
384
+ const remainder = match[3];
385
+ const tableName = unqualifiedTableName(rawTable);
386
+ const conflictKeys = UPSERT_KEYS[tableName];
387
+ if (!conflictKeys?.length) {
388
+ return sql;
389
+ }
390
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
391
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
392
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
393
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
394
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
395
+ }
396
+ function rewriteSql(sql) {
397
+ let out = sql;
398
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
399
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
400
+ out = rewriteBooleanLiterals(out);
401
+ out = rewriteInsertOrReplace(out);
402
+ out = rewriteInsertOrIgnore(out);
403
+ return stripTrailingSemicolon(out);
404
+ }
405
+ function toBoolean(value) {
406
+ if (value === null || value === void 0) return value;
407
+ if (typeof value === "boolean") return value;
408
+ if (typeof value === "number") return value !== 0;
409
+ if (typeof value === "bigint") return value !== 0n;
410
+ if (typeof value === "string") {
411
+ const normalized = value.trim().toLowerCase();
412
+ if (normalized === "0" || normalized === "false") return false;
413
+ if (normalized === "1" || normalized === "true") return true;
414
+ }
415
+ return Boolean(value);
416
+ }
417
+ function countQuestionMarks(sql, end) {
418
+ let count = 0;
419
+ let inSingle = false;
420
+ let inDouble = false;
421
+ let inLineComment = false;
422
+ let inBlockComment = false;
423
+ for (let i = 0; i < end; i++) {
424
+ const ch = sql[i];
425
+ const next = sql[i + 1];
426
+ if (inLineComment) {
427
+ if (ch === "\n") inLineComment = false;
428
+ continue;
429
+ }
430
+ if (inBlockComment) {
431
+ if (ch === "*" && next === "/") {
432
+ inBlockComment = false;
433
+ i += 1;
434
+ }
435
+ continue;
436
+ }
437
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
438
+ inLineComment = true;
439
+ i += 1;
440
+ continue;
441
+ }
442
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
443
+ inBlockComment = true;
444
+ i += 1;
445
+ continue;
446
+ }
447
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
448
+ inSingle = !inSingle;
449
+ continue;
450
+ }
451
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
452
+ inDouble = !inDouble;
453
+ continue;
454
+ }
455
+ if (!inSingle && !inDouble && ch === "?") {
456
+ count += 1;
457
+ }
458
+ }
459
+ return count;
460
+ }
461
+ function findBooleanPlaceholderIndexes(sql) {
462
+ const indexes = /* @__PURE__ */ new Set();
463
+ for (const column of BOOLEAN_COLUMN_NAMES) {
464
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
465
+ for (const match of sql.matchAll(pattern)) {
466
+ const matchText = match[0];
467
+ const qIndex = match.index + matchText.lastIndexOf("?");
468
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
469
+ }
470
+ }
471
+ return indexes;
472
+ }
473
+ function coerceInsertBooleanArgs(sql, args) {
474
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
475
+ if (!match) return;
476
+ const rawTable = match[1];
477
+ const rawColumns = match[2];
478
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
479
+ if (!boolColumns?.size) return;
480
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
481
+ for (const [index, column] of columns.entries()) {
482
+ if (boolColumns.has(column) && index < args.length) {
483
+ args[index] = toBoolean(args[index]);
484
+ }
485
+ }
486
+ }
487
+ function coerceUpdateBooleanArgs(sql, args) {
488
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
489
+ if (!match) return;
490
+ const rawTable = match[1];
491
+ const setClause = match[2];
492
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
493
+ if (!boolColumns?.size) return;
494
+ const assignments = setClause.split(",");
495
+ let placeholderIndex = 0;
496
+ for (const assignment of assignments) {
497
+ if (!assignment.includes("?")) continue;
498
+ placeholderIndex += 1;
499
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
500
+ if (colMatch && boolColumns.has(colMatch[1])) {
501
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
502
+ }
503
+ }
504
+ }
505
+ function coerceBooleanArgs(sql, args) {
506
+ const nextArgs = [...args];
507
+ coerceInsertBooleanArgs(sql, nextArgs);
508
+ coerceUpdateBooleanArgs(sql, nextArgs);
509
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
510
+ for (const index of placeholderIndexes) {
511
+ if (index > 0 && index <= nextArgs.length) {
512
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
513
+ }
514
+ }
515
+ return nextArgs;
516
+ }
517
+ function convertQuestionMarksToDollarParams(sql) {
518
+ let out = "";
519
+ let placeholder = 0;
520
+ let inSingle = false;
521
+ let inDouble = false;
522
+ let inLineComment = false;
523
+ let inBlockComment = false;
524
+ for (let i = 0; i < sql.length; i++) {
525
+ const ch = sql[i];
526
+ const next = sql[i + 1];
527
+ if (inLineComment) {
528
+ out += ch;
529
+ if (ch === "\n") inLineComment = false;
530
+ continue;
531
+ }
532
+ if (inBlockComment) {
533
+ out += ch;
534
+ if (ch === "*" && next === "/") {
535
+ out += next;
536
+ inBlockComment = false;
537
+ i += 1;
538
+ }
539
+ continue;
540
+ }
541
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
542
+ out += ch + next;
543
+ inLineComment = true;
544
+ i += 1;
545
+ continue;
546
+ }
547
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
548
+ out += ch + next;
549
+ inBlockComment = true;
550
+ i += 1;
551
+ continue;
552
+ }
553
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
554
+ inSingle = !inSingle;
555
+ out += ch;
556
+ continue;
557
+ }
558
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
559
+ inDouble = !inDouble;
560
+ out += ch;
561
+ continue;
562
+ }
563
+ if (!inSingle && !inDouble && ch === "?") {
564
+ placeholder += 1;
565
+ out += `$${placeholder}`;
566
+ continue;
567
+ }
568
+ out += ch;
569
+ }
570
+ return out;
571
+ }
572
+ function translateStatementForPostgres(stmt) {
573
+ const normalized = normalizeStatement(stmt);
574
+ if (normalized.kind === "named") {
575
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
576
+ }
577
+ const rewrittenSql = rewriteSql(normalized.sql);
578
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
579
+ return {
580
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
581
+ args: coercedArgs
582
+ };
583
+ }
584
+ function shouldBypassPostgres(stmt) {
585
+ const normalized = normalizeStatement(stmt);
586
+ if (normalized.kind === "named") {
587
+ return true;
588
+ }
589
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
590
+ }
591
+ function shouldFallbackOnError(error) {
592
+ const message = error instanceof Error ? error.message : String(error);
593
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
594
+ }
595
+ function isReadQuery(sql) {
596
+ const trimmed = sql.trimStart();
597
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
598
+ }
599
+ function buildRow(row, columns) {
600
+ const values = columns.map((column) => row[column]);
601
+ return Object.assign(values, row);
602
+ }
603
+ function buildResultSet(rows, rowsAffected = 0) {
604
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
605
+ const resultRows = rows.map((row) => buildRow(row, columns));
606
+ return {
607
+ columns,
608
+ columnTypes: columns.map(() => ""),
609
+ rows: resultRows,
610
+ rowsAffected,
611
+ lastInsertRowid: void 0,
612
+ toJSON() {
613
+ return {
614
+ columns,
615
+ columnTypes: columns.map(() => ""),
616
+ rows,
617
+ rowsAffected,
618
+ lastInsertRowid: void 0
619
+ };
620
+ }
621
+ };
622
+ }
623
+ async function loadPrismaClient() {
624
+ if (!prismaClientPromise) {
625
+ prismaClientPromise = (async () => {
626
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
627
+ if (explicitPath) {
628
+ const module2 = await import(pathToFileURL(explicitPath).href);
629
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
630
+ if (!PrismaClient2) {
631
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
632
+ }
633
+ return new PrismaClient2();
634
+ }
635
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
636
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
637
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
638
+ const module = await import(pathToFileURL(prismaEntry).href);
639
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
640
+ if (!PrismaClient) {
641
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
642
+ }
643
+ return new PrismaClient();
644
+ })();
645
+ }
646
+ return prismaClientPromise;
647
+ }
648
+ async function ensureCompatibilityViews(prisma) {
649
+ if (!compatibilityBootstrapPromise) {
650
+ compatibilityBootstrapPromise = (async () => {
651
+ for (const mapping of VIEW_MAPPINGS) {
652
+ const relation = mapping.source.replace(/"/g, "");
653
+ const rows = await prisma.$queryRawUnsafe(
654
+ "SELECT to_regclass($1) AS regclass",
655
+ relation
656
+ );
657
+ if (!rows[0]?.regclass) {
658
+ continue;
659
+ }
660
+ await prisma.$executeRawUnsafe(
661
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
662
+ );
663
+ }
664
+ })();
665
+ }
666
+ return compatibilityBootstrapPromise;
667
+ }
668
+ async function executeOnPrisma(executor, stmt) {
669
+ const translated = translateStatementForPostgres(stmt);
670
+ if (isReadQuery(translated.sql)) {
671
+ const rows = await executor.$queryRawUnsafe(
672
+ translated.sql,
673
+ ...translated.args
674
+ );
675
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
676
+ }
677
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
678
+ return buildResultSet([], rowsAffected);
679
+ }
680
+ function splitSqlStatements(sql) {
681
+ const parts = [];
682
+ let current = "";
683
+ let inSingle = false;
684
+ let inDouble = false;
685
+ let inLineComment = false;
686
+ let inBlockComment = false;
687
+ for (let i = 0; i < sql.length; i++) {
688
+ const ch = sql[i];
689
+ const next = sql[i + 1];
690
+ if (inLineComment) {
691
+ current += ch;
692
+ if (ch === "\n") inLineComment = false;
693
+ continue;
694
+ }
695
+ if (inBlockComment) {
696
+ current += ch;
697
+ if (ch === "*" && next === "/") {
698
+ current += next;
699
+ inBlockComment = false;
700
+ i += 1;
701
+ }
702
+ continue;
703
+ }
704
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
705
+ current += ch + next;
706
+ inLineComment = true;
707
+ i += 1;
708
+ continue;
709
+ }
710
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
711
+ current += ch + next;
712
+ inBlockComment = true;
713
+ i += 1;
714
+ continue;
715
+ }
716
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
717
+ inSingle = !inSingle;
718
+ current += ch;
719
+ continue;
720
+ }
721
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
722
+ inDouble = !inDouble;
723
+ current += ch;
724
+ continue;
725
+ }
726
+ if (!inSingle && !inDouble && ch === ";") {
727
+ if (current.trim()) {
728
+ parts.push(current.trim());
729
+ }
730
+ current = "";
731
+ continue;
732
+ }
733
+ current += ch;
734
+ }
735
+ if (current.trim()) {
736
+ parts.push(current.trim());
737
+ }
738
+ return parts;
739
+ }
740
+ async function createPrismaDbAdapter(fallbackClient) {
741
+ const prisma = await loadPrismaClient();
742
+ await ensureCompatibilityViews(prisma);
743
+ let closed = false;
744
+ let adapter;
745
+ const fallbackExecute = async (stmt, error) => {
746
+ if (!fallbackClient) {
747
+ if (error) throw error;
748
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
749
+ }
750
+ if (error) {
751
+ process.stderr.write(
752
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
753
+ `
754
+ );
755
+ }
756
+ return fallbackClient.execute(stmt);
757
+ };
758
+ adapter = {
759
+ async execute(stmt) {
760
+ if (shouldBypassPostgres(stmt)) {
761
+ return fallbackExecute(stmt);
762
+ }
763
+ try {
764
+ return await executeOnPrisma(prisma, stmt);
765
+ } catch (error) {
766
+ if (shouldFallbackOnError(error)) {
767
+ return fallbackExecute(stmt, error);
768
+ }
769
+ throw error;
770
+ }
771
+ },
772
+ async batch(stmts, mode) {
773
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
774
+ if (!fallbackClient) {
775
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
776
+ }
777
+ return fallbackClient.batch(stmts, mode);
778
+ }
779
+ try {
780
+ if (prisma.$transaction) {
781
+ return await prisma.$transaction(async (tx) => {
782
+ const results2 = [];
783
+ for (const stmt of stmts) {
784
+ results2.push(await executeOnPrisma(tx, stmt));
785
+ }
786
+ return results2;
787
+ });
788
+ }
789
+ const results = [];
790
+ for (const stmt of stmts) {
791
+ results.push(await executeOnPrisma(prisma, stmt));
792
+ }
793
+ return results;
794
+ } catch (error) {
795
+ if (fallbackClient && shouldFallbackOnError(error)) {
796
+ process.stderr.write(
797
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
798
+ `
799
+ );
800
+ return fallbackClient.batch(stmts, mode);
801
+ }
802
+ throw error;
803
+ }
804
+ },
805
+ async migrate(stmts) {
806
+ if (fallbackClient) {
807
+ return fallbackClient.migrate(stmts);
808
+ }
809
+ return adapter.batch(stmts, "deferred");
810
+ },
811
+ async transaction(mode) {
812
+ if (!fallbackClient) {
813
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
814
+ }
815
+ return fallbackClient.transaction(mode);
816
+ },
817
+ async executeMultiple(sql) {
818
+ if (fallbackClient && shouldBypassPostgres(sql)) {
819
+ return fallbackClient.executeMultiple(sql);
820
+ }
821
+ for (const statement of splitSqlStatements(sql)) {
822
+ await adapter.execute(statement);
823
+ }
824
+ },
825
+ async sync() {
826
+ if (fallbackClient) {
827
+ return fallbackClient.sync();
828
+ }
829
+ return { frame_no: 0, frames_synced: 0 };
830
+ },
831
+ close() {
832
+ closed = true;
833
+ prismaClientPromise = null;
834
+ compatibilityBootstrapPromise = null;
835
+ void prisma.$disconnect?.();
836
+ },
837
+ get closed() {
838
+ return closed;
839
+ },
840
+ get protocol() {
841
+ return "prisma-postgres";
842
+ }
843
+ };
844
+ return adapter;
845
+ }
846
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
847
+ var init_database_adapter = __esm({
848
+ "src/lib/database-adapter.ts"() {
849
+ "use strict";
850
+ VIEW_MAPPINGS = [
851
+ { view: "memories", source: "memory.memory_records" },
852
+ { view: "tasks", source: "memory.tasks" },
853
+ { view: "behaviors", source: "memory.behaviors" },
854
+ { view: "entities", source: "memory.entities" },
855
+ { view: "relationships", source: "memory.relationships" },
856
+ { view: "entity_memories", source: "memory.entity_memories" },
857
+ { view: "entity_aliases", source: "memory.entity_aliases" },
858
+ { view: "notifications", source: "memory.notifications" },
859
+ { view: "messages", source: "memory.messages" },
860
+ { view: "users", source: "wiki.users" },
861
+ { view: "workspaces", source: "wiki.workspaces" },
862
+ { view: "workspace_users", source: "wiki.workspace_users" },
863
+ { view: "documents", source: "wiki.workspace_documents" },
864
+ { view: "chats", source: "wiki.workspace_chats" }
865
+ ];
866
+ UPSERT_KEYS = {
867
+ memories: ["id"],
868
+ tasks: ["id"],
869
+ behaviors: ["id"],
870
+ entities: ["id"],
871
+ relationships: ["id"],
872
+ entity_aliases: ["alias"],
873
+ notifications: ["id"],
874
+ messages: ["id"],
875
+ users: ["id"],
876
+ workspaces: ["id"],
877
+ workspace_users: ["id"],
878
+ documents: ["id"],
879
+ chats: ["id"]
880
+ };
881
+ BOOLEAN_COLUMNS_BY_TABLE = {
882
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
883
+ behaviors: /* @__PURE__ */ new Set(["active"]),
884
+ notifications: /* @__PURE__ */ new Set(["read"]),
885
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
886
+ };
887
+ BOOLEAN_COLUMN_NAMES = new Set(
888
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
889
+ );
890
+ IMMEDIATE_FALLBACK_PATTERNS = [
891
+ /\bPRAGMA\b/i,
892
+ /\bsqlite_master\b/i,
893
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
894
+ /\bMATCH\b/i,
895
+ /\bvector_distance_cos\s*\(/i,
896
+ /\bjson_extract\s*\(/i,
897
+ /\bjulianday\s*\(/i,
898
+ /\bstrftime\s*\(/i,
899
+ /\blast_insert_rowid\s*\(/i
900
+ ];
901
+ prismaClientPromise = null;
902
+ compatibilityBootstrapPromise = null;
291
903
  }
292
904
  });
293
905
 
294
906
  // src/lib/database.ts
295
907
  import { createClient } from "@libsql/client";
296
908
  async function initDatabase(config) {
909
+ if (_walCheckpointTimer) {
910
+ clearInterval(_walCheckpointTimer);
911
+ _walCheckpointTimer = null;
912
+ }
913
+ if (_daemonClient) {
914
+ _daemonClient.close();
915
+ _daemonClient = null;
916
+ }
917
+ if (_adapterClient && _adapterClient !== _resilientClient) {
918
+ _adapterClient.close();
919
+ }
920
+ _adapterClient = null;
297
921
  if (_client) {
298
922
  _client.close();
299
923
  _client = null;
@@ -307,6 +931,7 @@ async function initDatabase(config) {
307
931
  }
308
932
  _client = createClient(opts);
309
933
  _resilientClient = wrapWithRetry(_client);
934
+ _adapterClient = _resilientClient;
310
935
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
311
936
  });
312
937
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -317,11 +942,17 @@ async function initDatabase(config) {
317
942
  });
318
943
  }, 3e4);
319
944
  _walCheckpointTimer.unref();
945
+ if (process.env.DATABASE_URL) {
946
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
947
+ }
320
948
  }
321
949
  function getClient() {
322
- if (!_resilientClient) {
950
+ if (!_adapterClient) {
323
951
  throw new Error("Database client not initialized. Call initDatabase() first.");
324
952
  }
953
+ if (process.env.DATABASE_URL) {
954
+ return _adapterClient;
955
+ }
325
956
  if (process.env.EXE_IS_DAEMON === "1") {
326
957
  return _resilientClient;
327
958
  }
@@ -614,6 +1245,7 @@ async function ensureSchema() {
614
1245
  project TEXT NOT NULL,
615
1246
  summary TEXT NOT NULL,
616
1247
  task_file TEXT,
1248
+ session_scope TEXT,
617
1249
  read INTEGER NOT NULL DEFAULT 0,
618
1250
  created_at TEXT NOT NULL
619
1251
  );
@@ -622,7 +1254,7 @@ async function ensureSchema() {
622
1254
  ON notifications(read);
623
1255
 
624
1256
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
625
- ON notifications(agent_id);
1257
+ ON notifications(agent_id, session_scope);
626
1258
 
627
1259
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
628
1260
  ON notifications(task_file);
@@ -660,6 +1292,7 @@ async function ensureSchema() {
660
1292
  target_agent TEXT NOT NULL,
661
1293
  target_project TEXT,
662
1294
  target_device TEXT NOT NULL DEFAULT 'local',
1295
+ session_scope TEXT,
663
1296
  content TEXT NOT NULL,
664
1297
  priority TEXT DEFAULT 'normal',
665
1298
  status TEXT DEFAULT 'pending',
@@ -673,10 +1306,31 @@ async function ensureSchema() {
673
1306
  );
674
1307
 
675
1308
  CREATE INDEX IF NOT EXISTS idx_messages_target
676
- ON messages(target_agent, status);
1309
+ ON messages(target_agent, session_scope, status);
677
1310
 
678
1311
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
679
- ON messages(target_agent, from_agent, server_seq);
1312
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1313
+ `);
1314
+ try {
1315
+ await client.execute({
1316
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1317
+ args: []
1318
+ });
1319
+ } catch {
1320
+ }
1321
+ try {
1322
+ await client.execute({
1323
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1324
+ args: []
1325
+ });
1326
+ } catch {
1327
+ }
1328
+ await client.executeMultiple(`
1329
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1330
+ ON notifications(agent_id, session_scope, read, created_at);
1331
+
1332
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1333
+ ON messages(target_agent, session_scope, status, created_at);
680
1334
  `);
681
1335
  try {
682
1336
  await client.execute({
@@ -1260,31 +1914,40 @@ async function ensureSchema() {
1260
1914
  } catch {
1261
1915
  }
1262
1916
  }
1917
+ try {
1918
+ await client.execute({
1919
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1920
+ args: []
1921
+ });
1922
+ } catch {
1923
+ }
1263
1924
  }
1264
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1925
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1265
1926
  var init_database = __esm({
1266
1927
  "src/lib/database.ts"() {
1267
1928
  "use strict";
1268
1929
  init_db_retry();
1269
1930
  init_employees();
1931
+ init_database_adapter();
1270
1932
  _client = null;
1271
1933
  _resilientClient = null;
1272
1934
  _walCheckpointTimer = null;
1273
1935
  _daemonClient = null;
1936
+ _adapterClient = null;
1274
1937
  initTurso = initDatabase;
1275
1938
  }
1276
1939
  });
1277
1940
 
1278
1941
  // src/lib/keychain.ts
1279
1942
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1280
- import { existsSync as existsSync3 } from "fs";
1281
- import path3 from "path";
1282
- import os3 from "os";
1943
+ import { existsSync as existsSync4 } from "fs";
1944
+ import path4 from "path";
1945
+ import os4 from "os";
1283
1946
  function getKeyDir() {
1284
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
1947
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1285
1948
  }
1286
1949
  function getKeyPath() {
1287
- return path3.join(getKeyDir(), "master.key");
1950
+ return path4.join(getKeyDir(), "master.key");
1288
1951
  }
1289
1952
  async function tryKeytar() {
1290
1953
  try {
@@ -1305,9 +1968,9 @@ async function getMasterKey() {
1305
1968
  }
1306
1969
  }
1307
1970
  const keyPath = getKeyPath();
1308
- if (!existsSync3(keyPath)) {
1971
+ if (!existsSync4(keyPath)) {
1309
1972
  process.stderr.write(
1310
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1973
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1311
1974
  `
1312
1975
  );
1313
1976
  return null;
@@ -1392,6 +2055,7 @@ var shard_manager_exports = {};
1392
2055
  __export(shard_manager_exports, {
1393
2056
  disposeShards: () => disposeShards,
1394
2057
  ensureShardSchema: () => ensureShardSchema,
2058
+ getOpenShardCount: () => getOpenShardCount,
1395
2059
  getReadyShardClient: () => getReadyShardClient,
1396
2060
  getShardClient: () => getShardClient,
1397
2061
  getShardsDir: () => getShardsDir,
@@ -1400,15 +2064,18 @@ __export(shard_manager_exports, {
1400
2064
  listShards: () => listShards,
1401
2065
  shardExists: () => shardExists
1402
2066
  });
1403
- import path4 from "path";
1404
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
2067
+ import path5 from "path";
2068
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1405
2069
  import { createClient as createClient2 } from "@libsql/client";
1406
2070
  function initShardManager(encryptionKey) {
1407
2071
  _encryptionKey = encryptionKey;
1408
- if (!existsSync4(SHARDS_DIR)) {
1409
- mkdirSync(SHARDS_DIR, { recursive: true });
2072
+ if (!existsSync5(SHARDS_DIR)) {
2073
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1410
2074
  }
1411
2075
  _shardingEnabled = true;
2076
+ if (_evictionTimer) clearInterval(_evictionTimer);
2077
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2078
+ _evictionTimer.unref();
1412
2079
  }
1413
2080
  function isShardingEnabled() {
1414
2081
  return _shardingEnabled;
@@ -1425,21 +2092,28 @@ function getShardClient(projectName) {
1425
2092
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1426
2093
  }
1427
2094
  const cached = _shards.get(safeName);
1428
- if (cached) return cached;
1429
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
2095
+ if (cached) {
2096
+ _shardLastAccess.set(safeName, Date.now());
2097
+ return cached;
2098
+ }
2099
+ while (_shards.size >= MAX_OPEN_SHARDS) {
2100
+ evictLRU();
2101
+ }
2102
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1430
2103
  const client = createClient2({
1431
2104
  url: `file:${dbPath}`,
1432
2105
  encryptionKey: _encryptionKey
1433
2106
  });
1434
2107
  _shards.set(safeName, client);
2108
+ _shardLastAccess.set(safeName, Date.now());
1435
2109
  return client;
1436
2110
  }
1437
2111
  function shardExists(projectName) {
1438
2112
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1439
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2113
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1440
2114
  }
1441
2115
  function listShards() {
1442
- if (!existsSync4(SHARDS_DIR)) return [];
2116
+ if (!existsSync5(SHARDS_DIR)) return [];
1443
2117
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1444
2118
  }
1445
2119
  async function ensureShardSchema(client) {
@@ -1491,6 +2165,8 @@ async function ensureShardSchema(client) {
1491
2165
  for (const col of [
1492
2166
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1493
2167
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2168
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2169
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1494
2170
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1495
2171
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1496
2172
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1513,7 +2189,23 @@ async function ensureShardSchema(client) {
1513
2189
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1514
2190
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1515
2191
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1516
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2192
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2193
+ // Metadata enrichment columns (must match database.ts)
2194
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2195
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2196
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2197
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2198
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2199
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2200
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2201
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2202
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2203
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2204
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2205
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2206
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2207
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2208
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1517
2209
  ]) {
1518
2210
  try {
1519
2211
  await client.execute(col);
@@ -1612,21 +2304,69 @@ async function getReadyShardClient(projectName) {
1612
2304
  await ensureShardSchema(client);
1613
2305
  return client;
1614
2306
  }
2307
+ function evictLRU() {
2308
+ let oldest = null;
2309
+ let oldestTime = Infinity;
2310
+ for (const [name, time] of _shardLastAccess) {
2311
+ if (time < oldestTime) {
2312
+ oldestTime = time;
2313
+ oldest = name;
2314
+ }
2315
+ }
2316
+ if (oldest) {
2317
+ const client = _shards.get(oldest);
2318
+ if (client) {
2319
+ client.close();
2320
+ }
2321
+ _shards.delete(oldest);
2322
+ _shardLastAccess.delete(oldest);
2323
+ }
2324
+ }
2325
+ function evictIdleShards() {
2326
+ const now = Date.now();
2327
+ const toEvict = [];
2328
+ for (const [name, lastAccess] of _shardLastAccess) {
2329
+ if (now - lastAccess > SHARD_IDLE_MS) {
2330
+ toEvict.push(name);
2331
+ }
2332
+ }
2333
+ for (const name of toEvict) {
2334
+ const client = _shards.get(name);
2335
+ if (client) {
2336
+ client.close();
2337
+ }
2338
+ _shards.delete(name);
2339
+ _shardLastAccess.delete(name);
2340
+ }
2341
+ }
2342
+ function getOpenShardCount() {
2343
+ return _shards.size;
2344
+ }
1615
2345
  function disposeShards() {
2346
+ if (_evictionTimer) {
2347
+ clearInterval(_evictionTimer);
2348
+ _evictionTimer = null;
2349
+ }
1616
2350
  for (const [, client] of _shards) {
1617
2351
  client.close();
1618
2352
  }
1619
2353
  _shards.clear();
2354
+ _shardLastAccess.clear();
1620
2355
  _shardingEnabled = false;
1621
2356
  _encryptionKey = null;
1622
2357
  }
1623
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2358
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1624
2359
  var init_shard_manager = __esm({
1625
2360
  "src/lib/shard-manager.ts"() {
1626
2361
  "use strict";
1627
2362
  init_config();
1628
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2363
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2364
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2365
+ MAX_OPEN_SHARDS = 10;
2366
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1629
2367
  _shards = /* @__PURE__ */ new Map();
2368
+ _shardLastAccess = /* @__PURE__ */ new Map();
2369
+ _evictionTimer = null;
1630
2370
  _encryptionKey = null;
1631
2371
  _shardingEnabled = false;
1632
2372
  }