@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
@@ -279,7 +279,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
279
279
  return [];
280
280
  }
281
281
  }
282
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
282
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
283
283
  var init_employees = __esm({
284
284
  "src/lib/employees.ts"() {
285
285
  "use strict";
@@ -287,12 +287,609 @@ var init_employees = __esm({
287
287
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
288
288
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
289
289
  COORDINATOR_ROLE = "COO";
290
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
291
+ }
292
+ });
293
+
294
+ // src/lib/database-adapter.ts
295
+ import os3 from "os";
296
+ import path3 from "path";
297
+ import { createRequire } from "module";
298
+ import { pathToFileURL } from "url";
299
+ function quotedIdentifier(identifier) {
300
+ return `"${identifier.replace(/"/g, '""')}"`;
301
+ }
302
+ function unqualifiedTableName(name) {
303
+ const raw = name.trim().replace(/^"|"$/g, "");
304
+ const parts = raw.split(".");
305
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
306
+ }
307
+ function stripTrailingSemicolon(sql) {
308
+ return sql.trim().replace(/;+\s*$/u, "");
309
+ }
310
+ function appendClause(sql, clause) {
311
+ const trimmed = stripTrailingSemicolon(sql);
312
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
313
+ if (!returningMatch) {
314
+ return `${trimmed}${clause}`;
315
+ }
316
+ const idx = returningMatch.index;
317
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
318
+ }
319
+ function normalizeStatement(stmt) {
320
+ if (typeof stmt === "string") {
321
+ return { kind: "positional", sql: stmt, args: [] };
322
+ }
323
+ const sql = stmt.sql;
324
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
325
+ return { kind: "positional", sql, args: stmt.args ?? [] };
326
+ }
327
+ return { kind: "named", sql, args: stmt.args };
328
+ }
329
+ function rewriteBooleanLiterals(sql) {
330
+ let out = sql;
331
+ for (const column of BOOLEAN_COLUMN_NAMES) {
332
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
333
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
334
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
335
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
336
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
337
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
338
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
339
+ }
340
+ return out;
341
+ }
342
+ function rewriteInsertOrIgnore(sql) {
343
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
344
+ return sql;
345
+ }
346
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
347
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
348
+ }
349
+ function rewriteInsertOrReplace(sql) {
350
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
351
+ if (!match) {
352
+ return sql;
353
+ }
354
+ const rawTable = match[1];
355
+ const rawColumns = match[2];
356
+ const remainder = match[3];
357
+ const tableName = unqualifiedTableName(rawTable);
358
+ const conflictKeys = UPSERT_KEYS[tableName];
359
+ if (!conflictKeys?.length) {
360
+ return sql;
361
+ }
362
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
363
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
364
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
365
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
366
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
367
+ }
368
+ function rewriteSql(sql) {
369
+ let out = sql;
370
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
371
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
372
+ out = rewriteBooleanLiterals(out);
373
+ out = rewriteInsertOrReplace(out);
374
+ out = rewriteInsertOrIgnore(out);
375
+ return stripTrailingSemicolon(out);
376
+ }
377
+ function toBoolean(value) {
378
+ if (value === null || value === void 0) return value;
379
+ if (typeof value === "boolean") return value;
380
+ if (typeof value === "number") return value !== 0;
381
+ if (typeof value === "bigint") return value !== 0n;
382
+ if (typeof value === "string") {
383
+ const normalized = value.trim().toLowerCase();
384
+ if (normalized === "0" || normalized === "false") return false;
385
+ if (normalized === "1" || normalized === "true") return true;
386
+ }
387
+ return Boolean(value);
388
+ }
389
+ function countQuestionMarks(sql, end) {
390
+ let count = 0;
391
+ let inSingle = false;
392
+ let inDouble = false;
393
+ let inLineComment = false;
394
+ let inBlockComment = false;
395
+ for (let i = 0; i < end; i++) {
396
+ const ch = sql[i];
397
+ const next = sql[i + 1];
398
+ if (inLineComment) {
399
+ if (ch === "\n") inLineComment = false;
400
+ continue;
401
+ }
402
+ if (inBlockComment) {
403
+ if (ch === "*" && next === "/") {
404
+ inBlockComment = false;
405
+ i += 1;
406
+ }
407
+ continue;
408
+ }
409
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
410
+ inLineComment = true;
411
+ i += 1;
412
+ continue;
413
+ }
414
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
415
+ inBlockComment = true;
416
+ i += 1;
417
+ continue;
418
+ }
419
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
420
+ inSingle = !inSingle;
421
+ continue;
422
+ }
423
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
424
+ inDouble = !inDouble;
425
+ continue;
426
+ }
427
+ if (!inSingle && !inDouble && ch === "?") {
428
+ count += 1;
429
+ }
430
+ }
431
+ return count;
432
+ }
433
+ function findBooleanPlaceholderIndexes(sql) {
434
+ const indexes = /* @__PURE__ */ new Set();
435
+ for (const column of BOOLEAN_COLUMN_NAMES) {
436
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
437
+ for (const match of sql.matchAll(pattern)) {
438
+ const matchText = match[0];
439
+ const qIndex = match.index + matchText.lastIndexOf("?");
440
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
441
+ }
442
+ }
443
+ return indexes;
444
+ }
445
+ function coerceInsertBooleanArgs(sql, args) {
446
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
447
+ if (!match) return;
448
+ const rawTable = match[1];
449
+ const rawColumns = match[2];
450
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
451
+ if (!boolColumns?.size) return;
452
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
453
+ for (const [index, column] of columns.entries()) {
454
+ if (boolColumns.has(column) && index < args.length) {
455
+ args[index] = toBoolean(args[index]);
456
+ }
457
+ }
458
+ }
459
+ function coerceUpdateBooleanArgs(sql, args) {
460
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
461
+ if (!match) return;
462
+ const rawTable = match[1];
463
+ const setClause = match[2];
464
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
465
+ if (!boolColumns?.size) return;
466
+ const assignments = setClause.split(",");
467
+ let placeholderIndex = 0;
468
+ for (const assignment of assignments) {
469
+ if (!assignment.includes("?")) continue;
470
+ placeholderIndex += 1;
471
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
472
+ if (colMatch && boolColumns.has(colMatch[1])) {
473
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
474
+ }
475
+ }
476
+ }
477
+ function coerceBooleanArgs(sql, args) {
478
+ const nextArgs = [...args];
479
+ coerceInsertBooleanArgs(sql, nextArgs);
480
+ coerceUpdateBooleanArgs(sql, nextArgs);
481
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
482
+ for (const index of placeholderIndexes) {
483
+ if (index > 0 && index <= nextArgs.length) {
484
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
485
+ }
486
+ }
487
+ return nextArgs;
488
+ }
489
+ function convertQuestionMarksToDollarParams(sql) {
490
+ let out = "";
491
+ let placeholder = 0;
492
+ let inSingle = false;
493
+ let inDouble = false;
494
+ let inLineComment = false;
495
+ let inBlockComment = false;
496
+ for (let i = 0; i < sql.length; i++) {
497
+ const ch = sql[i];
498
+ const next = sql[i + 1];
499
+ if (inLineComment) {
500
+ out += ch;
501
+ if (ch === "\n") inLineComment = false;
502
+ continue;
503
+ }
504
+ if (inBlockComment) {
505
+ out += ch;
506
+ if (ch === "*" && next === "/") {
507
+ out += next;
508
+ inBlockComment = false;
509
+ i += 1;
510
+ }
511
+ continue;
512
+ }
513
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
514
+ out += ch + next;
515
+ inLineComment = true;
516
+ i += 1;
517
+ continue;
518
+ }
519
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
520
+ out += ch + next;
521
+ inBlockComment = true;
522
+ i += 1;
523
+ continue;
524
+ }
525
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
526
+ inSingle = !inSingle;
527
+ out += ch;
528
+ continue;
529
+ }
530
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
531
+ inDouble = !inDouble;
532
+ out += ch;
533
+ continue;
534
+ }
535
+ if (!inSingle && !inDouble && ch === "?") {
536
+ placeholder += 1;
537
+ out += `$${placeholder}`;
538
+ continue;
539
+ }
540
+ out += ch;
541
+ }
542
+ return out;
543
+ }
544
+ function translateStatementForPostgres(stmt) {
545
+ const normalized = normalizeStatement(stmt);
546
+ if (normalized.kind === "named") {
547
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
548
+ }
549
+ const rewrittenSql = rewriteSql(normalized.sql);
550
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
551
+ return {
552
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
553
+ args: coercedArgs
554
+ };
555
+ }
556
+ function shouldBypassPostgres(stmt) {
557
+ const normalized = normalizeStatement(stmt);
558
+ if (normalized.kind === "named") {
559
+ return true;
560
+ }
561
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
562
+ }
563
+ function shouldFallbackOnError(error) {
564
+ const message = error instanceof Error ? error.message : String(error);
565
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
566
+ }
567
+ function isReadQuery(sql) {
568
+ const trimmed = sql.trimStart();
569
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
570
+ }
571
+ function buildRow(row, columns) {
572
+ const values = columns.map((column) => row[column]);
573
+ return Object.assign(values, row);
574
+ }
575
+ function buildResultSet(rows, rowsAffected = 0) {
576
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
577
+ const resultRows = rows.map((row) => buildRow(row, columns));
578
+ return {
579
+ columns,
580
+ columnTypes: columns.map(() => ""),
581
+ rows: resultRows,
582
+ rowsAffected,
583
+ lastInsertRowid: void 0,
584
+ toJSON() {
585
+ return {
586
+ columns,
587
+ columnTypes: columns.map(() => ""),
588
+ rows,
589
+ rowsAffected,
590
+ lastInsertRowid: void 0
591
+ };
592
+ }
593
+ };
594
+ }
595
+ async function loadPrismaClient() {
596
+ if (!prismaClientPromise) {
597
+ prismaClientPromise = (async () => {
598
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
599
+ if (explicitPath) {
600
+ const module2 = await import(pathToFileURL(explicitPath).href);
601
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
602
+ if (!PrismaClient2) {
603
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
604
+ }
605
+ return new PrismaClient2();
606
+ }
607
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
608
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
609
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
610
+ const module = await import(pathToFileURL(prismaEntry).href);
611
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
612
+ if (!PrismaClient) {
613
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
614
+ }
615
+ return new PrismaClient();
616
+ })();
617
+ }
618
+ return prismaClientPromise;
619
+ }
620
+ async function ensureCompatibilityViews(prisma) {
621
+ if (!compatibilityBootstrapPromise) {
622
+ compatibilityBootstrapPromise = (async () => {
623
+ for (const mapping of VIEW_MAPPINGS) {
624
+ const relation = mapping.source.replace(/"/g, "");
625
+ const rows = await prisma.$queryRawUnsafe(
626
+ "SELECT to_regclass($1) AS regclass",
627
+ relation
628
+ );
629
+ if (!rows[0]?.regclass) {
630
+ continue;
631
+ }
632
+ await prisma.$executeRawUnsafe(
633
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
634
+ );
635
+ }
636
+ })();
637
+ }
638
+ return compatibilityBootstrapPromise;
639
+ }
640
+ async function executeOnPrisma(executor, stmt) {
641
+ const translated = translateStatementForPostgres(stmt);
642
+ if (isReadQuery(translated.sql)) {
643
+ const rows = await executor.$queryRawUnsafe(
644
+ translated.sql,
645
+ ...translated.args
646
+ );
647
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
648
+ }
649
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
650
+ return buildResultSet([], rowsAffected);
651
+ }
652
+ function splitSqlStatements(sql) {
653
+ const parts = [];
654
+ let current = "";
655
+ let inSingle = false;
656
+ let inDouble = false;
657
+ let inLineComment = false;
658
+ let inBlockComment = false;
659
+ for (let i = 0; i < sql.length; i++) {
660
+ const ch = sql[i];
661
+ const next = sql[i + 1];
662
+ if (inLineComment) {
663
+ current += ch;
664
+ if (ch === "\n") inLineComment = false;
665
+ continue;
666
+ }
667
+ if (inBlockComment) {
668
+ current += ch;
669
+ if (ch === "*" && next === "/") {
670
+ current += next;
671
+ inBlockComment = false;
672
+ i += 1;
673
+ }
674
+ continue;
675
+ }
676
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
677
+ current += ch + next;
678
+ inLineComment = true;
679
+ i += 1;
680
+ continue;
681
+ }
682
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
683
+ current += ch + next;
684
+ inBlockComment = true;
685
+ i += 1;
686
+ continue;
687
+ }
688
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
689
+ inSingle = !inSingle;
690
+ current += ch;
691
+ continue;
692
+ }
693
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
694
+ inDouble = !inDouble;
695
+ current += ch;
696
+ continue;
697
+ }
698
+ if (!inSingle && !inDouble && ch === ";") {
699
+ if (current.trim()) {
700
+ parts.push(current.trim());
701
+ }
702
+ current = "";
703
+ continue;
704
+ }
705
+ current += ch;
706
+ }
707
+ if (current.trim()) {
708
+ parts.push(current.trim());
709
+ }
710
+ return parts;
711
+ }
712
+ async function createPrismaDbAdapter(fallbackClient) {
713
+ const prisma = await loadPrismaClient();
714
+ await ensureCompatibilityViews(prisma);
715
+ let closed = false;
716
+ let adapter;
717
+ const fallbackExecute = async (stmt, error) => {
718
+ if (!fallbackClient) {
719
+ if (error) throw error;
720
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
721
+ }
722
+ if (error) {
723
+ process.stderr.write(
724
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
725
+ `
726
+ );
727
+ }
728
+ return fallbackClient.execute(stmt);
729
+ };
730
+ adapter = {
731
+ async execute(stmt) {
732
+ if (shouldBypassPostgres(stmt)) {
733
+ return fallbackExecute(stmt);
734
+ }
735
+ try {
736
+ return await executeOnPrisma(prisma, stmt);
737
+ } catch (error) {
738
+ if (shouldFallbackOnError(error)) {
739
+ return fallbackExecute(stmt, error);
740
+ }
741
+ throw error;
742
+ }
743
+ },
744
+ async batch(stmts, mode) {
745
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
746
+ if (!fallbackClient) {
747
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
748
+ }
749
+ return fallbackClient.batch(stmts, mode);
750
+ }
751
+ try {
752
+ if (prisma.$transaction) {
753
+ return await prisma.$transaction(async (tx) => {
754
+ const results2 = [];
755
+ for (const stmt of stmts) {
756
+ results2.push(await executeOnPrisma(tx, stmt));
757
+ }
758
+ return results2;
759
+ });
760
+ }
761
+ const results = [];
762
+ for (const stmt of stmts) {
763
+ results.push(await executeOnPrisma(prisma, stmt));
764
+ }
765
+ return results;
766
+ } catch (error) {
767
+ if (fallbackClient && shouldFallbackOnError(error)) {
768
+ process.stderr.write(
769
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
770
+ `
771
+ );
772
+ return fallbackClient.batch(stmts, mode);
773
+ }
774
+ throw error;
775
+ }
776
+ },
777
+ async migrate(stmts) {
778
+ if (fallbackClient) {
779
+ return fallbackClient.migrate(stmts);
780
+ }
781
+ return adapter.batch(stmts, "deferred");
782
+ },
783
+ async transaction(mode) {
784
+ if (!fallbackClient) {
785
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
786
+ }
787
+ return fallbackClient.transaction(mode);
788
+ },
789
+ async executeMultiple(sql) {
790
+ if (fallbackClient && shouldBypassPostgres(sql)) {
791
+ return fallbackClient.executeMultiple(sql);
792
+ }
793
+ for (const statement of splitSqlStatements(sql)) {
794
+ await adapter.execute(statement);
795
+ }
796
+ },
797
+ async sync() {
798
+ if (fallbackClient) {
799
+ return fallbackClient.sync();
800
+ }
801
+ return { frame_no: 0, frames_synced: 0 };
802
+ },
803
+ close() {
804
+ closed = true;
805
+ prismaClientPromise = null;
806
+ compatibilityBootstrapPromise = null;
807
+ void prisma.$disconnect?.();
808
+ },
809
+ get closed() {
810
+ return closed;
811
+ },
812
+ get protocol() {
813
+ return "prisma-postgres";
814
+ }
815
+ };
816
+ return adapter;
817
+ }
818
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
819
+ var init_database_adapter = __esm({
820
+ "src/lib/database-adapter.ts"() {
821
+ "use strict";
822
+ VIEW_MAPPINGS = [
823
+ { view: "memories", source: "memory.memory_records" },
824
+ { view: "tasks", source: "memory.tasks" },
825
+ { view: "behaviors", source: "memory.behaviors" },
826
+ { view: "entities", source: "memory.entities" },
827
+ { view: "relationships", source: "memory.relationships" },
828
+ { view: "entity_memories", source: "memory.entity_memories" },
829
+ { view: "entity_aliases", source: "memory.entity_aliases" },
830
+ { view: "notifications", source: "memory.notifications" },
831
+ { view: "messages", source: "memory.messages" },
832
+ { view: "users", source: "wiki.users" },
833
+ { view: "workspaces", source: "wiki.workspaces" },
834
+ { view: "workspace_users", source: "wiki.workspace_users" },
835
+ { view: "documents", source: "wiki.workspace_documents" },
836
+ { view: "chats", source: "wiki.workspace_chats" }
837
+ ];
838
+ UPSERT_KEYS = {
839
+ memories: ["id"],
840
+ tasks: ["id"],
841
+ behaviors: ["id"],
842
+ entities: ["id"],
843
+ relationships: ["id"],
844
+ entity_aliases: ["alias"],
845
+ notifications: ["id"],
846
+ messages: ["id"],
847
+ users: ["id"],
848
+ workspaces: ["id"],
849
+ workspace_users: ["id"],
850
+ documents: ["id"],
851
+ chats: ["id"]
852
+ };
853
+ BOOLEAN_COLUMNS_BY_TABLE = {
854
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
855
+ behaviors: /* @__PURE__ */ new Set(["active"]),
856
+ notifications: /* @__PURE__ */ new Set(["read"]),
857
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
858
+ };
859
+ BOOLEAN_COLUMN_NAMES = new Set(
860
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
861
+ );
862
+ IMMEDIATE_FALLBACK_PATTERNS = [
863
+ /\bPRAGMA\b/i,
864
+ /\bsqlite_master\b/i,
865
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
866
+ /\bMATCH\b/i,
867
+ /\bvector_distance_cos\s*\(/i,
868
+ /\bjson_extract\s*\(/i,
869
+ /\bjulianday\s*\(/i,
870
+ /\bstrftime\s*\(/i,
871
+ /\blast_insert_rowid\s*\(/i
872
+ ];
873
+ prismaClientPromise = null;
874
+ compatibilityBootstrapPromise = null;
290
875
  }
291
876
  });
292
877
 
293
878
  // src/lib/database.ts
294
879
  import { createClient } from "@libsql/client";
295
880
  async function initDatabase(config) {
881
+ if (_walCheckpointTimer) {
882
+ clearInterval(_walCheckpointTimer);
883
+ _walCheckpointTimer = null;
884
+ }
885
+ if (_daemonClient) {
886
+ _daemonClient.close();
887
+ _daemonClient = null;
888
+ }
889
+ if (_adapterClient && _adapterClient !== _resilientClient) {
890
+ _adapterClient.close();
891
+ }
892
+ _adapterClient = null;
296
893
  if (_client) {
297
894
  _client.close();
298
895
  _client = null;
@@ -306,6 +903,7 @@ async function initDatabase(config) {
306
903
  }
307
904
  _client = createClient(opts);
308
905
  _resilientClient = wrapWithRetry(_client);
906
+ _adapterClient = _resilientClient;
309
907
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
310
908
  });
311
909
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -316,11 +914,17 @@ async function initDatabase(config) {
316
914
  });
317
915
  }, 3e4);
318
916
  _walCheckpointTimer.unref();
917
+ if (process.env.DATABASE_URL) {
918
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
919
+ }
319
920
  }
320
921
  function getClient() {
321
- if (!_resilientClient) {
922
+ if (!_adapterClient) {
322
923
  throw new Error("Database client not initialized. Call initDatabase() first.");
323
924
  }
925
+ if (process.env.DATABASE_URL) {
926
+ return _adapterClient;
927
+ }
324
928
  if (process.env.EXE_IS_DAEMON === "1") {
325
929
  return _resilientClient;
326
930
  }
@@ -1260,16 +1864,18 @@ async function ensureSchema() {
1260
1864
  }
1261
1865
  }
1262
1866
  }
1263
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1867
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1264
1868
  var init_database = __esm({
1265
1869
  "src/lib/database.ts"() {
1266
1870
  "use strict";
1267
1871
  init_db_retry();
1268
1872
  init_employees();
1873
+ init_database_adapter();
1269
1874
  _client = null;
1270
1875
  _resilientClient = null;
1271
1876
  _walCheckpointTimer = null;
1272
1877
  _daemonClient = null;
1878
+ _adapterClient = null;
1273
1879
  initTurso = initDatabase;
1274
1880
  }
1275
1881
  });
@@ -1287,7 +1893,7 @@ __export(shard_manager_exports, {
1287
1893
  listShards: () => listShards,
1288
1894
  shardExists: () => shardExists
1289
1895
  });
1290
- import path4 from "path";
1896
+ import path5 from "path";
1291
1897
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1292
1898
  import { createClient as createClient2 } from "@libsql/client";
1293
1899
  function initShardManager(encryptionKey) {
@@ -1313,7 +1919,7 @@ function getShardClient(projectName) {
1313
1919
  }
1314
1920
  const cached = _shards.get(safeName);
1315
1921
  if (cached) return cached;
1316
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1922
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1317
1923
  const client = createClient2({
1318
1924
  url: `file:${dbPath}`,
1319
1925
  encryptionKey: _encryptionKey
@@ -1323,7 +1929,7 @@ function getShardClient(projectName) {
1323
1929
  }
1324
1930
  function shardExists(projectName) {
1325
1931
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1326
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1932
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1327
1933
  }
1328
1934
  function listShards() {
1329
1935
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1400,7 +2006,23 @@ async function ensureShardSchema(client) {
1400
2006
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1401
2007
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1402
2008
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1403
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2009
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2010
+ // Metadata enrichment columns (must match database.ts)
2011
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2012
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2013
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2014
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2015
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2016
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2017
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2018
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2019
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2020
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2021
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2022
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2023
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2024
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2025
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1404
2026
  ]) {
1405
2027
  try {
1406
2028
  await client.execute(col);
@@ -1512,7 +2134,7 @@ var init_shard_manager = __esm({
1512
2134
  "src/lib/shard-manager.ts"() {
1513
2135
  "use strict";
1514
2136
  init_config();
1515
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2137
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1516
2138
  _shards = /* @__PURE__ */ new Map();
1517
2139
  _encryptionKey = null;
1518
2140
  _shardingEnabled = false;
@@ -1717,12 +2339,12 @@ __export(worker_gate_exports, {
1717
2339
  tryAcquireWorkerSlot: () => tryAcquireWorkerSlot
1718
2340
  });
1719
2341
  import { readdirSync as readdirSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2, mkdirSync as mkdirSync2, existsSync as existsSync5 } from "fs";
1720
- import path5 from "path";
2342
+ import path6 from "path";
1721
2343
  function tryAcquireWorkerSlot() {
1722
2344
  try {
1723
2345
  mkdirSync2(WORKER_PID_DIR, { recursive: true });
1724
2346
  const reservationId = `res-${process.pid}-${Date.now()}`;
1725
- const reservationPath = path5.join(WORKER_PID_DIR, `${reservationId}.pid`);
2347
+ const reservationPath = path6.join(WORKER_PID_DIR, `${reservationId}.pid`);
1726
2348
  writeFileSync2(reservationPath, String(process.pid));
1727
2349
  const files = readdirSync2(WORKER_PID_DIR);
1728
2350
  let alive = 0;
@@ -1740,7 +2362,7 @@ function tryAcquireWorkerSlot() {
1740
2362
  alive++;
1741
2363
  } catch {
1742
2364
  try {
1743
- unlinkSync2(path5.join(WORKER_PID_DIR, f));
2365
+ unlinkSync2(path6.join(WORKER_PID_DIR, f));
1744
2366
  } catch {
1745
2367
  }
1746
2368
  }
@@ -1764,13 +2386,13 @@ function tryAcquireWorkerSlot() {
1764
2386
  function registerWorkerPid(pid) {
1765
2387
  try {
1766
2388
  mkdirSync2(WORKER_PID_DIR, { recursive: true });
1767
- writeFileSync2(path5.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
2389
+ writeFileSync2(path6.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
1768
2390
  } catch {
1769
2391
  }
1770
2392
  }
1771
2393
  function cleanupWorkerPid() {
1772
2394
  try {
1773
- unlinkSync2(path5.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
2395
+ unlinkSync2(path6.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
1774
2396
  } catch {
1775
2397
  }
1776
2398
  }
@@ -1810,14 +2432,14 @@ var init_worker_gate = __esm({
1810
2432
  "src/lib/worker-gate.ts"() {
1811
2433
  "use strict";
1812
2434
  init_config();
1813
- WORKER_PID_DIR = path5.join(EXE_AI_DIR, "worker-pids");
2435
+ WORKER_PID_DIR = path6.join(EXE_AI_DIR, "worker-pids");
1814
2436
  MAX_CONCURRENT_WORKERS = 3;
1815
- BACKFILL_LOCK = path5.join(WORKER_PID_DIR, "backfill.lock");
2437
+ BACKFILL_LOCK = path6.join(WORKER_PID_DIR, "backfill.lock");
1816
2438
  }
1817
2439
  });
1818
2440
 
1819
2441
  // src/bin/exe-doctor.ts
1820
- import os4 from "os";
2442
+ import os5 from "os";
1821
2443
 
1822
2444
  // src/lib/store.ts
1823
2445
  import { createHash } from "crypto";
@@ -1826,15 +2448,15 @@ init_database();
1826
2448
  // src/lib/keychain.ts
1827
2449
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1828
2450
  import { existsSync as existsSync3 } from "fs";
1829
- import path3 from "path";
1830
- import os3 from "os";
2451
+ import path4 from "path";
2452
+ import os4 from "os";
1831
2453
  var SERVICE = "exe-mem";
1832
2454
  var ACCOUNT = "master-key";
1833
2455
  function getKeyDir() {
1834
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2456
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
1835
2457
  }
1836
2458
  function getKeyPath() {
1837
- return path3.join(getKeyDir(), "master.key");
2459
+ return path4.join(getKeyDir(), "master.key");
1838
2460
  }
1839
2461
  async function tryKeytar() {
1840
2462
  try {
@@ -1857,7 +2479,7 @@ async function getMasterKey() {
1857
2479
  const keyPath = getKeyPath();
1858
2480
  if (!existsSync3(keyPath)) {
1859
2481
  process.stderr.write(
1860
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2482
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
1861
2483
  `
1862
2484
  );
1863
2485
  return null;
@@ -2027,7 +2649,7 @@ function isMainModule(importMetaUrl) {
2027
2649
  // src/bin/exe-doctor.ts
2028
2650
  import { existsSync as existsSync6, readFileSync as readFileSync3 } from "fs";
2029
2651
  import { spawn } from "child_process";
2030
- import path6 from "path";
2652
+ import path7 from "path";
2031
2653
  import { randomUUID as randomUUID2 } from "crypto";
2032
2654
 
2033
2655
  // src/lib/conflict-detector.ts
@@ -2430,7 +3052,7 @@ async function auditOrphanedProjects(client) {
2430
3052
  for (const row of result.rows) {
2431
3053
  const name = row.project_name;
2432
3054
  const count = Number(row.cnt);
2433
- const exists = existsSync6(path6.join(home, name)) || existsSync6(path6.join(home, "..", name)) || existsSync6(path6.join(process.cwd(), "..", name));
3055
+ const exists = existsSync6(path7.join(home, name)) || existsSync6(path7.join(home, "..", name)) || existsSync6(path7.join(process.cwd(), "..", name));
2434
3056
  if (!exists) {
2435
3057
  orphans.push({ project_name: name, count });
2436
3058
  }
@@ -2438,7 +3060,7 @@ async function auditOrphanedProjects(client) {
2438
3060
  return orphans;
2439
3061
  }
2440
3062
  function auditHookHealth() {
2441
- const logPath = path6.join(
3063
+ const logPath = path7.join(
2442
3064
  process.env.HOME ?? process.env.USERPROFILE ?? "",
2443
3065
  ".exe-os",
2444
3066
  "logs",
@@ -2524,7 +3146,7 @@ function formatReport(report, flags) {
2524
3146
  }
2525
3147
  lines.push("");
2526
3148
  }
2527
- const totalMemGB = os4.totalmem() / (1024 * 1024 * 1024);
3149
+ const totalMemGB = os5.totalmem() / (1024 * 1024 * 1024);
2528
3150
  const isLowMemSystem = totalMemGB <= 8;
2529
3151
  if (isLowMemSystem && report.nullVectors > 0) {
2530
3152
  lines.push(`\u{1F7E2} Null vectors: ${fmtNum(report.nullVectors)} / ${fmtNum(s.total)} (expected \u2014 8GB system, keyword search mode)`);
@@ -2646,7 +3268,7 @@ async function fixNullVectors() {
2646
3268
  }
2647
3269
  }
2648
3270
  const npmRoot = (await import("child_process")).execSync("npm root -g", { encoding: "utf8" }).trim();
2649
- const backfillPath = path6.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
3271
+ const backfillPath = path7.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
2650
3272
  return new Promise((resolve, reject) => {
2651
3273
  const child = spawn("node", [backfillPath], { stdio: "inherit" });
2652
3274
  if (child.pid) registerWorkerPid2(child.pid);