@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
@@ -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
  }
@@ -1253,16 +1857,18 @@ async function ensureSchema() {
1253
1857
  }
1254
1858
  }
1255
1859
  }
1256
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1860
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1257
1861
  var init_database = __esm({
1258
1862
  "src/lib/database.ts"() {
1259
1863
  "use strict";
1260
1864
  init_db_retry();
1261
1865
  init_employees();
1866
+ init_database_adapter();
1262
1867
  _client = null;
1263
1868
  _resilientClient = null;
1264
1869
  _walCheckpointTimer = null;
1265
1870
  _daemonClient = null;
1871
+ _adapterClient = null;
1266
1872
  initTurso = initDatabase;
1267
1873
  }
1268
1874
  });
@@ -1335,7 +1941,7 @@ __export(shard_manager_exports, {
1335
1941
  listShards: () => listShards,
1336
1942
  shardExists: () => shardExists
1337
1943
  });
1338
- import path4 from "path";
1944
+ import path5 from "path";
1339
1945
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1340
1946
  import { createClient as createClient2 } from "@libsql/client";
1341
1947
  function initShardManager(encryptionKey) {
@@ -1361,7 +1967,7 @@ function getShardClient(projectName) {
1361
1967
  }
1362
1968
  const cached = _shards.get(safeName);
1363
1969
  if (cached) return cached;
1364
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1970
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1365
1971
  const client = createClient2({
1366
1972
  url: `file:${dbPath}`,
1367
1973
  encryptionKey: _encryptionKey
@@ -1371,7 +1977,7 @@ function getShardClient(projectName) {
1371
1977
  }
1372
1978
  function shardExists(projectName) {
1373
1979
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1374
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1980
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1375
1981
  }
1376
1982
  function listShards() {
1377
1983
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1448,7 +2054,23 @@ async function ensureShardSchema(client) {
1448
2054
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1449
2055
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1450
2056
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1451
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2057
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2058
+ // Metadata enrichment columns (must match database.ts)
2059
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2060
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2061
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2062
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2063
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2064
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2065
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2066
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2067
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2068
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2069
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2070
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2071
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2072
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2073
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1452
2074
  ]) {
1453
2075
  try {
1454
2076
  await client.execute(col);
@@ -1560,7 +2182,7 @@ var init_shard_manager = __esm({
1560
2182
  "src/lib/shard-manager.ts"() {
1561
2183
  "use strict";
1562
2184
  init_config();
1563
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2185
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1564
2186
  _shards = /* @__PURE__ */ new Map();
1565
2187
  _encryptionKey = null;
1566
2188
  _shardingEnabled = false;
@@ -1755,13 +2377,13 @@ ${p.content}`).join("\n\n");
1755
2377
  });
1756
2378
 
1757
2379
  // src/lib/session-registry.ts
1758
- import path5 from "path";
1759
- import os4 from "os";
2380
+ import path6 from "path";
2381
+ import os5 from "os";
1760
2382
  var REGISTRY_PATH;
1761
2383
  var init_session_registry = __esm({
1762
2384
  "src/lib/session-registry.ts"() {
1763
2385
  "use strict";
1764
- REGISTRY_PATH = path5.join(os4.homedir(), ".exe-os", "session-registry.json");
2386
+ REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
1765
2387
  }
1766
2388
  });
1767
2389
 
@@ -1837,14 +2459,14 @@ var init_runtime_table = __esm({
1837
2459
 
1838
2460
  // src/lib/agent-config.ts
1839
2461
  import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
1840
- import path6 from "path";
2462
+ import path7 from "path";
1841
2463
  var AGENT_CONFIG_PATH, DEFAULT_MODELS;
1842
2464
  var init_agent_config = __esm({
1843
2465
  "src/lib/agent-config.ts"() {
1844
2466
  "use strict";
1845
2467
  init_config();
1846
2468
  init_runtime_table();
1847
- AGENT_CONFIG_PATH = path6.join(EXE_AI_DIR, "agent-config.json");
2469
+ AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
1848
2470
  DEFAULT_MODELS = {
1849
2471
  claude: "claude-opus-4",
1850
2472
  codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
@@ -1855,37 +2477,37 @@ var init_agent_config = __esm({
1855
2477
 
1856
2478
  // src/lib/intercom-queue.ts
1857
2479
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
1858
- import path7 from "path";
1859
- import os5 from "os";
2480
+ import path8 from "path";
2481
+ import os6 from "os";
1860
2482
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
1861
2483
  var init_intercom_queue = __esm({
1862
2484
  "src/lib/intercom-queue.ts"() {
1863
2485
  "use strict";
1864
- QUEUE_PATH = path7.join(os5.homedir(), ".exe-os", "intercom-queue.json");
2486
+ QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
1865
2487
  TTL_MS = 60 * 60 * 1e3;
1866
- INTERCOM_LOG = path7.join(os5.homedir(), ".exe-os", "intercom.log");
2488
+ INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
1867
2489
  }
1868
2490
  });
1869
2491
 
1870
2492
  // src/lib/license.ts
1871
2493
  import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync7, mkdirSync as mkdirSync4 } from "fs";
1872
2494
  import { randomUUID as randomUUID2 } from "crypto";
1873
- import path8 from "path";
2495
+ import path9 from "path";
1874
2496
  import { jwtVerify, importSPKI } from "jose";
1875
2497
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
1876
2498
  var init_license = __esm({
1877
2499
  "src/lib/license.ts"() {
1878
2500
  "use strict";
1879
2501
  init_config();
1880
- LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
1881
- CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
1882
- DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
2502
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2503
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2504
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
1883
2505
  }
1884
2506
  });
1885
2507
 
1886
2508
  // src/lib/plan-limits.ts
1887
2509
  import { readFileSync as readFileSync6, existsSync as existsSync8 } from "fs";
1888
- import path9 from "path";
2510
+ import path10 from "path";
1889
2511
  var CACHE_PATH2;
1890
2512
  var init_plan_limits = __esm({
1891
2513
  "src/lib/plan-limits.ts"() {
@@ -1894,13 +2516,13 @@ var init_plan_limits = __esm({
1894
2516
  init_employees();
1895
2517
  init_license();
1896
2518
  init_config();
1897
- CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2519
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
1898
2520
  }
1899
2521
  });
1900
2522
 
1901
2523
  // src/lib/tmux-routing.ts
1902
- import path10 from "path";
1903
- import os6 from "os";
2524
+ import path11 from "path";
2525
+ import os7 from "os";
1904
2526
  import { fileURLToPath } from "url";
1905
2527
  var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
1906
2528
  var init_tmux_routing = __esm({
@@ -1917,10 +2539,10 @@ var init_tmux_routing = __esm({
1917
2539
  init_intercom_queue();
1918
2540
  init_plan_limits();
1919
2541
  init_employees();
1920
- SPAWN_LOCK_DIR = path10.join(os6.homedir(), ".exe-os", "spawn-locks");
1921
- SESSION_CACHE = path10.join(os6.homedir(), ".exe-os", "session-cache");
1922
- INTERCOM_LOG2 = path10.join(os6.homedir(), ".exe-os", "intercom.log");
1923
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
2542
+ SPAWN_LOCK_DIR = path11.join(os7.homedir(), ".exe-os", "spawn-locks");
2543
+ SESSION_CACHE = path11.join(os7.homedir(), ".exe-os", "session-cache");
2544
+ INTERCOM_LOG2 = path11.join(os7.homedir(), ".exe-os", "intercom.log");
2545
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
1924
2546
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1925
2547
  }
1926
2548
  });
@@ -1932,15 +2554,15 @@ init_database();
1932
2554
  // src/lib/keychain.ts
1933
2555
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1934
2556
  import { existsSync as existsSync3 } from "fs";
1935
- import path3 from "path";
1936
- import os3 from "os";
2557
+ import path4 from "path";
2558
+ import os4 from "os";
1937
2559
  var SERVICE = "exe-mem";
1938
2560
  var ACCOUNT = "master-key";
1939
2561
  function getKeyDir() {
1940
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2562
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1941
2563
  }
1942
2564
  function getKeyPath() {
1943
- return path3.join(getKeyDir(), "master.key");
2565
+ return path4.join(getKeyDir(), "master.key");
1944
2566
  }
1945
2567
  async function tryKeytar() {
1946
2568
  try {
@@ -1963,7 +2585,7 @@ async function getMasterKey() {
1963
2585
  const keyPath = getKeyPath();
1964
2586
  if (!existsSync3(keyPath)) {
1965
2587
  process.stderr.write(
1966
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2588
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1967
2589
  `
1968
2590
  );
1969
2591
  return null;