@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
@@ -273,7 +273,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
273
273
  return [];
274
274
  }
275
275
  }
276
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
276
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
277
277
  var init_employees = __esm({
278
278
  "src/lib/employees.ts"() {
279
279
  "use strict";
@@ -281,12 +281,609 @@ var init_employees = __esm({
281
281
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
282
282
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
283
283
  COORDINATOR_ROLE = "COO";
284
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
285
+ }
286
+ });
287
+
288
+ // src/lib/database-adapter.ts
289
+ import os3 from "os";
290
+ import path3 from "path";
291
+ import { createRequire } from "module";
292
+ import { pathToFileURL } from "url";
293
+ function quotedIdentifier(identifier) {
294
+ return `"${identifier.replace(/"/g, '""')}"`;
295
+ }
296
+ function unqualifiedTableName(name) {
297
+ const raw = name.trim().replace(/^"|"$/g, "");
298
+ const parts = raw.split(".");
299
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
300
+ }
301
+ function stripTrailingSemicolon(sql) {
302
+ return sql.trim().replace(/;+\s*$/u, "");
303
+ }
304
+ function appendClause(sql, clause) {
305
+ const trimmed = stripTrailingSemicolon(sql);
306
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
307
+ if (!returningMatch) {
308
+ return `${trimmed}${clause}`;
309
+ }
310
+ const idx = returningMatch.index;
311
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
312
+ }
313
+ function normalizeStatement(stmt) {
314
+ if (typeof stmt === "string") {
315
+ return { kind: "positional", sql: stmt, args: [] };
316
+ }
317
+ const sql = stmt.sql;
318
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
319
+ return { kind: "positional", sql, args: stmt.args ?? [] };
320
+ }
321
+ return { kind: "named", sql, args: stmt.args };
322
+ }
323
+ function rewriteBooleanLiterals(sql) {
324
+ let out = sql;
325
+ for (const column of BOOLEAN_COLUMN_NAMES) {
326
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
327
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
328
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
329
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
330
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
331
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
332
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
333
+ }
334
+ return out;
335
+ }
336
+ function rewriteInsertOrIgnore(sql) {
337
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
338
+ return sql;
339
+ }
340
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
341
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
342
+ }
343
+ function rewriteInsertOrReplace(sql) {
344
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
345
+ if (!match) {
346
+ return sql;
347
+ }
348
+ const rawTable = match[1];
349
+ const rawColumns = match[2];
350
+ const remainder = match[3];
351
+ const tableName = unqualifiedTableName(rawTable);
352
+ const conflictKeys = UPSERT_KEYS[tableName];
353
+ if (!conflictKeys?.length) {
354
+ return sql;
355
+ }
356
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
357
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
358
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
359
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
360
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
361
+ }
362
+ function rewriteSql(sql) {
363
+ let out = sql;
364
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
365
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
366
+ out = rewriteBooleanLiterals(out);
367
+ out = rewriteInsertOrReplace(out);
368
+ out = rewriteInsertOrIgnore(out);
369
+ return stripTrailingSemicolon(out);
370
+ }
371
+ function toBoolean(value) {
372
+ if (value === null || value === void 0) return value;
373
+ if (typeof value === "boolean") return value;
374
+ if (typeof value === "number") return value !== 0;
375
+ if (typeof value === "bigint") return value !== 0n;
376
+ if (typeof value === "string") {
377
+ const normalized = value.trim().toLowerCase();
378
+ if (normalized === "0" || normalized === "false") return false;
379
+ if (normalized === "1" || normalized === "true") return true;
380
+ }
381
+ return Boolean(value);
382
+ }
383
+ function countQuestionMarks(sql, end) {
384
+ let count = 0;
385
+ let inSingle = false;
386
+ let inDouble = false;
387
+ let inLineComment = false;
388
+ let inBlockComment = false;
389
+ for (let i = 0; i < end; i++) {
390
+ const ch = sql[i];
391
+ const next = sql[i + 1];
392
+ if (inLineComment) {
393
+ if (ch === "\n") inLineComment = false;
394
+ continue;
395
+ }
396
+ if (inBlockComment) {
397
+ if (ch === "*" && next === "/") {
398
+ inBlockComment = false;
399
+ i += 1;
400
+ }
401
+ continue;
402
+ }
403
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
404
+ inLineComment = true;
405
+ i += 1;
406
+ continue;
407
+ }
408
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
409
+ inBlockComment = true;
410
+ i += 1;
411
+ continue;
412
+ }
413
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
414
+ inSingle = !inSingle;
415
+ continue;
416
+ }
417
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
418
+ inDouble = !inDouble;
419
+ continue;
420
+ }
421
+ if (!inSingle && !inDouble && ch === "?") {
422
+ count += 1;
423
+ }
424
+ }
425
+ return count;
426
+ }
427
+ function findBooleanPlaceholderIndexes(sql) {
428
+ const indexes = /* @__PURE__ */ new Set();
429
+ for (const column of BOOLEAN_COLUMN_NAMES) {
430
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
431
+ for (const match of sql.matchAll(pattern)) {
432
+ const matchText = match[0];
433
+ const qIndex = match.index + matchText.lastIndexOf("?");
434
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
435
+ }
436
+ }
437
+ return indexes;
438
+ }
439
+ function coerceInsertBooleanArgs(sql, args) {
440
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
441
+ if (!match) return;
442
+ const rawTable = match[1];
443
+ const rawColumns = match[2];
444
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
445
+ if (!boolColumns?.size) return;
446
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
447
+ for (const [index, column] of columns.entries()) {
448
+ if (boolColumns.has(column) && index < args.length) {
449
+ args[index] = toBoolean(args[index]);
450
+ }
451
+ }
452
+ }
453
+ function coerceUpdateBooleanArgs(sql, args) {
454
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
455
+ if (!match) return;
456
+ const rawTable = match[1];
457
+ const setClause = match[2];
458
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
459
+ if (!boolColumns?.size) return;
460
+ const assignments = setClause.split(",");
461
+ let placeholderIndex = 0;
462
+ for (const assignment of assignments) {
463
+ if (!assignment.includes("?")) continue;
464
+ placeholderIndex += 1;
465
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
466
+ if (colMatch && boolColumns.has(colMatch[1])) {
467
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
468
+ }
469
+ }
470
+ }
471
+ function coerceBooleanArgs(sql, args) {
472
+ const nextArgs = [...args];
473
+ coerceInsertBooleanArgs(sql, nextArgs);
474
+ coerceUpdateBooleanArgs(sql, nextArgs);
475
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
476
+ for (const index of placeholderIndexes) {
477
+ if (index > 0 && index <= nextArgs.length) {
478
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
479
+ }
480
+ }
481
+ return nextArgs;
482
+ }
483
+ function convertQuestionMarksToDollarParams(sql) {
484
+ let out = "";
485
+ let placeholder = 0;
486
+ let inSingle = false;
487
+ let inDouble = false;
488
+ let inLineComment = false;
489
+ let inBlockComment = false;
490
+ for (let i = 0; i < sql.length; i++) {
491
+ const ch = sql[i];
492
+ const next = sql[i + 1];
493
+ if (inLineComment) {
494
+ out += ch;
495
+ if (ch === "\n") inLineComment = false;
496
+ continue;
497
+ }
498
+ if (inBlockComment) {
499
+ out += ch;
500
+ if (ch === "*" && next === "/") {
501
+ out += next;
502
+ inBlockComment = false;
503
+ i += 1;
504
+ }
505
+ continue;
506
+ }
507
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
508
+ out += ch + next;
509
+ inLineComment = true;
510
+ i += 1;
511
+ continue;
512
+ }
513
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
514
+ out += ch + next;
515
+ inBlockComment = true;
516
+ i += 1;
517
+ continue;
518
+ }
519
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
520
+ inSingle = !inSingle;
521
+ out += ch;
522
+ continue;
523
+ }
524
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
525
+ inDouble = !inDouble;
526
+ out += ch;
527
+ continue;
528
+ }
529
+ if (!inSingle && !inDouble && ch === "?") {
530
+ placeholder += 1;
531
+ out += `$${placeholder}`;
532
+ continue;
533
+ }
534
+ out += ch;
535
+ }
536
+ return out;
537
+ }
538
+ function translateStatementForPostgres(stmt) {
539
+ const normalized = normalizeStatement(stmt);
540
+ if (normalized.kind === "named") {
541
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
542
+ }
543
+ const rewrittenSql = rewriteSql(normalized.sql);
544
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
545
+ return {
546
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
547
+ args: coercedArgs
548
+ };
549
+ }
550
+ function shouldBypassPostgres(stmt) {
551
+ const normalized = normalizeStatement(stmt);
552
+ if (normalized.kind === "named") {
553
+ return true;
554
+ }
555
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
556
+ }
557
+ function shouldFallbackOnError(error) {
558
+ const message = error instanceof Error ? error.message : String(error);
559
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
560
+ }
561
+ function isReadQuery(sql) {
562
+ const trimmed = sql.trimStart();
563
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
564
+ }
565
+ function buildRow(row, columns) {
566
+ const values = columns.map((column) => row[column]);
567
+ return Object.assign(values, row);
568
+ }
569
+ function buildResultSet(rows, rowsAffected = 0) {
570
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
571
+ const resultRows = rows.map((row) => buildRow(row, columns));
572
+ return {
573
+ columns,
574
+ columnTypes: columns.map(() => ""),
575
+ rows: resultRows,
576
+ rowsAffected,
577
+ lastInsertRowid: void 0,
578
+ toJSON() {
579
+ return {
580
+ columns,
581
+ columnTypes: columns.map(() => ""),
582
+ rows,
583
+ rowsAffected,
584
+ lastInsertRowid: void 0
585
+ };
586
+ }
587
+ };
588
+ }
589
+ async function loadPrismaClient() {
590
+ if (!prismaClientPromise) {
591
+ prismaClientPromise = (async () => {
592
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
593
+ if (explicitPath) {
594
+ const module2 = await import(pathToFileURL(explicitPath).href);
595
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
596
+ if (!PrismaClient2) {
597
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
598
+ }
599
+ return new PrismaClient2();
600
+ }
601
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
602
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
603
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
604
+ const module = await import(pathToFileURL(prismaEntry).href);
605
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
606
+ if (!PrismaClient) {
607
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
608
+ }
609
+ return new PrismaClient();
610
+ })();
611
+ }
612
+ return prismaClientPromise;
613
+ }
614
+ async function ensureCompatibilityViews(prisma) {
615
+ if (!compatibilityBootstrapPromise) {
616
+ compatibilityBootstrapPromise = (async () => {
617
+ for (const mapping of VIEW_MAPPINGS) {
618
+ const relation = mapping.source.replace(/"/g, "");
619
+ const rows = await prisma.$queryRawUnsafe(
620
+ "SELECT to_regclass($1) AS regclass",
621
+ relation
622
+ );
623
+ if (!rows[0]?.regclass) {
624
+ continue;
625
+ }
626
+ await prisma.$executeRawUnsafe(
627
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
628
+ );
629
+ }
630
+ })();
631
+ }
632
+ return compatibilityBootstrapPromise;
633
+ }
634
+ async function executeOnPrisma(executor, stmt) {
635
+ const translated = translateStatementForPostgres(stmt);
636
+ if (isReadQuery(translated.sql)) {
637
+ const rows = await executor.$queryRawUnsafe(
638
+ translated.sql,
639
+ ...translated.args
640
+ );
641
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
642
+ }
643
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
644
+ return buildResultSet([], rowsAffected);
645
+ }
646
+ function splitSqlStatements(sql) {
647
+ const parts = [];
648
+ let current = "";
649
+ let inSingle = false;
650
+ let inDouble = false;
651
+ let inLineComment = false;
652
+ let inBlockComment = false;
653
+ for (let i = 0; i < sql.length; i++) {
654
+ const ch = sql[i];
655
+ const next = sql[i + 1];
656
+ if (inLineComment) {
657
+ current += ch;
658
+ if (ch === "\n") inLineComment = false;
659
+ continue;
660
+ }
661
+ if (inBlockComment) {
662
+ current += ch;
663
+ if (ch === "*" && next === "/") {
664
+ current += next;
665
+ inBlockComment = false;
666
+ i += 1;
667
+ }
668
+ continue;
669
+ }
670
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
671
+ current += ch + next;
672
+ inLineComment = true;
673
+ i += 1;
674
+ continue;
675
+ }
676
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
677
+ current += ch + next;
678
+ inBlockComment = true;
679
+ i += 1;
680
+ continue;
681
+ }
682
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
683
+ inSingle = !inSingle;
684
+ current += ch;
685
+ continue;
686
+ }
687
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
688
+ inDouble = !inDouble;
689
+ current += ch;
690
+ continue;
691
+ }
692
+ if (!inSingle && !inDouble && ch === ";") {
693
+ if (current.trim()) {
694
+ parts.push(current.trim());
695
+ }
696
+ current = "";
697
+ continue;
698
+ }
699
+ current += ch;
700
+ }
701
+ if (current.trim()) {
702
+ parts.push(current.trim());
703
+ }
704
+ return parts;
705
+ }
706
+ async function createPrismaDbAdapter(fallbackClient) {
707
+ const prisma = await loadPrismaClient();
708
+ await ensureCompatibilityViews(prisma);
709
+ let closed = false;
710
+ let adapter;
711
+ const fallbackExecute = async (stmt, error) => {
712
+ if (!fallbackClient) {
713
+ if (error) throw error;
714
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
715
+ }
716
+ if (error) {
717
+ process.stderr.write(
718
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
719
+ `
720
+ );
721
+ }
722
+ return fallbackClient.execute(stmt);
723
+ };
724
+ adapter = {
725
+ async execute(stmt) {
726
+ if (shouldBypassPostgres(stmt)) {
727
+ return fallbackExecute(stmt);
728
+ }
729
+ try {
730
+ return await executeOnPrisma(prisma, stmt);
731
+ } catch (error) {
732
+ if (shouldFallbackOnError(error)) {
733
+ return fallbackExecute(stmt, error);
734
+ }
735
+ throw error;
736
+ }
737
+ },
738
+ async batch(stmts, mode) {
739
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
740
+ if (!fallbackClient) {
741
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
742
+ }
743
+ return fallbackClient.batch(stmts, mode);
744
+ }
745
+ try {
746
+ if (prisma.$transaction) {
747
+ return await prisma.$transaction(async (tx) => {
748
+ const results2 = [];
749
+ for (const stmt of stmts) {
750
+ results2.push(await executeOnPrisma(tx, stmt));
751
+ }
752
+ return results2;
753
+ });
754
+ }
755
+ const results = [];
756
+ for (const stmt of stmts) {
757
+ results.push(await executeOnPrisma(prisma, stmt));
758
+ }
759
+ return results;
760
+ } catch (error) {
761
+ if (fallbackClient && shouldFallbackOnError(error)) {
762
+ process.stderr.write(
763
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
764
+ `
765
+ );
766
+ return fallbackClient.batch(stmts, mode);
767
+ }
768
+ throw error;
769
+ }
770
+ },
771
+ async migrate(stmts) {
772
+ if (fallbackClient) {
773
+ return fallbackClient.migrate(stmts);
774
+ }
775
+ return adapter.batch(stmts, "deferred");
776
+ },
777
+ async transaction(mode) {
778
+ if (!fallbackClient) {
779
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
780
+ }
781
+ return fallbackClient.transaction(mode);
782
+ },
783
+ async executeMultiple(sql) {
784
+ if (fallbackClient && shouldBypassPostgres(sql)) {
785
+ return fallbackClient.executeMultiple(sql);
786
+ }
787
+ for (const statement of splitSqlStatements(sql)) {
788
+ await adapter.execute(statement);
789
+ }
790
+ },
791
+ async sync() {
792
+ if (fallbackClient) {
793
+ return fallbackClient.sync();
794
+ }
795
+ return { frame_no: 0, frames_synced: 0 };
796
+ },
797
+ close() {
798
+ closed = true;
799
+ prismaClientPromise = null;
800
+ compatibilityBootstrapPromise = null;
801
+ void prisma.$disconnect?.();
802
+ },
803
+ get closed() {
804
+ return closed;
805
+ },
806
+ get protocol() {
807
+ return "prisma-postgres";
808
+ }
809
+ };
810
+ return adapter;
811
+ }
812
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
813
+ var init_database_adapter = __esm({
814
+ "src/lib/database-adapter.ts"() {
815
+ "use strict";
816
+ VIEW_MAPPINGS = [
817
+ { view: "memories", source: "memory.memory_records" },
818
+ { view: "tasks", source: "memory.tasks" },
819
+ { view: "behaviors", source: "memory.behaviors" },
820
+ { view: "entities", source: "memory.entities" },
821
+ { view: "relationships", source: "memory.relationships" },
822
+ { view: "entity_memories", source: "memory.entity_memories" },
823
+ { view: "entity_aliases", source: "memory.entity_aliases" },
824
+ { view: "notifications", source: "memory.notifications" },
825
+ { view: "messages", source: "memory.messages" },
826
+ { view: "users", source: "wiki.users" },
827
+ { view: "workspaces", source: "wiki.workspaces" },
828
+ { view: "workspace_users", source: "wiki.workspace_users" },
829
+ { view: "documents", source: "wiki.workspace_documents" },
830
+ { view: "chats", source: "wiki.workspace_chats" }
831
+ ];
832
+ UPSERT_KEYS = {
833
+ memories: ["id"],
834
+ tasks: ["id"],
835
+ behaviors: ["id"],
836
+ entities: ["id"],
837
+ relationships: ["id"],
838
+ entity_aliases: ["alias"],
839
+ notifications: ["id"],
840
+ messages: ["id"],
841
+ users: ["id"],
842
+ workspaces: ["id"],
843
+ workspace_users: ["id"],
844
+ documents: ["id"],
845
+ chats: ["id"]
846
+ };
847
+ BOOLEAN_COLUMNS_BY_TABLE = {
848
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
849
+ behaviors: /* @__PURE__ */ new Set(["active"]),
850
+ notifications: /* @__PURE__ */ new Set(["read"]),
851
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
852
+ };
853
+ BOOLEAN_COLUMN_NAMES = new Set(
854
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
855
+ );
856
+ IMMEDIATE_FALLBACK_PATTERNS = [
857
+ /\bPRAGMA\b/i,
858
+ /\bsqlite_master\b/i,
859
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
860
+ /\bMATCH\b/i,
861
+ /\bvector_distance_cos\s*\(/i,
862
+ /\bjson_extract\s*\(/i,
863
+ /\bjulianday\s*\(/i,
864
+ /\bstrftime\s*\(/i,
865
+ /\blast_insert_rowid\s*\(/i
866
+ ];
867
+ prismaClientPromise = null;
868
+ compatibilityBootstrapPromise = null;
284
869
  }
285
870
  });
286
871
 
287
872
  // src/lib/database.ts
288
873
  import { createClient } from "@libsql/client";
289
874
  async function initDatabase(config) {
875
+ if (_walCheckpointTimer) {
876
+ clearInterval(_walCheckpointTimer);
877
+ _walCheckpointTimer = null;
878
+ }
879
+ if (_daemonClient) {
880
+ _daemonClient.close();
881
+ _daemonClient = null;
882
+ }
883
+ if (_adapterClient && _adapterClient !== _resilientClient) {
884
+ _adapterClient.close();
885
+ }
886
+ _adapterClient = null;
290
887
  if (_client) {
291
888
  _client.close();
292
889
  _client = null;
@@ -300,6 +897,7 @@ async function initDatabase(config) {
300
897
  }
301
898
  _client = createClient(opts);
302
899
  _resilientClient = wrapWithRetry(_client);
900
+ _adapterClient = _resilientClient;
303
901
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
304
902
  });
305
903
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -310,11 +908,17 @@ async function initDatabase(config) {
310
908
  });
311
909
  }, 3e4);
312
910
  _walCheckpointTimer.unref();
911
+ if (process.env.DATABASE_URL) {
912
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
913
+ }
313
914
  }
314
915
  function getClient() {
315
- if (!_resilientClient) {
916
+ if (!_adapterClient) {
316
917
  throw new Error("Database client not initialized. Call initDatabase() first.");
317
918
  }
919
+ if (process.env.DATABASE_URL) {
920
+ return _adapterClient;
921
+ }
318
922
  if (process.env.EXE_IS_DAEMON === "1") {
319
923
  return _resilientClient;
320
924
  }
@@ -1254,16 +1858,18 @@ async function ensureSchema() {
1254
1858
  }
1255
1859
  }
1256
1860
  }
1257
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1861
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1258
1862
  var init_database = __esm({
1259
1863
  "src/lib/database.ts"() {
1260
1864
  "use strict";
1261
1865
  init_db_retry();
1262
1866
  init_employees();
1867
+ init_database_adapter();
1263
1868
  _client = null;
1264
1869
  _resilientClient = null;
1265
1870
  _walCheckpointTimer = null;
1266
1871
  _daemonClient = null;
1872
+ _adapterClient = null;
1267
1873
  initTurso = initDatabase;
1268
1874
  }
1269
1875
  });
@@ -1281,7 +1887,7 @@ __export(shard_manager_exports, {
1281
1887
  listShards: () => listShards,
1282
1888
  shardExists: () => shardExists
1283
1889
  });
1284
- import path4 from "path";
1890
+ import path5 from "path";
1285
1891
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1286
1892
  import { createClient as createClient2 } from "@libsql/client";
1287
1893
  function initShardManager(encryptionKey) {
@@ -1307,7 +1913,7 @@ function getShardClient(projectName) {
1307
1913
  }
1308
1914
  const cached = _shards.get(safeName);
1309
1915
  if (cached) return cached;
1310
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1916
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1311
1917
  const client = createClient2({
1312
1918
  url: `file:${dbPath}`,
1313
1919
  encryptionKey: _encryptionKey
@@ -1317,7 +1923,7 @@ function getShardClient(projectName) {
1317
1923
  }
1318
1924
  function shardExists(projectName) {
1319
1925
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1320
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1926
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1321
1927
  }
1322
1928
  function listShards() {
1323
1929
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1394,7 +2000,23 @@ async function ensureShardSchema(client) {
1394
2000
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1395
2001
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1396
2002
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1397
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2003
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2004
+ // Metadata enrichment columns (must match database.ts)
2005
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2006
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2007
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2008
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2009
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2010
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2011
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2012
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2013
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2014
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2015
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2016
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2017
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2018
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2019
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1398
2020
  ]) {
1399
2021
  try {
1400
2022
  await client.execute(col);
@@ -1506,7 +2128,7 @@ var init_shard_manager = __esm({
1506
2128
  "src/lib/shard-manager.ts"() {
1507
2129
  "use strict";
1508
2130
  init_config();
1509
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2131
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1510
2132
  _shards = /* @__PURE__ */ new Map();
1511
2133
  _encryptionKey = null;
1512
2134
  _shardingEnabled = false;
@@ -1707,15 +2329,15 @@ init_database();
1707
2329
  // src/lib/keychain.ts
1708
2330
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1709
2331
  import { existsSync as existsSync3 } from "fs";
1710
- import path3 from "path";
1711
- import os3 from "os";
2332
+ import path4 from "path";
2333
+ import os4 from "os";
1712
2334
  var SERVICE = "exe-mem";
1713
2335
  var ACCOUNT = "master-key";
1714
2336
  function getKeyDir() {
1715
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2337
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1716
2338
  }
1717
2339
  function getKeyPath() {
1718
- return path3.join(getKeyDir(), "master.key");
2340
+ return path4.join(getKeyDir(), "master.key");
1719
2341
  }
1720
2342
  async function tryKeytar() {
1721
2343
  try {
@@ -1738,7 +2360,7 @@ async function getMasterKey() {
1738
2360
  const keyPath = getKeyPath();
1739
2361
  if (!existsSync3(keyPath)) {
1740
2362
  process.stderr.write(
1741
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2363
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1742
2364
  `
1743
2365
  );
1744
2366
  return null;