@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
@@ -220,7 +220,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
220
220
  function getEmployee(employees, name) {
221
221
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
222
222
  }
223
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
223
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
224
224
  var init_employees = __esm({
225
225
  "src/lib/employees.ts"() {
226
226
  "use strict";
@@ -228,6 +228,7 @@ var init_employees = __esm({
228
228
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
229
229
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
230
230
  COORDINATOR_ROLE = "COO";
231
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
231
232
  }
232
233
  });
233
234
 
@@ -295,13 +296,597 @@ var init_db_retry = __esm({
295
296
  }
296
297
  });
297
298
 
299
+ // src/lib/database-adapter.ts
300
+ import os3 from "os";
301
+ import path4 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 ?? path4.join(os3.homedir(), "exe-db");
613
+ const requireFromExeDb = createRequire(path4.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/exe-daemon-client.ts
299
884
  import net from "net";
300
- import os3 from "os";
885
+ import os4 from "os";
301
886
  import { spawn } from "child_process";
302
887
  import { randomUUID } from "crypto";
303
888
  import { existsSync as existsSync3, unlinkSync as unlinkSync3, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
304
- import path4 from "path";
889
+ import path5 from "path";
305
890
  import { fileURLToPath } from "url";
306
891
  function handleData(chunk) {
307
892
  _buffer += chunk.toString();
@@ -352,17 +937,17 @@ function cleanupStaleFiles() {
352
937
  }
353
938
  }
354
939
  function findPackageRoot() {
355
- let dir = path4.dirname(fileURLToPath(import.meta.url));
356
- const { root } = path4.parse(dir);
940
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
941
+ const { root } = path5.parse(dir);
357
942
  while (dir !== root) {
358
- if (existsSync3(path4.join(dir, "package.json"))) return dir;
359
- dir = path4.dirname(dir);
943
+ if (existsSync3(path5.join(dir, "package.json"))) return dir;
944
+ dir = path5.dirname(dir);
360
945
  }
361
946
  return null;
362
947
  }
363
948
  function spawnDaemon() {
364
- const freeGB = os3.freemem() / (1024 * 1024 * 1024);
365
- const totalGB = os3.totalmem() / (1024 * 1024 * 1024);
949
+ const freeGB = os4.freemem() / (1024 * 1024 * 1024);
950
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
366
951
  if (totalGB <= 8) {
367
952
  process.stderr.write(
368
953
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -382,7 +967,7 @@ function spawnDaemon() {
382
967
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
383
968
  return;
384
969
  }
385
- const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
970
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
386
971
  if (!existsSync3(daemonPath)) {
387
972
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
388
973
  `);
@@ -391,7 +976,7 @@ function spawnDaemon() {
391
976
  const resolvedPath = daemonPath;
392
977
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
393
978
  `);
394
- const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
979
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
395
980
  let stderrFd = "ignore";
396
981
  try {
397
982
  stderrFd = openSync(logPath, "a");
@@ -538,9 +1123,9 @@ var init_exe_daemon_client = __esm({
538
1123
  "src/lib/exe-daemon-client.ts"() {
539
1124
  "use strict";
540
1125
  init_config();
541
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
542
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
543
- SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
1126
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1127
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1128
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
544
1129
  SPAWN_LOCK_STALE_MS = 3e4;
545
1130
  CONNECT_TIMEOUT_MS = 15e3;
546
1131
  REQUEST_TIMEOUT_MS = 3e4;
@@ -622,7 +1207,7 @@ __export(db_daemon_client_exports, {
622
1207
  createDaemonDbClient: () => createDaemonDbClient,
623
1208
  initDaemonDbClient: () => initDaemonDbClient
624
1209
  });
625
- function normalizeStatement(stmt) {
1210
+ function normalizeStatement2(stmt) {
626
1211
  if (typeof stmt === "string") {
627
1212
  return { sql: stmt, args: [] };
628
1213
  }
@@ -646,7 +1231,7 @@ function createDaemonDbClient(fallbackClient) {
646
1231
  if (!_useDaemon || !isClientConnected()) {
647
1232
  return fallbackClient.execute(stmt);
648
1233
  }
649
- const { sql, args } = normalizeStatement(stmt);
1234
+ const { sql, args } = normalizeStatement2(stmt);
650
1235
  const response = await sendDaemonRequest({
651
1236
  type: "db-execute",
652
1237
  sql,
@@ -671,7 +1256,7 @@ function createDaemonDbClient(fallbackClient) {
671
1256
  if (!_useDaemon || !isClientConnected()) {
672
1257
  return fallbackClient.batch(stmts, mode);
673
1258
  }
674
- const statements = stmts.map(normalizeStatement);
1259
+ const statements = stmts.map(normalizeStatement2);
675
1260
  const response = await sendDaemonRequest({
676
1261
  type: "db-batch",
677
1262
  statements,
@@ -766,6 +1351,18 @@ __export(database_exports, {
766
1351
  });
767
1352
  import { createClient } from "@libsql/client";
768
1353
  async function initDatabase(config) {
1354
+ if (_walCheckpointTimer) {
1355
+ clearInterval(_walCheckpointTimer);
1356
+ _walCheckpointTimer = null;
1357
+ }
1358
+ if (_daemonClient) {
1359
+ _daemonClient.close();
1360
+ _daemonClient = null;
1361
+ }
1362
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1363
+ _adapterClient.close();
1364
+ }
1365
+ _adapterClient = null;
769
1366
  if (_client) {
770
1367
  _client.close();
771
1368
  _client = null;
@@ -779,6 +1376,7 @@ async function initDatabase(config) {
779
1376
  }
780
1377
  _client = createClient(opts);
781
1378
  _resilientClient = wrapWithRetry(_client);
1379
+ _adapterClient = _resilientClient;
782
1380
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
783
1381
  });
784
1382
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -789,14 +1387,20 @@ async function initDatabase(config) {
789
1387
  });
790
1388
  }, 3e4);
791
1389
  _walCheckpointTimer.unref();
1390
+ if (process.env.DATABASE_URL) {
1391
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1392
+ }
792
1393
  }
793
1394
  function isInitialized() {
794
- return _client !== null;
1395
+ return _adapterClient !== null || _client !== null;
795
1396
  }
796
1397
  function getClient() {
797
- if (!_resilientClient) {
1398
+ if (!_adapterClient) {
798
1399
  throw new Error("Database client not initialized. Call initDatabase() first.");
799
1400
  }
1401
+ if (process.env.DATABASE_URL) {
1402
+ return _adapterClient;
1403
+ }
800
1404
  if (process.env.EXE_IS_DAEMON === "1") {
801
1405
  return _resilientClient;
802
1406
  }
@@ -806,6 +1410,7 @@ function getClient() {
806
1410
  return _resilientClient;
807
1411
  }
808
1412
  async function initDaemonClient() {
1413
+ if (process.env.DATABASE_URL) return;
809
1414
  if (process.env.EXE_IS_DAEMON === "1") return;
810
1415
  if (!_resilientClient) return;
811
1416
  try {
@@ -1750,26 +2355,36 @@ async function ensureSchema() {
1750
2355
  }
1751
2356
  }
1752
2357
  async function disposeDatabase() {
2358
+ if (_walCheckpointTimer) {
2359
+ clearInterval(_walCheckpointTimer);
2360
+ _walCheckpointTimer = null;
2361
+ }
1753
2362
  if (_daemonClient) {
1754
2363
  _daemonClient.close();
1755
2364
  _daemonClient = null;
1756
2365
  }
2366
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2367
+ _adapterClient.close();
2368
+ }
2369
+ _adapterClient = null;
1757
2370
  if (_client) {
1758
2371
  _client.close();
1759
2372
  _client = null;
1760
2373
  _resilientClient = null;
1761
2374
  }
1762
2375
  }
1763
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
2376
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1764
2377
  var init_database = __esm({
1765
2378
  "src/lib/database.ts"() {
1766
2379
  "use strict";
1767
2380
  init_db_retry();
1768
2381
  init_employees();
2382
+ init_database_adapter();
1769
2383
  _client = null;
1770
2384
  _resilientClient = null;
1771
2385
  _walCheckpointTimer = null;
1772
2386
  _daemonClient = null;
2387
+ _adapterClient = null;
1773
2388
  initTurso = initDatabase;
1774
2389
  disposeTurso = disposeDatabase;
1775
2390
  }
@@ -1778,13 +2393,13 @@ var init_database = __esm({
1778
2393
  // src/lib/keychain.ts
1779
2394
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1780
2395
  import { existsSync as existsSync4 } from "fs";
1781
- import path5 from "path";
1782
- import os4 from "os";
2396
+ import path6 from "path";
2397
+ import os5 from "os";
1783
2398
  function getKeyDir() {
1784
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path5.join(os4.homedir(), ".exe-os");
2399
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
1785
2400
  }
1786
2401
  function getKeyPath() {
1787
- return path5.join(getKeyDir(), "master.key");
2402
+ return path6.join(getKeyDir(), "master.key");
1788
2403
  }
1789
2404
  async function tryKeytar() {
1790
2405
  try {
@@ -1807,7 +2422,7 @@ async function getMasterKey() {
1807
2422
  const keyPath = getKeyPath();
1808
2423
  if (!existsSync4(keyPath)) {
1809
2424
  process.stderr.write(
1810
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2425
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1811
2426
  `
1812
2427
  );
1813
2428
  return null;
@@ -1900,7 +2515,7 @@ __export(shard_manager_exports, {
1900
2515
  listShards: () => listShards,
1901
2516
  shardExists: () => shardExists
1902
2517
  });
1903
- import path6 from "path";
2518
+ import path7 from "path";
1904
2519
  import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync2 } from "fs";
1905
2520
  import { createClient as createClient2 } from "@libsql/client";
1906
2521
  function initShardManager(encryptionKey) {
@@ -1926,7 +2541,7 @@ function getShardClient(projectName) {
1926
2541
  }
1927
2542
  const cached = _shards.get(safeName);
1928
2543
  if (cached) return cached;
1929
- const dbPath = path6.join(SHARDS_DIR, `${safeName}.db`);
2544
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
1930
2545
  const client = createClient2({
1931
2546
  url: `file:${dbPath}`,
1932
2547
  encryptionKey: _encryptionKey
@@ -1936,7 +2551,7 @@ function getShardClient(projectName) {
1936
2551
  }
1937
2552
  function shardExists(projectName) {
1938
2553
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1939
- return existsSync5(path6.join(SHARDS_DIR, `${safeName}.db`));
2554
+ return existsSync5(path7.join(SHARDS_DIR, `${safeName}.db`));
1940
2555
  }
1941
2556
  function listShards() {
1942
2557
  if (!existsSync5(SHARDS_DIR)) return [];
@@ -2013,7 +2628,23 @@ async function ensureShardSchema(client) {
2013
2628
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2014
2629
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2015
2630
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2016
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2631
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2632
+ // Metadata enrichment columns (must match database.ts)
2633
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2634
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2635
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2636
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2637
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2638
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2639
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2640
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2641
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2642
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2643
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2644
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2645
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2646
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2647
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2017
2648
  ]) {
2018
2649
  try {
2019
2650
  await client.execute(col);
@@ -2125,7 +2756,7 @@ var init_shard_manager = __esm({
2125
2756
  "src/lib/shard-manager.ts"() {
2126
2757
  "use strict";
2127
2758
  init_config();
2128
- SHARDS_DIR = path6.join(EXE_AI_DIR, "shards");
2759
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2129
2760
  _shards = /* @__PURE__ */ new Map();
2130
2761
  _encryptionKey = null;
2131
2762
  _shardingEnabled = false;