@askexenow/exe-os 0.9.7 → 0.9.8

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 (95) hide show
  1. package/dist/bin/backfill-conversations.js +754 -79
  2. package/dist/bin/backfill-responses.js +752 -77
  3. package/dist/bin/backfill-vectors.js +752 -77
  4. package/dist/bin/cleanup-stale-review-tasks.js +657 -35
  5. package/dist/bin/cli.js +1388 -605
  6. package/dist/bin/exe-agent-config.js +123 -95
  7. package/dist/bin/exe-agent.js +41 -25
  8. package/dist/bin/exe-assign.js +732 -57
  9. package/dist/bin/exe-boot.js +784 -153
  10. package/dist/bin/exe-call.js +209 -138
  11. package/dist/bin/exe-cloud.js +35 -12
  12. package/dist/bin/exe-dispatch.js +692 -70
  13. package/dist/bin/exe-doctor.js +648 -26
  14. package/dist/bin/exe-export-behaviors.js +650 -20
  15. package/dist/bin/exe-forget.js +635 -13
  16. package/dist/bin/exe-gateway.js +1053 -271
  17. package/dist/bin/exe-heartbeat.js +665 -43
  18. package/dist/bin/exe-kill.js +646 -16
  19. package/dist/bin/exe-launch-agent.js +887 -97
  20. package/dist/bin/exe-link.js +658 -43
  21. package/dist/bin/exe-new-employee.js +378 -177
  22. package/dist/bin/exe-pending-messages.js +656 -34
  23. package/dist/bin/exe-pending-notifications.js +635 -13
  24. package/dist/bin/exe-pending-reviews.js +659 -37
  25. package/dist/bin/exe-rename.js +645 -30
  26. package/dist/bin/exe-review.js +635 -13
  27. package/dist/bin/exe-search.js +771 -88
  28. package/dist/bin/exe-session-cleanup.js +834 -150
  29. package/dist/bin/exe-settings.js +127 -91
  30. package/dist/bin/exe-start-codex.js +729 -94
  31. package/dist/bin/exe-start-opencode.js +717 -82
  32. package/dist/bin/exe-status.js +657 -35
  33. package/dist/bin/exe-team.js +635 -13
  34. package/dist/bin/git-sweep.js +720 -89
  35. package/dist/bin/graph-backfill.js +643 -13
  36. package/dist/bin/graph-export.js +646 -16
  37. package/dist/bin/install.js +596 -193
  38. package/dist/bin/scan-tasks.js +724 -93
  39. package/dist/bin/setup.js +1038 -210
  40. package/dist/bin/shard-migrate.js +645 -15
  41. package/dist/bin/wiki-sync.js +646 -16
  42. package/dist/gateway/index.js +1027 -245
  43. package/dist/hooks/bug-report-worker.js +891 -170
  44. package/dist/hooks/commit-complete.js +718 -87
  45. package/dist/hooks/error-recall.js +776 -93
  46. package/dist/hooks/exe-heartbeat-hook.js +85 -71
  47. package/dist/hooks/ingest-worker.js +840 -156
  48. package/dist/hooks/ingest.js +90 -73
  49. package/dist/hooks/instructions-loaded.js +669 -38
  50. package/dist/hooks/notification.js +661 -30
  51. package/dist/hooks/post-compact.js +674 -43
  52. package/dist/hooks/pre-compact.js +718 -87
  53. package/dist/hooks/pre-tool-use.js +872 -125
  54. package/dist/hooks/prompt-ingest-worker.js +758 -83
  55. package/dist/hooks/prompt-submit.js +1060 -319
  56. package/dist/hooks/response-ingest-worker.js +758 -83
  57. package/dist/hooks/session-end.js +721 -90
  58. package/dist/hooks/session-start.js +1031 -207
  59. package/dist/hooks/stop.js +680 -49
  60. package/dist/hooks/subagent-stop.js +674 -43
  61. package/dist/hooks/summary-worker.js +816 -132
  62. package/dist/index.js +1015 -232
  63. package/dist/lib/cloud-sync.js +663 -48
  64. package/dist/lib/consolidation.js +26 -3
  65. package/dist/lib/database.js +626 -18
  66. package/dist/lib/db.js +2261 -0
  67. package/dist/lib/device-registry.js +640 -25
  68. package/dist/lib/embedder.js +96 -43
  69. package/dist/lib/employee-templates.js +16 -0
  70. package/dist/lib/employees.js +259 -83
  71. package/dist/lib/exe-daemon-client.js +101 -63
  72. package/dist/lib/exe-daemon.js +894 -162
  73. package/dist/lib/hybrid-search.js +771 -88
  74. package/dist/lib/identity.js +27 -7
  75. package/dist/lib/messaging.js +55 -28
  76. package/dist/lib/reminders.js +21 -1
  77. package/dist/lib/schedules.js +636 -14
  78. package/dist/lib/skill-learning.js +21 -1
  79. package/dist/lib/store.js +643 -13
  80. package/dist/lib/task-router.js +82 -71
  81. package/dist/lib/tasks.js +98 -71
  82. package/dist/lib/tmux-routing.js +87 -60
  83. package/dist/lib/token-spend.js +26 -6
  84. package/dist/mcp/server.js +1784 -458
  85. package/dist/mcp/tools/complete-reminder.js +21 -1
  86. package/dist/mcp/tools/create-reminder.js +21 -1
  87. package/dist/mcp/tools/create-task.js +290 -164
  88. package/dist/mcp/tools/deactivate-behavior.js +24 -4
  89. package/dist/mcp/tools/list-reminders.js +21 -1
  90. package/dist/mcp/tools/list-tasks.js +195 -38
  91. package/dist/mcp/tools/send-message.js +58 -31
  92. package/dist/mcp/tools/update-task.js +75 -48
  93. package/dist/runtime/index.js +720 -89
  94. package/dist/tui/App.js +853 -123
  95. package/package.json +3 -2
