@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
@@ -75,9 +75,34 @@ var init_db_retry = __esm({
75
75
  }
76
76
  });
77
77
 
78
+ // src/lib/secure-files.ts
79
+ import { chmodSync, existsSync, mkdirSync } from "fs";
80
+ import { chmod, mkdir } from "fs/promises";
81
+ async function ensurePrivateDir(dirPath) {
82
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
83
+ try {
84
+ await chmod(dirPath, PRIVATE_DIR_MODE);
85
+ } catch {
86
+ }
87
+ }
88
+ async function enforcePrivateFile(filePath) {
89
+ try {
90
+ await chmod(filePath, PRIVATE_FILE_MODE);
91
+ } catch {
92
+ }
93
+ }
94
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
95
+ var init_secure_files = __esm({
96
+ "src/lib/secure-files.ts"() {
97
+ "use strict";
98
+ PRIVATE_DIR_MODE = 448;
99
+ PRIVATE_FILE_MODE = 384;
100
+ }
101
+ });
102
+
78
103
  // src/lib/config.ts
79
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
80
- import { readFileSync, existsSync, renameSync } from "fs";
104
+ import { readFile, writeFile } from "fs/promises";
105
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
81
106
  import path from "path";
82
107
  import os from "os";
83
108
  function resolveDataDir() {
@@ -85,7 +110,7 @@ function resolveDataDir() {
85
110
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
86
111
  const newDir = path.join(os.homedir(), ".exe-os");
87
112
  const legacyDir = path.join(os.homedir(), ".exe-mem");
88
- if (!existsSync(newDir) && existsSync(legacyDir)) {
113
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
89
114
  try {
90
115
  renameSync(legacyDir, newDir);
91
116
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -148,9 +173,9 @@ function normalizeAutoUpdate(raw) {
148
173
  }
149
174
  async function loadConfig() {
150
175
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
151
- await mkdir(dir, { recursive: true });
176
+ await ensurePrivateDir(dir);
152
177
  const configPath = path.join(dir, "config.json");
153
- if (!existsSync(configPath)) {
178
+ if (!existsSync2(configPath)) {
154
179
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
155
180
  }
156
181
  const raw = await readFile(configPath, "utf-8");
@@ -163,6 +188,7 @@ async function loadConfig() {
163
188
  `);
164
189
  try {
165
190
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
191
+ await enforcePrivateFile(configPath);
166
192
  } catch {
167
193
  }
168
194
  }
@@ -181,7 +207,7 @@ async function loadConfig() {
181
207
  function loadConfigSync() {
182
208
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
183
209
  const configPath = path.join(dir, "config.json");
184
- if (!existsSync(configPath)) {
210
+ if (!existsSync2(configPath)) {
185
211
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
186
212
  }
187
213
  try {
@@ -201,6 +227,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
201
227
  var init_config = __esm({
202
228
  "src/lib/config.ts"() {
203
229
  "use strict";
230
+ init_secure_files();
204
231
  EXE_AI_DIR = resolveDataDir();
205
232
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
206
233
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -279,7 +306,7 @@ var init_config = __esm({
279
306
 
280
307
  // src/lib/employees.ts
281
308
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
282
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
309
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
283
310
  import { execSync } from "child_process";
284
311
  import path2 from "path";
285
312
  import os2 from "os";
@@ -296,14 +323,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
296
323
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
297
324
  }
298
325
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
299
- if (!existsSync2(employeesPath)) return [];
326
+ if (!existsSync3(employeesPath)) return [];
300
327
  try {
301
328
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
302
329
  } catch {
303
330
  return [];
304
331
  }
305
332
  }
306
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
333
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
307
334
  var init_employees = __esm({
308
335
  "src/lib/employees.ts"() {
309
336
  "use strict";
@@ -311,12 +338,609 @@ var init_employees = __esm({
311
338
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
312
339
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
313
340
  COORDINATOR_ROLE = "COO";
341
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
342
+ }
343
+ });
344
+
345
+ // src/lib/database-adapter.ts
346
+ import os3 from "os";
347
+ import path3 from "path";
348
+ import { createRequire } from "module";
349
+ import { pathToFileURL } from "url";
350
+ function quotedIdentifier(identifier) {
351
+ return `"${identifier.replace(/"/g, '""')}"`;
352
+ }
353
+ function unqualifiedTableName(name) {
354
+ const raw = name.trim().replace(/^"|"$/g, "");
355
+ const parts = raw.split(".");
356
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
357
+ }
358
+ function stripTrailingSemicolon(sql) {
359
+ return sql.trim().replace(/;+\s*$/u, "");
360
+ }
361
+ function appendClause(sql, clause) {
362
+ const trimmed = stripTrailingSemicolon(sql);
363
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
364
+ if (!returningMatch) {
365
+ return `${trimmed}${clause}`;
366
+ }
367
+ const idx = returningMatch.index;
368
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
369
+ }
370
+ function normalizeStatement(stmt) {
371
+ if (typeof stmt === "string") {
372
+ return { kind: "positional", sql: stmt, args: [] };
373
+ }
374
+ const sql = stmt.sql;
375
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
376
+ return { kind: "positional", sql, args: stmt.args ?? [] };
377
+ }
378
+ return { kind: "named", sql, args: stmt.args };
379
+ }
380
+ function rewriteBooleanLiterals(sql) {
381
+ let out = sql;
382
+ for (const column of BOOLEAN_COLUMN_NAMES) {
383
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
384
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
385
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
386
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
387
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
388
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
389
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
390
+ }
391
+ return out;
392
+ }
393
+ function rewriteInsertOrIgnore(sql) {
394
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
395
+ return sql;
396
+ }
397
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
398
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
399
+ }
400
+ function rewriteInsertOrReplace(sql) {
401
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
402
+ if (!match) {
403
+ return sql;
404
+ }
405
+ const rawTable = match[1];
406
+ const rawColumns = match[2];
407
+ const remainder = match[3];
408
+ const tableName = unqualifiedTableName(rawTable);
409
+ const conflictKeys = UPSERT_KEYS[tableName];
410
+ if (!conflictKeys?.length) {
411
+ return sql;
412
+ }
413
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
414
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
415
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
416
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
417
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
418
+ }
419
+ function rewriteSql(sql) {
420
+ let out = sql;
421
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
422
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
423
+ out = rewriteBooleanLiterals(out);
424
+ out = rewriteInsertOrReplace(out);
425
+ out = rewriteInsertOrIgnore(out);
426
+ return stripTrailingSemicolon(out);
427
+ }
428
+ function toBoolean(value) {
429
+ if (value === null || value === void 0) return value;
430
+ if (typeof value === "boolean") return value;
431
+ if (typeof value === "number") return value !== 0;
432
+ if (typeof value === "bigint") return value !== 0n;
433
+ if (typeof value === "string") {
434
+ const normalized = value.trim().toLowerCase();
435
+ if (normalized === "0" || normalized === "false") return false;
436
+ if (normalized === "1" || normalized === "true") return true;
437
+ }
438
+ return Boolean(value);
439
+ }
440
+ function countQuestionMarks(sql, end) {
441
+ let count = 0;
442
+ let inSingle = false;
443
+ let inDouble = false;
444
+ let inLineComment = false;
445
+ let inBlockComment = false;
446
+ for (let i = 0; i < end; i++) {
447
+ const ch = sql[i];
448
+ const next = sql[i + 1];
449
+ if (inLineComment) {
450
+ if (ch === "\n") inLineComment = false;
451
+ continue;
452
+ }
453
+ if (inBlockComment) {
454
+ if (ch === "*" && next === "/") {
455
+ inBlockComment = false;
456
+ i += 1;
457
+ }
458
+ continue;
459
+ }
460
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
461
+ inLineComment = true;
462
+ i += 1;
463
+ continue;
464
+ }
465
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
466
+ inBlockComment = true;
467
+ i += 1;
468
+ continue;
469
+ }
470
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
471
+ inSingle = !inSingle;
472
+ continue;
473
+ }
474
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
475
+ inDouble = !inDouble;
476
+ continue;
477
+ }
478
+ if (!inSingle && !inDouble && ch === "?") {
479
+ count += 1;
480
+ }
481
+ }
482
+ return count;
483
+ }
484
+ function findBooleanPlaceholderIndexes(sql) {
485
+ const indexes = /* @__PURE__ */ new Set();
486
+ for (const column of BOOLEAN_COLUMN_NAMES) {
487
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
488
+ for (const match of sql.matchAll(pattern)) {
489
+ const matchText = match[0];
490
+ const qIndex = match.index + matchText.lastIndexOf("?");
491
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
492
+ }
493
+ }
494
+ return indexes;
495
+ }
496
+ function coerceInsertBooleanArgs(sql, args) {
497
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
498
+ if (!match) return;
499
+ const rawTable = match[1];
500
+ const rawColumns = match[2];
501
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
502
+ if (!boolColumns?.size) return;
503
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
504
+ for (const [index, column] of columns.entries()) {
505
+ if (boolColumns.has(column) && index < args.length) {
506
+ args[index] = toBoolean(args[index]);
507
+ }
508
+ }
509
+ }
510
+ function coerceUpdateBooleanArgs(sql, args) {
511
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
512
+ if (!match) return;
513
+ const rawTable = match[1];
514
+ const setClause = match[2];
515
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
516
+ if (!boolColumns?.size) return;
517
+ const assignments = setClause.split(",");
518
+ let placeholderIndex = 0;
519
+ for (const assignment of assignments) {
520
+ if (!assignment.includes("?")) continue;
521
+ placeholderIndex += 1;
522
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
523
+ if (colMatch && boolColumns.has(colMatch[1])) {
524
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
525
+ }
526
+ }
527
+ }
528
+ function coerceBooleanArgs(sql, args) {
529
+ const nextArgs = [...args];
530
+ coerceInsertBooleanArgs(sql, nextArgs);
531
+ coerceUpdateBooleanArgs(sql, nextArgs);
532
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
533
+ for (const index of placeholderIndexes) {
534
+ if (index > 0 && index <= nextArgs.length) {
535
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
536
+ }
537
+ }
538
+ return nextArgs;
539
+ }
540
+ function convertQuestionMarksToDollarParams(sql) {
541
+ let out = "";
542
+ let placeholder = 0;
543
+ let inSingle = false;
544
+ let inDouble = false;
545
+ let inLineComment = false;
546
+ let inBlockComment = false;
547
+ for (let i = 0; i < sql.length; i++) {
548
+ const ch = sql[i];
549
+ const next = sql[i + 1];
550
+ if (inLineComment) {
551
+ out += ch;
552
+ if (ch === "\n") inLineComment = false;
553
+ continue;
554
+ }
555
+ if (inBlockComment) {
556
+ out += ch;
557
+ if (ch === "*" && next === "/") {
558
+ out += next;
559
+ inBlockComment = false;
560
+ i += 1;
561
+ }
562
+ continue;
563
+ }
564
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
565
+ out += ch + next;
566
+ inLineComment = true;
567
+ i += 1;
568
+ continue;
569
+ }
570
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
571
+ out += ch + next;
572
+ inBlockComment = true;
573
+ i += 1;
574
+ continue;
575
+ }
576
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
577
+ inSingle = !inSingle;
578
+ out += ch;
579
+ continue;
580
+ }
581
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
582
+ inDouble = !inDouble;
583
+ out += ch;
584
+ continue;
585
+ }
586
+ if (!inSingle && !inDouble && ch === "?") {
587
+ placeholder += 1;
588
+ out += `$${placeholder}`;
589
+ continue;
590
+ }
591
+ out += ch;
592
+ }
593
+ return out;
594
+ }
595
+ function translateStatementForPostgres(stmt) {
596
+ const normalized = normalizeStatement(stmt);
597
+ if (normalized.kind === "named") {
598
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
599
+ }
600
+ const rewrittenSql = rewriteSql(normalized.sql);
601
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
602
+ return {
603
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
604
+ args: coercedArgs
605
+ };
606
+ }
607
+ function shouldBypassPostgres(stmt) {
608
+ const normalized = normalizeStatement(stmt);
609
+ if (normalized.kind === "named") {
610
+ return true;
611
+ }
612
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
613
+ }
614
+ function shouldFallbackOnError(error) {
615
+ const message = error instanceof Error ? error.message : String(error);
616
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
617
+ }
618
+ function isReadQuery(sql) {
619
+ const trimmed = sql.trimStart();
620
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
621
+ }
622
+ function buildRow(row, columns) {
623
+ const values = columns.map((column) => row[column]);
624
+ return Object.assign(values, row);
625
+ }
626
+ function buildResultSet(rows, rowsAffected = 0) {
627
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
628
+ const resultRows = rows.map((row) => buildRow(row, columns));
629
+ return {
630
+ columns,
631
+ columnTypes: columns.map(() => ""),
632
+ rows: resultRows,
633
+ rowsAffected,
634
+ lastInsertRowid: void 0,
635
+ toJSON() {
636
+ return {
637
+ columns,
638
+ columnTypes: columns.map(() => ""),
639
+ rows,
640
+ rowsAffected,
641
+ lastInsertRowid: void 0
642
+ };
643
+ }
644
+ };
645
+ }
646
+ async function loadPrismaClient() {
647
+ if (!prismaClientPromise) {
648
+ prismaClientPromise = (async () => {
649
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
650
+ if (explicitPath) {
651
+ const module2 = await import(pathToFileURL(explicitPath).href);
652
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
653
+ if (!PrismaClient2) {
654
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
655
+ }
656
+ return new PrismaClient2();
657
+ }
658
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
659
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
660
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
661
+ const module = await import(pathToFileURL(prismaEntry).href);
662
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
663
+ if (!PrismaClient) {
664
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
665
+ }
666
+ return new PrismaClient();
667
+ })();
668
+ }
669
+ return prismaClientPromise;
670
+ }
671
+ async function ensureCompatibilityViews(prisma) {
672
+ if (!compatibilityBootstrapPromise) {
673
+ compatibilityBootstrapPromise = (async () => {
674
+ for (const mapping of VIEW_MAPPINGS) {
675
+ const relation = mapping.source.replace(/"/g, "");
676
+ const rows = await prisma.$queryRawUnsafe(
677
+ "SELECT to_regclass($1) AS regclass",
678
+ relation
679
+ );
680
+ if (!rows[0]?.regclass) {
681
+ continue;
682
+ }
683
+ await prisma.$executeRawUnsafe(
684
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
685
+ );
686
+ }
687
+ })();
688
+ }
689
+ return compatibilityBootstrapPromise;
690
+ }
691
+ async function executeOnPrisma(executor, stmt) {
692
+ const translated = translateStatementForPostgres(stmt);
693
+ if (isReadQuery(translated.sql)) {
694
+ const rows = await executor.$queryRawUnsafe(
695
+ translated.sql,
696
+ ...translated.args
697
+ );
698
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
699
+ }
700
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
701
+ return buildResultSet([], rowsAffected);
702
+ }
703
+ function splitSqlStatements(sql) {
704
+ const parts = [];
705
+ let current = "";
706
+ let inSingle = false;
707
+ let inDouble = false;
708
+ let inLineComment = false;
709
+ let inBlockComment = false;
710
+ for (let i = 0; i < sql.length; i++) {
711
+ const ch = sql[i];
712
+ const next = sql[i + 1];
713
+ if (inLineComment) {
714
+ current += ch;
715
+ if (ch === "\n") inLineComment = false;
716
+ continue;
717
+ }
718
+ if (inBlockComment) {
719
+ current += ch;
720
+ if (ch === "*" && next === "/") {
721
+ current += next;
722
+ inBlockComment = false;
723
+ i += 1;
724
+ }
725
+ continue;
726
+ }
727
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
728
+ current += ch + next;
729
+ inLineComment = true;
730
+ i += 1;
731
+ continue;
732
+ }
733
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
734
+ current += ch + next;
735
+ inBlockComment = true;
736
+ i += 1;
737
+ continue;
738
+ }
739
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
740
+ inSingle = !inSingle;
741
+ current += ch;
742
+ continue;
743
+ }
744
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
745
+ inDouble = !inDouble;
746
+ current += ch;
747
+ continue;
748
+ }
749
+ if (!inSingle && !inDouble && ch === ";") {
750
+ if (current.trim()) {
751
+ parts.push(current.trim());
752
+ }
753
+ current = "";
754
+ continue;
755
+ }
756
+ current += ch;
757
+ }
758
+ if (current.trim()) {
759
+ parts.push(current.trim());
760
+ }
761
+ return parts;
762
+ }
763
+ async function createPrismaDbAdapter(fallbackClient) {
764
+ const prisma = await loadPrismaClient();
765
+ await ensureCompatibilityViews(prisma);
766
+ let closed = false;
767
+ let adapter;
768
+ const fallbackExecute = async (stmt, error) => {
769
+ if (!fallbackClient) {
770
+ if (error) throw error;
771
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
772
+ }
773
+ if (error) {
774
+ process.stderr.write(
775
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
776
+ `
777
+ );
778
+ }
779
+ return fallbackClient.execute(stmt);
780
+ };
781
+ adapter = {
782
+ async execute(stmt) {
783
+ if (shouldBypassPostgres(stmt)) {
784
+ return fallbackExecute(stmt);
785
+ }
786
+ try {
787
+ return await executeOnPrisma(prisma, stmt);
788
+ } catch (error) {
789
+ if (shouldFallbackOnError(error)) {
790
+ return fallbackExecute(stmt, error);
791
+ }
792
+ throw error;
793
+ }
794
+ },
795
+ async batch(stmts, mode) {
796
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
797
+ if (!fallbackClient) {
798
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
799
+ }
800
+ return fallbackClient.batch(stmts, mode);
801
+ }
802
+ try {
803
+ if (prisma.$transaction) {
804
+ return await prisma.$transaction(async (tx) => {
805
+ const results2 = [];
806
+ for (const stmt of stmts) {
807
+ results2.push(await executeOnPrisma(tx, stmt));
808
+ }
809
+ return results2;
810
+ });
811
+ }
812
+ const results = [];
813
+ for (const stmt of stmts) {
814
+ results.push(await executeOnPrisma(prisma, stmt));
815
+ }
816
+ return results;
817
+ } catch (error) {
818
+ if (fallbackClient && shouldFallbackOnError(error)) {
819
+ process.stderr.write(
820
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
821
+ `
822
+ );
823
+ return fallbackClient.batch(stmts, mode);
824
+ }
825
+ throw error;
826
+ }
827
+ },
828
+ async migrate(stmts) {
829
+ if (fallbackClient) {
830
+ return fallbackClient.migrate(stmts);
831
+ }
832
+ return adapter.batch(stmts, "deferred");
833
+ },
834
+ async transaction(mode) {
835
+ if (!fallbackClient) {
836
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
837
+ }
838
+ return fallbackClient.transaction(mode);
839
+ },
840
+ async executeMultiple(sql) {
841
+ if (fallbackClient && shouldBypassPostgres(sql)) {
842
+ return fallbackClient.executeMultiple(sql);
843
+ }
844
+ for (const statement of splitSqlStatements(sql)) {
845
+ await adapter.execute(statement);
846
+ }
847
+ },
848
+ async sync() {
849
+ if (fallbackClient) {
850
+ return fallbackClient.sync();
851
+ }
852
+ return { frame_no: 0, frames_synced: 0 };
853
+ },
854
+ close() {
855
+ closed = true;
856
+ prismaClientPromise = null;
857
+ compatibilityBootstrapPromise = null;
858
+ void prisma.$disconnect?.();
859
+ },
860
+ get closed() {
861
+ return closed;
862
+ },
863
+ get protocol() {
864
+ return "prisma-postgres";
865
+ }
866
+ };
867
+ return adapter;
868
+ }
869
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
870
+ var init_database_adapter = __esm({
871
+ "src/lib/database-adapter.ts"() {
872
+ "use strict";
873
+ VIEW_MAPPINGS = [
874
+ { view: "memories", source: "memory.memory_records" },
875
+ { view: "tasks", source: "memory.tasks" },
876
+ { view: "behaviors", source: "memory.behaviors" },
877
+ { view: "entities", source: "memory.entities" },
878
+ { view: "relationships", source: "memory.relationships" },
879
+ { view: "entity_memories", source: "memory.entity_memories" },
880
+ { view: "entity_aliases", source: "memory.entity_aliases" },
881
+ { view: "notifications", source: "memory.notifications" },
882
+ { view: "messages", source: "memory.messages" },
883
+ { view: "users", source: "wiki.users" },
884
+ { view: "workspaces", source: "wiki.workspaces" },
885
+ { view: "workspace_users", source: "wiki.workspace_users" },
886
+ { view: "documents", source: "wiki.workspace_documents" },
887
+ { view: "chats", source: "wiki.workspace_chats" }
888
+ ];
889
+ UPSERT_KEYS = {
890
+ memories: ["id"],
891
+ tasks: ["id"],
892
+ behaviors: ["id"],
893
+ entities: ["id"],
894
+ relationships: ["id"],
895
+ entity_aliases: ["alias"],
896
+ notifications: ["id"],
897
+ messages: ["id"],
898
+ users: ["id"],
899
+ workspaces: ["id"],
900
+ workspace_users: ["id"],
901
+ documents: ["id"],
902
+ chats: ["id"]
903
+ };
904
+ BOOLEAN_COLUMNS_BY_TABLE = {
905
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
906
+ behaviors: /* @__PURE__ */ new Set(["active"]),
907
+ notifications: /* @__PURE__ */ new Set(["read"]),
908
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
909
+ };
910
+ BOOLEAN_COLUMN_NAMES = new Set(
911
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
912
+ );
913
+ IMMEDIATE_FALLBACK_PATTERNS = [
914
+ /\bPRAGMA\b/i,
915
+ /\bsqlite_master\b/i,
916
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
917
+ /\bMATCH\b/i,
918
+ /\bvector_distance_cos\s*\(/i,
919
+ /\bjson_extract\s*\(/i,
920
+ /\bjulianday\s*\(/i,
921
+ /\bstrftime\s*\(/i,
922
+ /\blast_insert_rowid\s*\(/i
923
+ ];
924
+ prismaClientPromise = null;
925
+ compatibilityBootstrapPromise = null;
314
926
  }
315
927
  });
316
928
 
317
929
  // src/lib/database.ts
318
930
  import { createClient } from "@libsql/client";
319
931
  async function initDatabase(config) {
932
+ if (_walCheckpointTimer) {
933
+ clearInterval(_walCheckpointTimer);
934
+ _walCheckpointTimer = null;
935
+ }
936
+ if (_daemonClient) {
937
+ _daemonClient.close();
938
+ _daemonClient = null;
939
+ }
940
+ if (_adapterClient && _adapterClient !== _resilientClient) {
941
+ _adapterClient.close();
942
+ }
943
+ _adapterClient = null;
320
944
  if (_client) {
321
945
  _client.close();
322
946
  _client = null;
@@ -330,6 +954,7 @@ async function initDatabase(config) {
330
954
  }
331
955
  _client = createClient(opts);
332
956
  _resilientClient = wrapWithRetry(_client);
957
+ _adapterClient = _resilientClient;
333
958
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
334
959
  });
335
960
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -340,11 +965,17 @@ async function initDatabase(config) {
340
965
  });
341
966
  }, 3e4);
342
967
  _walCheckpointTimer.unref();
968
+ if (process.env.DATABASE_URL) {
969
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
970
+ }
343
971
  }
344
972
  function getClient() {
345
- if (!_resilientClient) {
973
+ if (!_adapterClient) {
346
974
  throw new Error("Database client not initialized. Call initDatabase() first.");
347
975
  }
976
+ if (process.env.DATABASE_URL) {
977
+ return _adapterClient;
978
+ }
348
979
  if (process.env.EXE_IS_DAEMON === "1") {
349
980
  return _resilientClient;
350
981
  }
@@ -637,6 +1268,7 @@ async function ensureSchema() {
637
1268
  project TEXT NOT NULL,
638
1269
  summary TEXT NOT NULL,
639
1270
  task_file TEXT,
1271
+ session_scope TEXT,
640
1272
  read INTEGER NOT NULL DEFAULT 0,
641
1273
  created_at TEXT NOT NULL
642
1274
  );
@@ -645,7 +1277,7 @@ async function ensureSchema() {
645
1277
  ON notifications(read);
646
1278
 
647
1279
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
648
- ON notifications(agent_id);
1280
+ ON notifications(agent_id, session_scope);
649
1281
 
650
1282
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
651
1283
  ON notifications(task_file);
@@ -683,6 +1315,7 @@ async function ensureSchema() {
683
1315
  target_agent TEXT NOT NULL,
684
1316
  target_project TEXT,
685
1317
  target_device TEXT NOT NULL DEFAULT 'local',
1318
+ session_scope TEXT,
686
1319
  content TEXT NOT NULL,
687
1320
  priority TEXT DEFAULT 'normal',
688
1321
  status TEXT DEFAULT 'pending',
@@ -696,10 +1329,31 @@ async function ensureSchema() {
696
1329
  );
697
1330
 
698
1331
  CREATE INDEX IF NOT EXISTS idx_messages_target
699
- ON messages(target_agent, status);
1332
+ ON messages(target_agent, session_scope, status);
700
1333
 
701
1334
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
702
- ON messages(target_agent, from_agent, server_seq);
1335
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1336
+ `);
1337
+ try {
1338
+ await client.execute({
1339
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1340
+ args: []
1341
+ });
1342
+ } catch {
1343
+ }
1344
+ try {
1345
+ await client.execute({
1346
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1347
+ args: []
1348
+ });
1349
+ } catch {
1350
+ }
1351
+ await client.executeMultiple(`
1352
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1353
+ ON notifications(agent_id, session_scope, read, created_at);
1354
+
1355
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1356
+ ON messages(target_agent, session_scope, status, created_at);
703
1357
  `);
704
1358
  try {
705
1359
  await client.execute({
@@ -1283,17 +1937,26 @@ async function ensureSchema() {
1283
1937
  } catch {
1284
1938
  }
1285
1939
  }
1940
+ try {
1941
+ await client.execute({
1942
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1943
+ args: []
1944
+ });
1945
+ } catch {
1946
+ }
1286
1947
  }
1287
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1948
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1288
1949
  var init_database = __esm({
1289
1950
  "src/lib/database.ts"() {
1290
1951
  "use strict";
1291
1952
  init_db_retry();
1292
1953
  init_employees();
1954
+ init_database_adapter();
1293
1955
  _client = null;
1294
1956
  _resilientClient = null;
1295
1957
  _walCheckpointTimer = null;
1296
1958
  _daemonClient = null;
1959
+ _adapterClient = null;
1297
1960
  initTurso = initDatabase;
1298
1961
  }
1299
1962
  });
@@ -1358,6 +2021,7 @@ var shard_manager_exports = {};
1358
2021
  __export(shard_manager_exports, {
1359
2022
  disposeShards: () => disposeShards,
1360
2023
  ensureShardSchema: () => ensureShardSchema,
2024
+ getOpenShardCount: () => getOpenShardCount,
1361
2025
  getReadyShardClient: () => getReadyShardClient,
1362
2026
  getShardClient: () => getShardClient,
1363
2027
  getShardsDir: () => getShardsDir,
@@ -1366,15 +2030,18 @@ __export(shard_manager_exports, {
1366
2030
  listShards: () => listShards,
1367
2031
  shardExists: () => shardExists
1368
2032
  });
1369
- import path4 from "path";
1370
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
2033
+ import path5 from "path";
2034
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1371
2035
  import { createClient as createClient2 } from "@libsql/client";
1372
2036
  function initShardManager(encryptionKey) {
1373
2037
  _encryptionKey = encryptionKey;
1374
- if (!existsSync4(SHARDS_DIR)) {
1375
- mkdirSync(SHARDS_DIR, { recursive: true });
2038
+ if (!existsSync5(SHARDS_DIR)) {
2039
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1376
2040
  }
1377
2041
  _shardingEnabled = true;
2042
+ if (_evictionTimer) clearInterval(_evictionTimer);
2043
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2044
+ _evictionTimer.unref();
1378
2045
  }
1379
2046
  function isShardingEnabled() {
1380
2047
  return _shardingEnabled;
@@ -1391,21 +2058,28 @@ function getShardClient(projectName) {
1391
2058
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1392
2059
  }
1393
2060
  const cached = _shards.get(safeName);
1394
- if (cached) return cached;
1395
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
2061
+ if (cached) {
2062
+ _shardLastAccess.set(safeName, Date.now());
2063
+ return cached;
2064
+ }
2065
+ while (_shards.size >= MAX_OPEN_SHARDS) {
2066
+ evictLRU();
2067
+ }
2068
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1396
2069
  const client = createClient2({
1397
2070
  url: `file:${dbPath}`,
1398
2071
  encryptionKey: _encryptionKey
1399
2072
  });
1400
2073
  _shards.set(safeName, client);
2074
+ _shardLastAccess.set(safeName, Date.now());
1401
2075
  return client;
1402
2076
  }
1403
2077
  function shardExists(projectName) {
1404
2078
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1405
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2079
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1406
2080
  }
1407
2081
  function listShards() {
1408
- if (!existsSync4(SHARDS_DIR)) return [];
2082
+ if (!existsSync5(SHARDS_DIR)) return [];
1409
2083
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1410
2084
  }
1411
2085
  async function ensureShardSchema(client) {
@@ -1457,6 +2131,8 @@ async function ensureShardSchema(client) {
1457
2131
  for (const col of [
1458
2132
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1459
2133
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2134
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2135
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1460
2136
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1461
2137
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1462
2138
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1479,7 +2155,23 @@ async function ensureShardSchema(client) {
1479
2155
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1480
2156
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1481
2157
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1482
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2158
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2159
+ // Metadata enrichment columns (must match database.ts)
2160
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2161
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2162
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2163
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2164
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2165
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2166
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2167
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2168
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2169
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2170
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2171
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2172
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2173
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2174
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1483
2175
  ]) {
1484
2176
  try {
1485
2177
  await client.execute(col);
@@ -1578,21 +2270,69 @@ async function getReadyShardClient(projectName) {
1578
2270
  await ensureShardSchema(client);
1579
2271
  return client;
1580
2272
  }
2273
+ function evictLRU() {
2274
+ let oldest = null;
2275
+ let oldestTime = Infinity;
2276
+ for (const [name, time] of _shardLastAccess) {
2277
+ if (time < oldestTime) {
2278
+ oldestTime = time;
2279
+ oldest = name;
2280
+ }
2281
+ }
2282
+ if (oldest) {
2283
+ const client = _shards.get(oldest);
2284
+ if (client) {
2285
+ client.close();
2286
+ }
2287
+ _shards.delete(oldest);
2288
+ _shardLastAccess.delete(oldest);
2289
+ }
2290
+ }
2291
+ function evictIdleShards() {
2292
+ const now = Date.now();
2293
+ const toEvict = [];
2294
+ for (const [name, lastAccess] of _shardLastAccess) {
2295
+ if (now - lastAccess > SHARD_IDLE_MS) {
2296
+ toEvict.push(name);
2297
+ }
2298
+ }
2299
+ for (const name of toEvict) {
2300
+ const client = _shards.get(name);
2301
+ if (client) {
2302
+ client.close();
2303
+ }
2304
+ _shards.delete(name);
2305
+ _shardLastAccess.delete(name);
2306
+ }
2307
+ }
2308
+ function getOpenShardCount() {
2309
+ return _shards.size;
2310
+ }
1581
2311
  function disposeShards() {
2312
+ if (_evictionTimer) {
2313
+ clearInterval(_evictionTimer);
2314
+ _evictionTimer = null;
2315
+ }
1582
2316
  for (const [, client] of _shards) {
1583
2317
  client.close();
1584
2318
  }
1585
2319
  _shards.clear();
2320
+ _shardLastAccess.clear();
1586
2321
  _shardingEnabled = false;
1587
2322
  _encryptionKey = null;
1588
2323
  }
1589
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2324
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1590
2325
  var init_shard_manager = __esm({
1591
2326
  "src/lib/shard-manager.ts"() {
1592
2327
  "use strict";
1593
2328
  init_config();
1594
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2329
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2330
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2331
+ MAX_OPEN_SHARDS = 10;
2332
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1595
2333
  _shards = /* @__PURE__ */ new Map();
2334
+ _shardLastAccess = /* @__PURE__ */ new Map();
2335
+ _evictionTimer = null;
1596
2336
  _encryptionKey = null;
1597
2337
  _shardingEnabled = false;
1598
2338
  }
@@ -1785,24 +2525,6 @@ ${p.content}`).join("\n\n");
1785
2525
  }
1786
2526
  });
1787
2527
 
1788
- // src/lib/notifications.ts
1789
- import crypto from "crypto";
1790
- import path5 from "path";
1791
- import os4 from "os";
1792
- import {
1793
- readFileSync as readFileSync3,
1794
- readdirSync as readdirSync2,
1795
- unlinkSync as unlinkSync2,
1796
- existsSync as existsSync5,
1797
- rmdirSync
1798
- } from "fs";
1799
- var init_notifications = __esm({
1800
- "src/lib/notifications.ts"() {
1801
- "use strict";
1802
- init_database();
1803
- }
1804
- });
1805
-
1806
2528
  // src/lib/session-registry.ts
1807
2529
  import path6 from "path";
1808
2530
  import os5 from "os";
@@ -2045,7 +2767,7 @@ var init_runtime_table = __esm({
2045
2767
  });
2046
2768
 
2047
2769
  // src/lib/agent-config.ts
2048
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
2770
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync6 } from "fs";
2049
2771
  import path7 from "path";
