@askexenow/exe-os 0.9.7 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/bin/backfill-conversations.js +754 -79
  2. package/dist/bin/backfill-responses.js +752 -77
  3. package/dist/bin/backfill-vectors.js +752 -77
  4. package/dist/bin/cleanup-stale-review-tasks.js +657 -35
  5. package/dist/bin/cli.js +1388 -605
  6. package/dist/bin/exe-agent-config.js +123 -95
  7. package/dist/bin/exe-agent.js +41 -25
  8. package/dist/bin/exe-assign.js +732 -57
  9. package/dist/bin/exe-boot.js +784 -153
  10. package/dist/bin/exe-call.js +209 -138
  11. package/dist/bin/exe-cloud.js +35 -12
  12. package/dist/bin/exe-dispatch.js +692 -70
  13. package/dist/bin/exe-doctor.js +648 -26
  14. package/dist/bin/exe-export-behaviors.js +650 -20
  15. package/dist/bin/exe-forget.js +635 -13
  16. package/dist/bin/exe-gateway.js +1053 -271
  17. package/dist/bin/exe-heartbeat.js +665 -43
  18. package/dist/bin/exe-kill.js +646 -16
  19. package/dist/bin/exe-launch-agent.js +887 -97
  20. package/dist/bin/exe-link.js +658 -43
  21. package/dist/bin/exe-new-employee.js +378 -177
  22. package/dist/bin/exe-pending-messages.js +656 -34
  23. package/dist/bin/exe-pending-notifications.js +635 -13
  24. package/dist/bin/exe-pending-reviews.js +659 -37
  25. package/dist/bin/exe-rename.js +645 -30
  26. package/dist/bin/exe-review.js +635 -13
  27. package/dist/bin/exe-search.js +771 -88
  28. package/dist/bin/exe-session-cleanup.js +834 -150
  29. package/dist/bin/exe-settings.js +127 -91
  30. package/dist/bin/exe-start-codex.js +729 -94
  31. package/dist/bin/exe-start-opencode.js +717 -82
  32. package/dist/bin/exe-status.js +657 -35
  33. package/dist/bin/exe-team.js +635 -13
  34. package/dist/bin/git-sweep.js +720 -89
  35. package/dist/bin/graph-backfill.js +643 -13
  36. package/dist/bin/graph-export.js +646 -16
  37. package/dist/bin/install.js +596 -193
  38. package/dist/bin/scan-tasks.js +724 -93
  39. package/dist/bin/setup.js +1038 -210
  40. package/dist/bin/shard-migrate.js +645 -15
  41. package/dist/bin/wiki-sync.js +646 -16
  42. package/dist/gateway/index.js +1027 -245
  43. package/dist/hooks/bug-report-worker.js +891 -170
  44. package/dist/hooks/commit-complete.js +718 -87
  45. package/dist/hooks/error-recall.js +776 -93
  46. package/dist/hooks/exe-heartbeat-hook.js +85 -71
  47. package/dist/hooks/ingest-worker.js +840 -156
  48. package/dist/hooks/ingest.js +90 -73
  49. package/dist/hooks/instructions-loaded.js +669 -38
  50. package/dist/hooks/notification.js +661 -30
  51. package/dist/hooks/post-compact.js +674 -43
  52. package/dist/hooks/pre-compact.js +718 -87
  53. package/dist/hooks/pre-tool-use.js +872 -125
  54. package/dist/hooks/prompt-ingest-worker.js +758 -83
  55. package/dist/hooks/prompt-submit.js +1060 -319
  56. package/dist/hooks/response-ingest-worker.js +758 -83
  57. package/dist/hooks/session-end.js +721 -90
  58. package/dist/hooks/session-start.js +1031 -207
  59. package/dist/hooks/stop.js +680 -49
  60. package/dist/hooks/subagent-stop.js +674 -43
  61. package/dist/hooks/summary-worker.js +816 -132
  62. package/dist/index.js +1015 -232
  63. package/dist/lib/cloud-sync.js +663 -48
  64. package/dist/lib/consolidation.js +26 -3
  65. package/dist/lib/database.js +626 -18
  66. package/dist/lib/db.js +2261 -0
  67. package/dist/lib/device-registry.js +640 -25
  68. package/dist/lib/embedder.js +96 -43
  69. package/dist/lib/employee-templates.js +16 -0
  70. package/dist/lib/employees.js +259 -83
  71. package/dist/lib/exe-daemon-client.js +101 -63
  72. package/dist/lib/exe-daemon.js +894 -162
  73. package/dist/lib/hybrid-search.js +771 -88
  74. package/dist/lib/identity.js +27 -7
  75. package/dist/lib/messaging.js +55 -28
  76. package/dist/lib/reminders.js +21 -1
  77. package/dist/lib/schedules.js +636 -14
  78. package/dist/lib/skill-learning.js +21 -1
  79. package/dist/lib/store.js +643 -13
  80. package/dist/lib/task-router.js +82 -71
  81. package/dist/lib/tasks.js +98 -71
  82. package/dist/lib/tmux-routing.js +87 -60
  83. package/dist/lib/token-spend.js +26 -6
  84. package/dist/mcp/server.js +1784 -458
  85. package/dist/mcp/tools/complete-reminder.js +21 -1
  86. package/dist/mcp/tools/create-reminder.js +21 -1
  87. package/dist/mcp/tools/create-task.js +290 -164
  88. package/dist/mcp/tools/deactivate-behavior.js +24 -4
  89. package/dist/mcp/tools/list-reminders.js +21 -1
  90. package/dist/mcp/tools/list-tasks.js +195 -38
  91. package/dist/mcp/tools/send-message.js +58 -31
  92. package/dist/mcp/tools/update-task.js +75 -48
  93. package/dist/runtime/index.js +720 -89
  94. package/dist/tui/App.js +853 -123
  95. package/package.json +3 -2
