@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
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
6
  var __esm = (fn, res) => function __init() {
5
7
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
8
  };
@@ -8,6 +10,15 @@ var __export = (target, all) => {
8
10
  for (var name in all)
9
11
  __defProp(target, name, { get: all[name], enumerable: true });
10
12
  };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
11
22
 
12
23
  // src/lib/db-retry.ts
13
24
  function isBusyError(err) {
@@ -64,9 +75,34 @@ var init_db_retry = __esm({
64
75
  }
65
76
  });
66
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
+
67
103
  // src/lib/config.ts
68
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
69
- import { readFileSync, existsSync, renameSync } from "fs";
104
+ import { readFile, writeFile } from "fs/promises";
105
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
70
106
  import path from "path";
71
107
  import os from "os";
72
108
  function resolveDataDir() {
@@ -74,7 +110,7 @@ function resolveDataDir() {
74
110
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
75
111
  const newDir = path.join(os.homedir(), ".exe-os");
76
112
  const legacyDir = path.join(os.homedir(), ".exe-mem");
77
- if (!existsSync(newDir) && existsSync(legacyDir)) {
113
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
78
114
  try {
79
115
  renameSync(legacyDir, newDir);
80
116
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -137,9 +173,9 @@ function normalizeAutoUpdate(raw) {
137
173
  }
138
174
  async function loadConfig() {
139
175
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
140
- await mkdir(dir, { recursive: true });
176
+ await ensurePrivateDir(dir);
141
177
  const configPath = path.join(dir, "config.json");
142
- if (!existsSync(configPath)) {
178
+ if (!existsSync2(configPath)) {
143
179
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
144
180
  }
145
181
  const raw = await readFile(configPath, "utf-8");
@@ -152,6 +188,7 @@ async function loadConfig() {
152
188
  `);
153
189
  try {
154
190
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
191
+ await enforcePrivateFile(configPath);
155
192
  } catch {
156
193
  }
157
194
  }
@@ -171,6 +208,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
171
208
  var init_config = __esm({
172
209
  "src/lib/config.ts"() {
173
210
  "use strict";
211
+ init_secure_files();
174
212
  EXE_AI_DIR = resolveDataDir();
175
213
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
176
214
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -249,7 +287,7 @@ var init_config = __esm({
249
287
 
250
288
  // src/lib/employees.ts
251
289
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
252
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
290
+ import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
253
291
  import { execSync } from "child_process";
254
292
  import path2 from "path";
255
293
  import os2 from "os";
@@ -266,14 +304,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
266
304
  return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
267
305
  }
268
306
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
269
- if (!existsSync2(employeesPath)) return [];
307
+ if (!existsSync3(employeesPath)) return [];
270
308
  try {
271
309
  return JSON.parse(readFileSync2(employeesPath, "utf-8"));
272
310
  } catch {
273
311
  return [];
274
312
  }
275
313
  }
276
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
314
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
277
315
  var init_employees = __esm({
278
316
  "src/lib/employees.ts"() {
279
317
  "use strict";
@@ -281,12 +319,609 @@ var init_employees = __esm({
281
319
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
282
320
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
283
321
  COORDINATOR_ROLE = "COO";
322
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
323
+ }
324
+ });
325
+
326
+ // src/lib/database-adapter.ts
327
+ import os3 from "os";
328
+ import path3 from "path";
329
+ import { createRequire } from "module";
330
+ import { pathToFileURL } from "url";
331
+ function quotedIdentifier(identifier) {
332
+ return `"${identifier.replace(/"/g, '""')}"`;
333
+ }
334
+ function unqualifiedTableName(name) {
335
+ const raw = name.trim().replace(/^"|"$/g, "");
336
+ const parts = raw.split(".");
337
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
338
+ }
339
+ function stripTrailingSemicolon(sql) {
340
+ return sql.trim().replace(/;+\s*$/u, "");
341
+ }
342
+ function appendClause(sql, clause) {
343
+ const trimmed = stripTrailingSemicolon(sql);
344
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
345
+ if (!returningMatch) {
346
+ return `${trimmed}${clause}`;
347
+ }
348
+ const idx = returningMatch.index;
349
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
350
+ }
351
+ function normalizeStatement(stmt) {
352
+ if (typeof stmt === "string") {
353
+ return { kind: "positional", sql: stmt, args: [] };
354
+ }
355
+ const sql = stmt.sql;
356
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
357
+ return { kind: "positional", sql, args: stmt.args ?? [] };
358
+ }
359
+ return { kind: "named", sql, args: stmt.args };
360
+ }
361
+ function rewriteBooleanLiterals(sql) {
362
+ let out = sql;
363
+ for (const column of BOOLEAN_COLUMN_NAMES) {
364
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
365
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
366
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
367
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
368
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
369
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
370
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
371
+ }
372
+ return out;
373
+ }
374
+ function rewriteInsertOrIgnore(sql) {
375
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
376
+ return sql;
377
+ }
378
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
379
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
380
+ }
381
+ function rewriteInsertOrReplace(sql) {
382
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
383
+ if (!match) {
384
+ return sql;
385
+ }
386
+ const rawTable = match[1];
387
+ const rawColumns = match[2];
388
+ const remainder = match[3];
389
+ const tableName = unqualifiedTableName(rawTable);
390
+ const conflictKeys = UPSERT_KEYS[tableName];
391
+ if (!conflictKeys?.length) {
392
+ return sql;
393
+ }
394
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
395
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
396
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
397
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
398
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
399
+ }
400
+ function rewriteSql(sql) {
401
+ let out = sql;
402
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
403
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
404
+ out = rewriteBooleanLiterals(out);
405
+ out = rewriteInsertOrReplace(out);
406
+ out = rewriteInsertOrIgnore(out);
407
+ return stripTrailingSemicolon(out);
408
+ }
409
+ function toBoolean(value) {
410
+ if (value === null || value === void 0) return value;
411
+ if (typeof value === "boolean") return value;
412
+ if (typeof value === "number") return value !== 0;
413
+ if (typeof value === "bigint") return value !== 0n;
414
+ if (typeof value === "string") {
415
+ const normalized = value.trim().toLowerCase();
416
+ if (normalized === "0" || normalized === "false") return false;
417
+ if (normalized === "1" || normalized === "true") return true;
418
+ }
419
+ return Boolean(value);
420
+ }
421
+ function countQuestionMarks(sql, end) {
422
+ let count = 0;
423
+ let inSingle = false;
424
+ let inDouble = false;
425
+ let inLineComment = false;
426
+ let inBlockComment = false;
427
+ for (let i = 0; i < end; i++) {
428
+ const ch = sql[i];
429
+ const next = sql[i + 1];
430
+ if (inLineComment) {
431
+ if (ch === "\n") inLineComment = false;
432
+ continue;
433
+ }
434
+ if (inBlockComment) {
435
+ if (ch === "*" && next === "/") {
436
+ inBlockComment = false;
437
+ i += 1;
438
+ }
439
+ continue;
440
+ }
441
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
442
+ inLineComment = true;
443
+ i += 1;
444
+ continue;
445
+ }
446
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
447
+ inBlockComment = true;
448
+ i += 1;
449
+ continue;
450
+ }
451
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
452
+ inSingle = !inSingle;
453
+ continue;
454
+ }
455
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
456
+ inDouble = !inDouble;
457
+ continue;
458
+ }
459
+ if (!inSingle && !inDouble && ch === "?") {
460
+ count += 1;
461
+ }
462
+ }
463
+ return count;
464
+ }
465
+ function findBooleanPlaceholderIndexes(sql) {
466
+ const indexes = /* @__PURE__ */ new Set();
467
+ for (const column of BOOLEAN_COLUMN_NAMES) {
468
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
469
+ for (const match of sql.matchAll(pattern)) {
470
+ const matchText = match[0];
471
+ const qIndex = match.index + matchText.lastIndexOf("?");
472
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
473
+ }
474
+ }
475
+ return indexes;
476
+ }
477
+ function coerceInsertBooleanArgs(sql, args) {
478
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
479
+ if (!match) return;
480
+ const rawTable = match[1];
481
+ const rawColumns = match[2];
482
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
483
+ if (!boolColumns?.size) return;
484
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
485
+ for (const [index, column] of columns.entries()) {
486
+ if (boolColumns.has(column) && index < args.length) {
487
+ args[index] = toBoolean(args[index]);
488
+ }
489
+ }
490
+ }
491
+ function coerceUpdateBooleanArgs(sql, args) {
492
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
493
+ if (!match) return;
494
+ const rawTable = match[1];
495
+ const setClause = match[2];
496
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
497
+ if (!boolColumns?.size) return;
498
+ const assignments = setClause.split(",");
499
+ let placeholderIndex = 0;
500
+ for (const assignment of assignments) {
501
+ if (!assignment.includes("?")) continue;
502
+ placeholderIndex += 1;
503
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
504
+ if (colMatch && boolColumns.has(colMatch[1])) {
505
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
506
+ }
507
+ }
508
+ }
509
+ function coerceBooleanArgs(sql, args) {
510
+ const nextArgs = [...args];
511
+ coerceInsertBooleanArgs(sql, nextArgs);
512
+ coerceUpdateBooleanArgs(sql, nextArgs);
513
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
514
+ for (const index of placeholderIndexes) {
515
+ if (index > 0 && index <= nextArgs.length) {
516
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
517
+ }
518
+ }
519
+ return nextArgs;
520
+ }
521
+ function convertQuestionMarksToDollarParams(sql) {
522
+ let out = "";
523
+ let placeholder = 0;
524
+ let inSingle = false;
525
+ let inDouble = false;
526
+ let inLineComment = false;
527
+ let inBlockComment = false;
528
+ for (let i = 0; i < sql.length; i++) {
529
+ const ch = sql[i];
530
+ const next = sql[i + 1];
531
+ if (inLineComment) {
532
+ out += ch;
533
+ if (ch === "\n") inLineComment = false;
534
+ continue;
535
+ }
536
+ if (inBlockComment) {
537
+ out += ch;
538
+ if (ch === "*" && next === "/") {
539
+ out += next;
540
+ inBlockComment = false;
541
+ i += 1;
542
+ }
543
+ continue;
544
+ }
545
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
546
+ out += ch + next;
547
+ inLineComment = true;
548
+ i += 1;
549
+ continue;
550
+ }
551
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
552
+ out += ch + next;
553
+ inBlockComment = true;
554
+ i += 1;
555
+ continue;
556
+ }
557
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
558
+ inSingle = !inSingle;
559
+ out += ch;
560
+ continue;
561
+ }
562
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
563
+ inDouble = !inDouble;
564
+ out += ch;
565
+ continue;
566
+ }
567
+ if (!inSingle && !inDouble && ch === "?") {
568
+ placeholder += 1;
569
+ out += `$${placeholder}`;
570
+ continue;
571
+ }
572
+ out += ch;
573
+ }
574
+ return out;
575
+ }
576
+ function translateStatementForPostgres(stmt) {
577
+ const normalized = normalizeStatement(stmt);
578
+ if (normalized.kind === "named") {
579
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
580
+ }
581
+ const rewrittenSql = rewriteSql(normalized.sql);
582
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
583
+ return {
584
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
585
+ args: coercedArgs
586
+ };
587
+ }
588
+ function shouldBypassPostgres(stmt) {
589
+ const normalized = normalizeStatement(stmt);
590
+ if (normalized.kind === "named") {
591
+ return true;
592
+ }
593
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
594
+ }
595
+ function shouldFallbackOnError(error) {
596
+ const message = error instanceof Error ? error.message : String(error);
597
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
598
+ }
599
+ function isReadQuery(sql) {
600
+ const trimmed = sql.trimStart();
601
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
602
+ }
603
+ function buildRow(row, columns) {
604
+ const values = columns.map((column) => row[column]);
605
+ return Object.assign(values, row);
606
+ }
607
+ function buildResultSet(rows, rowsAffected = 0) {
608
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
609
+ const resultRows = rows.map((row) => buildRow(row, columns));
610
+ return {
611
+ columns,
612
+ columnTypes: columns.map(() => ""),
613
+ rows: resultRows,
614
+ rowsAffected,
615
+ lastInsertRowid: void 0,
616
+ toJSON() {
617
+ return {
618
+ columns,
619
+ columnTypes: columns.map(() => ""),
620
+ rows,
621
+ rowsAffected,
622
+ lastInsertRowid: void 0
623
+ };
624
+ }
625
+ };
626
+ }
627
+ async function loadPrismaClient() {
628
+ if (!prismaClientPromise) {
629
+ prismaClientPromise = (async () => {
630
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
631
+ if (explicitPath) {
632
+ const module2 = await import(pathToFileURL(explicitPath).href);
633
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
634
+ if (!PrismaClient2) {
635
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
636
+ }
637
+ return new PrismaClient2();
638
+ }
639
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
640
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
641
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
642
+ const module = await import(pathToFileURL(prismaEntry).href);
643
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
644
+ if (!PrismaClient) {
645
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
646
+ }
647
+ return new PrismaClient();
648
+ })();
649
+ }
650
+ return prismaClientPromise;
651
+ }
652
+ async function ensureCompatibilityViews(prisma) {
653
+ if (!compatibilityBootstrapPromise) {
654
+ compatibilityBootstrapPromise = (async () => {
655
+ for (const mapping of VIEW_MAPPINGS) {
656
+ const relation = mapping.source.replace(/"/g, "");
657
+ const rows = await prisma.$queryRawUnsafe(
658
+ "SELECT to_regclass($1) AS regclass",
659
+ relation
660
+ );
661
+ if (!rows[0]?.regclass) {
662
+ continue;
663
+ }
664
+ await prisma.$executeRawUnsafe(
665
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
666
+ );
667
+ }
668
+ })();
669
+ }
670
+ return compatibilityBootstrapPromise;
671
+ }
672
+ async function executeOnPrisma(executor, stmt) {
673
+ const translated = translateStatementForPostgres(stmt);
674
+ if (isReadQuery(translated.sql)) {
675
+ const rows = await executor.$queryRawUnsafe(
676
+ translated.sql,
677
+ ...translated.args
678
+ );
679
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
680
+ }
681
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
682
+ return buildResultSet([], rowsAffected);
683
+ }
684
+ function splitSqlStatements(sql) {
685
+ const parts = [];
686
+ let current = "";
687
+ let inSingle = false;
688
+ let inDouble = false;
689
+ let inLineComment = false;
690
+ let inBlockComment = false;
691
+ for (let i = 0; i < sql.length; i++) {
692
+ const ch = sql[i];
693
+ const next = sql[i + 1];
694
+ if (inLineComment) {
695
+ current += ch;
696
+ if (ch === "\n") inLineComment = false;
697
+ continue;
698
+ }
699
+ if (inBlockComment) {
700
+ current += ch;
701
+ if (ch === "*" && next === "/") {
702
+ current += next;
703
+ inBlockComment = false;
704
+ i += 1;
705
+ }
706
+ continue;
707
+ }
708
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
709
+ current += ch + next;
710
+ inLineComment = true;
711
+ i += 1;
712
+ continue;
713
+ }
714
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
715
+ current += ch + next;
716
+ inBlockComment = true;
717
+ i += 1;
718
+ continue;
719
+ }
720
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
721
+ inSingle = !inSingle;
722
+ current += ch;
723
+ continue;
724
+ }
725
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
726
+ inDouble = !inDouble;
727
+ current += ch;
728
+ continue;
729
+ }
730
+ if (!inSingle && !inDouble && ch === ";") {
731
+ if (current.trim()) {
732
+ parts.push(current.trim());
733
+ }
734
+ current = "";
735
+ continue;
736
+ }
737
+ current += ch;
738
+ }
739
+ if (current.trim()) {
740
+ parts.push(current.trim());
741
+ }
742
+ return parts;
743
+ }
744
+ async function createPrismaDbAdapter(fallbackClient) {
745
+ const prisma = await loadPrismaClient();
746
+ await ensureCompatibilityViews(prisma);
747
+ let closed = false;
748
+ let adapter;
749
+ const fallbackExecute = async (stmt, error) => {
750
+ if (!fallbackClient) {
751
+ if (error) throw error;
752
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
753
+ }
754
+ if (error) {
755
+ process.stderr.write(
756
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
757
+ `
758
+ );
759
+ }
760
+ return fallbackClient.execute(stmt);
761
+ };
762
+ adapter = {
763
+ async execute(stmt) {
764
+ if (shouldBypassPostgres(stmt)) {
765
+ return fallbackExecute(stmt);
766
+ }
767
+ try {
768
+ return await executeOnPrisma(prisma, stmt);
769
+ } catch (error) {
770
+ if (shouldFallbackOnError(error)) {
771
+ return fallbackExecute(stmt, error);
772
+ }
773
+ throw error;
774
+ }
775
+ },
776
+ async batch(stmts, mode) {
777
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
778
+ if (!fallbackClient) {
779
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
780
+ }
781
+ return fallbackClient.batch(stmts, mode);
782
+ }
783
+ try {
784
+ if (prisma.$transaction) {
785
+ return await prisma.$transaction(async (tx) => {
786
+ const results2 = [];
787
+ for (const stmt of stmts) {
788
+ results2.push(await executeOnPrisma(tx, stmt));
789
+ }
790
+ return results2;
791
+ });
792
+ }
793
+ const results = [];
794
+ for (const stmt of stmts) {
795
+ results.push(await executeOnPrisma(prisma, stmt));
796
+ }
797
+ return results;
798
+ } catch (error) {
799
+ if (fallbackClient && shouldFallbackOnError(error)) {
800
+ process.stderr.write(
801
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
802
+ `
803
+ );
804
+ return fallbackClient.batch(stmts, mode);
805
+ }
806
+ throw error;
807
+ }
808
+ },
809
+ async migrate(stmts) {
810
+ if (fallbackClient) {
811
+ return fallbackClient.migrate(stmts);
812
+ }
813
+ return adapter.batch(stmts, "deferred");
814
+ },
815
+ async transaction(mode) {
816
+ if (!fallbackClient) {
817
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
818
+ }
819
+ return fallbackClient.transaction(mode);
820
+ },
821
+ async executeMultiple(sql) {
822
+ if (fallbackClient && shouldBypassPostgres(sql)) {
823
+ return fallbackClient.executeMultiple(sql);
824
+ }
825
+ for (const statement of splitSqlStatements(sql)) {
826
+ await adapter.execute(statement);
827
+ }
828
+ },
829
+ async sync() {
830
+ if (fallbackClient) {
831
+ return fallbackClient.sync();
832
+ }
833
+ return { frame_no: 0, frames_synced: 0 };
834
+ },
835
+ close() {
836
+ closed = true;
837
+ prismaClientPromise = null;
838
+ compatibilityBootstrapPromise = null;
839
+ void prisma.$disconnect?.();
840
+ },
841
+ get closed() {
842
+ return closed;
843
+ },
844
+ get protocol() {
845
+ return "prisma-postgres";
846
+ }
847
+ };
848
+ return adapter;
849
+ }
850
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
851
+ var init_database_adapter = __esm({
852
+ "src/lib/database-adapter.ts"() {
853
+ "use strict";
854
+ VIEW_MAPPINGS = [
855
+ { view: "memories", source: "memory.memory_records" },
856
+ { view: "tasks", source: "memory.tasks" },
857
+ { view: "behaviors", source: "memory.behaviors" },
858
+ { view: "entities", source: "memory.entities" },
859
+ { view: "relationships", source: "memory.relationships" },
860
+ { view: "entity_memories", source: "memory.entity_memories" },
861
+ { view: "entity_aliases", source: "memory.entity_aliases" },
862
+ { view: "notifications", source: "memory.notifications" },
863
+ { view: "messages", source: "memory.messages" },
864
+ { view: "users", source: "wiki.users" },
865
+ { view: "workspaces", source: "wiki.workspaces" },
866
+ { view: "workspace_users", source: "wiki.workspace_users" },
867
+ { view: "documents", source: "wiki.workspace_documents" },
868
+ { view: "chats", source: "wiki.workspace_chats" }
869
+ ];
870
+ UPSERT_KEYS = {
871
+ memories: ["id"],
872
+ tasks: ["id"],
873
+ behaviors: ["id"],
874
+ entities: ["id"],
875
+ relationships: ["id"],
876
+ entity_aliases: ["alias"],
877
+ notifications: ["id"],
878
+ messages: ["id"],
879
+ users: ["id"],
880
+ workspaces: ["id"],
881
+ workspace_users: ["id"],
882
+ documents: ["id"],
883
+ chats: ["id"]
884
+ };
885
+ BOOLEAN_COLUMNS_BY_TABLE = {
886
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
887
+ behaviors: /* @__PURE__ */ new Set(["active"]),
888
+ notifications: /* @__PURE__ */ new Set(["read"]),
889
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
890
+ };
891
+ BOOLEAN_COLUMN_NAMES = new Set(
892
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
893
+ );
894
+ IMMEDIATE_FALLBACK_PATTERNS = [
895
+ /\bPRAGMA\b/i,
896
+ /\bsqlite_master\b/i,
897
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
898
+ /\bMATCH\b/i,
899
+ /\bvector_distance_cos\s*\(/i,
900
+ /\bjson_extract\s*\(/i,
901
+ /\bjulianday\s*\(/i,
902
+ /\bstrftime\s*\(/i,
903
+ /\blast_insert_rowid\s*\(/i
904
+ ];
905
+ prismaClientPromise = null;
906
+ compatibilityBootstrapPromise = null;
284
907
  }
285
908
  });
286
909
 
287
910
  // src/lib/database.ts
288
911
  import { createClient } from "@libsql/client";
289
912
  async function initDatabase(config) {
913
+ if (_walCheckpointTimer) {
914
+ clearInterval(_walCheckpointTimer);
915
+ _walCheckpointTimer = null;
916
+ }
917
+ if (_daemonClient) {
918
+ _daemonClient.close();
919
+ _daemonClient = null;
920
+ }
921
+ if (_adapterClient && _adapterClient !== _resilientClient) {
922
+ _adapterClient.close();
923
+ }
924
+ _adapterClient = null;
290
925
  if (_client) {
291
926
  _client.close();
292
927
  _client = null;
@@ -300,6 +935,7 @@ async function initDatabase(config) {
300
935
  }
301
936
  _client = createClient(opts);
302
937
  _resilientClient = wrapWithRetry(_client);
938
+ _adapterClient = _resilientClient;
303
939
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
304
940
  });
305
941
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -310,11 +946,17 @@ async function initDatabase(config) {
310
946
  });
311
947
  }, 3e4);
312
948
  _walCheckpointTimer.unref();
949
+ if (process.env.DATABASE_URL) {
950
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
951
+ }
313
952
  }
314
953
  function getClient() {
315
- if (!_resilientClient) {
954
+ if (!_adapterClient) {
316
955
  throw new Error("Database client not initialized. Call initDatabase() first.");
317
956
  }
957
+ if (process.env.DATABASE_URL) {
958
+ return _adapterClient;
959
+ }
318
960
  if (process.env.EXE_IS_DAEMON === "1") {
319
961
  return _resilientClient;
320
962
  }
@@ -607,6 +1249,7 @@ async function ensureSchema() {
607
1249
  project TEXT NOT NULL,
608
1250
  summary TEXT NOT NULL,
609
1251
  task_file TEXT,
1252
+ session_scope TEXT,
610
1253
  read INTEGER NOT NULL DEFAULT 0,
611
1254
  created_at TEXT NOT NULL
612
1255
  );
@@ -615,7 +1258,7 @@ async function ensureSchema() {
615
1258
  ON notifications(read);
616
1259
 
617
1260
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
618
- ON notifications(agent_id);
1261
+ ON notifications(agent_id, session_scope);
619
1262
 
620
1263
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
621
1264
  ON notifications(task_file);
@@ -653,6 +1296,7 @@ async function ensureSchema() {
653
1296
  target_agent TEXT NOT NULL,
654
1297
  target_project TEXT,
655
1298
  target_device TEXT NOT NULL DEFAULT 'local',
1299
+ session_scope TEXT,
656
1300
  content TEXT NOT NULL,
657
1301
  priority TEXT DEFAULT 'normal',
658
1302
  status TEXT DEFAULT 'pending',
@@ -666,10 +1310,31 @@ async function ensureSchema() {
666
1310
  );
667
1311
 
668
1312
  CREATE INDEX IF NOT EXISTS idx_messages_target
669
- ON messages(target_agent, status);
1313
+ ON messages(target_agent, session_scope, status);
670
1314
 
671
1315
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
672
- ON messages(target_agent, from_agent, server_seq);
1316
+ ON messages(target_agent, session_scope, from_agent, server_seq);
1317
+ `);
1318
+ try {
1319
+ await client.execute({
1320
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1321
+ args: []
1322
+ });
1323
+ } catch {
1324
+ }
1325
+ try {
1326
+ await client.execute({
1327
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1328
+ args: []
1329
+ });
1330
+ } catch {
1331
+ }
1332
+ await client.executeMultiple(`
1333
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1334
+ ON notifications(agent_id, session_scope, read, created_at);
1335
+
1336
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1337
+ ON messages(target_agent, session_scope, status, created_at);
673
1338
  `);
674
1339
  try {
675
1340
  await client.execute({
@@ -1253,26 +1918,91 @@ async function ensureSchema() {
1253
1918
  } catch {
1254
1919
  }
1255
1920
  }
1921
+ try {
1922
+ await client.execute({
1923
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1924
+ args: []
1925
+ });
1926
+ } catch {
1927
+ }
1256
1928
  }
1257
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1929
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1258
1930
  var init_database = __esm({
1259
1931
  "src/lib/database.ts"() {
1260
1932
  "use strict";
1261
1933
  init_db_retry();
1262
1934
  init_employees();
1935
+ init_database_adapter();
1263
1936
  _client = null;
1264
1937
  _resilientClient = null;
1265
1938
  _walCheckpointTimer = null;
1266
1939
  _daemonClient = null;
1940
+ _adapterClient = null;
1267
1941
  initTurso = initDatabase;
1268
1942
  }
1269
1943
  });
1270
1944
 
1945
+ // src/lib/state-bus.ts
1946
+ var StateBus, orgBus;
1947
+ var init_state_bus = __esm({
1948
+ "src/lib/state-bus.ts"() {
1949
+ "use strict";
1950
+ StateBus = class {
1951
+ handlers = /* @__PURE__ */ new Map();
1952
+ globalHandlers = /* @__PURE__ */ new Set();
1953
+ /** Emit an event to all subscribers */
1954
+ emit(event) {
1955
+ const typeHandlers = this.handlers.get(event.type);
1956
+ if (typeHandlers) {
1957
+ for (const handler of typeHandlers) {
1958
+ try {
1959
+ handler(event);
1960
+ } catch {
1961
+ }
1962
+ }
1963
+ }
1964
+ for (const handler of this.globalHandlers) {
1965
+ try {
1966
+ handler(event);
1967
+ } catch {
1968
+ }
1969
+ }
1970
+ }
1971
+ /** Subscribe to a specific event type */
1972
+ on(type, handler) {
1973
+ if (!this.handlers.has(type)) {
1974
+ this.handlers.set(type, /* @__PURE__ */ new Set());
1975
+ }
1976
+ this.handlers.get(type).add(handler);
1977
+ }
1978
+ /** Subscribe to ALL events */
1979
+ onAny(handler) {
1980
+ this.globalHandlers.add(handler);
1981
+ }
1982
+ /** Unsubscribe from a specific event type */
1983
+ off(type, handler) {
1984
+ this.handlers.get(type)?.delete(handler);
1985
+ }
1986
+ /** Unsubscribe from ALL events */
1987
+ offAny(handler) {
1988
+ this.globalHandlers.delete(handler);
1989
+ }
1990
+ /** Remove all listeners */
1991
+ clear() {
1992
+ this.handlers.clear();
1993
+ this.globalHandlers.clear();
1994
+ }
1995
+ };
1996
+ orgBus = new StateBus();
1997
+ }
1998
+ });
1999
+
1271
2000
  // src/lib/shard-manager.ts
1272
2001
  var shard_manager_exports = {};
1273
2002
  __export(shard_manager_exports, {
1274
2003
  disposeShards: () => disposeShards,
1275
2004
  ensureShardSchema: () => ensureShardSchema,
2005
+ getOpenShardCount: () => getOpenShardCount,
1276
2006
  getReadyShardClient: () => getReadyShardClient,
1277
2007
  getShardClient: () => getShardClient,
1278
2008
  getShardsDir: () => getShardsDir,
@@ -1281,15 +2011,18 @@ __export(shard_manager_exports, {
1281
2011
  listShards: () => listShards,
1282
2012
  shardExists: () => shardExists
1283
2013
  });
1284
- import path4 from "path";
1285
- import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
2014
+ import path5 from "path";
2015
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
1286
2016
  import { createClient as createClient2 } from "@libsql/client";
1287
2017
  function initShardManager(encryptionKey) {
1288
2018
  _encryptionKey = encryptionKey;
1289
- if (!existsSync4(SHARDS_DIR)) {
1290
- mkdirSync(SHARDS_DIR, { recursive: true });
2019
+ if (!existsSync5(SHARDS_DIR)) {
2020
+ mkdirSync2(SHARDS_DIR, { recursive: true });
1291
2021
  }
1292
2022
  _shardingEnabled = true;
2023
+ if (_evictionTimer) clearInterval(_evictionTimer);
2024
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2025
+ _evictionTimer.unref();
1293
2026
  }
1294
2027
  function isShardingEnabled() {
1295
2028
  return _shardingEnabled;
@@ -1306,21 +2039,28 @@ function getShardClient(projectName) {
1306
2039
  throw new Error(`Invalid project name for shard: "${projectName}"`);
1307
2040
  }
1308
2041
  const cached = _shards.get(safeName);
1309
- if (cached) return cached;
1310
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
2042
+ if (cached) {
2043
+ _shardLastAccess.set(safeName, Date.now());
2044
+ return cached;
2045
+ }
2046
+ while (_shards.size >= MAX_OPEN_SHARDS) {
2047
+ evictLRU();
2048
+ }
2049
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1311
2050
  const client = createClient2({
1312
2051
  url: `file:${dbPath}`,
1313
2052
  encryptionKey: _encryptionKey
1314
2053
  });
1315
2054
  _shards.set(safeName, client);
2055
+ _shardLastAccess.set(safeName, Date.now());
1316
2056
  return client;
1317
2057
  }
1318
2058
  function shardExists(projectName) {
1319
2059
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1320
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2060
+ return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
1321
2061
  }
1322
2062
  function listShards() {
1323
- if (!existsSync4(SHARDS_DIR)) return [];
2063
+ if (!existsSync5(SHARDS_DIR)) return [];
1324
2064
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1325
2065
  }
1326
2066
  async function ensureShardSchema(client) {
@@ -1372,6 +2112,8 @@ async function ensureShardSchema(client) {
1372
2112
  for (const col of [
1373
2113
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
1374
2114
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2115
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2116
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
1375
2117
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1376
2118
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1377
2119
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -1394,7 +2136,23 @@ async function ensureShardSchema(client) {
1394
2136
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1395
2137
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1396
2138
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1397
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2139
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2140
+ // Metadata enrichment columns (must match database.ts)
2141
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2142
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2143
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2144
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2145
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2146
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2147
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2148
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2149
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2150
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2151
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2152
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2153
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2154
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2155
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1398
2156
  ]) {
1399
2157
  try {
1400
2158
  await client.execute(col);
@@ -1493,21 +2251,69 @@ async function getReadyShardClient(projectName) {
1493
2251
  await ensureShardSchema(client);
1494
2252
  return client;
1495
2253
  }
2254
+ function evictLRU() {
2255
+ let oldest = null;
2256
+ let oldestTime = Infinity;
2257
+ for (const [name, time] of _shardLastAccess) {
2258
+ if (time < oldestTime) {
2259
+ oldestTime = time;
2260
+ oldest = name;
2261
+ }
2262
+ }
2263
+ if (oldest) {
2264
+ const client = _shards.get(oldest);
2265
+ if (client) {
2266
+ client.close();
2267
+ }
2268
+ _shards.delete(oldest);
2269
+ _shardLastAccess.delete(oldest);
2270
+ }
2271
+ }
2272
+ function evictIdleShards() {
2273
+ const now = Date.now();
2274
+ const toEvict = [];
2275
+ for (const [name, lastAccess] of _shardLastAccess) {
2276
+ if (now - lastAccess > SHARD_IDLE_MS) {
2277
+ toEvict.push(name);
2278
+ }
2279
+ }
2280
+ for (const name of toEvict) {
2281
+ const client = _shards.get(name);
2282
+ if (client) {
2283
+ client.close();
2284
+ }
2285
+ _shards.delete(name);
2286
+ _shardLastAccess.delete(name);
2287
+ }
2288
+ }
2289
+ function getOpenShardCount() {
2290
+ return _shards.size;
2291
+ }
1496
2292
  function disposeShards() {
2293
+ if (_evictionTimer) {
2294
+ clearInterval(_evictionTimer);
2295
+ _evictionTimer = null;
2296
+ }
1497
2297
  for (const [, client] of _shards) {
1498
2298
  client.close();
1499
2299
  }
1500
2300
  _shards.clear();
2301
+ _shardLastAccess.clear();
1501
2302
  _shardingEnabled = false;
1502
2303
  _encryptionKey = null;
1503
2304
  }
1504
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
2305
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
1505
2306
  var init_shard_manager = __esm({
1506
2307
  "src/lib/shard-manager.ts"() {
1507
2308
  "use strict";
1508
2309
  init_config();
1509
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2310
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2311
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
2312
+ MAX_OPEN_SHARDS = 10;
2313
+ EVICTION_INTERVAL_MS = 60 * 1e3;
1510
2314
  _shards = /* @__PURE__ */ new Map();
2315
+ _shardLastAccess = /* @__PURE__ */ new Map();
2316
+ _evictionTimer = null;
1511
2317
  _encryptionKey = null;
1512
2318
  _shardingEnabled = false;
1513
2319
  }
@@ -1700,22 +2506,486 @@ ${p.content}`).join("\n\n");
1700
2506
  }
1701
2507
  });
1702
2508
 
2509
+ // src/lib/session-registry.ts
2510
+ import path6 from "path";
2511
+ import os5 from "os";
2512
+ var REGISTRY_PATH;
2513
+ var init_session_registry = __esm({
2514
+ "src/lib/session-registry.ts"() {
2515
+ "use strict";
2516
+ REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
2517
+ }
2518
+ });
2519
+
2520
+ // src/lib/session-key.ts
2521
+ import { execSync as execSync2 } from "child_process";
2522
+ function normalizeCommand(command) {
2523
+ const trimmed = command.trim().toLowerCase();
2524
+ const parts = trimmed.split(/[\\/]/);
2525
+ return parts[parts.length - 1] ?? trimmed;
2526
+ }
2527
+ function detectRuntimeFromCommand(command) {
2528
+ const normalized = normalizeCommand(command);
2529
+ for (const [runtime, commands] of Object.entries(RUNTIME_COMMANDS)) {
2530
+ if (commands.includes(normalized)) {
2531
+ return runtime;
2532
+ }
2533
+ }
2534
+ return null;
2535
+ }
2536
+ function resolveRuntimeProcess() {
2537
+ let pid = process.ppid;
2538
+ for (let i = 0; i < 10; i++) {
2539
+ try {
2540
+ const info = execSync2(`ps -p ${pid} -o ppid=,comm=`, {
2541
+ encoding: "utf8",
2542
+ timeout: 2e3
2543
+ }).trim();
2544
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
2545
+ if (!match) break;
2546
+ const [, ppid, cmd] = match;
2547
+ const runtime = detectRuntimeFromCommand(cmd ?? "");
2548
+ if (runtime) {
2549
+ return { pid: String(pid), runtime };
2550
+ }
2551
+ pid = parseInt(ppid, 10);
2552
+ if (pid <= 1) break;
2553
+ } catch {
2554
+ break;
2555
+ }
2556
+ }
2557
+ return null;
2558
+ }
2559
+ function getSessionKey() {
2560
+ if (_cached) return _cached;
2561
+ if (process.env.EXE_SESSION_KEY) {
2562
+ _cached = process.env.EXE_SESSION_KEY;
2563
+ return _cached;
2564
+ }
2565
+ const resolved = resolveRuntimeProcess();
2566
+ if (resolved) {
2567
+ _cachedRuntime = resolved.runtime;
2568
+ _cached = resolved.pid;
2569
+ return _cached;
2570
+ }
2571
+ _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2572
+ return _cached;
2573
+ }
2574
+ var _cached, _cachedRuntime, RUNTIME_COMMANDS;
2575
+ var init_session_key = __esm({
2576
+ "src/lib/session-key.ts"() {
2577
+ "use strict";
2578
+ _cached = null;
2579
+ _cachedRuntime = null;
2580
+ RUNTIME_COMMANDS = {
2581
+ claude: ["claude", "claude.exe", "claude-native"],
2582
+ codex: ["codex"],
2583
+ opencode: ["opencode"]
2584
+ };
2585
+ }
2586
+ });
2587
+
2588
+ // src/lib/tmux-transport.ts
2589
+ var tmux_transport_exports = {};
2590
+ __export(tmux_transport_exports, {
2591
+ TmuxTransport: () => TmuxTransport
2592
+ });
2593
+ import { execFileSync } from "child_process";
2594
+ var QUIET, TmuxTransport;
2595
+ var init_tmux_transport = __esm({
2596
+ "src/lib/tmux-transport.ts"() {
2597
+ "use strict";
2598
+ QUIET = {
2599
+ encoding: "utf8",
2600
+ stdio: ["pipe", "pipe", "pipe"]
2601
+ };
2602
+ TmuxTransport = class {
2603
+ getMySession() {
2604
+ try {
2605
+ return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
2606
+ } catch {
2607
+ return null;
2608
+ }
2609
+ }
2610
+ listSessions() {
2611
+ try {
2612
+ return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
2613
+ } catch {
2614
+ return [];
2615
+ }
2616
+ }
2617
+ isAlive(target) {
2618
+ try {
2619
+ const sessions = this.listSessions();
2620
+ if (!sessions.includes(target)) return false;
2621
+ const paneStatus = execFileSync(
2622
+ "tmux",
2623
+ ["list-panes", "-t", target, "-F", "#{pane_dead}"],
2624
+ QUIET
2625
+ ).trim();
2626
+ return paneStatus !== "1";
2627
+ } catch {
2628
+ return false;
2629
+ }
2630
+ }
2631
+ sendKeys(target, keys) {
2632
+ execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
2633
+ }
2634
+ capturePane(target, lines) {
2635
+ const args = ["capture-pane", "-t", target, "-p"];
2636
+ if (lines) args.push("-S", `-${lines}`);
2637
+ return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
2638
+ }
2639
+ isPaneInCopyMode(target) {
2640
+ try {
2641
+ const result = execFileSync(
2642
+ "tmux",
2643
+ ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
2644
+ { ...QUIET, timeout: 3e3 }
2645
+ ).trim();
2646
+ return result === "1";
2647
+ } catch {
2648
+ return false;
2649
+ }
2650
+ }
2651
+ spawn(name, config) {
2652
+ try {
2653
+ const args = ["new-session", "-d", "-s", name];
2654
+ if (config.cwd) args.push("-c", config.cwd);
2655
+ args.push(config.command);
2656
+ execFileSync("tmux", args);
2657
+ return { sessionName: name };
2658
+ } catch (e) {
2659
+ return { sessionName: name, error: `spawn failed: ${e}` };
2660
+ }
2661
+ }
2662
+ kill(target) {
2663
+ try {
2664
+ execFileSync("tmux", ["kill-session", "-t", target], QUIET);
2665
+ } catch {
2666
+ }
2667
+ }
2668
+ pipeLog(target, logFile) {
2669
+ try {
2670
+ const safePath = logFile.replace(/'/g, "'\\''");
2671
+ execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
2672
+ } catch {
2673
+ }
2674
+ }
2675
+ };
2676
+ }
2677
+ });
2678
+
2679
+ // src/lib/transport.ts
2680
+ function getTransport() {
2681
+ if (!_transport) {
2682
+ const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
2683
+ _transport = new TmuxTransport2();
2684
+ }
2685
+ return _transport;
2686
+ }
2687
+ var _transport;
2688
+ var init_transport = __esm({
2689
+ "src/lib/transport.ts"() {
2690
+ "use strict";
2691
+ _transport = null;
2692
+ }
2693
+ });
2694
+
2695
+ // src/lib/cc-agent-support.ts
2696
+ import { execSync as execSync3 } from "child_process";
2697
+ var init_cc_agent_support = __esm({
2698
+ "src/lib/cc-agent-support.ts"() {
2699
+ "use strict";
2700
+ }
2701
+ });
2702
+
2703
+ // src/lib/mcp-prefix.ts
2704
+ var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2705
+ var init_mcp_prefix = __esm({
2706
+ "src/lib/mcp-prefix.ts"() {
2707
+ "use strict";
2708
+ MCP_PRIMARY_KEY = "exe-os";
2709
+ MCP_LEGACY_KEY = "exe-mem";
2710
+ MCP_TOOL_PREFIXES = [
2711
+ `mcp__${MCP_PRIMARY_KEY}__`,
2712
+ `mcp__${MCP_LEGACY_KEY}__`
2713
+ ];
2714
+ }
2715
+ });
2716
+
2717
+ // src/lib/provider-table.ts
2718
+ var init_provider_table = __esm({
2719
+ "src/lib/provider-table.ts"() {
2720
+ "use strict";
2721
+ }
2722
+ });
2723
+
2724
+ // src/lib/runtime-table.ts
2725
+ var RUNTIME_TABLE;
2726
+ var init_runtime_table = __esm({
2727
+ "src/lib/runtime-table.ts"() {
2728
+ "use strict";
2729
+ RUNTIME_TABLE = {
2730
+ codex: {
2731
+ binary: "codex",
2732
+ launchMode: "interactive",
2733
+ autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
2734
+ inlineFlag: "--no-alt-screen",
2735
+ apiKeyEnv: "OPENAI_API_KEY",
2736
+ defaultModel: "gpt-5.4"
2737
+ },
2738
+ opencode: {
2739
+ binary: "opencode",
2740
+ launchMode: "exec",
2741
+ autoApproveFlag: "--dangerously-skip-permissions",
2742
+ inlineFlag: "",
2743
+ apiKeyEnv: "ANTHROPIC_API_KEY",
2744
+ defaultModel: "anthropic/claude-sonnet-4-6"
2745
+ }
2746
+ };
2747
+ }
2748
+ });
2749
+
2750
+ // src/lib/agent-config.ts
2751
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync6 } from "fs";
2752
+ import path7 from "path";
2753
+ var AGENT_CONFIG_PATH, DEFAULT_MODELS;
2754
+ var init_agent_config = __esm({
2755
+ "src/lib/agent-config.ts"() {
2756
+ "use strict";
2757
+ init_config();
2758
+ init_runtime_table();
2759
+ init_secure_files();
2760
+ AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
2761
+ DEFAULT_MODELS = {
2762
+ claude: "claude-opus-4",
2763
+ codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
2764
+ opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
2765
+ };
2766
+ }
2767
+ });
2768
+
2769
+ // src/lib/intercom-queue.ts
2770
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
2771
+ import path8 from "path";
2772
+ import os6 from "os";
2773
+ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2774
+ var init_intercom_queue = __esm({
2775
+ "src/lib/intercom-queue.ts"() {
2776
+ "use strict";
2777
+ QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
2778
+ TTL_MS = 60 * 60 * 1e3;
2779
+ INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
2780
+ }
2781
+ });
2782
+
2783
+ // src/lib/license.ts
2784
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2785
+ import { randomUUID as randomUUID2 } from "crypto";
2786
+ import { createRequire as createRequire2 } from "module";
2787
+ import { pathToFileURL as pathToFileURL2 } from "url";
2788
+ import os7 from "os";
2789
+ import path9 from "path";
2790
+ import { jwtVerify, importSPKI } from "jose";
2791
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2792
+ var init_license = __esm({
2793
+ "src/lib/license.ts"() {
2794
+ "use strict";
2795
+ init_config();
2796
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2797
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2798
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2799
+ }
2800
+ });
2801
+
2802
+ // src/lib/plan-limits.ts
2803
+ import { readFileSync as readFileSync6, existsSync as existsSync9 } from "fs";
2804
+ import path10 from "path";
2805
+ var CACHE_PATH2;
2806
+ var init_plan_limits = __esm({
2807
+ "src/lib/plan-limits.ts"() {
2808
+ "use strict";
2809
+ init_database();
2810
+ init_employees();
2811
+ init_license();
2812
+ init_config();
2813
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2814
+ }
2815
+ });
2816
+
2817
+ // src/lib/tmux-routing.ts
2818
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync, readdirSync as readdirSync2 } from "fs";
2819
+ import path11 from "path";
2820
+ import os8 from "os";
2821
+ import { fileURLToPath } from "url";
2822
+ function getMySession() {
2823
+ return getTransport().getMySession();
2824
+ }
2825
+ function extractRootExe(name) {
2826
+ if (!name) return null;
2827
+ if (!name.includes("-")) return name;
2828
+ const parts = name.split("-").filter(Boolean);
2829
+ return parts.length > 0 ? parts[parts.length - 1] : null;
2830
+ }
2831
+ function getParentExe(sessionKey) {
2832
+ try {
2833
+ const data = JSON.parse(readFileSync7(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2834
+ return data.parentExe || null;
2835
+ } catch {
2836
+ return null;
2837
+ }
2838
+ }
2839
+ function resolveExeSession() {
2840
+ const mySession = getMySession();
2841
+ if (!mySession) return null;
2842
+ const fromSessionName = extractRootExe(mySession);
2843
+ try {
2844
+ const key = getSessionKey();
2845
+ const parentExe = getParentExe(key);
2846
+ if (parentExe) {
2847
+ const fromCache = extractRootExe(parentExe) ?? parentExe;
2848
+ if (fromSessionName && fromCache !== fromSessionName) {
2849
+ process.stderr.write(
2850
+ `[tmux-routing] WARN: cache says "${fromCache}" but session name says "${fromSessionName}". Trusting session name.
2851
+ `
2852
+ );
2853
+ return fromSessionName;
2854
+ }
2855
+ return fromCache;
2856
+ }
2857
+ } catch {
2858
+ }
2859
+ return fromSessionName ?? mySession;
2860
+ }
2861
+ var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
2862
+ var init_tmux_routing = __esm({
2863
+ "src/lib/tmux-routing.ts"() {
2864
+ "use strict";
2865
+ init_session_registry();
2866
+ init_session_key();
2867
+ init_transport();
2868
+ init_cc_agent_support();
2869
+ init_mcp_prefix();
2870
+ init_provider_table();
2871
+ init_agent_config();
2872
+ init_runtime_table();
2873
+ init_intercom_queue();
2874
+ init_plan_limits();
2875
+ init_employees();
2876
+ SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
2877
+ SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
2878
+ INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
2879
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2880
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2881
+ }
2882
+ });
2883
+
2884
+ // src/lib/task-scope.ts
2885
+ function getCurrentSessionScope() {
2886
+ try {
2887
+ return resolveExeSession();
2888
+ } catch {
2889
+ return null;
2890
+ }
2891
+ }
2892
+ function strictSessionScopeFilter(sessionScope, tableAlias) {
2893
+ const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
2894
+ if (!scope) return { sql: "", args: [] };
2895
+ const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
2896
+ return {
2897
+ sql: ` AND ${col} = ?`,
2898
+ args: [scope]
2899
+ };
2900
+ }
2901
+ var init_task_scope = __esm({
2902
+ "src/lib/task-scope.ts"() {
2903
+ "use strict";
2904
+ init_tmux_routing();
2905
+ }
2906
+ });
2907
+
2908
+ // src/lib/notifications.ts
2909
+ import crypto from "crypto";
2910
+ import path12 from "path";
2911
+ import os9 from "os";
2912
+ import {
2913
+ readFileSync as readFileSync8,
2914
+ readdirSync as readdirSync3,
2915
+ unlinkSync as unlinkSync2,
2916
+ existsSync as existsSync11,
2917
+ rmdirSync
2918
+ } from "fs";
2919
+ async function readUnreadNotifications(agentFilter, sessionScope) {
2920
+ try {
2921
+ const client = getClient();
2922
+ const conditions = ["read = 0"];
2923
+ const args = [];
2924
+ const scope = strictSessionScopeFilter(sessionScope);
2925
+ if (agentFilter) {
2926
+ conditions.push("agent_id = ?");
2927
+ args.push(agentFilter);
2928
+ }
2929
+ const result = await client.execute({
2930
+ sql: `SELECT id, agent_id, agent_role, event, project, summary, task_file, session_scope, created_at
2931
+ FROM notifications
2932
+ WHERE ${conditions.join(" AND ")}${scope.sql}
2933
+ ORDER BY created_at ASC`,
2934
+ args: [...args, ...scope.args]
2935
+ });
2936
+ return result.rows.map((r) => ({
2937
+ id: String(r.id),
2938
+ agentId: String(r.agent_id),
2939
+ agentRole: String(r.agent_role),
2940
+ event: String(r.event),
2941
+ project: String(r.project),
2942
+ summary: String(r.summary),
2943
+ taskFile: r.task_file ? String(r.task_file) : void 0,
2944
+ sessionScope: r.session_scope == null ? null : String(r.session_scope),
2945
+ timestamp: String(r.created_at),
2946
+ read: false
2947
+ }));
2948
+ } catch {
2949
+ return [];
2950
+ }
2951
+ }
2952
+ async function markAsRead(ids, sessionScope) {
2953
+ if (ids.length === 0) return;
2954
+ try {
2955
+ const client = getClient();
2956
+ const placeholders = ids.map(() => "?").join(", ");
2957
+ const scope = strictSessionScopeFilter(sessionScope);
2958
+ await client.execute({
2959
+ sql: `UPDATE notifications SET read = 1 WHERE id IN (${placeholders})${scope.sql}`,
2960
+ args: [...ids, ...scope.args]
2961
+ });
2962
+ } catch {
2963
+ }
2964
+ }
2965
+ var init_notifications = __esm({
2966
+ "src/lib/notifications.ts"() {
2967
+ "use strict";
2968
+ init_database();
2969
+ init_task_scope();
2970
+ }
2971
+ });
2972
+
1703
2973
  // src/lib/store.ts
1704
2974
  import { createHash } from "crypto";
1705
2975
  init_database();
1706
2976
 
1707
2977
  // src/lib/keychain.ts
1708
2978
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1709
- import { existsSync as existsSync3 } from "fs";
1710
- import path3 from "path";
1711
- import os3 from "os";
2979
+ import { existsSync as existsSync4 } from "fs";
2980
+ import path4 from "path";
2981
+ import os4 from "os";
1712
2982
  var SERVICE = "exe-mem";
1713
2983
  var ACCOUNT = "master-key";
1714
2984
  function getKeyDir() {
1715
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2985
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1716
2986
  }
1717
2987
  function getKeyPath() {
1718
- return path3.join(getKeyDir(), "master.key");
2988
+ return path4.join(getKeyDir(), "master.key");
1719
2989
  }
1720
2990
  async function tryKeytar() {
1721
2991
  try {
@@ -1736,9 +3006,9 @@ async function getMasterKey() {
1736
3006
  }
1737
3007
  }
1738
3008
  const keyPath = getKeyPath();
1739
- if (!existsSync3(keyPath)) {
3009
+ if (!existsSync4(keyPath)) {
1740
3010
  process.stderr.write(
1741
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3011
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1742
3012
  `
1743
3013
  );
1744
3014
  return null;
@@ -1757,57 +3027,7 @@ async function getMasterKey() {
1757
3027
 
1758
3028
  // src/lib/store.ts
1759
3029
  init_config();
1760
-
1761
- // src/lib/state-bus.ts
1762
- var StateBus = class {
1763
- handlers = /* @__PURE__ */ new Map();
1764
- globalHandlers = /* @__PURE__ */ new Set();
1765
- /** Emit an event to all subscribers */
1766
- emit(event) {
1767
- const typeHandlers = this.handlers.get(event.type);
1768
- if (typeHandlers) {
1769
- for (const handler of typeHandlers) {
1770
- try {
1771
- handler(event);
1772
- } catch {
1773
- }
1774
- }
1775
- }
1776
- for (const handler of this.globalHandlers) {
1777
- try {
1778
- handler(event);
1779
- } catch {
1780
- }
1781
- }
1782
- }
1783
- /** Subscribe to a specific event type */
1784
- on(type, handler) {
1785
- if (!this.handlers.has(type)) {
1786
- this.handlers.set(type, /* @__PURE__ */ new Set());
1787
- }
1788
- this.handlers.get(type).add(handler);
1789
- }
1790
- /** Subscribe to ALL events */
1791
- onAny(handler) {
1792
- this.globalHandlers.add(handler);
1793
- }
1794
- /** Unsubscribe from a specific event type */
1795
- off(type, handler) {
1796
- this.handlers.get(type)?.delete(handler);
1797
- }
1798
- /** Unsubscribe from ALL events */
1799
- offAny(handler) {
1800
- this.globalHandlers.delete(handler);
1801
- }
1802
- /** Remove all listeners */
1803
- clear() {
1804
- this.handlers.clear();
1805
- this.globalHandlers.clear();
1806
- }
1807
- };
1808
- var orgBus = new StateBus();
1809
-
1810
- // src/lib/store.ts
3030
+ init_state_bus();
1811
3031
  var INIT_MAX_RETRIES = 3;
1812
3032
  var INIT_RETRY_DELAY_MS = 1e3;
1813
3033
  function isBusyError2(err) {
@@ -1888,17 +3108,17 @@ async function initStore(options) {
1888
3108
  }
1889
3109
 
1890
3110
  // src/bin/exe-pending-notifications.ts
1891
- init_database();
3111
+ init_notifications();
1892
3112
 
1893
3113
  // src/lib/is-main.ts
1894
3114
  import { realpathSync } from "fs";
1895
- import { fileURLToPath } from "url";
3115
+ import { fileURLToPath as fileURLToPath2 } from "url";
1896
3116
  function isMainModule(importMetaUrl) {
1897
3117
  if (process.argv[1] == null) return false;
1898
3118
  if (process.argv[1].includes("mcp/server")) return false;
1899
3119
  try {
1900
3120
  const scriptPath = realpathSync(process.argv[1]);
1901
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
3121
+ const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
1902
3122
  return scriptPath === modulePath;
1903
3123
  } catch {
1904
3124
  return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
@@ -1906,7 +3126,6 @@ function isMainModule(importMetaUrl) {
1906
3126
  }
1907
3127
 
1908
3128
  // src/bin/exe-pending-notifications.ts
1909
- var RECENT_WINDOW = "-24 hours";
1910
3129
  function formatLine(row) {
1911
3130
  switch (row.event) {
1912
3131
  case "subtasks_complete":
@@ -1941,38 +3160,26 @@ async function main() {
1941
3160
  process.exit(0);
1942
3161
  }
1943
3162
  await initStore();
1944
- const client = getClient();
1945
- const result = await client.execute({
1946
- sql: `SELECT id, event, project, summary, task_file, created_at
1947
- FROM notifications
1948
- WHERE agent_id = ?
1949
- AND read = 0
1950
- AND created_at > datetime('now', ?)
1951
- ORDER BY created_at ASC`,
1952
- args: [agentId, RECENT_WINDOW]
1953
- });
1954
- if (result.rows.length === 0) {
3163
+ const notifications = await readUnreadNotifications(agentId);
3164
+ const recentCutoff = Date.now() - 24 * 60 * 60 * 1e3;
3165
+ const pending = notifications.filter((row) => new Date(row.timestamp).getTime() > recentCutoff).map((row) => ({
3166
+ id: row.id,
3167
+ event: row.event,
3168
+ project: row.project,
3169
+ summary: row.summary,
3170
+ task_file: row.taskFile ?? null,
3171
+ created_at: row.timestamp
3172
+ }));
3173
+ if (pending.length === 0) {
1955
3174
  process.exit(0);
1956
3175
  }
1957
3176
  const ids = [];
1958
- for (const raw of result.rows) {
1959
- const row = {
1960
- id: String(raw.id),
1961
- event: String(raw.event),
1962
- project: String(raw.project),
1963
- summary: String(raw.summary),
1964
- task_file: raw.task_file == null ? null : String(raw.task_file),
1965
- created_at: String(raw.created_at)
1966
- };
3177
+ for (const row of pending) {
1967
3178
  process.stdout.write(formatLine(row));
1968
3179
  ids.push(row.id);
1969
3180
  }
1970
3181
  if (ids.length > 0) {
1971
- const placeholders = ids.map(() => "?").join(", ");
1972
- await client.execute({
1973
- sql: `UPDATE notifications SET read = 1 WHERE id IN (${placeholders})`,
1974
- args: ids
1975
- });
3182
+ await markAsRead(ids);
1976
3183
  }
1977
3184
  }
1978
3185
  if (isMainModule(import.meta.url)) {