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