@@ -273,7 +273,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
273
273
  return [];
274
274
  }
275
275
  }
276
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
276
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
277
277
  var init_employees = __esm({
278
278
  "src/lib/employees.ts"() {
279
279
  "use strict";
@@ -281,12 +281,609 @@ var init_employees = __esm({
281
281
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
282
282
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
283
283
  COORDINATOR_ROLE = "COO";
284
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
285
+ }
286
+ });
287
+
288
+ // src/lib/database-adapter.ts
289
+ import os3 from "os";
290
+ import path3 from "path";
291
+ import { createRequire } from "module";
292
+ import { pathToFileURL } from "url";
293
+ function quotedIdentifier(identifier) {
294
+ return `"${identifier.replace(/"/g, '""')}"`;
295
+ }
296
+ function unqualifiedTableName(name) {
297
+ const raw = name.trim().replace(/^"|"$/g, "");
298
+ const parts = raw.split(".");
299
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
300
+ }
301
+ function stripTrailingSemicolon(sql) {
302
+ return sql.trim().replace(/;+\s*$/u, "");
303
+ }
304
+ function appendClause(sql, clause) {
305
+ const trimmed = stripTrailingSemicolon(sql);
306
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
307
+ if (!returningMatch) {
308
+ return `${trimmed}${clause}`;
309
+ }
310
+ const idx = returningMatch.index;
311
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
312
+ }
313
+ function normalizeStatement(stmt) {
314
+ if (typeof stmt === "string") {
315
+ return { kind: "positional", sql: stmt, args: [] };
316
+ }
317
+ const sql = stmt.sql;
318
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
319
+ return { kind: "positional", sql, args: stmt.args ?? [] };
320
+ }
321
+ return { kind: "named", sql, args: stmt.args };
322
+ }
323
+ function rewriteBooleanLiterals(sql) {
324
+ let out = sql;
325
+ for (const column of BOOLEAN_COLUMN_NAMES) {
326
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
327
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
328
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
329
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
330
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
331
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
332
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
333
+ }
334
+ return out;
335
+ }
336
+ function rewriteInsertOrIgnore(sql) {
337
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
338
+ return sql;
339
+ }
340
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
341
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
342
+ }
343
+ function rewriteInsertOrReplace(sql) {
344
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
345
+ if (!match) {
346
+ return sql;
347
+ }
348
+ const rawTable = match[1];
349
+ const rawColumns = match[2];
350
+ const remainder = match[3];
351
+ const tableName = unqualifiedTableName(rawTable);
352
+ const conflictKeys = UPSERT_KEYS[tableName];
353
+ if (!conflictKeys?.length) {
354
+ return sql;
355
+ }
356
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
357
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
358
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
359
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
360
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
361
+ }
362
+ function rewriteSql(sql) {
363
+ let out = sql;
364
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
365
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
366
+ out = rewriteBooleanLiterals(out);
367
+ out = rewriteInsertOrReplace(out);
368
+ out = rewriteInsertOrIgnore(out);
369
+ return stripTrailingSemicolon(out);
370
+ }
371
+ function toBoolean(value) {
372
+ if (value === null || value === void 0) return value;
373
+ if (typeof value === "boolean") return value;
374
+ if (typeof value === "number") return value !== 0;
375
+ if (typeof value === "bigint") return value !== 0n;
376
+ if (typeof value === "string") {
377
+ const normalized = value.trim().toLowerCase();
378
+ if (normalized === "0" || normalized === "false") return false;
379
+ if (normalized === "1" || normalized === "true") return true;
380
+ }
381
+ return Boolean(value);
382
+ }
383
+ function countQuestionMarks(sql, end) {
384
+ let count = 0;
385
+ let inSingle = false;
386
+ let inDouble = false;
387
+ let inLineComment = false;
388
+ let inBlockComment = false;
389
+ for (let i = 0; i < end; i++) {
390
+ const ch = sql[i];
391
+ const next = sql[i + 1];
392
+ if (inLineComment) {
393
+ if (ch === "\n") inLineComment = false;
394
+ continue;
395
+ }
396
+ if (inBlockComment) {
397
+ if (ch === "*" && next === "/") {
398
+ inBlockComment = false;
399
+ i += 1;
400
+ }
401
+ continue;
402
+ }
403
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
404
+ inLineComment = true;
405
+ i += 1;
406
+ continue;
407
+ }
408
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
409
+ inBlockComment = true;
410
+ i += 1;
411
+ continue;
412
+ }
413
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
414
+ inSingle = !inSingle;
415
+ continue;
416
+ }
417
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
418
+ inDouble = !inDouble;
419
+ continue;
420
+ }
421
+ if (!inSingle && !inDouble && ch === "?") {
422
+ count += 1;
423
+ }
424
+ }
425
+ return count;
426
+ }
427
+ function findBooleanPlaceholderIndexes(sql) {
428
+ const indexes = /* @__PURE__ */ new Set();
429
+ for (const column of BOOLEAN_COLUMN_NAMES) {
430
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
431
+ for (const match of sql.matchAll(pattern)) {
432
+ const matchText = match[0];
433
+ const qIndex = match.index + matchText.lastIndexOf("?");
434
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
435
+ }
436
+ }
437
+ return indexes;
438
+ }
439
+ function coerceInsertBooleanArgs(sql, args) {
440
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
441
+ if (!match) return;
442
+ const rawTable = match[1];
443
+ const rawColumns = match[2];
444
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
445
+ if (!boolColumns?.size) return;
446
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
447
+ for (const [index, column] of columns.entries()) {
448
+ if (boolColumns.has(column) && index < args.length) {
449
+ args[index] = toBoolean(args[index]);
450
+ }
451
+ }
452
+ }
453
+ function coerceUpdateBooleanArgs(sql, args) {
454
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
455
+ if (!match) return;
456
+ const rawTable = match[1];
457
+ const setClause = match[2];
458
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
459
+ if (!boolColumns?.size) return;
460
+ const assignments = setClause.split(",");
461
+ let placeholderIndex = 0;
462
+ for (const assignment of assignments) {
463
+ if (!assignment.includes("?")) continue;
464
+ placeholderIndex += 1;
465
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
466
+ if (colMatch && boolColumns.has(colMatch[1])) {
467
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
468
+ }
469
+ }
470
+ }
471
+ function coerceBooleanArgs(sql, args) {
472
+ const nextArgs = [...args];
473
+ coerceInsertBooleanArgs(sql, nextArgs);
474
+ coerceUpdateBooleanArgs(sql, nextArgs);
475
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
476
+ for (const index of placeholderIndexes) {
477
+ if (index > 0 && index <= nextArgs.length) {
478
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
479
+ }
480
+ }
481
+ return nextArgs;
482
+ }
483
+ function convertQuestionMarksToDollarParams(sql) {
484
+ let out = "";
485
+ let placeholder = 0;
486
+ let inSingle = false;
487
+ let inDouble = false;
488
+ let inLineComment = false;
489
+ let inBlockComment = false;
490
+ for (let i = 0; i < sql.length; i++) {
491
+ const ch = sql[i];
492
+ const next = sql[i + 1];
493
+ if (inLineComment) {
494
+ out += ch;
495
+ if (ch === "\n") inLineComment = false;
496
+ continue;
497
+ }
498
+ if (inBlockComment) {
499
+ out += ch;
500
+ if (ch === "*" && next === "/") {
501
+ out += next;
502
+ inBlockComment = false;
503
+ i += 1;
504
+ }
505
+ continue;
506
+ }
507
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
508
+ out += ch + next;
509
+ inLineComment = true;
510
+ i += 1;
511
+ continue;
512
+ }
513
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
514
+ out += ch + next;
515
+ inBlockComment = true;
516
+ i += 1;
517
+ continue;
518
+ }
519
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
520
+ inSingle = !inSingle;
521
+ out += ch;
522
+ continue;
523
+ }
524
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
525
+ inDouble = !inDouble;
526
+ out += ch;
527
+ continue;
528
+ }
529
+ if (!inSingle && !inDouble && ch === "?") {
530
+ placeholder += 1;
531
+ out += `$${placeholder}`;
532
+ continue;
533
+ }
534
+ out += ch;
535
+ }
536
+ return out;
537
+ }
538
+ function translateStatementForPostgres(stmt) {
539
+ const normalized = normalizeStatement(stmt);
540
+ if (normalized.kind === "named") {
541
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
542
+ }
543
+ const rewrittenSql = rewriteSql(normalized.sql);
544
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
545
+ return {
546
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
547
+ args: coercedArgs
548
+ };
549
+ }
550
+ function shouldBypassPostgres(stmt) {
551
+ const normalized = normalizeStatement(stmt);
552
+ if (normalized.kind === "named") {
553
+ return true;
554
+ }
555
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
556
+ }
557
+ function shouldFallbackOnError(error) {
558
+ const message = error instanceof Error ? error.message : String(error);
559
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
560
+ }
561
+ function isReadQuery(sql) {
562
+ const trimmed = sql.trimStart();
563
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
564
+ }
565
+ function buildRow(row, columns) {
566
+ const values = columns.map((column) => row[column]);
567
+ return Object.assign(values, row);
568
+ }
569
+ function buildResultSet(rows, rowsAffected = 0) {
570
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
571
+ const resultRows = rows.map((row) => buildRow(row, columns));
572
+ return {
573
+ columns,
574
+ columnTypes: columns.map(() => ""),
575
+ rows: resultRows,
576
+ rowsAffected,
577
+ lastInsertRowid: void 0,
578
+ toJSON() {
579
+ return {
580
+ columns,
581
+ columnTypes: columns.map(() => ""),
582
+ rows,
583
+ rowsAffected,
584
+ lastInsertRowid: void 0
585
+ };
586
+ }
587
+ };
588
+ }
589
+ async function loadPrismaClient() {
590
+ if (!prismaClientPromise) {
591
+ prismaClientPromise = (async () => {
592
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
593
+ if (explicitPath) {
594
+ const module2 = await import(pathToFileURL(explicitPath).href);
595
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
596
+ if (!PrismaClient2) {
597
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
598
+ }
599
+ return new PrismaClient2();
600
+ }
601
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
602
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
603
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
604
+ const module = await import(pathToFileURL(prismaEntry).href);
605
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
606
+ if (!PrismaClient) {
607
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
608
+ }
609
+ return new PrismaClient();
610
+ })();
611
+ }
612
+ return prismaClientPromise;
613
+ }
614
+ async function ensureCompatibilityViews(prisma) {
615
+ if (!compatibilityBootstrapPromise) {
616
+ compatibilityBootstrapPromise = (async () => {
617
+ for (const mapping of VIEW_MAPPINGS) {
618
+ const relation = mapping.source.replace(/"/g, "");
619
+ const rows = await prisma.$queryRawUnsafe(
620
+ "SELECT to_regclass($1) AS regclass",
621
+ relation
622
+ );
623
+ if (!rows[0]?.regclass) {
624
+ continue;
625
+ }
626
+ await prisma.$executeRawUnsafe(
627
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
628
+ );
629
+ }
630
+ })();
631
+ }
632
+ return compatibilityBootstrapPromise;
633
+ }
634
+ async function executeOnPrisma(executor, stmt) {
635
+ const translated = translateStatementForPostgres(stmt);
636
+ if (isReadQuery(translated.sql)) {
637
+ const rows = await executor.$queryRawUnsafe(
638
+ translated.sql,
639
+ ...translated.args
640
+ );
641
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
642
+ }
643
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
644
+ return buildResultSet([], rowsAffected);
645
+ }
646
+ function splitSqlStatements(sql) {
647
+ const parts = [];
648
+ let current = "";
649
+ let inSingle = false;
650
+ let inDouble = false;
651
+ let inLineComment = false;
652
+ let inBlockComment = false;
653
+ for (let i = 0; i < sql.length; i++) {
654
+ const ch = sql[i];
655
+ const next = sql[i + 1];
656
+ if (inLineComment) {
657
+ current += ch;
658
+ if (ch === "\n") inLineComment = false;
659
+ continue;
660
+ }
661
+ if (inBlockComment) {
662
+ current += ch;
663
+ if (ch === "*" && next === "/") {
664
+ current += next;
665
+ inBlockComment = false;
666
+ i += 1;
667
+ }
668
+ continue;
669
+ }
670
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
671
+ current += ch + next;
672
+ inLineComment = true;
673
+ i += 1;
674
+ continue;
675
+ }
676
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
677
+ current += ch + next;
678
+ inBlockComment = true;
679
+ i += 1;
680
+ continue;
681
+ }
682
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
683
+ inSingle = !inSingle;
684
+ current += ch;
685
+ continue;
686
+ }
687
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
688
+ inDouble = !inDouble;
689
+ current += ch;
690
+ continue;
691
+ }
692
+ if (!inSingle && !inDouble && ch === ";") {
693
+ if (current.trim()) {
694
+ parts.push(current.trim());
695
+ }
696
+ current = "";
697
+ continue;
698
+ }
699
+ current += ch;
700
+ }
701
+ if (current.trim()) {
702
+ parts.push(current.trim());
703
+ }
704
+ return parts;
705
+ }
706
+ async function createPrismaDbAdapter(fallbackClient) {
707
+ const prisma = await loadPrismaClient();
708
+ await ensureCompatibilityViews(prisma);
709
+ let closed = false;
710
+ let adapter;
711
+ const fallbackExecute = async (stmt, error) => {
712
+ if (!fallbackClient) {
713
+ if (error) throw error;
714
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
715
+ }
716
+ if (error) {
717
+ process.stderr.write(
718
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
719
+ `
720
+ );
721
+ }
722
+ return fallbackClient.execute(stmt);
723
+ };
724
+ adapter = {
725
+ async execute(stmt) {
726
+ if (shouldBypassPostgres(stmt)) {
727
+ return fallbackExecute(stmt);
728
+ }
729
+ try {
730
+ return await executeOnPrisma(prisma, stmt);
731
+ } catch (error) {
732
+ if (shouldFallbackOnError(error)) {
733
+ return fallbackExecute(stmt, error);
734
+ }
735
+ throw error;
736
+ }
737
+ },
738
+ async batch(stmts, mode) {
739
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
740
+ if (!fallbackClient) {
741
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
742
+ }
743
+ return fallbackClient.batch(stmts, mode);
744
+ }
745
+ try {
746
+ if (prisma.$transaction) {
747
+ return await prisma.$transaction(async (tx) => {
748
+ const results2 = [];
749
+ for (const stmt of stmts) {
750
+ results2.push(await executeOnPrisma(tx, stmt));
751
+ }
752
+ return results2;
753
+ });
754
+ }
755
+ const results = [];
756
+ for (const stmt of stmts) {
757
+ results.push(await executeOnPrisma(prisma, stmt));
758
+ }
759
+ return results;
760
+ } catch (error) {
761
+ if (fallbackClient && shouldFallbackOnError(error)) {
762
+ process.stderr.write(
763
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
764
+ `
765
+ );
766
+ return fallbackClient.batch(stmts, mode);
767
+ }
768
+ throw error;
769
+ }
770
+ },
771
+ async migrate(stmts) {
772
+ if (fallbackClient) {
773
+ return fallbackClient.migrate(stmts);
774
+ }
775
+ return adapter.batch(stmts, "deferred");
776
+ },
777
+ async transaction(mode) {
778
+ if (!fallbackClient) {
779
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
780
+ }
781
+ return fallbackClient.transaction(mode);
782
+ },
783
+ async executeMultiple(sql) {
784
+ if (fallbackClient && shouldBypassPostgres(sql)) {
785
+ return fallbackClient.executeMultiple(sql);
786
+ }
787
+ for (const statement of splitSqlStatements(sql)) {
788
+ await adapter.execute(statement);
789
+ }
790
+ },
791
+ async sync() {
792
+ if (fallbackClient) {
793
+ return fallbackClient.sync();
794
+ }
795
+ return { frame_no: 0, frames_synced: 0 };
796
+ },
797
+ close() {
798
+ closed = true;
799
+ prismaClientPromise = null;
800
+ compatibilityBootstrapPromise = null;
801
+ void prisma.$disconnect?.();
802
+ },
803
+ get closed() {
804
+ return closed;
805
+ },
806
+ get protocol() {
807
+ return "prisma-postgres";
808
+ }
809
+ };
810
+ return adapter;
811
+ }
812
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
813
+ var init_database_adapter = __esm({
814
+ "src/lib/database-adapter.ts"() {
815
+ "use strict";
816
+ VIEW_MAPPINGS = [
817
+ { view: "memories", source: "memory.memory_records" },
818
+ { view: "tasks", source: "memory.tasks" },
819
+ { view: "behaviors", source: "memory.behaviors" },
820
+ { view: "entities", source: "memory.entities" },
821
+ { view: "relationships", source: "memory.relationships" },
822
+ { view: "entity_memories", source: "memory.entity_memories" },
823
+ { view: "entity_aliases", source: "memory.entity_aliases" },
824
+ { view: "notifications", source: "memory.notifications" },
825
+ { view: "messages", source: "memory.messages" },
826
+ { view: "users", source: "wiki.users" },
827
+ { view: "workspaces", source: "wiki.workspaces" },
828
+ { view: "workspace_users", source: "wiki.workspace_users" },
829
+ { view: "documents", source: "wiki.workspace_documents" },
830
+ { view: "chats", source: "wiki.workspace_chats" }
831
+ ];
832
+ UPSERT_KEYS = {
833
+ memories: ["id"],
834
+ tasks: ["id"],
835
+ behaviors: ["id"],
836
+ entities: ["id"],
837
+ relationships: ["id"],
838
+ entity_aliases: ["alias"],
839
+ notifications: ["id"],
840
+ messages: ["id"],
841
+ users: ["id"],
842
+ workspaces: ["id"],
843
+ workspace_users: ["id"],
844
+ documents: ["id"],
845
+ chats: ["id"]
846
+ };
847
+ BOOLEAN_COLUMNS_BY_TABLE = {
848
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
849
+ behaviors: /* @__PURE__ */ new Set(["active"]),
850
+ notifications: /* @__PURE__ */ new Set(["read"]),
851
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
852
+ };
853
+ BOOLEAN_COLUMN_NAMES = new Set(
854
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
855
+ );
856
+ IMMEDIATE_FALLBACK_PATTERNS = [
857
+ /\bPRAGMA\b/i,
858
+ /\bsqlite_master\b/i,
859
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
860
+ /\bMATCH\b/i,
861
+ /\bvector_distance_cos\s*\(/i,
862
+ /\bjson_extract\s*\(/i,
863
+ /\bjulianday\s*\(/i,
864
+ /\bstrftime\s*\(/i,
865
+ /\blast_insert_rowid\s*\(/i
866
+ ];
867
+ prismaClientPromise = null;
868
+ compatibilityBootstrapPromise = null;
284
869
  }
285
870
  });
286
871
 
287
872
  // src/lib/database.ts
288
873
  import { createClient } from "@libsql/client";
289
874
  async function initDatabase(config) {
875
+ if (_walCheckpointTimer) {
876
+ clearInterval(_walCheckpointTimer);
877
+ _walCheckpointTimer = null;
878
+ }
879
+ if (_daemonClient) {
880
+ _daemonClient.close();
881
+ _daemonClient = null;
882
+ }
883
+ if (_adapterClient && _adapterClient !== _resilientClient) {
884
+ _adapterClient.close();
885
+ }
886
+ _adapterClient = null;
290
887
  if (_client) {
291
888
  _client.close();
292
889
  _client = null;
@@ -300,6 +897,7 @@ async function initDatabase(config) {
300
897
  }
301
898
  _client = createClient(opts);
302
899
  _resilientClient = wrapWithRetry(_client);
900
+ _adapterClient = _resilientClient;
303
901
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
304
902
  });
305
903
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -310,11 +908,17 @@ async function initDatabase(config) {
310
908
  });
311
909
  }, 3e4);
312
910
  _walCheckpointTimer.unref();
911
+ if (process.env.DATABASE_URL) {
912
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
913
+ }
313
914
  }
314
915
  function getClient() {
315
- if (!_resilientClient) {
916
+ if (!_adapterClient) {
316
917
  throw new Error("Database client not initialized. Call initDatabase() first.");
317
918
  }
919
+ if (process.env.DATABASE_URL) {
920
+ return _adapterClient;
921
+ }
318
922
  if (process.env.EXE_IS_DAEMON === "1") {
319
923
  return _resilientClient;
320
924
  }
@@ -1255,26 +1859,36 @@ async function ensureSchema() {
1255
1859
  }
1256
1860
  }
1257
1861
  async function disposeDatabase() {
1862
+ if (_walCheckpointTimer) {
1863
+ clearInterval(_walCheckpointTimer);
1864
+ _walCheckpointTimer = null;
1865
+ }
1258
1866
  if (_daemonClient) {
1259
1867
  _daemonClient.close();
1260
1868
  _daemonClient = null;
1261
1869
  }
1870
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1871
+ _adapterClient.close();
1872
+ }
1873
+ _adapterClient = null;
1262
1874
  if (_client) {
1263
1875
  _client.close();
1264
1876
  _client = null;
1265
1877
  _resilientClient = null;
1266
1878
  }
1267
1879
  }
1268
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
1880
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1269
1881
  var init_database = __esm({
1270
1882
  "src/lib/database.ts"() {
1271
1883
  "use strict";
1272
1884
  init_db_retry();
1273
1885
  init_employees();
1886
+ init_database_adapter();
1274
1887
  _client = null;
1275
1888
  _resilientClient = null;
1276
1889
  _walCheckpointTimer = null;
1277
1890
  _daemonClient = null;
1891
+ _adapterClient = null;
1278
1892
  initTurso = initDatabase;
1279
1893
  disposeTurso = disposeDatabase;
1280
1894
  }
@@ -1293,7 +1907,7 @@ __export(shard_manager_exports, {
1293
1907
  listShards: () => listShards,
1294
1908
  shardExists: () => shardExists
1295
1909
  });
1296
- import path4 from "path";
1910
+ import path5 from "path";
1297
1911
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1298
1912
  import { createClient as createClient2 } from "@libsql/client";
1299
1913
  function initShardManager(encryptionKey) {
@@ -1319,7 +1933,7 @@ function getShardClient(projectName) {
1319
1933
  }
1320
1934
  const cached = _shards.get(safeName);
1321
1935
  if (cached) return cached;
1322
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1936
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1323
1937
  const client = createClient2({
1324
1938
  url: `file:${dbPath}`,
1325
1939
  encryptionKey: _encryptionKey
@@ -1329,7 +1943,7 @@ function getShardClient(projectName) {
1329
1943
  }
1330
1944
  function shardExists(projectName) {
1331
1945
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1332
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1946
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1333
1947
  }
1334
1948
  function listShards() {
1335
1949
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1406,7 +2020,23 @@ async function ensureShardSchema(client) {
1406
2020
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1407
2021
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1408
2022
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1409
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2023
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2024
+ // Metadata enrichment columns (must match database.ts)
2025
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2026
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2027
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2028
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2029
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2030
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2031
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2032
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2033
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2034
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2035
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2036
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2037
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2038
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2039
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1410
2040
  ]) {
1411
2041
  try {
1412
2042
  await client.execute(col);
@@ -1518,7 +2148,7 @@ var init_shard_manager = __esm({
1518
2148
  "src/lib/shard-manager.ts"() {
1519
2149
  "use strict";
1520
2150
  init_config();
1521
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2151
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1522
2152
  _shards = /* @__PURE__ */ new Map();
1523
2153
  _encryptionKey = null;
1524
2154
  _shardingEnabled = false;
@@ -1719,15 +2349,15 @@ init_database();
1719
2349
  // src/lib/keychain.ts
1720
2350
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1721
2351
  import { existsSync as existsSync3 } from "fs";
1722
- import path3 from "path";
1723
- import os3 from "os";
2352
+ import path4 from "path";
2353
+ import os4 from "os";
1724
2354
  var SERVICE = "exe-mem";
1725
2355
  var ACCOUNT = "master-key";
1726
2356
  function getKeyDir() {
1727
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2357
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1728
2358
  }
1729
2359
  function getKeyPath() {
1730
- return path3.join(getKeyDir(), "master.key");
2360
+ return path4.join(getKeyDir(), "master.key");
1731
2361
  }
1732
2362
  async function tryKeytar() {
1733
2363
  try {
@@ -1750,7 +2380,7 @@ async function getMasterKey() {
1750
2380
  const keyPath = getKeyPath();
1751
2381
  if (!existsSync3(keyPath)) {
1752
2382
  process.stderr.write(
1753
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2383
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1754
2384
  `
1755
2385
  );
1756
2386
  return null;
@@ -2064,8 +2694,8 @@ function vectorToBlob(vector) {
2064
2694
  init_database();
2065
2695
 
2066
2696
  // src/lib/wiki-sync.ts
2067
- async function wikiRequest(config, path5, method = "GET", body) {
2068
- const url = `${config.wikiUrl}/api/v1${path5}`;
2697
+ async function wikiRequest(config, path6, method = "GET", body) {
2698
+ const url = `${config.wikiUrl}/api/v1${path6}`;
2069
2699
  const headers = {
2070
2700
  "Authorization": `Bearer ${config.wikiApiKey}`,
2071
2701
  "Content-Type": "application/json"
@@ -2077,7 +2707,7 @@ async function wikiRequest(config, path5, method = "GET", body) {
2077
2707
  signal: AbortSignal.timeout(3e4)
2078
2708
  });
2079
2709
  if (!response.ok) {
2080
- throw new Error(`Wiki API ${method} ${path5}: ${response.status} ${response.statusText}`);
2710
+ throw new Error(`Wiki API ${method} ${path6}: ${response.status} ${response.statusText}`);
2081
2711
  }
2082
2712
  return response.json();
2083
2713
  }