@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
@@ -70,9 +70,34 @@ var init_db_retry = __esm({
70
70
  }
71
71
  });
72
72
 
73
+ // src/lib/secure-files.ts
74
+ import { chmodSync, existsSync, mkdirSync } from "fs";
75
+ import { chmod, mkdir } from "fs/promises";
76
+ async function ensurePrivateDir(dirPath) {
77
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
78
+ try {
79
+ await chmod(dirPath, PRIVATE_DIR_MODE);
80
+ } catch {
81
+ }
82
+ }
83
+ async function enforcePrivateFile(filePath) {
84
+ try {
85
+ await chmod(filePath, PRIVATE_FILE_MODE);
86
+ } catch {
87
+ }
88
+ }
89
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
90
+ var init_secure_files = __esm({
91
+ "src/lib/secure-files.ts"() {
92
+ "use strict";
93
+ PRIVATE_DIR_MODE = 448;
94
+ PRIVATE_FILE_MODE = 384;
95
+ }
96
+ });
97
+
73
98
  // src/lib/config.ts
74
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
75
- import { readFileSync, existsSync, renameSync } from "fs";
99
+ import { readFile, writeFile } from "fs/promises";
100
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
76
101
  import path from "path";
77
102
  import os from "os";
78
103
  function resolveDataDir() {
@@ -80,7 +105,7 @@ function resolveDataDir() {
80
105
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
81
106
  const newDir = path.join(os.homedir(), ".exe-os");
82
107
  const legacyDir = path.join(os.homedir(), ".exe-mem");
83
- if (!existsSync(newDir) && existsSync(legacyDir)) {
108
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
84
109
  try {
85
110
  renameSync(legacyDir, newDir);
86
111
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -143,9 +168,9 @@ function normalizeAutoUpdate(raw) {
143
168
  }
144
169
  async function loadConfig() {
145
170
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
146
- await mkdir(dir, { recursive: true });
171
+ await ensurePrivateDir(dir);
147
172
  const configPath = path.join(dir, "config.json");
148
- if (!existsSync(configPath)) {
173
+ if (!existsSync2(configPath)) {
149
174
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
150
175
  }
151
176
  const raw = await readFile(configPath, "utf-8");
@@ -158,6 +183,7 @@ async function loadConfig() {
158
183
  `);
159
184
  try {
160
185
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
186
+ await enforcePrivateFile(configPath);
161
187
  } catch {
162
188
  }
163
189
  }
@@ -177,6 +203,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
177
203
  var init_config = __esm({
178
204
  "src/lib/config.ts"() {
179
205
  "use strict";
206
+ init_secure_files();
180
207
  EXE_AI_DIR = resolveDataDir();
181
208
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
182
209
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -255,7 +282,7 @@ var init_config = __esm({
255
282
 
256
283
  // src/lib/employees.ts
257
284
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
258
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
285
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
259
286
  import { execSync } from "child_process";
260
287
  import path2 from "path";
261
288
  import os2 from "os";
@@ -272,14 +299,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
272
299
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
273
300
  }
274
301
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
275
- if (!existsSync2(employeesPath)) return [];
302
+ if (!existsSync3(employeesPath)) return [];
276
303
  try {
277
304
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
278
305
  } catch {
279
306
  return [];
280
307
  }
281
308
  }
282
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
309
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
283
310
  var init_employees = __esm({
284
311
  "src/lib/employees.ts"() {
285
312
  "use strict";
@@ -287,12 +314,609 @@ var init_employees = __esm({
287
314
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
288
315
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
289
316
  COORDINATOR_ROLE = "COO";
317
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
318
+ }
319
+ });
320
+
321
+ // src/lib/database-adapter.ts
322
+ import os3 from "os";
323
+ import path3 from "path";
324
+ import { createRequire } from "module";
325
+ import { pathToFileURL } from "url";
326
+ function quotedIdentifier(identifier) {
327
+ return `"${identifier.replace(/"/g, '""')}"`;
328
+ }
329
+ function unqualifiedTableName(name) {
330
+ const raw = name.trim().replace(/^"|"$/g, "");
331
+ const parts = raw.split(".");
332
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
333
+ }
334
+ function stripTrailingSemicolon(sql) {
335
+ return sql.trim().replace(/;+\s*$/u, "");
336
+ }
337
+ function appendClause(sql, clause) {
338
+ const trimmed = stripTrailingSemicolon(sql);
339
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
340
+ if (!returningMatch) {
341
+ return `${trimmed}${clause}`;
342
+ }
343
+ const idx = returningMatch.index;
344
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
345
+ }
346
+ function normalizeStatement(stmt) {
347
+ if (typeof stmt === "string") {
348
+ return { kind: "positional", sql: stmt, args: [] };
349
+ }
350
+ const sql = stmt.sql;
351
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
352
+ return { kind: "positional", sql, args: stmt.args ?? [] };
353
+ }
354
+ return { kind: "named", sql, args: stmt.args };
355
+ }
356
+ function rewriteBooleanLiterals(sql) {
357
+ let out = sql;
358
+ for (const column of BOOLEAN_COLUMN_NAMES) {
359
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
360
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
361
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
362
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
363
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
364
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
365
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
366
+ }
367
+ return out;
368
+ }
369
+ function rewriteInsertOrIgnore(sql) {
370
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
371
+ return sql;
372
+ }
373
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
374
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
375
+ }
376
+ function rewriteInsertOrReplace(sql) {
377
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
378
+ if (!match) {
379
+ return sql;
380
+ }
381
+ const rawTable = match[1];
382
+ const rawColumns = match[2];
383
+ const remainder = match[3];
384
+ const tableName = unqualifiedTableName(rawTable);
385
+ const conflictKeys = UPSERT_KEYS[tableName];
386
+ if (!conflictKeys?.length) {
387
+ return sql;
388
+ }
389
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
390
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
391
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
392
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
393
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
394
+ }
395
+ function rewriteSql(sql) {
396
+ let out = sql;
397
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
398
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
399
+ out = rewriteBooleanLiterals(out);
400
+ out = rewriteInsertOrReplace(out);
401
+ out = rewriteInsertOrIgnore(out);
402
+ return stripTrailingSemicolon(out);
403
+ }
404
+ function toBoolean(value) {
405
+ if (value === null || value === void 0) return value;
406
+ if (typeof value === "boolean") return value;
407
+ if (typeof value === "number") return value !== 0;
408
+ if (typeof value === "bigint") return value !== 0n;
409
+ if (typeof value === "string") {
410
+ const normalized = value.trim().toLowerCase();
411
+ if (normalized === "0" || normalized === "false") return false;
412
+ if (normalized === "1" || normalized === "true") return true;
413
+ }
414
+ return Boolean(value);
415
+ }
416
+ function countQuestionMarks(sql, end) {
417
+ let count = 0;
418
+ let inSingle = false;
419
+ let inDouble = false;
420
+ let inLineComment = false;
421
+ let inBlockComment = false;
422
+ for (let i = 0; i < end; i++) {
423
+ const ch = sql[i];
424
+ const next = sql[i + 1];
425
+ if (inLineComment) {
426
+ if (ch === "\n") inLineComment = false;
427
+ continue;
428
+ }
429
+ if (inBlockComment) {
430
+ if (ch === "*" && next === "/") {
431
+ inBlockComment = false;
432
+ i += 1;
433
+ }
434
+ continue;
435
+ }
436
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
437
+ inLineComment = true;
438
+ i += 1;
439
+ continue;
440
+ }
441
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
442
+ inBlockComment = true;
443
+ i += 1;
444
+ continue;
445
+ }
446
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
447
+ inSingle = !inSingle;
448
+ continue;
449
+ }
450
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
451
+ inDouble = !inDouble;
452
+ continue;
453
+ }
454
+ if (!inSingle && !inDouble && ch === "?") {
455
+ count += 1;
456
+ }
457
+ }
458
+ return count;
459
+ }
460
+ function findBooleanPlaceholderIndexes(sql) {
461
+ const indexes = /* @__PURE__ */ new Set();
462
+ for (const column of BOOLEAN_COLUMN_NAMES) {
463
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
464
+ for (const match of sql.matchAll(pattern)) {
465
+ const matchText = match[0];
466
+ const qIndex = match.index + matchText.lastIndexOf("?");
467
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
468
+ }
469
+ }
470
+ return indexes;
471
+ }
472
+ function coerceInsertBooleanArgs(sql, args) {
473
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
474
+ if (!match) return;
475
+ const rawTable = match[1];
476
+ const rawColumns = match[2];
477
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
478
+ if (!boolColumns?.size) return;
479
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
480
+ for (const [index, column] of columns.entries()) {
481
+ if (boolColumns.has(column) && index < args.length) {
482
+ args[index] = toBoolean(args[index]);
483
+ }
484
+ }
485
+ }
486
+ function coerceUpdateBooleanArgs(sql, args) {
487
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
488
+ if (!match) return;
489
+ const rawTable = match[1];
490
+ const setClause = match[2];
491
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
492
+ if (!boolColumns?.size) return;
493
+ const assignments = setClause.split(",");
494
+ let placeholderIndex = 0;
495
+ for (const assignment of assignments) {
496
+ if (!assignment.includes("?")) continue;
497
+ placeholderIndex += 1;
498
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
499
+ if (colMatch && boolColumns.has(colMatch[1])) {
500
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
501
+ }
502
+ }
503
+ }
504
+ function coerceBooleanArgs(sql, args) {
505
+ const nextArgs = [...args];
506
+ coerceInsertBooleanArgs(sql, nextArgs);
507
+ coerceUpdateBooleanArgs(sql, nextArgs);
508
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
509
+ for (const index of placeholderIndexes) {
510
+ if (index > 0 && index <= nextArgs.length) {
511
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
512
+ }
513
+ }
514
+ return nextArgs;
515
+ }
516
+ function convertQuestionMarksToDollarParams(sql) {
517
+ let out = "";
518
+ let placeholder = 0;
519
+ let inSingle = false;
520
+ let inDouble = false;
521
+ let inLineComment = false;
522
+ let inBlockComment = false;
523
+ for (let i = 0; i < sql.length; i++) {
524
+ const ch = sql[i];
525
+ const next = sql[i + 1];
526
+ if (inLineComment) {
527
+ out += ch;
528
+ if (ch === "\n") inLineComment = false;
529
+ continue;
530
+ }
531
+ if (inBlockComment) {
532
+ out += ch;
533
+ if (ch === "*" && next === "/") {
534
+ out += next;
535
+ inBlockComment = false;
536
+ i += 1;
537
+ }
538
+ continue;
539
+ }
540
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
541
+ out += ch + next;
542
+ inLineComment = true;
543
+ i += 1;
544
+ continue;
545
+ }
546
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
547
+ out += ch + next;
548
+ inBlockComment = true;
549
+ i += 1;
550
+ continue;
551
+ }
552
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
553
+ inSingle = !inSingle;
554
+ out += ch;
555
+ continue;
556
+ }
557
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
558
+ inDouble = !inDouble;
559
+ out += ch;
560
+ continue;
561
+ }
562
+ if (!inSingle && !inDouble && ch === "?") {
563
+ placeholder += 1;
564
+ out += `$${placeholder}`;
565
+ continue;
566
+ }
567
+ out += ch;
568
+ }
569
+ return out;
570
+ }
571
+ function translateStatementForPostgres(stmt) {
572
+ const normalized = normalizeStatement(stmt);
573
+ if (normalized.kind === "named") {
574
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
575
+ }
576
+ const rewrittenSql = rewriteSql(normalized.sql);
577
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
578
+ return {
579
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
580
+ args: coercedArgs
581
+ };
582
+ }
583
+ function shouldBypassPostgres(stmt) {
584
+ const normalized = normalizeStatement(stmt);
585
+ if (normalized.kind === "named") {
586
+ return true;
587
+ }
588
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
589
+ }
590
+ function shouldFallbackOnError(error) {
591
+ const message = error instanceof Error ? error.message : String(error);
592
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
593
+ }
594
+ function isReadQuery(sql) {
595
+ const trimmed = sql.trimStart();
596
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
597
+ }
598
+ function buildRow(row, columns) {
599
+ const values = columns.map((column) => row[column]);
600
+ return Object.assign(values, row);
601
+ }
602
+ function buildResultSet(rows, rowsAffected = 0) {
603
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
604
+ const resultRows = rows.map((row) => buildRow(row, columns));
605
+ return {
606
+ columns,
607
+ columnTypes: columns.map(() => ""),
608
+ rows: resultRows,
609
+ rowsAffected,
610
+ lastInsertRowid: void 0,
611
+ toJSON() {
612
+ return {
613
+ columns,
614
+ columnTypes: columns.map(() => ""),
615
+ rows,
616
+ rowsAffected,
617
+ lastInsertRowid: void 0
618
+ };
619
+ }
620
+ };
621
+ }
622
+ async function loadPrismaClient() {
623
+ if (!prismaClientPromise) {
624
+ prismaClientPromise = (async () => {
625
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
626
+ if (explicitPath) {
627
+ const module2 = await import(pathToFileURL(explicitPath).href);
628
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
629
+ if (!PrismaClient2) {
630
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
631
+ }
632
+ return new PrismaClient2();
633
+ }
634
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
635
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
636
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
637
+ const module = await import(pathToFileURL(prismaEntry).href);
638
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
639
+ if (!PrismaClient) {
640
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
641
+ }
642
+ return new PrismaClient();
643
+ })();
644
+ }
645
+ return prismaClientPromise;
646
+ }
647
+ async function ensureCompatibilityViews(prisma) {
648
+ if (!compatibilityBootstrapPromise) {
649
+ compatibilityBootstrapPromise = (async () => {
650
+ for (const mapping of VIEW_MAPPINGS) {
651
+ const relation = mapping.source.replace(/"/g, "");
652
+ const rows = await prisma.$queryRawUnsafe(
653
+ "SELECT to_regclass($1) AS regclass",
654
+ relation
655
+ );
656
+ if (!rows[0]?.regclass) {
657
+ continue;
658
+ }
659
+ await prisma.$executeRawUnsafe(
660
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
661
+ );
662
+ }
663
+ })();
664
+ }
665
+ return compatibilityBootstrapPromise;
666
+ }
667
+ async function executeOnPrisma(executor, stmt) {
668
+ const translated = translateStatementForPostgres(stmt);
669
+ if (isReadQuery(translated.sql)) {
670
+ const rows = await executor.$queryRawUnsafe(
671
+ translated.sql,
672
+ ...translated.args
673
+ );
674
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
675
+ }
676
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
677
+ return buildResultSet([], rowsAffected);
678
+ }
679
+ function splitSqlStatements(sql) {
680
+ const parts = [];
681
+ let current = "";
682
+ let inSingle = false;
683
+ let inDouble = false;
684
+ let inLineComment = false;
685
+ let inBlockComment = false;
686
+ for (let i = 0; i < sql.length; i++) {
687
+ const ch = sql[i];
688
+ const next = sql[i + 1];
689
+ if (inLineComment) {
690
+ current += ch;
691
+ if (ch === "\n") inLineComment = false;
692
+ continue;
693
+ }
694
+ if (inBlockComment) {
695
+ current += ch;
696
+ if (ch === "*" && next === "/") {
697
+ current += next;
698
+ inBlockComment = false;
699
+ i += 1;
700
+ }
701
+ continue;
702
+ }
703
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
704
+ current += ch + next;
705
+ inLineComment = true;
706
+ i += 1;
707
+ continue;
708
+ }
709
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
710
+ current += ch + next;
711
+ inBlockComment = true;
712
+ i += 1;
713
+ continue;
714
+ }
715
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
716
+ inSingle = !inSingle;
717
+ current += ch;
718
+ continue;
719
+ }
720
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
721
+ inDouble = !inDouble;
722
+ current += ch;
723
+ continue;
724
+ }
725
+ if (!inSingle && !inDouble && ch === ";") {
726
+ if (current.trim()) {
727
+ parts.push(current.trim());
728
+ }
729
+ current = "";
730
+ continue;
731
+ }
732
+ current += ch;
733
+ }
734
+ if (current.trim()) {
735
+ parts.push(current.trim());
736
+ }
737
+ return parts;
738
+ }
739
+ async function createPrismaDbAdapter(fallbackClient) {
740
+ const prisma = await loadPrismaClient();
741
+ await ensureCompatibilityViews(prisma);
742
+ let closed = false;
743
+ let adapter;
744
+ const fallbackExecute = async (stmt, error) => {
745
+ if (!fallbackClient) {
746
+ if (error) throw error;
747
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
748
+ }
749
+ if (error) {
750
+ process.stderr.write(
751
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
752
+ `
753
+ );
754
+ }
755
+ return fallbackClient.execute(stmt);
756
+ };
757
+ adapter = {
758
+ async execute(stmt) {
759
+ if (shouldBypassPostgres(stmt)) {
760
+ return fallbackExecute(stmt);
761
+ }
762
+ try {
763
+ return await executeOnPrisma(prisma, stmt);
764
+ } catch (error) {
765
+ if (shouldFallbackOnError(error)) {
766
+ return fallbackExecute(stmt, error);
767
+ }
768
+ throw error;
769
+ }
770
+ },
771
+ async batch(stmts, mode) {
772
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
773
+ if (!fallbackClient) {
774
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
775
+ }
776
+ return fallbackClient.batch(stmts, mode);
777
+ }
778
+ try {
779
+ if (prisma.$transaction) {
780
+ return await prisma.$transaction(async (tx) => {
781
+ const results2 = [];
782
+ for (const stmt of stmts) {
783
+ results2.push(await executeOnPrisma(tx, stmt));
784
+ }
785
+ return results2;
786
+ });
787
+ }
788
+ const results = [];
789
+ for (const stmt of stmts) {
790
+ results.push(await executeOnPrisma(prisma, stmt));
791
+ }
792
+ return results;
793
+ } catch (error) {
794
+ if (fallbackClient && shouldFallbackOnError(error)) {
795
+ process.stderr.write(
796
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
797
+ `
798
+ );
799
+ return fallbackClient.batch(stmts, mode);
800
+ }
801
+ throw error;
802
+ }
803
+ },
804
+ async migrate(stmts) {
805
+ if (fallbackClient) {
806
+ return fallbackClient.migrate(stmts);
807
+ }
808
+ return adapter.batch(stmts, "deferred");
809
+ },
810
+ async transaction(mode) {
811
+ if (!fallbackClient) {
812
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
813
+ }
814
+ return fallbackClient.transaction(mode);
815
+ },
816
+ async executeMultiple(sql) {
817
+ if (fallbackClient && shouldBypassPostgres(sql)) {
818
+ return fallbackClient.executeMultiple(sql);
819
+ }
820
+ for (const statement of splitSqlStatements(sql)) {
821
+ await adapter.execute(statement);
822
+ }
823
+ },
824
+ async sync() {
825
+ if (fallbackClient) {
826
+ return fallbackClient.sync();
827
+ }
828
+ return { frame_no: 0, frames_synced: 0 };
829
+ },
830
+ close() {
831
+ closed = true;
832
+ prismaClientPromise = null;
833
+ compatibilityBootstrapPromise = null;
834
+ void prisma.$disconnect?.();
835
+ },
836
+ get closed() {
837
+ return closed;
838
+ },
839
+ get protocol() {
840
+ return "prisma-postgres";
841
+ }
842
+ };
843
+ return adapter;
844
+ }
845
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
846
+ var init_database_adapter = __esm({
847
+ "src/lib/database-adapter.ts"() {
848
+ "use strict";
849
+ VIEW_MAPPINGS = [
850
+ { view: "memories", source: "memory.memory_records" },
851
+ { view: "tasks", source: "memory.tasks" },
852
+ { view: "behaviors", source: "memory.behaviors" },
853
+ { view: "entities", source: "memory.entities" },
854
+ { view: "relationships", source: "memory.relationships" },
855
+ { view: "entity_memories", source: "memory.entity_memories" },
856
+ { view: "entity_aliases", source: "memory.entity_aliases" },
857
+ { view: "notifications", source: "memory.notifications" },
858
+ { view: "messages", source: "memory.messages" },
859
+ { view: "users", source: "wiki.users" },
860
+ { view: "workspaces", source: "wiki.workspaces" },
861
+ { view: "workspace_users", source: "wiki.workspace_users" },
862
+ { view: "documents", source: "wiki.workspace_documents" },
863
+ { view: "chats", source: "wiki.workspace_chats" }
864
+ ];
865
+ UPSERT_KEYS = {
866
+ memories: ["id"],
867
+ tasks: ["id"],
868
+ behaviors: ["id"],
869
+ entities: ["id"],
870
+ relationships: ["id"],
871
+ entity_aliases: ["alias"],
872
+ notifications: ["id"],
873
+ messages: ["id"],
874
+ users: ["id"],
875
+ workspaces: ["id"],
876
+ workspace_users: ["id"],
877
+ documents: ["id"],
878
+ chats: ["id"]
879
+ };
880
+ BOOLEAN_COLUMNS_BY_TABLE = {
881
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
882
+ behaviors: /* @__PURE__ */ new Set(["active"]),
883
+ notifications: /* @__PURE__ */ new Set(["read"]),
884
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
885
+ };
886
+ BOOLEAN_COLUMN_NAMES = new Set(
887
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
888
+ );
889
+ IMMEDIATE_FALLBACK_PATTERNS = [
890
+ /\bPRAGMA\b/i,
891
+ /\bsqlite_master\b/i,
892
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
893
+ /\bMATCH\b/i,
894
+ /\bvector_distance_cos\s*\(/i,
895
+ /\bjson_extract\s*\(/i,
896
+ /\bjulianday\s*\(/i,
897
+ /\bstrftime\s*\(/i,
898
+ /\blast_insert_rowid\s*\(/i
899
+ ];
900
+ prismaClientPromise = null;
901
+ compatibilityBootstrapPromise = null;
290
902
  }
291
903
  });
292
904
 
293
905
  // src/lib/database.ts
294
906
  import { createClient } from "@libsql/client";
295
907
  async function initDatabase(config) {
908
+ if (_walCheckpointTimer) {
909
+ clearInterval(_walCheckpointTimer);
910
+ _walCheckpointTimer = null;
911
+ }
912
+ if (_daemonClient) {
913
+ _daemonClient.close();
914
+ _daemonClient = null;
915
+ }
916
+ if (_adapterClient && _adapterClient !== _resilientClient) {
917
+ _adapterClient.close();
918
+ }
919
+ _adapterClient = null;
296
920
  if (_client) {
297
921
  _client.close();
298
922
  _client = null;
@@ -306,6 +930,7 @@ async function initDatabase(config) {
306
930
  }
307
931
  _client = createClient(opts);
308
932
  _resilientClient = wrapWithRetry(_client);
933
+ _adapterClient = _resilientClient;
309
934
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
310
935
  });
311
936
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -316,11 +941,17 @@ async function initDatabase(config) {
316
941
  });
317
942
  }, 3e4);
318
943
  _walCheckpointTimer.unref();
944
+ if (process.env.DATABASE_URL) {
945
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
946
+ }
319
947
  }
320
948
  function getClient() {
321
- if (!_resilientClient) {
949
+ if (!_adapterClient) {
322
950
  throw new Error("Database client not initialized. Call initDatabase() first.");
323
951
  }
952
+ if (process.env.DATABASE_URL) {
953
+ return _adapterClient;
954
+ }
324
955
  if (process.env.EXE_IS_DAEMON === "1") {
325
956
  return _resilientClient;
326
957
  }
@@ -613,6 +1244,7 @@ async function ensureSchema() {
613
1244
  project TEXT NOT NULL,
614
1245
  summary TEXT NOT NULL,
615
1246
  task_file TEXT,
1247
+ session_scope TEXT,
616
1248
  read INTEGER NOT NULL DEFAULT 0,
617
1249
  created_at TEXT NOT NULL
618
1250
  );
@@ -621,7 +1253,7 @@ async function ensureSchema() {
621
1253
  ON notifications(read);
622
1254
 
623
1255
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
624
- ON notifications(agent_id);
1256
+ ON notifications(agent_id, session_scope);
625
1257
 
626
1258
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
627
1259
  ON notifications(task_file);
@@ -659,6 +1291,7 @@ async function ensureSchema() {
659
1291
  target_agent TEXT NOT NULL,
660
1292
  target_project TEXT,
661
1293
  target_device TEXT NOT NULL DEFAULT 'local',
1294
+ session_scope TEXT,
662
1295
  content TEXT NOT NULL,
663
1296
  priority TEXT DEFAULT 'normal',
664
1297
  status TEXT DEFAULT 'pending',
@@ -672,10 +1305,31 @@ async function ensureSchema() {
672
1305
  );
673
1306
 
674
1307
  CREATE INDEX IF NOT EXISTS idx_messages_target
675
- ON messages(target_agent, status);
1308
+ ON messages(target_agent, session_scope, status);
676
1309
 
677
1310
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
678
- ON messages(target_agent, from_agent, server_seq);
1311
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1312
+ `);
1313
+ try {
1314
+ await client.execute({
1315
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1316
+ args: []
1317
+ });
1318
+ } catch {
1319
+ }
1320
+ try {
1321
+ await client.execute({
1322
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1323
+ args: []
1324
+ });
1325
+ } catch {
1326
+ }
1327
+ await client.executeMultiple(`
1328
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1329
+ ON notifications(agent_id, session_scope, read, created_at);
1330
+
1331
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1332
+ ON messages(target_agent, session_scope, status, created_at);
679
1333
  `);
680
1334
  try {
681
1335
  await client.execute({
@@ -1259,17 +1913,26 @@ async function ensureSchema() {
1259
1913
  } catch {
1260
1914
  }
1261
1915
  }
1916
+ try {
1917
+ await client.execute({
1918
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1919
+ args: []
1920
+ });
1921
+ } catch {
1922
+ }
1262
1923
  }
1263
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1924
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1264
1925
  var init_database = __esm({
1265
1926
  "src/lib/database.ts"() {
1266
1927
  "use strict";
1267
1928
  init_db_retry();
1268
1929
  init_employees();
1930
+ init_database_adapter();
1269
1931
  _client = null;
1270
1932
  _resilientClient = null;
1271
1933
  _walCheckpointTimer = null;
1272
1934
  _daemonClient = null;
1935
+ _adapterClient = null;
1273
1936
  initTurso = initDatabase;
1274
1937
  }
1275
1938
  });
@@ -1279,6 +1942,7 @@ var shard_manager_exports = {};
1279
1942
  __export(shard_manager_exports, {
1280
1943
  disposeShards: () => disposeShards,
1281
1944
  ensureShardSchema: () => ensureShardSchema,
1945
+ getOpenShardCount: () => getOpenShardCount,
1282
1946
  getReadyShardClient: () => getReadyShardClient,
1283
1947
  getShardClient: () => getShardClient,
1284
1948
  getShardsDir: () => getShardsDir,
@@ -1287,15 +1951,18 @@ __export(shard_manager_exports, {
1287
1951
  listShards: () => listShards,
1288
1952
  shardExists: () => shardExists
1289
1953
  });
1290
- import path4 from "path";
1291
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1954
+ import path5 from "path";
1955
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1292
1956
  import { createClient as createClient2 } from "@libsql/client";
1293
1957
  function initShardManager(encryptionKey) {
1294
1958
  _encryptionKey = encryptionKey;
1295
- if (!existsSync4(SHARDS_DIR)) {
1296
- mkdirSync(SHARDS_DIR, { recursive: true });
1959
+ if (!existsSync5(SHARDS_DIR)) {
1960
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1297
1961
  }
1298
1962
  _shardingEnabled = true;
1963
+ if (_evictionTimer) clearInterval(_evictionTimer);
1964
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
1965
+ _evictionTimer.unref();
1299
1966
  }
1300
1967
  function isShardingEnabled() {
1301
1968
  return _shardingEnabled;
@@ -1312,21 +1979,28 @@ function getShardClient(projectName) {
1312
1979
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1313
1980
  }
1314
1981
  const cached = _shards.get(safeName);
1315
- if (cached) return cached;
1316
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1982
+ if (cached) {
1983
+ _shardLastAccess.set(safeName, Date.now());
1984
+ return cached;
1985
+ }
1986
+ while (_shards.size >= MAX_OPEN_SHARDS) {
1987
+ evictLRU();
1988
+ }
1989
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1317
1990
  const client = createClient2({
1318
1991
  url: `file:${dbPath}`,
1319
1992
  encryptionKey: _encryptionKey
1320
1993
  });
1321
1994
  _shards.set(safeName, client);
1995
+ _shardLastAccess.set(safeName, Date.now());
1322
1996
  return client;
1323
1997
  }
1324
1998
  function shardExists(projectName) {
1325
1999
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1326
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2000
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1327
2001
  }
1328
2002
  function listShards() {
1329
- if (!existsSync4(SHARDS_DIR)) return [];
2003
+ if (!existsSync5(SHARDS_DIR)) return [];
1330
2004
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1331
2005
  }
1332
2006
  async function ensureShardSchema(client) {
@@ -1378,6 +2052,8 @@ async function ensureShardSchema(client) {
1378
2052
  for (const col of [
1379
2053
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1380
2054
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2055
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2056
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1381
2057
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1382
2058
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1383
2059
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1400,7 +2076,23 @@ async function ensureShardSchema(client) {
1400
2076
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1401
2077
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1402
2078
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1403
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2079
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2080
+ // Metadata enrichment columns (must match database.ts)
2081
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2082
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2083
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2084
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2085
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2086
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2087
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2088
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2089
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2090
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2091
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2092
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2093
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2094
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2095
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1404
2096
  ]) {
1405
2097
  try {
1406
2098
  await client.execute(col);
@@ -1499,21 +2191,69 @@ async function getReadyShardClient(projectName) {
1499
2191
  await ensureShardSchema(client);
1500
2192
  return client;
1501
2193
  }
2194
+ function evictLRU() {
2195
+ let oldest = null;
2196
+ let oldestTime = Infinity;
2197
+ for (const [name, time] of _shardLastAccess) {
2198
+ if (time < oldestTime) {
2199
+ oldestTime = time;
2200
+ oldest = name;
2201
+ }
2202
+ }
2203
+ if (oldest) {
2204
+ const client = _shards.get(oldest);
2205
+ if (client) {
2206
+ client.close();
2207
+ }
2208
+ _shards.delete(oldest);
2209
+ _shardLastAccess.delete(oldest);
2210
+ }
2211
+ }
2212
+ function evictIdleShards() {
2213
+ const now = Date.now();
2214
+ const toEvict = [];
2215
+ for (const [name, lastAccess] of _shardLastAccess) {
2216
+ if (now - lastAccess > SHARD_IDLE_MS) {
2217
+ toEvict.push(name);
2218
+ }
2219
+ }
2220
+ for (const name of toEvict) {
2221
+ const client = _shards.get(name);
2222
+ if (client) {
2223
+ client.close();
2224
+ }
2225
+ _shards.delete(name);
2226
+ _shardLastAccess.delete(name);
2227
+ }
2228
+ }
2229
+ function getOpenShardCount() {
2230
+ return _shards.size;
2231
+ }
1502
2232
  function disposeShards() {
2233
+ if (_evictionTimer) {
2234
+ clearInterval(_evictionTimer);
2235
+ _evictionTimer = null;
2236
+ }
1503
2237
  for (const [, client] of _shards) {
1504
2238
  client.close();
1505
2239
  }
1506
2240
  _shards.clear();
2241
+ _shardLastAccess.clear();
1507
2242
  _shardingEnabled = false;
1508
2243
  _encryptionKey = null;
1509
2244
  }
1510
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2245
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1511
2246
  var init_shard_manager = __esm({
1512
2247
  "src/lib/shard-manager.ts"() {
1513
2248
  "use strict";
1514
2249
  init_config();
1515
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2250
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2251
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2252
+ MAX_OPEN_SHARDS = 10;
2253
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1516
2254
  _shards = /* @__PURE__ */ new Map();
2255
+ _shardLastAccess = /* @__PURE__ */ new Map();
2256
+ _evictionTimer = null;
1517
2257
  _encryptionKey = null;
1518
2258
  _shardingEnabled = false;
1519
2259
  }
@@ -1716,13 +2456,13 @@ __export(worker_gate_exports, {
1716
2456
  tryAcquireBackfillLock: () => tryAcquireBackfillLock,
1717
2457
  tryAcquireWorkerSlot: () => tryAcquireWorkerSlot
1718
2458
  });
1719
- import { readdirSync as readdirSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2, mkdirSync as mkdirSync2, existsSync as existsSync5 } from "fs";
1720
- import path5 from "path";
2459
+ import { readdirSync as readdirSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2, mkdirSync as mkdirSync3, existsSync as existsSync6 } from "fs";
2460
+ import path6 from "path";
1721
2461
  function tryAcquireWorkerSlot() {
1722
2462
  try {
1723
- mkdirSync2(WORKER_PID_DIR, { recursive: true });
2463
+ mkdirSync3(WORKER_PID_DIR, { recursive: true });
1724
2464
  const reservationId = `res-${process.pid}-${Date.now()}`;
1725
- const reservationPath = path5.join(WORKER_PID_DIR, `${reservationId}.pid`);
2465
+ const reservationPath = path6.join(WORKER_PID_DIR, `${reservationId}.pid`);
1726
2466
  writeFileSync2(reservationPath, String(process.pid));
1727
2467
  const files = readdirSync2(WORKER_PID_DIR);
1728
2468
  let alive = 0;
@@ -1740,7 +2480,7 @@ function tryAcquireWorkerSlot() {
1740
2480
  alive++;
1741
2481
  } catch {
1742
2482
  try {
1743
- unlinkSync2(path5.join(WORKER_PID_DIR, f));
2483
+ unlinkSync2(path6.join(WORKER_PID_DIR, f));
1744
2484
  } catch {
1745
2485
  }
1746
2486
  }
@@ -1763,21 +2503,21 @@ function tryAcquireWorkerSlot() {
1763
2503
  }
1764
2504
  function registerWorkerPid(pid) {
1765
2505
  try {
1766
- mkdirSync2(WORKER_PID_DIR, { recursive: true });
1767
- writeFileSync2(path5.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
2506
+ mkdirSync3(WORKER_PID_DIR, { recursive: true });
2507
+ writeFileSync2(path6.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
1768
2508
  } catch {
1769
2509
  }
1770
2510
  }
1771
2511
  function cleanupWorkerPid() {
1772
2512
  try {
1773
- unlinkSync2(path5.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
2513
+ unlinkSync2(path6.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
1774
2514
  } catch {
1775
2515
  }
1776
2516
  }
1777
2517
  function tryAcquireBackfillLock() {
1778
2518
  try {
1779
- mkdirSync2(WORKER_PID_DIR, { recursive: true });
1780
- if (existsSync5(BACKFILL_LOCK)) {
2519
+ mkdirSync3(WORKER_PID_DIR, { recursive: true });
2520
+ if (existsSync6(BACKFILL_LOCK)) {
1781
2521
  try {
1782
2522
  const pid = parseInt(
1783
2523
  __require("fs").readFileSync(BACKFILL_LOCK, "utf8").trim(),
@@ -1810,14 +2550,14 @@ var init_worker_gate = __esm({
1810
2550
  "src/lib/worker-gate.ts"() {
1811
2551
  "use strict";
1812
2552
  init_config();
1813
- WORKER_PID_DIR = path5.join(EXE_AI_DIR, "worker-pids");
2553
+ WORKER_PID_DIR = path6.join(EXE_AI_DIR, "worker-pids");
1814
2554
  MAX_CONCURRENT_WORKERS = 3;
1815
- BACKFILL_LOCK = path5.join(WORKER_PID_DIR, "backfill.lock");
2555
+ BACKFILL_LOCK = path6.join(WORKER_PID_DIR, "backfill.lock");
1816
2556
  }
1817
2557
  });
1818
2558
 
1819
2559
  // src/bin/exe-doctor.ts
1820
- import os4 from "os";
2560
+ import os5 from "os";
1821
2561
 
1822
2562
  // src/lib/store.ts
1823
2563
  import { createHash } from "crypto";
@@ -1825,16 +2565,16 @@ init_database();
1825
2565
 
1826
2566
  // src/lib/keychain.ts
1827
2567
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1828
- import { existsSync as existsSync3 } from "fs";
1829
- import path3 from "path";
1830
- import os3 from "os";
2568
+ import { existsSync as existsSync4 } from "fs";
2569
+ import path4 from "path";
2570
+ import os4 from "os";
1831
2571
  var SERVICE = "exe-mem";
1832
2572
  var ACCOUNT = "master-key";
1833
2573
  function getKeyDir() {
1834
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2574
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1835
2575
  }
1836
2576
  function getKeyPath() {
1837
- return path3.join(getKeyDir(), "master.key");
2577
+ return path4.join(getKeyDir(), "master.key");
1838
2578
  }
1839
2579
  async function tryKeytar() {
1840
2580
  try {
@@ -1855,9 +2595,9 @@ async function getMasterKey() {
1855
2595
  }
1856
2596
  }
1857
2597
  const keyPath = getKeyPath();
1858
- if (!existsSync3(keyPath)) {
2598
+ if (!existsSync4(keyPath)) {
1859
2599
  process.stderr.write(
1860
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2600
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1861
2601
  `
1862
2602
  );
1863
2603
  return null;
@@ -2025,9 +2765,9 @@ function isMainModule(importMetaUrl) {
2025
2765
  }
2026
2766
 
2027
2767
  // src/bin/exe-doctor.ts
2028
- import { existsSync as existsSync6, readFileSync as readFileSync3 } from "fs";
2768
+ import { existsSync as existsSync7, readFileSync as readFileSync3 } from "fs";
2029
2769
  import { spawn } from "child_process";
2030
- import path6 from "path";
2770
+ import path7 from "path";
2031
2771
  import { randomUUID as randomUUID2 } from "crypto";
2032
2772
 
2033
2773
  // src/lib/conflict-detector.ts
@@ -2430,7 +3170,7 @@ async function auditOrphanedProjects(client) {
2430
3170
  for (const row of result.rows) {
2431
3171
  const name = row.project_name;
2432
3172
  const count = Number(row.cnt);
2433
- const exists = existsSync6(path6.join(home, name)) || existsSync6(path6.join(home, "..", name)) || existsSync6(path6.join(process.cwd(), "..", name));
3173
+ const exists = existsSync7(path7.join(home, name)) || existsSync7(path7.join(home, "..", name)) || existsSync7(path7.join(process.cwd(), "..", name));
2434
3174
  if (!exists) {
2435
3175
  orphans.push({ project_name: name, count });
2436
3176
  }
@@ -2438,13 +3178,13 @@ async function auditOrphanedProjects(client) {
2438
3178
  return orphans;
2439
3179
  }
2440
3180
  function auditHookHealth() {
2441
- const logPath = path6.join(
3181
+ const logPath = path7.join(
2442
3182
  process.env.HOME ?? process.env.USERPROFILE ?? "",
2443
3183
  ".exe-os",
2444
3184
  "logs",
2445
3185
  "hooks.log"
2446
3186
  );
2447
- if (!existsSync6(logPath)) {
3187
+ if (!existsSync7(logPath)) {
2448
3188
  return { logExists: false, totalLines: 0, errorsLastHour: 0, topPatterns: [] };
2449
3189
  }
2450
3190
  let content;
@@ -2524,7 +3264,7 @@ function formatReport(report, flags) {
2524
3264
  }
2525
3265
  lines.push("");
2526
3266
  }
2527
- const totalMemGB = os4.totalmem() / (1024 * 1024 * 1024);
3267
+ const totalMemGB = os5.totalmem() / (1024 * 1024 * 1024);
2528
3268
  const isLowMemSystem = totalMemGB <= 8;
2529
3269
  if (isLowMemSystem && report.nullVectors > 0) {
2530
3270
  lines.push(`\u{1F7E2} Null vectors: ${fmtNum(report.nullVectors)} / ${fmtNum(s.total)} (expected \u2014 8GB system, keyword search mode)`);
@@ -2646,7 +3386,7 @@ async function fixNullVectors() {
2646
3386
  }
2647
3387
  }
2648
3388
  const npmRoot = (await import("child_process")).execSync("npm root -g", { encoding: "utf8" }).trim();
2649
- const backfillPath = path6.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
3389
+ const backfillPath = path7.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
2650
3390
  return new Promise((resolve, reject) => {
2651
3391
  const child = spawn("node", [backfillPath], { stdio: "inherit" });
2652
3392
  if (child.pid) registerWorkerPid2(child.pid);