@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
@@ -232,7 +232,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
232
232
  function getEmployee(employees, name) {
233
233
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
234
234
  }
235
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
235
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
236
236
  var init_employees = __esm({
237
237
  "src/lib/employees.ts"() {
238
238
  "use strict";
@@ -240,6 +240,7 @@ var init_employees = __esm({
240
240
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
241
241
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
242
242
  COORDINATOR_ROLE = "COO";
243
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
243
244
  }
244
245
  });
245
246
 
@@ -298,9 +299,605 @@ var init_db_retry = __esm({
298
299
  }
299
300
  });
300
301
 
302
+ // src/lib/database-adapter.ts
303
+ import os3 from "os";
304
+ import path3 from "path";
305
+ import { createRequire } from "module";
306
+ import { pathToFileURL } from "url";
307
+ function quotedIdentifier(identifier) {
308
+ return `"${identifier.replace(/"/g, '""')}"`;
309
+ }
310
+ function unqualifiedTableName(name) {
311
+ const raw = name.trim().replace(/^"|"$/g, "");
312
+ const parts = raw.split(".");
313
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
314
+ }
315
+ function stripTrailingSemicolon(sql) {
316
+ return sql.trim().replace(/;+\s*$/u, "");
317
+ }
318
+ function appendClause(sql, clause) {
319
+ const trimmed = stripTrailingSemicolon(sql);
320
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
321
+ if (!returningMatch) {
322
+ return `${trimmed}${clause}`;
323
+ }
324
+ const idx = returningMatch.index;
325
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
326
+ }
327
+ function normalizeStatement(stmt) {
328
+ if (typeof stmt === "string") {
329
+ return { kind: "positional", sql: stmt, args: [] };
330
+ }
331
+ const sql = stmt.sql;
332
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
333
+ return { kind: "positional", sql, args: stmt.args ?? [] };
334
+ }
335
+ return { kind: "named", sql, args: stmt.args };
336
+ }
337
+ function rewriteBooleanLiterals(sql) {
338
+ let out = sql;
339
+ for (const column of BOOLEAN_COLUMN_NAMES) {
340
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
341
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
342
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
343
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
344
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
345
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
346
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
347
+ }
348
+ return out;
349
+ }
350
+ function rewriteInsertOrIgnore(sql) {
351
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
352
+ return sql;
353
+ }
354
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
355
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
356
+ }
357
+ function rewriteInsertOrReplace(sql) {
358
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
359
+ if (!match) {
360
+ return sql;
361
+ }
362
+ const rawTable = match[1];
363
+ const rawColumns = match[2];
364
+ const remainder = match[3];
365
+ const tableName = unqualifiedTableName(rawTable);
366
+ const conflictKeys = UPSERT_KEYS[tableName];
367
+ if (!conflictKeys?.length) {
368
+ return sql;
369
+ }
370
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
371
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
372
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
373
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
374
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
375
+ }
376
+ function rewriteSql(sql) {
377
+ let out = sql;
378
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
379
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
380
+ out = rewriteBooleanLiterals(out);
381
+ out = rewriteInsertOrReplace(out);
382
+ out = rewriteInsertOrIgnore(out);
383
+ return stripTrailingSemicolon(out);
384
+ }
385
+ function toBoolean(value) {
386
+ if (value === null || value === void 0) return value;
387
+ if (typeof value === "boolean") return value;
388
+ if (typeof value === "number") return value !== 0;
389
+ if (typeof value === "bigint") return value !== 0n;
390
+ if (typeof value === "string") {
391
+ const normalized = value.trim().toLowerCase();
392
+ if (normalized === "0" || normalized === "false") return false;
393
+ if (normalized === "1" || normalized === "true") return true;
394
+ }
395
+ return Boolean(value);
396
+ }
397
+ function countQuestionMarks(sql, end) {
398
+ let count = 0;
399
+ let inSingle = false;
400
+ let inDouble = false;
401
+ let inLineComment = false;
402
+ let inBlockComment = false;
403
+ for (let i = 0; i < end; i++) {
404
+ const ch = sql[i];
405
+ const next = sql[i + 1];
406
+ if (inLineComment) {
407
+ if (ch === "\n") inLineComment = false;
408
+ continue;
409
+ }
410
+ if (inBlockComment) {
411
+ if (ch === "*" && next === "/") {
412
+ inBlockComment = false;
413
+ i += 1;
414
+ }
415
+ continue;
416
+ }
417
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
418
+ inLineComment = true;
419
+ i += 1;
420
+ continue;
421
+ }
422
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
423
+ inBlockComment = true;
424
+ i += 1;
425
+ continue;
426
+ }
427
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
428
+ inSingle = !inSingle;
429
+ continue;
430
+ }
431
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
432
+ inDouble = !inDouble;
433
+ continue;
434
+ }
435
+ if (!inSingle && !inDouble && ch === "?") {
436
+ count += 1;
437
+ }
438
+ }
439
+ return count;
440
+ }
441
+ function findBooleanPlaceholderIndexes(sql) {
442
+ const indexes = /* @__PURE__ */ new Set();
443
+ for (const column of BOOLEAN_COLUMN_NAMES) {
444
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
445
+ for (const match of sql.matchAll(pattern)) {
446
+ const matchText = match[0];
447
+ const qIndex = match.index + matchText.lastIndexOf("?");
448
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
449
+ }
450
+ }
451
+ return indexes;
452
+ }
453
+ function coerceInsertBooleanArgs(sql, args) {
454
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
455
+ if (!match) return;
456
+ const rawTable = match[1];
457
+ const rawColumns = match[2];
458
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
459
+ if (!boolColumns?.size) return;
460
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
461
+ for (const [index, column] of columns.entries()) {
462
+ if (boolColumns.has(column) && index < args.length) {
463
+ args[index] = toBoolean(args[index]);
464
+ }
465
+ }
466
+ }
467
+ function coerceUpdateBooleanArgs(sql, args) {
468
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
469
+ if (!match) return;
470
+ const rawTable = match[1];
471
+ const setClause = match[2];
472
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
473
+ if (!boolColumns?.size) return;
474
+ const assignments = setClause.split(",");
475
+ let placeholderIndex = 0;
476
+ for (const assignment of assignments) {
477
+ if (!assignment.includes("?")) continue;
478
+ placeholderIndex += 1;
479
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
480
+ if (colMatch && boolColumns.has(colMatch[1])) {
481
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
482
+ }
483
+ }
484
+ }
485
+ function coerceBooleanArgs(sql, args) {
486
+ const nextArgs = [...args];
487
+ coerceInsertBooleanArgs(sql, nextArgs);
488
+ coerceUpdateBooleanArgs(sql, nextArgs);
489
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
490
+ for (const index of placeholderIndexes) {
491
+ if (index > 0 && index <= nextArgs.length) {
492
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
493
+ }
494
+ }
495
+ return nextArgs;
496
+ }
497
+ function convertQuestionMarksToDollarParams(sql) {
498
+ let out = "";
499
+ let placeholder = 0;
500
+ let inSingle = false;
501
+ let inDouble = false;
502
+ let inLineComment = false;
503
+ let inBlockComment = false;
504
+ for (let i = 0; i < sql.length; i++) {
505
+ const ch = sql[i];
506
+ const next = sql[i + 1];
507
+ if (inLineComment) {
508
+ out += ch;
509
+ if (ch === "\n") inLineComment = false;
510
+ continue;
511
+ }
512
+ if (inBlockComment) {
513
+ out += ch;
514
+ if (ch === "*" && next === "/") {
515
+ out += next;
516
+ inBlockComment = false;
517
+ i += 1;
518
+ }
519
+ continue;
520
+ }
521
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
522
+ out += ch + next;
523
+ inLineComment = true;
524
+ i += 1;
525
+ continue;
526
+ }
527
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
528
+ out += ch + next;
529
+ inBlockComment = true;
530
+ i += 1;
531
+ continue;
532
+ }
533
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
534
+ inSingle = !inSingle;
535
+ out += ch;
536
+ continue;
537
+ }
538
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
539
+ inDouble = !inDouble;
540
+ out += ch;
541
+ continue;
542
+ }
543
+ if (!inSingle && !inDouble && ch === "?") {
544
+ placeholder += 1;
545
+ out += `$${placeholder}`;
546
+ continue;
547
+ }
548
+ out += ch;
549
+ }
550
+ return out;
551
+ }
552
+ function translateStatementForPostgres(stmt) {
553
+ const normalized = normalizeStatement(stmt);
554
+ if (normalized.kind === "named") {
555
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
556
+ }
557
+ const rewrittenSql = rewriteSql(normalized.sql);
558
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
559
+ return {
560
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
561
+ args: coercedArgs
562
+ };
563
+ }
564
+ function shouldBypassPostgres(stmt) {
565
+ const normalized = normalizeStatement(stmt);
566
+ if (normalized.kind === "named") {
567
+ return true;
568
+ }
569
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
570
+ }
571
+ function shouldFallbackOnError(error) {
572
+ const message = error instanceof Error ? error.message : String(error);
573
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
574
+ }
575
+ function isReadQuery(sql) {
576
+ const trimmed = sql.trimStart();
577
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
578
+ }
579
+ function buildRow(row, columns) {
580
+ const values = columns.map((column) => row[column]);
581
+ return Object.assign(values, row);
582
+ }
583
+ function buildResultSet(rows, rowsAffected = 0) {
584
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
585
+ const resultRows = rows.map((row) => buildRow(row, columns));
586
+ return {
587
+ columns,
588
+ columnTypes: columns.map(() => ""),
589
+ rows: resultRows,
590
+ rowsAffected,
591
+ lastInsertRowid: void 0,
592
+ toJSON() {
593
+ return {
594
+ columns,
595
+ columnTypes: columns.map(() => ""),
596
+ rows,
597
+ rowsAffected,
598
+ lastInsertRowid: void 0
599
+ };
600
+ }
601
+ };
602
+ }
603
+ async function loadPrismaClient() {
604
+ if (!prismaClientPromise) {
605
+ prismaClientPromise = (async () => {
606
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
607
+ if (explicitPath) {
608
+ const module2 = await import(pathToFileURL(explicitPath).href);
609
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
610
+ if (!PrismaClient2) {
611
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
612
+ }
613
+ return new PrismaClient2();
614
+ }
615
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
616
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
617
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
618
+ const module = await import(pathToFileURL(prismaEntry).href);
619
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
620
+ if (!PrismaClient) {
621
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
622
+ }
623
+ return new PrismaClient();
624
+ })();
625
+ }
626
+ return prismaClientPromise;
627
+ }
628
+ async function ensureCompatibilityViews(prisma) {
629
+ if (!compatibilityBootstrapPromise) {
630
+ compatibilityBootstrapPromise = (async () => {
631
+ for (const mapping of VIEW_MAPPINGS) {
632
+ const relation = mapping.source.replace(/"/g, "");
633
+ const rows = await prisma.$queryRawUnsafe(
634
+ "SELECT to_regclass($1) AS regclass",
635
+ relation
636
+ );
637
+ if (!rows[0]?.regclass) {
638
+ continue;
639
+ }
640
+ await prisma.$executeRawUnsafe(
641
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
642
+ );
643
+ }
644
+ })();
645
+ }
646
+ return compatibilityBootstrapPromise;
647
+ }
648
+ async function executeOnPrisma(executor, stmt) {
649
+ const translated = translateStatementForPostgres(stmt);
650
+ if (isReadQuery(translated.sql)) {
651
+ const rows = await executor.$queryRawUnsafe(
652
+ translated.sql,
653
+ ...translated.args
654
+ );
655
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
656
+ }
657
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
658
+ return buildResultSet([], rowsAffected);
659
+ }
660
+ function splitSqlStatements(sql) {
661
+ const parts = [];
662
+ let current = "";
663
+ let inSingle = false;
664
+ let inDouble = false;
665
+ let inLineComment = false;
666
+ let inBlockComment = false;
667
+ for (let i = 0; i < sql.length; i++) {
668
+ const ch = sql[i];
669
+ const next = sql[i + 1];
670
+ if (inLineComment) {
671
+ current += ch;
672
+ if (ch === "\n") inLineComment = false;
673
+ continue;
674
+ }
675
+ if (inBlockComment) {
676
+ current += ch;
677
+ if (ch === "*" && next === "/") {
678
+ current += next;
679
+ inBlockComment = false;
680
+ i += 1;
681
+ }
682
+ continue;
683
+ }
684
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
685
+ current += ch + next;
686
+ inLineComment = true;
687
+ i += 1;
688
+ continue;
689
+ }
690
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
691
+ current += ch + next;
692
+ inBlockComment = true;
693
+ i += 1;
694
+ continue;
695
+ }
696
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
697
+ inSingle = !inSingle;
698
+ current += ch;
699
+ continue;
700
+ }
701
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
702
+ inDouble = !inDouble;
703
+ current += ch;
704
+ continue;
705
+ }
706
+ if (!inSingle && !inDouble && ch === ";") {
707
+ if (current.trim()) {
708
+ parts.push(current.trim());
709
+ }
710
+ current = "";
711
+ continue;
712
+ }
713
+ current += ch;
714
+ }
715
+ if (current.trim()) {
716
+ parts.push(current.trim());
717
+ }
718
+ return parts;
719
+ }
720
+ async function createPrismaDbAdapter(fallbackClient) {
721
+ const prisma = await loadPrismaClient();
722
+ await ensureCompatibilityViews(prisma);
723
+ let closed = false;
724
+ let adapter;
725
+ const fallbackExecute = async (stmt, error) => {
726
+ if (!fallbackClient) {
727
+ if (error) throw error;
728
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
729
+ }
730
+ if (error) {
731
+ process.stderr.write(
732
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
733
+ `
734
+ );
735
+ }
736
+ return fallbackClient.execute(stmt);
737
+ };
738
+ adapter = {
739
+ async execute(stmt) {
740
+ if (shouldBypassPostgres(stmt)) {
741
+ return fallbackExecute(stmt);
742
+ }
743
+ try {
744
+ return await executeOnPrisma(prisma, stmt);
745
+ } catch (error) {
746
+ if (shouldFallbackOnError(error)) {
747
+ return fallbackExecute(stmt, error);
748
+ }
749
+ throw error;
750
+ }
751
+ },
752
+ async batch(stmts, mode) {
753
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
754
+ if (!fallbackClient) {
755
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
756
+ }
757
+ return fallbackClient.batch(stmts, mode);
758
+ }
759
+ try {
760
+ if (prisma.$transaction) {
761
+ return await prisma.$transaction(async (tx) => {
762
+ const results2 = [];
763
+ for (const stmt of stmts) {
764
+ results2.push(await executeOnPrisma(tx, stmt));
765
+ }
766
+ return results2;
767
+ });
768
+ }
769
+ const results = [];
770
+ for (const stmt of stmts) {
771
+ results.push(await executeOnPrisma(prisma, stmt));
772
+ }
773
+ return results;
774
+ } catch (error) {
775
+ if (fallbackClient && shouldFallbackOnError(error)) {
776
+ process.stderr.write(
777
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
778
+ `
779
+ );
780
+ return fallbackClient.batch(stmts, mode);
781
+ }
782
+ throw error;
783
+ }
784
+ },
785
+ async migrate(stmts) {
786
+ if (fallbackClient) {
787
+ return fallbackClient.migrate(stmts);
788
+ }
789
+ return adapter.batch(stmts, "deferred");
790
+ },
791
+ async transaction(mode) {
792
+ if (!fallbackClient) {
793
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
794
+ }
795
+ return fallbackClient.transaction(mode);
796
+ },
797
+ async executeMultiple(sql) {
798
+ if (fallbackClient && shouldBypassPostgres(sql)) {
799
+ return fallbackClient.executeMultiple(sql);
800
+ }
801
+ for (const statement of splitSqlStatements(sql)) {
802
+ await adapter.execute(statement);
803
+ }
804
+ },
805
+ async sync() {
806
+ if (fallbackClient) {
807
+ return fallbackClient.sync();
808
+ }
809
+ return { frame_no: 0, frames_synced: 0 };
810
+ },
811
+ close() {
812
+ closed = true;
813
+ prismaClientPromise = null;
814
+ compatibilityBootstrapPromise = null;
815
+ void prisma.$disconnect?.();
816
+ },
817
+ get closed() {
818
+ return closed;
819
+ },
820
+ get protocol() {
821
+ return "prisma-postgres";
822
+ }
823
+ };
824
+ return adapter;
825
+ }
826
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
827
+ var init_database_adapter = __esm({
828
+ "src/lib/database-adapter.ts"() {
829
+ "use strict";
830
+ VIEW_MAPPINGS = [
831
+ { view: "memories", source: "memory.memory_records" },
832
+ { view: "tasks", source: "memory.tasks" },
833
+ { view: "behaviors", source: "memory.behaviors" },
834
+ { view: "entities", source: "memory.entities" },
835
+ { view: "relationships", source: "memory.relationships" },
836
+ { view: "entity_memories", source: "memory.entity_memories" },
837
+ { view: "entity_aliases", source: "memory.entity_aliases" },
838
+ { view: "notifications", source: "memory.notifications" },
839
+ { view: "messages", source: "memory.messages" },
840
+ { view: "users", source: "wiki.users" },
841
+ { view: "workspaces", source: "wiki.workspaces" },
842
+ { view: "workspace_users", source: "wiki.workspace_users" },
843
+ { view: "documents", source: "wiki.workspace_documents" },
844
+ { view: "chats", source: "wiki.workspace_chats" }
845
+ ];
846
+ UPSERT_KEYS = {
847
+ memories: ["id"],
848
+ tasks: ["id"],
849
+ behaviors: ["id"],
850
+ entities: ["id"],
851
+ relationships: ["id"],
852
+ entity_aliases: ["alias"],
853
+ notifications: ["id"],
854
+ messages: ["id"],
855
+ users: ["id"],
856
+ workspaces: ["id"],
857
+ workspace_users: ["id"],
858
+ documents: ["id"],
859
+ chats: ["id"]
860
+ };
861
+ BOOLEAN_COLUMNS_BY_TABLE = {
862
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
863
+ behaviors: /* @__PURE__ */ new Set(["active"]),
864
+ notifications: /* @__PURE__ */ new Set(["read"]),
865
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
866
+ };
867
+ BOOLEAN_COLUMN_NAMES = new Set(
868
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
869
+ );
870
+ IMMEDIATE_FALLBACK_PATTERNS = [
871
+ /\bPRAGMA\b/i,
872
+ /\bsqlite_master\b/i,
873
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
874
+ /\bMATCH\b/i,
875
+ /\bvector_distance_cos\s*\(/i,
876
+ /\bjson_extract\s*\(/i,
877
+ /\bjulianday\s*\(/i,
878
+ /\bstrftime\s*\(/i,
879
+ /\blast_insert_rowid\s*\(/i
880
+ ];
881
+ prismaClientPromise = null;
882
+ compatibilityBootstrapPromise = null;
883
+ }
884
+ });
885
+
301
886
  // src/lib/database.ts
302
887
  import { createClient } from "@libsql/client";
303
888
  async function initDatabase(config) {
889
+ if (_walCheckpointTimer) {
890
+ clearInterval(_walCheckpointTimer);
891
+ _walCheckpointTimer = null;
892
+ }
893
+ if (_daemonClient) {
894
+ _daemonClient.close();
895
+ _daemonClient = null;
896
+ }
897
+ if (_adapterClient && _adapterClient !== _resilientClient) {
898
+ _adapterClient.close();
899
+ }
900
+ _adapterClient = null;
304
901
  if (_client) {
305
902
  _client.close();
306
903
  _client = null;
@@ -314,6 +911,7 @@ async function initDatabase(config) {
314
911
  }
315
912
  _client = createClient(opts);
316
913
  _resilientClient = wrapWithRetry(_client);
914
+ _adapterClient = _resilientClient;
317
915
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
318
916
  });
319
917
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -324,11 +922,17 @@ async function initDatabase(config) {
324
922
  });
325
923
  }, 3e4);
326
924
  _walCheckpointTimer.unref();
925
+ if (process.env.DATABASE_URL) {
926
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
927
+ }
327
928
  }
328
929
  function getClient() {
329
- if (!_resilientClient) {
930
+ if (!_adapterClient) {
330
931
  throw new Error("Database client not initialized. Call initDatabase() first.");
331
932
  }
933
+ if (process.env.DATABASE_URL) {
934
+ return _adapterClient;
935
+ }
332
936
  if (process.env.EXE_IS_DAEMON === "1") {
333
937
  return _resilientClient;
334
938
  }
@@ -1268,16 +1872,18 @@ async function ensureSchema() {
1268
1872
  }
1269
1873
  }
1270
1874
  }
1271
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1875
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1272
1876
  var init_database = __esm({
1273
1877
  "src/lib/database.ts"() {
1274
1878
  "use strict";
1275
1879
  init_db_retry();
1276
1880
  init_employees();
1881
+ init_database_adapter();
1277
1882
  _client = null;
1278
1883
  _resilientClient = null;
1279
1884
  _walCheckpointTimer = null;
1280
1885
  _daemonClient = null;
1886
+ _adapterClient = null;
1281
1887
  initTurso = initDatabase;
1282
1888
  }
1283
1889
  });
@@ -1295,7 +1901,7 @@ __export(shard_manager_exports, {
1295
1901
  listShards: () => listShards,
1296
1902
  shardExists: () => shardExists
1297
1903
  });
1298
- import path4 from "path";
1904
+ import path5 from "path";
1299
1905
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1300
1906
  import { createClient as createClient2 } from "@libsql/client";
1301
1907
  function initShardManager(encryptionKey) {
@@ -1321,7 +1927,7 @@ function getShardClient(projectName) {
1321
1927
  }
1322
1928
  const cached = _shards.get(safeName);
1323
1929
  if (cached) return cached;
1324
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1930
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1325
1931
  const client = createClient2({
1326
1932
  url: `file:${dbPath}`,
1327
1933
  encryptionKey: _encryptionKey
@@ -1331,7 +1937,7 @@ function getShardClient(projectName) {
1331
1937
  }
1332
1938
  function shardExists(projectName) {
1333
1939
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1334
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1940
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1335
1941
  }
1336
1942
  function listShards() {
1337
1943
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1408,7 +2014,23 @@ async function ensureShardSchema(client) {
1408
2014
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1409
2015
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1410
2016
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1411
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2017
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2018
+ // Metadata enrichment columns (must match database.ts)
2019
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2020
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2021
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2022
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2023
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2024
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2025
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2026
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2027
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2028
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2029
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2030
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2031
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2032
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2033
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1412
2034
  ]) {
1413
2035
  try {
1414
2036
  await client.execute(col);
@@ -1520,7 +2142,7 @@ var init_shard_manager = __esm({
1520
2142
  "src/lib/shard-manager.ts"() {
1521
2143
  "use strict";
1522
2144
  init_config();
1523
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2145
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1524
2146
  _shards = /* @__PURE__ */ new Map();
1525
2147
  _encryptionKey = null;
1526
2148
  _shardingEnabled = false;
@@ -1730,15 +2352,15 @@ init_database();
1730
2352
  // src/lib/keychain.ts
1731
2353
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1732
2354
  import { existsSync as existsSync3 } from "fs";
1733
- import path3 from "path";
1734
- import os3 from "os";
2355
+ import path4 from "path";
2356
+ import os4 from "os";
1735
2357
  var SERVICE = "exe-mem";
1736
2358
  var ACCOUNT = "master-key";
1737
2359
  function getKeyDir() {
1738
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2360
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1739
2361
  }
1740
2362
  function getKeyPath() {
1741
- return path3.join(getKeyDir(), "master.key");
2363
+ return path4.join(getKeyDir(), "master.key");
1742
2364
  }
1743
2365
  async function tryKeytar() {
1744
2366
  try {
@@ -1761,7 +2383,7 @@ async function getMasterKey() {
1761
2383
  const keyPath = getKeyPath();
1762
2384
  if (!existsSync3(keyPath)) {
1763
2385
  process.stderr.write(
1764
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2386
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1765
2387
  `
1766
2388
  );
1767
2389
  return null;