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