2050
2772
  var AGENT_CONFIG_PATH, DEFAULT_MODELS;
2051
2773
  var init_agent_config = __esm({
@@ -2053,6 +2775,7 @@ var init_agent_config = __esm({
2053
2775
  "use strict";
2054
2776
  init_config();
2055
2777
  init_runtime_table();
2778
+ init_secure_files();
2056
2779
  AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
2057
2780
  DEFAULT_MODELS = {
2058
2781
  claude: "claude-opus-4",
@@ -2063,7 +2786,7 @@ var init_agent_config = __esm({
2063
2786
  });
2064
2787
 
2065
2788
  // src/lib/intercom-queue.ts
2066
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
2789
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
2067
2790
  import path8 from "path";
2068
2791
  import os6 from "os";
2069
2792
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
@@ -2077,8 +2800,11 @@ var init_intercom_queue = __esm({
2077
2800
  });
2078
2801
 
2079
2802
  // src/lib/license.ts
2080
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2803
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2081
2804
  import { randomUUID as randomUUID2 } from "crypto";
2805
+ import { createRequire as createRequire2 } from "module";
2806
+ import { pathToFileURL as pathToFileURL2 } from "url";
2807
+ import os7 from "os";
2082
2808
  import path9 from "path";
2083
2809
  import { jwtVerify, importSPKI } from "jose";
2084
2810
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
@@ -2093,7 +2819,7 @@ var init_license = __esm({
2093
2819
  });
2094
2820
 
2095
2821
  // src/lib/plan-limits.ts
2096
- import { readFileSync as readFileSync7, existsSync as existsSync9 } from "fs";
2822
+ import { readFileSync as readFileSync6, existsSync as existsSync9 } from "fs";
2097
2823
  import path10 from "path";
2098
2824
  var CACHE_PATH2;
2099
2825
  var init_plan_limits = __esm({
@@ -2108,9 +2834,9 @@ var init_plan_limits = __esm({
2108
2834
  });
2109
2835
 
2110
2836
  // src/lib/tmux-routing.ts
2111
- import { readFileSync as readFileSync8, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync, readdirSync as readdirSync3 } from "fs";
2837
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync, readdirSync as readdirSync2 } from "fs";
2112
2838
  import path11 from "path";
2113
- import os7 from "os";
2839
+ import os8 from "os";
2114
2840
  import { fileURLToPath as fileURLToPath2 } from "url";
2115
2841
  function getMySession() {
2116
2842
  return getTransport().getMySession();
@@ -2123,7 +2849,7 @@ function extractRootExe(name) {
2123
2849
  }
2124
2850
  function getParentExe(sessionKey) {
2125
2851
  try {
2126
- const data = JSON.parse(readFileSync8(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2852
+ const data = JSON.parse(readFileSync7(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2127
2853
  return data.parentExe || null;
2128
2854
  } catch {
2129
2855
  return null;
@@ -2171,50 +2897,14 @@ var init_tmux_routing = __esm({
2171
2897
  init_intercom_queue();
2172
2898
  init_plan_limits();
2173
2899
  init_employees();
2174
- SPAWN_LOCK_DIR = path11.join(os7.homedir(), ".exe-os", "spawn-locks");
2175
- SESSION_CACHE = path11.join(os7.homedir(), ".exe-os", "session-cache");
2176
- INTERCOM_LOG2 = path11.join(os7.homedir(), ".exe-os", "intercom.log");
2900
+ SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
2901
+ SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
2902
+ INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
2177
2903
  DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2178
2904
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2179
2905
  }
2180
2906
  });
2181
2907
 
2182
- // src/lib/tasks-review.ts
2183
- import path12 from "path";
2184
- import { existsSync as existsSync11, readdirSync as readdirSync4, unlinkSync as unlinkSync3 } from "fs";
2185
- async function listPendingReviews(limit, sessionScope) {
2186
- const client = getClient();
2187
- if (sessionScope) {
2188
- const result2 = await client.execute({
2189
- sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
2190
- WHERE status = 'needs_review'
2191
- AND session_scope = ?
2192
- ORDER BY updated_at ASC LIMIT ?`,
2193
- args: [sessionScope, limit]
2194
- });
2195
- return result2.rows;
2196
- }
2197
- const result = await client.execute({
2198
- sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
2199
- WHERE status = 'needs_review'
2200
- ORDER BY updated_at ASC LIMIT ?`,
2201
- args: [limit]
2202
- });
2203
- return result.rows;
2204
- }
2205
- var init_tasks_review = __esm({
2206
- "src/lib/tasks-review.ts"() {
2207
- "use strict";
2208
- init_database();
2209
- init_config();
2210
- init_employees();
2211
- init_notifications();
2212
- init_tmux_routing();
2213
- init_session_key();
2214
- init_state_bus();
2215
- }
2216
- });
2217
-
2218
2908
  // src/lib/task-scope.ts
2219
2909
  function getCurrentSessionScope() {
2220
2910
  try {
@@ -2223,12 +2913,12 @@ function getCurrentSessionScope() {
2223
2913
  return null;
2224
2914
  }
2225
2915
  }
2226
- function sessionScopeFilter(sessionScope, tableAlias) {
2916
+ function strictSessionScopeFilter(sessionScope, tableAlias) {
2227
2917
  const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
2228
2918
  if (!scope) return { sql: "", args: [] };
2229
2919
  const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
2230
2920
  return {
2231
- sql: ` AND (${col} IS NULL OR ${col} = ?)`,
2921
+ sql: ` AND ${col} = ?`,
2232
2922
  args: [scope]
2233
2923
  };
2234
2924
  }
@@ -2239,11 +2929,60 @@ var init_task_scope = __esm({
2239
2929
  }
2240
2930
  });
2241
2931
 
2932
+ // src/lib/notifications.ts
2933
+ import crypto from "crypto";
2934
+ import path12 from "path";
2935
+ import os9 from "os";
2936
+ import {
2937
+ readFileSync as readFileSync8,
2938
+ readdirSync as readdirSync3,
2939
+ unlinkSync as unlinkSync2,
2940
+ existsSync as existsSync11,
2941
+ rmdirSync
2942
+ } from "fs";
2943
+ var init_notifications = __esm({
2944
+ "src/lib/notifications.ts"() {
2945
+ "use strict";
2946
+ init_database();
2947
+ init_task_scope();
2948
+ }
2949
+ });
2950
+
2951
+ // src/lib/tasks-review.ts
2952
+ import path13 from "path";
2953
+ import { existsSync as existsSync12, readdirSync as readdirSync4, unlinkSync as unlinkSync3 } from "fs";
2954
+ async function listPendingReviews(limit, sessionScope) {
2955
+ const client = getClient();
2956
+ const scope = strictSessionScopeFilter(
2957
+ sessionScope === void 0 ? getCurrentSessionScope() : sessionScope
2958
+ );
2959
+ const result = await client.execute({
2960
+ sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
2961
+ WHERE status = 'needs_review'${scope.sql}
2962
+ ORDER BY updated_at ASC LIMIT ?`,
2963
+ args: [...scope.args, limit]
2964
+ });
2965
+ return result.rows;
2966
+ }
2967
+ var init_tasks_review = __esm({
2968
+ "src/lib/tasks-review.ts"() {
2969
+ "use strict";
2970
+ init_database();
2971
+ init_config();
2972
+ init_employees();
2973
+ init_notifications();
2974
+ init_tmux_routing();
2975
+ init_session_key();
2976
+ init_state_bus();
2977
+ init_task_scope();
2978
+ }
2979
+ });
2980
+
2242
2981
  // src/bin/exe-heartbeat.ts
2243
2982
  import { createHash as createHash2 } from "crypto";
2244
2983
  import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync6 } from "fs";
2245
- import os8 from "os";
2246
- import path13 from "path";
2984
+ import os10 from "os";
2985
+ import path14 from "path";
2247
2986
 
2248
2987
  // src/lib/store.ts
2249
2988
  import { createHash } from "crypto";
@@ -2251,16 +2990,16 @@ init_database();
2251
2990
 
2252
2991
  // src/lib/keychain.ts
2253
2992
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2254
- import { existsSync as existsSync3 } from "fs";
2255
- import path3 from "path";
2256
- import os3 from "os";
2993
+ import { existsSync as existsSync4 } from "fs";
2994
+ import path4 from "path";
2995
+ import os4 from "os";
2257
2996
  var SERVICE = "exe-mem";
2258
2997
  var ACCOUNT = "master-key";
2259
2998
  function getKeyDir() {
2260
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2999
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2261
3000
  }
2262
3001
  function getKeyPath() {
2263
- return path3.join(getKeyDir(), "master.key");
3002
+ return path4.join(getKeyDir(), "master.key");
2264
3003
  }
2265
3004
  async function tryKeytar() {
2266
3005
  try {
@@ -2281,9 +3020,9 @@ async function getMasterKey() {
2281
3020
  }
2282
3021
  }
2283
3022
  const keyPath = getKeyPath();
2284
- if (!existsSync3(keyPath)) {
3023
+ if (!existsSync4(keyPath)) {
2285
3024
  process.stderr.write(
2286
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3025
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2287
3026
  `
2288
3027
  );
2289
3028
  return null;
@@ -2416,13 +3155,13 @@ var MESSAGE_PREVIEW_CHARS = 80;
2416
3155
  var MARKER_FILENAME = "exe-heartbeat-marker.json";
2417
3156
  var SESSION_CACHE_SUBDIR = "session-cache";
2418
3157
  function resolveExeOsDir() {
2419
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path13.join(os8.homedir(), ".exe-os");
3158
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path14.join(os10.homedir(), ".exe-os");
2420
3159
  }
2421
3160
  function getMarkerDir() {
2422
- return path13.join(resolveExeOsDir(), SESSION_CACHE_SUBDIR);
3161
+ return path14.join(resolveExeOsDir(), SESSION_CACHE_SUBDIR);
2423
3162
  }
2424
3163
  function getMarkerPath() {
2425
- return path13.join(getMarkerDir(), MARKER_FILENAME);
3164
+ return path14.join(getMarkerDir(), MARKER_FILENAME);
2426
3165
  }
2427
3166
  var UNREAD_MESSAGE_STATUSES = ["pending", "delivered"];
2428
3167
  function readMarker() {
@@ -2465,12 +3204,13 @@ async function queryPendingReviews() {
2465
3204
  }
2466
3205
  async function queryUnreadMessages() {
2467
3206
  const client = getClient();
3207
+ const hbScope = strictSessionScopeFilter();
2468
3208
  const placeholders = UNREAD_MESSAGE_STATUSES.map(() => "?").join(", ");
2469
3209
  const result = await client.execute({
2470
3210
  sql: `SELECT from_agent, content FROM messages
2471
- WHERE target_agent = 'exe' AND status IN (${placeholders})
3211
+ WHERE target_agent = 'exe' AND status IN (${placeholders})${hbScope.sql}
2472
3212
  ORDER BY created_at ASC LIMIT ?`,
2473
- args: [...UNREAD_MESSAGE_STATUSES, UNREAD_MESSAGE_LIMIT]
3213
+ args: [...UNREAD_MESSAGE_STATUSES, ...hbScope.args, UNREAD_MESSAGE_LIMIT]
2474
3214
  });
2475
3215
  if (result.rows.length === 0) return "";
2476
3216
  const lines = [`\u{1F4E8} ${result.rows.length} unread message(s):`];
@@ -2494,7 +3234,7 @@ function formatRelative(updatedAtIso) {
2494
3234
  }
2495
3235
  async function queryStaleInProgress(thresholdHours) {
2496
3236
  const client = getClient();
2497
- const hbScope = sessionScopeFilter();
3237
+ const hbScope = strictSessionScopeFilter();
2498
3238
  const result = await client.execute({
2499
3239
  sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
2500
3240
  WHERE status = 'in_progress'
@@ -2511,7 +3251,7 @@ async function queryStaleInProgress(thresholdHours) {
2511
3251
  }
2512
3252
  async function queryNewErrors(sinceIso) {
2513
3253
  const client = getClient();
2514
- const erScope = sessionScopeFilter();
3254
+ const erScope = strictSessionScopeFilter();
2515
3255
  const result = await client.execute({
2516
3256
  sql: erScope.args.length > 0 ? `SELECT COUNT(*) as cnt FROM memories
2517
3257
  WHERE has_error = 1 AND timestamp > ?
@@ -2556,10 +3296,11 @@ async function runHeartbeat() {
2556
3296
  writeMarker({ lastFiredAt: new Date(now).toISOString(), lastSurfaceHash: hash });
2557
3297
  try {
2558
3298
  const client = getClient();
3299
+ const ackScope = strictSessionScopeFilter();
2559
3300
  await client.execute({
2560
3301
  sql: `UPDATE messages SET status = 'acknowledged', processed_at = datetime('now')
2561
- WHERE target_agent = 'exe' AND status IN ('pending', 'delivered')`,
2562
- args: []
3302
+ WHERE target_agent = 'exe' AND status IN ('pending', 'delivered')${ackScope.sql}`,
3303
+ args: [...ackScope.args]
2563
3304
  });
2564
3305
  } catch {
2565
3306
  }