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