@@ -240,7 +240,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
240
240
  return [];
241
241
  }
242
242
  }
243
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
243
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
244
244
  var init_employees = __esm({
245
245
  "src/lib/employees.ts"() {
246
246
  "use strict";
@@ -248,6 +248,7 @@ var init_employees = __esm({
248
248
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
249
249
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
250
250
  COORDINATOR_ROLE = "COO";
251
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
251
252
  }
252
253
  });
253
254
 
@@ -306,9 +307,605 @@ var init_db_retry = __esm({
306
307
  }
307
308
  });
308
309
 
310
+ // src/lib/database-adapter.ts
311
+ import os3 from "os";
312
+ import path3 from "path";
313
+ import { createRequire } from "module";
314
+ import { pathToFileURL } from "url";
315
+ function quotedIdentifier(identifier) {
316
+ return `"${identifier.replace(/"/g, '""')}"`;
317
+ }
318
+ function unqualifiedTableName(name) {
319
+ const raw = name.trim().replace(/^"|"$/g, "");
320
+ const parts = raw.split(".");
321
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
322
+ }
323
+ function stripTrailingSemicolon(sql) {
324
+ return sql.trim().replace(/;+\s*$/u, "");
325
+ }
326
+ function appendClause(sql, clause) {
327
+ const trimmed = stripTrailingSemicolon(sql);
328
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
329
+ if (!returningMatch) {
330
+ return `${trimmed}${clause}`;
331
+ }
332
+ const idx = returningMatch.index;
333
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
334
+ }
335
+ function normalizeStatement(stmt) {
336
+ if (typeof stmt === "string") {
337
+ return { kind: "positional", sql: stmt, args: [] };
338
+ }
339
+ const sql = stmt.sql;
340
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
341
+ return { kind: "positional", sql, args: stmt.args ?? [] };
342
+ }
343
+ return { kind: "named", sql, args: stmt.args };
344
+ }
345
+ function rewriteBooleanLiterals(sql) {
346
+ let out = sql;
347
+ for (const column of BOOLEAN_COLUMN_NAMES) {
348
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
349
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
350
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
351
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
352
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
353
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
354
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
355
+ }
356
+ return out;
357
+ }
358
+ function rewriteInsertOrIgnore(sql) {
359
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
360
+ return sql;
361
+ }
362
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
363
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
364
+ }
365
+ function rewriteInsertOrReplace(sql) {
366
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
367
+ if (!match) {
368
+ return sql;
369
+ }
370
+ const rawTable = match[1];
371
+ const rawColumns = match[2];
372
+ const remainder = match[3];
373
+ const tableName = unqualifiedTableName(rawTable);
374
+ const conflictKeys = UPSERT_KEYS[tableName];
375
+ if (!conflictKeys?.length) {
376
+ return sql;
377
+ }
378
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
379
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
380
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
381
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
382
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
383
+ }
384
+ function rewriteSql(sql) {
385
+ let out = sql;
386
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
387
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
388
+ out = rewriteBooleanLiterals(out);
389
+ out = rewriteInsertOrReplace(out);
390
+ out = rewriteInsertOrIgnore(out);
391
+ return stripTrailingSemicolon(out);
392
+ }
393
+ function toBoolean(value) {
394
+ if (value === null || value === void 0) return value;
395
+ if (typeof value === "boolean") return value;
396
+ if (typeof value === "number") return value !== 0;
397
+ if (typeof value === "bigint") return value !== 0n;
398
+ if (typeof value === "string") {
399
+ const normalized = value.trim().toLowerCase();
400
+ if (normalized === "0" || normalized === "false") return false;
401
+ if (normalized === "1" || normalized === "true") return true;
402
+ }
403
+ return Boolean(value);
404
+ }
405
+ function countQuestionMarks(sql, end) {
406
+ let count = 0;
407
+ let inSingle = false;
408
+ let inDouble = false;
409
+ let inLineComment = false;
410
+ let inBlockComment = false;
411
+ for (let i = 0; i < end; i++) {
412
+ const ch = sql[i];
413
+ const next = sql[i + 1];
414
+ if (inLineComment) {
415
+ if (ch === "\n") inLineComment = false;
416
+ continue;
417
+ }
418
+ if (inBlockComment) {
419
+ if (ch === "*" && next === "/") {
420
+ inBlockComment = false;
421
+ i += 1;
422
+ }
423
+ continue;
424
+ }
425
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
426
+ inLineComment = true;
427
+ i += 1;
428
+ continue;
429
+ }
430
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
431
+ inBlockComment = true;
432
+ i += 1;
433
+ continue;
434
+ }
435
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
436
+ inSingle = !inSingle;
437
+ continue;
438
+ }
439
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
440
+ inDouble = !inDouble;
441
+ continue;
442
+ }
443
+ if (!inSingle && !inDouble && ch === "?") {
444
+ count += 1;
445
+ }
446
+ }
447
+ return count;
448
+ }
449
+ function findBooleanPlaceholderIndexes(sql) {
450
+ const indexes = /* @__PURE__ */ new Set();
451
+ for (const column of BOOLEAN_COLUMN_NAMES) {
452
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
453
+ for (const match of sql.matchAll(pattern)) {
454
+ const matchText = match[0];
455
+ const qIndex = match.index + matchText.lastIndexOf("?");
456
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
457
+ }
458
+ }
459
+ return indexes;
460
+ }
461
+ function coerceInsertBooleanArgs(sql, args) {
462
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
463
+ if (!match) return;
464
+ const rawTable = match[1];
465
+ const rawColumns = match[2];
466
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
467
+ if (!boolColumns?.size) return;
468
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
469
+ for (const [index, column] of columns.entries()) {
470
+ if (boolColumns.has(column) && index < args.length) {
471
+ args[index] = toBoolean(args[index]);
472
+ }
473
+ }
474
+ }
475
+ function coerceUpdateBooleanArgs(sql, args) {
476
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
477
+ if (!match) return;
478
+ const rawTable = match[1];
479
+ const setClause = match[2];
480
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
481
+ if (!boolColumns?.size) return;
482
+ const assignments = setClause.split(",");
483
+ let placeholderIndex = 0;
484
+ for (const assignment of assignments) {
485
+ if (!assignment.includes("?")) continue;
486
+ placeholderIndex += 1;
487
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
488
+ if (colMatch && boolColumns.has(colMatch[1])) {
489
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
490
+ }
491
+ }
492
+ }
493
+ function coerceBooleanArgs(sql, args) {
494
+ const nextArgs = [...args];
495
+ coerceInsertBooleanArgs(sql, nextArgs);
496
+ coerceUpdateBooleanArgs(sql, nextArgs);
497
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
498
+ for (const index of placeholderIndexes) {
499
+ if (index > 0 && index <= nextArgs.length) {
500
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
501
+ }
502
+ }
503
+ return nextArgs;
504
+ }
505
+ function convertQuestionMarksToDollarParams(sql) {
506
+ let out = "";
507
+ let placeholder = 0;
508
+ let inSingle = false;
509
+ let inDouble = false;
510
+ let inLineComment = false;
511
+ let inBlockComment = false;
512
+ for (let i = 0; i < sql.length; i++) {
513
+ const ch = sql[i];
514
+ const next = sql[i + 1];
515
+ if (inLineComment) {
516
+ out += ch;
517
+ if (ch === "\n") inLineComment = false;
518
+ continue;
519
+ }
520
+ if (inBlockComment) {
521
+ out += ch;
522
+ if (ch === "*" && next === "/") {
523
+ out += next;
524
+ inBlockComment = false;
525
+ i += 1;
526
+ }
527
+ continue;
528
+ }
529
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
530
+ out += ch + next;
531
+ inLineComment = true;
532
+ i += 1;
533
+ continue;
534
+ }
535
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
536
+ out += ch + next;
537
+ inBlockComment = true;
538
+ i += 1;
539
+ continue;
540
+ }
541
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
542
+ inSingle = !inSingle;
543
+ out += ch;
544
+ continue;
545
+ }
546
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
547
+ inDouble = !inDouble;
548
+ out += ch;
549
+ continue;
550
+ }
551
+ if (!inSingle && !inDouble && ch === "?") {
552
+ placeholder += 1;
553
+ out += `$${placeholder}`;
554
+ continue;
555
+ }
556
+ out += ch;
557
+ }
558
+ return out;
559
+ }
560
+ function translateStatementForPostgres(stmt) {
561
+ const normalized = normalizeStatement(stmt);
562
+ if (normalized.kind === "named") {
563
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
564
+ }
565
+ const rewrittenSql = rewriteSql(normalized.sql);
566
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
567
+ return {
568
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
569
+ args: coercedArgs
570
+ };
571
+ }
572
+ function shouldBypassPostgres(stmt) {
573
+ const normalized = normalizeStatement(stmt);
574
+ if (normalized.kind === "named") {
575
+ return true;
576
+ }
577
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
578
+ }
579
+ function shouldFallbackOnError(error) {
580
+ const message = error instanceof Error ? error.message : String(error);
581
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
582
+ }
583
+ function isReadQuery(sql) {
584
+ const trimmed = sql.trimStart();
585
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
586
+ }
587
+ function buildRow(row, columns) {
588
+ const values = columns.map((column) => row[column]);
589
+ return Object.assign(values, row);
590
+ }
591
+ function buildResultSet(rows, rowsAffected = 0) {
592
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
593
+ const resultRows = rows.map((row) => buildRow(row, columns));
594
+ return {
595
+ columns,
596
+ columnTypes: columns.map(() => ""),
597
+ rows: resultRows,
598
+ rowsAffected,
599
+ lastInsertRowid: void 0,
600
+ toJSON() {
601
+ return {
602
+ columns,
603
+ columnTypes: columns.map(() => ""),
604
+ rows,
605
+ rowsAffected,
606
+ lastInsertRowid: void 0
607
+ };
608
+ }
609
+ };
610
+ }
611
+ async function loadPrismaClient() {
612
+ if (!prismaClientPromise) {
613
+ prismaClientPromise = (async () => {
614
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
615
+ if (explicitPath) {
616
+ const module2 = await import(pathToFileURL(explicitPath).href);
617
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
618
+ if (!PrismaClient2) {
619
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
620
+ }
621
+ return new PrismaClient2();
622
+ }
623
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
624
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
625
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
626
+ const module = await import(pathToFileURL(prismaEntry).href);
627
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
628
+ if (!PrismaClient) {
629
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
630
+ }
631
+ return new PrismaClient();
632
+ })();
633
+ }
634
+ return prismaClientPromise;
635
+ }
636
+ async function ensureCompatibilityViews(prisma) {
637
+ if (!compatibilityBootstrapPromise) {
638
+ compatibilityBootstrapPromise = (async () => {
639
+ for (const mapping of VIEW_MAPPINGS) {
640
+ const relation = mapping.source.replace(/"/g, "");
641
+ const rows = await prisma.$queryRawUnsafe(
642
+ "SELECT to_regclass($1) AS regclass",
643
+ relation
644
+ );
645
+ if (!rows[0]?.regclass) {
646
+ continue;
647
+ }
648
+ await prisma.$executeRawUnsafe(
649
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
650
+ );
651
+ }
652
+ })();
653
+ }
654
+ return compatibilityBootstrapPromise;
655
+ }
656
+ async function executeOnPrisma(executor, stmt) {
657
+ const translated = translateStatementForPostgres(stmt);
658
+ if (isReadQuery(translated.sql)) {
659
+ const rows = await executor.$queryRawUnsafe(
660
+ translated.sql,
661
+ ...translated.args
662
+ );
663
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
664
+ }
665
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
666
+ return buildResultSet([], rowsAffected);
667
+ }
668
+ function splitSqlStatements(sql) {
669
+ const parts = [];
670
+ let current = "";
671
+ let inSingle = false;
672
+ let inDouble = false;
673
+ let inLineComment = false;
674
+ let inBlockComment = false;
675
+ for (let i = 0; i < sql.length; i++) {
676
+ const ch = sql[i];
677
+ const next = sql[i + 1];
678
+ if (inLineComment) {
679
+ current += ch;
680
+ if (ch === "\n") inLineComment = false;
681
+ continue;
682
+ }
683
+ if (inBlockComment) {
684
+ current += ch;
685
+ if (ch === "*" && next === "/") {
686
+ current += next;
687
+ inBlockComment = false;
688
+ i += 1;
689
+ }
690
+ continue;
691
+ }
692
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
693
+ current += ch + next;
694
+ inLineComment = true;
695
+ i += 1;
696
+ continue;
697
+ }
698
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
699
+ current += ch + next;
700
+ inBlockComment = true;
701
+ i += 1;
702
+ continue;
703
+ }
704
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
705
+ inSingle = !inSingle;
706
+ current += ch;
707
+ continue;
708
+ }
709
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
710
+ inDouble = !inDouble;
711
+ current += ch;
712
+ continue;
713
+ }
714
+ if (!inSingle && !inDouble && ch === ";") {
715
+ if (current.trim()) {
716
+ parts.push(current.trim());
717
+ }
718
+ current = "";
719
+ continue;
720
+ }
721
+ current += ch;
722
+ }
723
+ if (current.trim()) {
724
+ parts.push(current.trim());
725
+ }
726
+ return parts;
727
+ }
728
+ async function createPrismaDbAdapter(fallbackClient) {
729
+ const prisma = await loadPrismaClient();
730
+ await ensureCompatibilityViews(prisma);
731
+ let closed = false;
732
+ let adapter;
733
+ const fallbackExecute = async (stmt, error) => {
734
+ if (!fallbackClient) {
735
+ if (error) throw error;
736
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
737
+ }
738
+ if (error) {
739
+ process.stderr.write(
740
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
741
+ `
742
+ );
743
+ }
744
+ return fallbackClient.execute(stmt);
745
+ };
746
+ adapter = {
747
+ async execute(stmt) {
748
+ if (shouldBypassPostgres(stmt)) {
749
+ return fallbackExecute(stmt);
750
+ }
751
+ try {
752
+ return await executeOnPrisma(prisma, stmt);
753
+ } catch (error) {
754
+ if (shouldFallbackOnError(error)) {
755
+ return fallbackExecute(stmt, error);
756
+ }
757
+ throw error;
758
+ }
759
+ },
760
+ async batch(stmts, mode) {
761
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
762
+ if (!fallbackClient) {
763
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
764
+ }
765
+ return fallbackClient.batch(stmts, mode);
766
+ }
767
+ try {
768
+ if (prisma.$transaction) {
769
+ return await prisma.$transaction(async (tx) => {
770
+ const results2 = [];
771
+ for (const stmt of stmts) {
772
+ results2.push(await executeOnPrisma(tx, stmt));
773
+ }
774
+ return results2;
775
+ });
776
+ }
777
+ const results = [];
778
+ for (const stmt of stmts) {
779
+ results.push(await executeOnPrisma(prisma, stmt));
780
+ }
781
+ return results;
782
+ } catch (error) {
783
+ if (fallbackClient && shouldFallbackOnError(error)) {
784
+ process.stderr.write(
785
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
786
+ `
787
+ );
788
+ return fallbackClient.batch(stmts, mode);
789
+ }
790
+ throw error;
791
+ }
792
+ },
793
+ async migrate(stmts) {
794
+ if (fallbackClient) {
795
+ return fallbackClient.migrate(stmts);
796
+ }
797
+ return adapter.batch(stmts, "deferred");
798
+ },
799
+ async transaction(mode) {
800
+ if (!fallbackClient) {
801
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
802
+ }
803
+ return fallbackClient.transaction(mode);
804
+ },
805
+ async executeMultiple(sql) {
806
+ if (fallbackClient && shouldBypassPostgres(sql)) {
807
+ return fallbackClient.executeMultiple(sql);
808
+ }
809
+ for (const statement of splitSqlStatements(sql)) {
810
+ await adapter.execute(statement);
811
+ }
812
+ },
813
+ async sync() {
814
+ if (fallbackClient) {
815
+ return fallbackClient.sync();
816
+ }
817
+ return { frame_no: 0, frames_synced: 0 };
818
+ },
819
+ close() {
820
+ closed = true;
821
+ prismaClientPromise = null;
822
+ compatibilityBootstrapPromise = null;
823
+ void prisma.$disconnect?.();
824
+ },
825
+ get closed() {
826
+ return closed;
827
+ },
828
+ get protocol() {
829
+ return "prisma-postgres";
830
+ }
831
+ };
832
+ return adapter;
833
+ }
834
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
835
+ var init_database_adapter = __esm({
836
+ "src/lib/database-adapter.ts"() {
837
+ "use strict";
838
+ VIEW_MAPPINGS = [
839
+ { view: "memories", source: "memory.memory_records" },
840
+ { view: "tasks", source: "memory.tasks" },
841
+ { view: "behaviors", source: "memory.behaviors" },
842
+ { view: "entities", source: "memory.entities" },
843
+ { view: "relationships", source: "memory.relationships" },
844
+ { view: "entity_memories", source: "memory.entity_memories" },
845
+ { view: "entity_aliases", source: "memory.entity_aliases" },
846
+ { view: "notifications", source: "memory.notifications" },
847
+ { view: "messages", source: "memory.messages" },
848
+ { view: "users", source: "wiki.users" },
849
+ { view: "workspaces", source: "wiki.workspaces" },
850
+ { view: "workspace_users", source: "wiki.workspace_users" },
851
+ { view: "documents", source: "wiki.workspace_documents" },
852
+ { view: "chats", source: "wiki.workspace_chats" }
853
+ ];
854
+ UPSERT_KEYS = {
855
+ memories: ["id"],
856
+ tasks: ["id"],
857
+ behaviors: ["id"],
858
+ entities: ["id"],
859
+ relationships: ["id"],
860
+ entity_aliases: ["alias"],
861
+ notifications: ["id"],
862
+ messages: ["id"],
863
+ users: ["id"],
864
+ workspaces: ["id"],
865
+ workspace_users: ["id"],
866
+ documents: ["id"],
867
+ chats: ["id"]
868
+ };
869
+ BOOLEAN_COLUMNS_BY_TABLE = {
870
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
871
+ behaviors: /* @__PURE__ */ new Set(["active"]),
872
+ notifications: /* @__PURE__ */ new Set(["read"]),
873
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
874
+ };
875
+ BOOLEAN_COLUMN_NAMES = new Set(
876
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
877
+ );
878
+ IMMEDIATE_FALLBACK_PATTERNS = [
879
+ /\bPRAGMA\b/i,
880
+ /\bsqlite_master\b/i,
881
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
882
+ /\bMATCH\b/i,
883
+ /\bvector_distance_cos\s*\(/i,
884
+ /\bjson_extract\s*\(/i,
885
+ /\bjulianday\s*\(/i,
886
+ /\bstrftime\s*\(/i,
887
+ /\blast_insert_rowid\s*\(/i
888
+ ];
889
+ prismaClientPromise = null;
890
+ compatibilityBootstrapPromise = null;
891
+ }
892
+ });
893
+
309
894
  // src/lib/database.ts
310
895
  import { createClient } from "@libsql/client";
311
896
  async function initDatabase(config) {
897
+ if (_walCheckpointTimer) {
898
+ clearInterval(_walCheckpointTimer);
899
+ _walCheckpointTimer = null;
900
+ }
901
+ if (_daemonClient) {
902
+ _daemonClient.close();
903
+ _daemonClient = null;
904
+ }
905
+ if (_adapterClient && _adapterClient !== _resilientClient) {
906
+ _adapterClient.close();
907
+ }
908
+ _adapterClient = null;
312
909
  if (_client) {
313
910
  _client.close();
314
911
  _client = null;
@@ -322,6 +919,7 @@ async function initDatabase(config) {
322
919
  }
323
920
  _client = createClient(opts);
324
921
  _resilientClient = wrapWithRetry(_client);
922
+ _adapterClient = _resilientClient;
325
923
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
326
924
  });
327
925
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -332,11 +930,17 @@ async function initDatabase(config) {
332
930
  });
333
931
  }, 3e4);
334
932
  _walCheckpointTimer.unref();
933
+ if (process.env.DATABASE_URL) {
934
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
935
+ }
335
936
  }
336
937
  function getClient() {
337
- if (!_resilientClient) {
938
+ if (!_adapterClient) {
338
939
  throw new Error("Database client not initialized. Call initDatabase() first.");
339
940
  }
941
+ if (process.env.DATABASE_URL) {
942
+ return _adapterClient;
943
+ }
340
944
  if (process.env.EXE_IS_DAEMON === "1") {
341
945
  return _resilientClient;
342
946
  }
@@ -1276,16 +1880,18 @@ async function ensureSchema() {
1276
1880
  }
1277
1881
  }
1278
1882
  }
1279
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1883
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1280
1884
  var init_database = __esm({
1281
1885
  "src/lib/database.ts"() {
1282
1886
  "use strict";
1283
1887
  init_db_retry();
1284
1888
  init_employees();
1889
+ init_database_adapter();
1285
1890
  _client = null;
1286
1891
  _resilientClient = null;
1287
1892
  _walCheckpointTimer = null;
1288
1893
  _daemonClient = null;
1894
+ _adapterClient = null;
1289
1895
  initTurso = initDatabase;
1290
1896
  }
1291
1897
  });
@@ -1358,7 +1964,7 @@ __export(shard_manager_exports, {
1358
1964
  listShards: () => listShards,
1359
1965
  shardExists: () => shardExists
1360
1966
  });
1361
- import path4 from "path";
1967
+ import path5 from "path";
1362
1968
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1363
1969
  import { createClient as createClient2 } from "@libsql/client";
1364
1970
  function initShardManager(encryptionKey) {
@@ -1384,7 +1990,7 @@ function getShardClient(projectName) {
1384
1990
  }
1385
1991
  const cached = _shards.get(safeName);
1386
1992
  if (cached) return cached;
1387
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1993
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1388
1994
  const client = createClient2({
1389
1995
  url: `file:${dbPath}`,
1390
1996
  encryptionKey: _encryptionKey
@@ -1394,7 +2000,7 @@ function getShardClient(projectName) {
1394
2000
  }
1395
2001
  function shardExists(projectName) {
1396
2002
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1397
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
2003
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1398
2004
  }
1399
2005
  function listShards() {
1400
2006
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1471,7 +2077,23 @@ async function ensureShardSchema(client) {
1471
2077
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1472
2078
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1473
2079
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1474
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2080
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2081
+ // Metadata enrichment columns (must match database.ts)
2082
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2083
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2084
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2085
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2086
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2087
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2088
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2089
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2090
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2091
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2092
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2093
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2094
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2095
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2096
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1475
2097
  ]) {
1476
2098
  try {
1477
2099
  await client.execute(col);
@@ -1583,7 +2205,7 @@ var init_shard_manager = __esm({
1583
2205
  "src/lib/shard-manager.ts"() {
1584
2206
  "use strict";
1585
2207
  init_config();
1586
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2208
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1587
2209
  _shards = /* @__PURE__ */ new Map();
1588
2210
  _encryptionKey = null;
1589
2211
  _shardingEnabled = false;
@@ -1778,13 +2400,13 @@ ${p.content}`).join("\n\n");
1778
2400
  });
1779
2401
 
1780
2402
  // src/lib/session-registry.ts
1781
- import path5 from "path";
1782
- import os4 from "os";
2403
+ import path6 from "path";
2404
+ import os5 from "os";
1783
2405
  var REGISTRY_PATH;
1784
2406
  var init_session_registry = __esm({
1785
2407
  "src/lib/session-registry.ts"() {
1786
2408
  "use strict";
1787
- REGISTRY_PATH = path5.join(os4.homedir(), ".exe-os", "session-registry.json");
2409
+ REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
1788
2410
  }
1789
2411
  });
1790
2412
 
@@ -2020,14 +2642,14 @@ var init_runtime_table = __esm({
2020
2642
 
2021
2643
  // src/lib/agent-config.ts
2022
2644
  import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
2023
- import path6 from "path";
2645
+ import path7 from "path";
2024
2646
  var AGENT_CONFIG_PATH, DEFAULT_MODELS;
2025
2647
  var init_agent_config = __esm({
2026
2648
  "src/lib/agent-config.ts"() {
2027
2649
  "use strict";
2028
2650
  init_config();
2029
2651
  init_runtime_table();
2030
- AGENT_CONFIG_PATH = path6.join(EXE_AI_DIR, "agent-config.json");
2652
+ AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
2031
2653
  DEFAULT_MODELS = {
2032
2654
  claude: "claude-opus-4",
2033
2655
  codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
@@ -2038,37 +2660,37 @@ var init_agent_config = __esm({
2038
2660
 
2039
2661
  // src/lib/intercom-queue.ts
2040
2662
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
2041
- import path7 from "path";
2042
- import os5 from "os";
2663
+ import path8 from "path";
2664
+ import os6 from "os";
2043
2665
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2044
2666
  var init_intercom_queue = __esm({
2045
2667
  "src/lib/intercom-queue.ts"() {
2046
2668
  "use strict";
2047
- QUEUE_PATH = path7.join(os5.homedir(), ".exe-os", "intercom-queue.json");
2669
+ QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
2048
2670
  TTL_MS = 60 * 60 * 1e3;
2049
- INTERCOM_LOG = path7.join(os5.homedir(), ".exe-os", "intercom.log");
2671
+ INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
2050
2672
  }
2051
2673
  });
2052
2674
 
2053
2675
  // src/lib/license.ts
2054
2676
  import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync7, mkdirSync as mkdirSync4 } from "fs";
2055
2677
  import { randomUUID as randomUUID2 } from "crypto";
2056
- import path8 from "path";
2678
+ import path9 from "path";
2057
2679
  import { jwtVerify, importSPKI } from "jose";
2058
2680
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2059
2681
  var init_license = __esm({
2060
2682
  "src/lib/license.ts"() {
2061
2683
  "use strict";
2062
2684
  init_config();
2063
- LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
2064
- CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
2065
- DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
2685
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2686
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2687
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2066
2688
  }
2067
2689
  });
2068
2690
 
2069
2691
  // src/lib/plan-limits.ts
2070
2692
  import { readFileSync as readFileSync6, existsSync as existsSync8 } from "fs";
2071
- import path9 from "path";
2693
+ import path10 from "path";
2072
2694
  var CACHE_PATH2;
2073
2695
  var init_plan_limits = __esm({
2074
2696
  "src/lib/plan-limits.ts"() {
@@ -2077,14 +2699,14 @@ var init_plan_limits = __esm({
2077
2699
  init_employees();
2078
2700
  init_license();
2079
2701
  init_config();
2080
- CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2702
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2081
2703
  }
2082
2704
  });
2083
2705
 
2084
2706
  // src/lib/tmux-routing.ts
2085
2707
  import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync9, appendFileSync, readdirSync as readdirSync2 } from "fs";
2086
- import path10 from "path";
2087
- import os6 from "os";
2708
+ import path11 from "path";
2709
+ import os7 from "os";
2088
2710
  import { fileURLToPath as fileURLToPath2 } from "url";
2089
2711
  function getMySession() {
2090
2712
  return getTransport().getMySession();
@@ -2097,7 +2719,7 @@ function extractRootExe(name) {
2097
2719
  }
2098
2720
  function getParentExe(sessionKey) {
2099
2721
  try {
2100
- const data = JSON.parse(readFileSync7(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2722
+ const data = JSON.parse(readFileSync7(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2101
2723
  return data.parentExe || null;
2102
2724
  } catch {
2103
2725
  return null;
@@ -2140,10 +2762,10 @@ var init_tmux_routing = __esm({
2140
2762
  init_intercom_queue();
2141
2763
  init_plan_limits();
2142
2764
  init_employees();
2143
- SPAWN_LOCK_DIR = path10.join(os6.homedir(), ".exe-os", "spawn-locks");
2144
- SESSION_CACHE = path10.join(os6.homedir(), ".exe-os", "session-cache");
2145
- INTERCOM_LOG2 = path10.join(os6.homedir(), ".exe-os", "intercom.log");
2146
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
2765
+ SPAWN_LOCK_DIR = path11.join(os7.homedir(), ".exe-os", "spawn-locks");
2766
+ SESSION_CACHE = path11.join(os7.homedir(), ".exe-os", "session-cache");
2767
+ INTERCOM_LOG2 = path11.join(os7.homedir(), ".exe-os", "intercom.log");
2768
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2147
2769
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2148
2770
  }
2149
2771
  });
@@ -2182,15 +2804,15 @@ init_database();
2182
2804
  // src/lib/keychain.ts
2183
2805
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2184
2806
  import { existsSync as existsSync3 } from "fs";
2185
- import path3 from "path";
2186
- import os3 from "os";
2807
+ import path4 from "path";
2808
+ import os4 from "os";
2187
2809
  var SERVICE = "exe-mem";
2188
2810
  var ACCOUNT = "master-key";
2189
2811
  function getKeyDir() {
2190
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2812
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2191
2813
  }
2192
2814
  function getKeyPath() {
2193
- return path3.join(getKeyDir(), "master.key");
2815
+ return path4.join(getKeyDir(), "master.key");
2194
2816
  }
2195
2817
  async function tryKeytar() {
2196
2818
  try {
@@ -2213,7 +2835,7 @@ async function getMasterKey() {
2213
2835
  const keyPath = getKeyPath();
2214
2836
  if (!existsSync3(keyPath)) {
2215
2837
  process.stderr.write(
2216
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2838
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2217
2839
  `
2218
2840
  );
2219
2841
  return null;