@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
@@ -299,7 +299,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
299
299
  function getEmployee(employees, name) {
300
300
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
301
301
  }
302
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
302
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
303
303
  var init_employees = __esm({
304
304
  "src/lib/employees.ts"() {
305
305
  "use strict";
@@ -307,6 +307,7 @@ var init_employees = __esm({
307
307
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
308
308
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
309
309
  COORDINATOR_ROLE = "COO";
310
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
310
311
  }
311
312
  });
312
313
 
@@ -570,13 +571,597 @@ var init_db_retry = __esm({
570
571
  }
571
572
  });
572
573
 
574
+ // src/lib/database-adapter.ts
575
+ import os5 from "os";
576
+ import path7 from "path";
577
+ import { createRequire } from "module";
578
+ import { pathToFileURL } from "url";
579
+ function quotedIdentifier(identifier) {
580
+ return `"${identifier.replace(/"/g, '""')}"`;
581
+ }
582
+ function unqualifiedTableName(name) {
583
+ const raw = name.trim().replace(/^"|"$/g, "");
584
+ const parts = raw.split(".");
585
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
586
+ }
587
+ function stripTrailingSemicolon(sql) {
588
+ return sql.trim().replace(/;+\s*$/u, "");
589
+ }
590
+ function appendClause(sql, clause) {
591
+ const trimmed = stripTrailingSemicolon(sql);
592
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
593
+ if (!returningMatch) {
594
+ return `${trimmed}${clause}`;
595
+ }
596
+ const idx = returningMatch.index;
597
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
598
+ }
599
+ function normalizeStatement(stmt) {
600
+ if (typeof stmt === "string") {
601
+ return { kind: "positional", sql: stmt, args: [] };
602
+ }
603
+ const sql = stmt.sql;
604
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
605
+ return { kind: "positional", sql, args: stmt.args ?? [] };
606
+ }
607
+ return { kind: "named", sql, args: stmt.args };
608
+ }
609
+ function rewriteBooleanLiterals(sql) {
610
+ let out = sql;
611
+ for (const column of BOOLEAN_COLUMN_NAMES) {
612
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
613
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
614
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
615
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
616
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
617
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
618
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
619
+ }
620
+ return out;
621
+ }
622
+ function rewriteInsertOrIgnore(sql) {
623
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
624
+ return sql;
625
+ }
626
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
627
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
628
+ }
629
+ function rewriteInsertOrReplace(sql) {
630
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
631
+ if (!match) {
632
+ return sql;
633
+ }
634
+ const rawTable = match[1];
635
+ const rawColumns = match[2];
636
+ const remainder = match[3];
637
+ const tableName = unqualifiedTableName(rawTable);
638
+ const conflictKeys = UPSERT_KEYS[tableName];
639
+ if (!conflictKeys?.length) {
640
+ return sql;
641
+ }
642
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
643
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
644
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
645
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
646
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
647
+ }
648
+ function rewriteSql(sql) {
649
+ let out = sql;
650
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
651
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
652
+ out = rewriteBooleanLiterals(out);
653
+ out = rewriteInsertOrReplace(out);
654
+ out = rewriteInsertOrIgnore(out);
655
+ return stripTrailingSemicolon(out);
656
+ }
657
+ function toBoolean(value) {
658
+ if (value === null || value === void 0) return value;
659
+ if (typeof value === "boolean") return value;
660
+ if (typeof value === "number") return value !== 0;
661
+ if (typeof value === "bigint") return value !== 0n;
662
+ if (typeof value === "string") {
663
+ const normalized = value.trim().toLowerCase();
664
+ if (normalized === "0" || normalized === "false") return false;
665
+ if (normalized === "1" || normalized === "true") return true;
666
+ }
667
+ return Boolean(value);
668
+ }
669
+ function countQuestionMarks(sql, end) {
670
+ let count = 0;
671
+ let inSingle = false;
672
+ let inDouble = false;
673
+ let inLineComment = false;
674
+ let inBlockComment = false;
675
+ for (let i = 0; i < end; i++) {
676
+ const ch = sql[i];
677
+ const next = sql[i + 1];
678
+ if (inLineComment) {
679
+ if (ch === "\n") inLineComment = false;
680
+ continue;
681
+ }
682
+ if (inBlockComment) {
683
+ if (ch === "*" && next === "/") {
684
+ inBlockComment = false;
685
+ i += 1;
686
+ }
687
+ continue;
688
+ }
689
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
690
+ inLineComment = true;
691
+ i += 1;
692
+ continue;
693
+ }
694
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
695
+ inBlockComment = true;
696
+ i += 1;
697
+ continue;
698
+ }
699
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
700
+ inSingle = !inSingle;
701
+ continue;
702
+ }
703
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
704
+ inDouble = !inDouble;
705
+ continue;
706
+ }
707
+ if (!inSingle && !inDouble && ch === "?") {
708
+ count += 1;
709
+ }
710
+ }
711
+ return count;
712
+ }
713
+ function findBooleanPlaceholderIndexes(sql) {
714
+ const indexes = /* @__PURE__ */ new Set();
715
+ for (const column of BOOLEAN_COLUMN_NAMES) {
716
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
717
+ for (const match of sql.matchAll(pattern)) {
718
+ const matchText = match[0];
719
+ const qIndex = match.index + matchText.lastIndexOf("?");
720
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
721
+ }
722
+ }
723
+ return indexes;
724
+ }
725
+ function coerceInsertBooleanArgs(sql, args) {
726
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
727
+ if (!match) return;
728
+ const rawTable = match[1];
729
+ const rawColumns = match[2];
730
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
731
+ if (!boolColumns?.size) return;
732
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
733
+ for (const [index, column] of columns.entries()) {
734
+ if (boolColumns.has(column) && index < args.length) {
735
+ args[index] = toBoolean(args[index]);
736
+ }
737
+ }
738
+ }
739
+ function coerceUpdateBooleanArgs(sql, args) {
740
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
741
+ if (!match) return;
742
+ const rawTable = match[1];
743
+ const setClause = match[2];
744
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
745
+ if (!boolColumns?.size) return;
746
+ const assignments = setClause.split(",");
747
+ let placeholderIndex = 0;
748
+ for (const assignment of assignments) {
749
+ if (!assignment.includes("?")) continue;
750
+ placeholderIndex += 1;
751
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
752
+ if (colMatch && boolColumns.has(colMatch[1])) {
753
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
754
+ }
755
+ }
756
+ }
757
+ function coerceBooleanArgs(sql, args) {
758
+ const nextArgs = [...args];
759
+ coerceInsertBooleanArgs(sql, nextArgs);
760
+ coerceUpdateBooleanArgs(sql, nextArgs);
761
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
762
+ for (const index of placeholderIndexes) {
763
+ if (index > 0 && index <= nextArgs.length) {
764
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
765
+ }
766
+ }
767
+ return nextArgs;
768
+ }
769
+ function convertQuestionMarksToDollarParams(sql) {
770
+ let out = "";
771
+ let placeholder = 0;
772
+ let inSingle = false;
773
+ let inDouble = false;
774
+ let inLineComment = false;
775
+ let inBlockComment = false;
776
+ for (let i = 0; i < sql.length; i++) {
777
+ const ch = sql[i];
778
+ const next = sql[i + 1];
779
+ if (inLineComment) {
780
+ out += ch;
781
+ if (ch === "\n") inLineComment = false;
782
+ continue;
783
+ }
784
+ if (inBlockComment) {
785
+ out += ch;
786
+ if (ch === "*" && next === "/") {
787
+ out += next;
788
+ inBlockComment = false;
789
+ i += 1;
790
+ }
791
+ continue;
792
+ }
793
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
794
+ out += ch + next;
795
+ inLineComment = true;
796
+ i += 1;
797
+ continue;
798
+ }
799
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
800
+ out += ch + next;
801
+ inBlockComment = true;
802
+ i += 1;
803
+ continue;
804
+ }
805
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
806
+ inSingle = !inSingle;
807
+ out += ch;
808
+ continue;
809
+ }
810
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
811
+ inDouble = !inDouble;
812
+ out += ch;
813
+ continue;
814
+ }
815
+ if (!inSingle && !inDouble && ch === "?") {
816
+ placeholder += 1;
817
+ out += `$${placeholder}`;
818
+ continue;
819
+ }
820
+ out += ch;
821
+ }
822
+ return out;
823
+ }
824
+ function translateStatementForPostgres(stmt) {
825
+ const normalized = normalizeStatement(stmt);
826
+ if (normalized.kind === "named") {
827
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
828
+ }
829
+ const rewrittenSql = rewriteSql(normalized.sql);
830
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
831
+ return {
832
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
833
+ args: coercedArgs
834
+ };
835
+ }
836
+ function shouldBypassPostgres(stmt) {
837
+ const normalized = normalizeStatement(stmt);
838
+ if (normalized.kind === "named") {
839
+ return true;
840
+ }
841
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
842
+ }
843
+ function shouldFallbackOnError(error) {
844
+ const message = error instanceof Error ? error.message : String(error);
845
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
846
+ }
847
+ function isReadQuery(sql) {
848
+ const trimmed = sql.trimStart();
849
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
850
+ }
851
+ function buildRow(row, columns) {
852
+ const values = columns.map((column) => row[column]);
853
+ return Object.assign(values, row);
854
+ }
855
+ function buildResultSet(rows, rowsAffected = 0) {
856
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
857
+ const resultRows = rows.map((row) => buildRow(row, columns));
858
+ return {
859
+ columns,
860
+ columnTypes: columns.map(() => ""),
861
+ rows: resultRows,
862
+ rowsAffected,
863
+ lastInsertRowid: void 0,
864
+ toJSON() {
865
+ return {
866
+ columns,
867
+ columnTypes: columns.map(() => ""),
868
+ rows,
869
+ rowsAffected,
870
+ lastInsertRowid: void 0
871
+ };
872
+ }
873
+ };
874
+ }
875
+ async function loadPrismaClient() {
876
+ if (!prismaClientPromise) {
877
+ prismaClientPromise = (async () => {
878
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
879
+ if (explicitPath) {
880
+ const module2 = await import(pathToFileURL(explicitPath).href);
881
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
882
+ if (!PrismaClient2) {
883
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
884
+ }
885
+ return new PrismaClient2();
886
+ }
887
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path7.join(os5.homedir(), "exe-db");
888
+ const requireFromExeDb = createRequire(path7.join(exeDbRoot, "package.json"));
889
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
890
+ const module = await import(pathToFileURL(prismaEntry).href);
891
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
892
+ if (!PrismaClient) {
893
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
894
+ }
895
+ return new PrismaClient();
896
+ })();
897
+ }
898
+ return prismaClientPromise;
899
+ }
900
+ async function ensureCompatibilityViews(prisma) {
901
+ if (!compatibilityBootstrapPromise) {
902
+ compatibilityBootstrapPromise = (async () => {
903
+ for (const mapping of VIEW_MAPPINGS) {
904
+ const relation = mapping.source.replace(/"/g, "");
905
+ const rows = await prisma.$queryRawUnsafe(
906
+ "SELECT to_regclass($1) AS regclass",
907
+ relation
908
+ );
909
+ if (!rows[0]?.regclass) {
910
+ continue;
911
+ }
912
+ await prisma.$executeRawUnsafe(
913
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
914
+ );
915
+ }
916
+ })();
917
+ }
918
+ return compatibilityBootstrapPromise;
919
+ }
920
+ async function executeOnPrisma(executor, stmt) {
921
+ const translated = translateStatementForPostgres(stmt);
922
+ if (isReadQuery(translated.sql)) {
923
+ const rows = await executor.$queryRawUnsafe(
924
+ translated.sql,
925
+ ...translated.args
926
+ );
927
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
928
+ }
929
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
930
+ return buildResultSet([], rowsAffected);
931
+ }
932
+ function splitSqlStatements(sql) {
933
+ const parts = [];
934
+ let current = "";
935
+ let inSingle = false;
936
+ let inDouble = false;
937
+ let inLineComment = false;
938
+ let inBlockComment = false;
939
+ for (let i = 0; i < sql.length; i++) {
940
+ const ch = sql[i];
941
+ const next = sql[i + 1];
942
+ if (inLineComment) {
943
+ current += ch;
944
+ if (ch === "\n") inLineComment = false;
945
+ continue;
946
+ }
947
+ if (inBlockComment) {
948
+ current += ch;
949
+ if (ch === "*" && next === "/") {
950
+ current += next;
951
+ inBlockComment = false;
952
+ i += 1;
953
+ }
954
+ continue;
955
+ }
956
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
957
+ current += ch + next;
958
+ inLineComment = true;
959
+ i += 1;
960
+ continue;
961
+ }
962
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
963
+ current += ch + next;
964
+ inBlockComment = true;
965
+ i += 1;
966
+ continue;
967
+ }
968
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
969
+ inSingle = !inSingle;
970
+ current += ch;
971
+ continue;
972
+ }
973
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
974
+ inDouble = !inDouble;
975
+ current += ch;
976
+ continue;
977
+ }
978
+ if (!inSingle && !inDouble && ch === ";") {
979
+ if (current.trim()) {
980
+ parts.push(current.trim());
981
+ }
982
+ current = "";
983
+ continue;
984
+ }
985
+ current += ch;
986
+ }
987
+ if (current.trim()) {
988
+ parts.push(current.trim());
989
+ }
990
+ return parts;
991
+ }
992
+ async function createPrismaDbAdapter(fallbackClient) {
993
+ const prisma = await loadPrismaClient();
994
+ await ensureCompatibilityViews(prisma);
995
+ let closed = false;
996
+ let adapter;
997
+ const fallbackExecute = async (stmt, error) => {
998
+ if (!fallbackClient) {
999
+ if (error) throw error;
1000
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
1001
+ }
1002
+ if (error) {
1003
+ process.stderr.write(
1004
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
1005
+ `
1006
+ );
1007
+ }
1008
+ return fallbackClient.execute(stmt);
1009
+ };
1010
+ adapter = {
1011
+ async execute(stmt) {
1012
+ if (shouldBypassPostgres(stmt)) {
1013
+ return fallbackExecute(stmt);
1014
+ }
1015
+ try {
1016
+ return await executeOnPrisma(prisma, stmt);
1017
+ } catch (error) {
1018
+ if (shouldFallbackOnError(error)) {
1019
+ return fallbackExecute(stmt, error);
1020
+ }
1021
+ throw error;
1022
+ }
1023
+ },
1024
+ async batch(stmts, mode) {
1025
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
1026
+ if (!fallbackClient) {
1027
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
1028
+ }
1029
+ return fallbackClient.batch(stmts, mode);
1030
+ }
1031
+ try {
1032
+ if (prisma.$transaction) {
1033
+ return await prisma.$transaction(async (tx) => {
1034
+ const results2 = [];
1035
+ for (const stmt of stmts) {
1036
+ results2.push(await executeOnPrisma(tx, stmt));
1037
+ }
1038
+ return results2;
1039
+ });
1040
+ }
1041
+ const results = [];
1042
+ for (const stmt of stmts) {
1043
+ results.push(await executeOnPrisma(prisma, stmt));
1044
+ }
1045
+ return results;
1046
+ } catch (error) {
1047
+ if (fallbackClient && shouldFallbackOnError(error)) {
1048
+ process.stderr.write(
1049
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
1050
+ `
1051
+ );
1052
+ return fallbackClient.batch(stmts, mode);
1053
+ }
1054
+ throw error;
1055
+ }
1056
+ },
1057
+ async migrate(stmts) {
1058
+ if (fallbackClient) {
1059
+ return fallbackClient.migrate(stmts);
1060
+ }
1061
+ return adapter.batch(stmts, "deferred");
1062
+ },
1063
+ async transaction(mode) {
1064
+ if (!fallbackClient) {
1065
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
1066
+ }
1067
+ return fallbackClient.transaction(mode);
1068
+ },
1069
+ async executeMultiple(sql) {
1070
+ if (fallbackClient && shouldBypassPostgres(sql)) {
1071
+ return fallbackClient.executeMultiple(sql);
1072
+ }
1073
+ for (const statement of splitSqlStatements(sql)) {
1074
+ await adapter.execute(statement);
1075
+ }
1076
+ },
1077
+ async sync() {
1078
+ if (fallbackClient) {
1079
+ return fallbackClient.sync();
1080
+ }
1081
+ return { frame_no: 0, frames_synced: 0 };
1082
+ },
1083
+ close() {
1084
+ closed = true;
1085
+ prismaClientPromise = null;
1086
+ compatibilityBootstrapPromise = null;
1087
+ void prisma.$disconnect?.();
1088
+ },
1089
+ get closed() {
1090
+ return closed;
1091
+ },
1092
+ get protocol() {
1093
+ return "prisma-postgres";
1094
+ }
1095
+ };
1096
+ return adapter;
1097
+ }
1098
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
1099
+ var init_database_adapter = __esm({
1100
+ "src/lib/database-adapter.ts"() {
1101
+ "use strict";
1102
+ VIEW_MAPPINGS = [
1103
+ { view: "memories", source: "memory.memory_records" },
1104
+ { view: "tasks", source: "memory.tasks" },
1105
+ { view: "behaviors", source: "memory.behaviors" },
1106
+ { view: "entities", source: "memory.entities" },
1107
+ { view: "relationships", source: "memory.relationships" },
1108
+ { view: "entity_memories", source: "memory.entity_memories" },
1109
+ { view: "entity_aliases", source: "memory.entity_aliases" },
1110
+ { view: "notifications", source: "memory.notifications" },
1111
+ { view: "messages", source: "memory.messages" },
1112
+ { view: "users", source: "wiki.users" },
1113
+ { view: "workspaces", source: "wiki.workspaces" },
1114
+ { view: "workspace_users", source: "wiki.workspace_users" },
1115
+ { view: "documents", source: "wiki.workspace_documents" },
1116
+ { view: "chats", source: "wiki.workspace_chats" }
1117
+ ];
1118
+ UPSERT_KEYS = {
1119
+ memories: ["id"],
1120
+ tasks: ["id"],
1121
+ behaviors: ["id"],
1122
+ entities: ["id"],
1123
+ relationships: ["id"],
1124
+ entity_aliases: ["alias"],
1125
+ notifications: ["id"],
1126
+ messages: ["id"],
1127
+ users: ["id"],
1128
+ workspaces: ["id"],
1129
+ workspace_users: ["id"],
1130
+ documents: ["id"],
1131
+ chats: ["id"]
1132
+ };
1133
+ BOOLEAN_COLUMNS_BY_TABLE = {
1134
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
1135
+ behaviors: /* @__PURE__ */ new Set(["active"]),
1136
+ notifications: /* @__PURE__ */ new Set(["read"]),
1137
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
1138
+ };
1139
+ BOOLEAN_COLUMN_NAMES = new Set(
1140
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
1141
+ );
1142
+ IMMEDIATE_FALLBACK_PATTERNS = [
1143
+ /\bPRAGMA\b/i,
1144
+ /\bsqlite_master\b/i,
1145
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
1146
+ /\bMATCH\b/i,
1147
+ /\bvector_distance_cos\s*\(/i,
1148
+ /\bjson_extract\s*\(/i,
1149
+ /\bjulianday\s*\(/i,
1150
+ /\bstrftime\s*\(/i,
1151
+ /\blast_insert_rowid\s*\(/i
1152
+ ];
1153
+ prismaClientPromise = null;
1154
+ compatibilityBootstrapPromise = null;
1155
+ }
1156
+ });
1157
+
573
1158
  // src/lib/exe-daemon-client.ts
574
1159
  import net from "net";
575
- import os5 from "os";
1160
+ import os6 from "os";
576
1161
  import { spawn } from "child_process";
577
1162
  import { randomUUID } from "crypto";
578
1163
  import { existsSync as existsSync5, unlinkSync as unlinkSync3, readFileSync as readFileSync6, openSync, closeSync, statSync } from "fs";
579
- import path7 from "path";
1164
+ import path8 from "path";
580
1165
  import { fileURLToPath } from "url";
581
1166
  function handleData(chunk) {
582
1167
  _buffer += chunk.toString();
@@ -627,17 +1212,17 @@ function cleanupStaleFiles() {
627
1212
  }
628
1213
  }
629
1214
  function findPackageRoot() {
630
- let dir = path7.dirname(fileURLToPath(import.meta.url));
631
- const { root } = path7.parse(dir);
1215
+ let dir = path8.dirname(fileURLToPath(import.meta.url));
1216
+ const { root } = path8.parse(dir);
632
1217
  while (dir !== root) {
633
- if (existsSync5(path7.join(dir, "package.json"))) return dir;
634
- dir = path7.dirname(dir);
1218
+ if (existsSync5(path8.join(dir, "package.json"))) return dir;
1219
+ dir = path8.dirname(dir);
635
1220
  }
636
1221
  return null;
637
1222
  }
638
1223
  function spawnDaemon() {
639
- const freeGB = os5.freemem() / (1024 * 1024 * 1024);
640
- const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
1224
+ const freeGB = os6.freemem() / (1024 * 1024 * 1024);
1225
+ const totalGB = os6.totalmem() / (1024 * 1024 * 1024);
641
1226
  if (totalGB <= 8) {
642
1227
  process.stderr.write(
643
1228
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -657,7 +1242,7 @@ function spawnDaemon() {
657
1242
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
658
1243
  return;
659
1244
  }
660
- const daemonPath = path7.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1245
+ const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
661
1246
  if (!existsSync5(daemonPath)) {
662
1247
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
663
1248
  `);
@@ -666,7 +1251,7 @@ function spawnDaemon() {
666
1251
  const resolvedPath = daemonPath;
667
1252
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
668
1253
  `);
669
- const logPath = path7.join(path7.dirname(SOCKET_PATH), "exed.log");
1254
+ const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
670
1255
  let stderrFd = "ignore";
671
1256
  try {
672
1257
  stderrFd = openSync(logPath, "a");
@@ -813,9 +1398,9 @@ var init_exe_daemon_client = __esm({
813
1398
  "src/lib/exe-daemon-client.ts"() {
814
1399
  "use strict";
815
1400
  init_config();
816
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path7.join(EXE_AI_DIR, "exed.sock");
817
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path7.join(EXE_AI_DIR, "exed.pid");
818
- SPAWN_LOCK_PATH = path7.join(EXE_AI_DIR, "exed-spawn.lock");
1401
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
1402
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
1403
+ SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
819
1404
  SPAWN_LOCK_STALE_MS = 3e4;
820
1405
  CONNECT_TIMEOUT_MS = 15e3;
821
1406
  REQUEST_TIMEOUT_MS = 3e4;
@@ -897,7 +1482,7 @@ __export(db_daemon_client_exports, {
897
1482
  createDaemonDbClient: () => createDaemonDbClient,
898
1483
  initDaemonDbClient: () => initDaemonDbClient
899
1484
  });
900
- function normalizeStatement(stmt) {
1485
+ function normalizeStatement2(stmt) {
901
1486
  if (typeof stmt === "string") {
902
1487
  return { sql: stmt, args: [] };
903
1488
  }
@@ -921,7 +1506,7 @@ function createDaemonDbClient(fallbackClient) {
921
1506
  if (!_useDaemon || !isClientConnected()) {
922
1507
  return fallbackClient.execute(stmt);
923
1508
  }
924
- const { sql, args } = normalizeStatement(stmt);
1509
+ const { sql, args } = normalizeStatement2(stmt);
925
1510
  const response = await sendDaemonRequest({
926
1511
  type: "db-execute",
927
1512
  sql,
@@ -946,7 +1531,7 @@ function createDaemonDbClient(fallbackClient) {
946
1531
  if (!_useDaemon || !isClientConnected()) {
947
1532
  return fallbackClient.batch(stmts, mode);
948
1533
  }
949
- const statements = stmts.map(normalizeStatement);
1534
+ const statements = stmts.map(normalizeStatement2);
950
1535
  const response = await sendDaemonRequest({
951
1536
  type: "db-batch",
952
1537
  statements,
@@ -1041,6 +1626,18 @@ __export(database_exports, {
1041
1626
  });
1042
1627
  import { createClient } from "@libsql/client";
1043
1628
  async function initDatabase(config) {
1629
+ if (_walCheckpointTimer) {
1630
+ clearInterval(_walCheckpointTimer);
1631
+ _walCheckpointTimer = null;
1632
+ }
1633
+ if (_daemonClient) {
1634
+ _daemonClient.close();
1635
+ _daemonClient = null;
1636
+ }
1637
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1638
+ _adapterClient.close();
1639
+ }
1640
+ _adapterClient = null;
1044
1641
  if (_client) {
1045
1642
  _client.close();
1046
1643
  _client = null;
@@ -1054,6 +1651,7 @@ async function initDatabase(config) {
1054
1651
  }
1055
1652
  _client = createClient(opts);
1056
1653
  _resilientClient = wrapWithRetry(_client);
1654
+ _adapterClient = _resilientClient;
1057
1655
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1058
1656
  });
1059
1657
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -1064,14 +1662,20 @@ async function initDatabase(config) {
1064
1662
  });
1065
1663
  }, 3e4);
1066
1664
  _walCheckpointTimer.unref();
1665
+ if (process.env.DATABASE_URL) {
1666
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1667
+ }
1067
1668
  }
1068
1669
  function isInitialized() {
1069
- return _client !== null;
1670
+ return _adapterClient !== null || _client !== null;
1070
1671
  }
1071
1672
  function getClient() {
1072
- if (!_resilientClient) {
1673
+ if (!_adapterClient) {
1073
1674
  throw new Error("Database client not initialized. Call initDatabase() first.");
1074
1675
  }
1676
+ if (process.env.DATABASE_URL) {
1677
+ return _adapterClient;
1678
+ }
1075
1679
  if (process.env.EXE_IS_DAEMON === "1") {
1076
1680
  return _resilientClient;
1077
1681
  }
@@ -1081,6 +1685,7 @@ function getClient() {
1081
1685
  return _resilientClient;
1082
1686
  }
1083
1687
  async function initDaemonClient() {
1688
+ if (process.env.DATABASE_URL) return;
1084
1689
  if (process.env.EXE_IS_DAEMON === "1") return;
1085
1690
  if (!_resilientClient) return;
1086
1691
  try {
@@ -2025,26 +2630,36 @@ async function ensureSchema() {
2025
2630
  }
2026
2631
  }
2027
2632
  async function disposeDatabase() {
2633
+ if (_walCheckpointTimer) {
2634
+ clearInterval(_walCheckpointTimer);
2635
+ _walCheckpointTimer = null;
2636
+ }
2028
2637
  if (_daemonClient) {
2029
2638
  _daemonClient.close();
2030
2639
  _daemonClient = null;
2031
2640
  }
2641
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2642
+ _adapterClient.close();
2643
+ }
2644
+ _adapterClient = null;
2032
2645
  if (_client) {
2033
2646
  _client.close();
2034
2647
  _client = null;
2035
2648
  _resilientClient = null;
2036
2649
  }
2037
2650
  }
2038
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
2651
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2039
2652
  var init_database = __esm({
2040
2653
  "src/lib/database.ts"() {
2041
2654
  "use strict";
2042
2655
  init_db_retry();
2043
2656
  init_employees();
2657
+ init_database_adapter();
2044
2658
  _client = null;
2045
2659
  _resilientClient = null;
2046
2660
  _walCheckpointTimer = null;
2047
2661
  _daemonClient = null;
2662
+ _adapterClient = null;
2048
2663
  initTurso = initDatabase;
2049
2664
  disposeTurso = disposeDatabase;
2050
2665
  }
@@ -2053,22 +2668,22 @@ var init_database = __esm({
2053
2668
  // src/lib/license.ts
2054
2669
  import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync6, mkdirSync as mkdirSync4 } from "fs";
2055
2670
  import { randomUUID as randomUUID2 } from "crypto";
2056
- import path8 from "path";
2671
+ import path9 from "path";
2057
2672
  import { jwtVerify, importSPKI } from "jose";
2058
2673
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2059
2674
  var init_license = __esm({
2060
2675
  "src/lib/license.ts"() {
2061
2676
  "use strict";
2062
2677
  init_config();
2063
- LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
2064
- CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
2065
- DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
2678
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2679
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2680
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2066
2681
  }
2067
2682
  });
2068
2683
 
2069
2684
  // src/lib/plan-limits.ts
2070
2685
  import { readFileSync as readFileSync8, existsSync as existsSync7 } from "fs";
2071
- import path9 from "path";
2686
+ import path10 from "path";
2072
2687
  var CACHE_PATH2;
2073
2688
  var init_plan_limits = __esm({
2074
2689
  "src/lib/plan-limits.ts"() {
@@ -2077,14 +2692,14 @@ var init_plan_limits = __esm({
2077
2692
  init_employees();
2078
2693
  init_license();
2079
2694
  init_config();
2080
- CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2695
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2081
2696
  }
2082
2697
  });
2083
2698
 
2084
2699
  // src/lib/tmux-routing.ts
2085
2700
  import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync5, existsSync as existsSync8, appendFileSync, readdirSync as readdirSync2 } from "fs";
2086
- import path10 from "path";
2087
- import os6 from "os";
2701
+ import path11 from "path";
2702
+ import os7 from "os";
2088
2703
  import { fileURLToPath as fileURLToPath2 } from "url";
2089
2704
  function getMySession() {
2090
2705
  return getTransport().getMySession();
@@ -2097,7 +2712,7 @@ function extractRootExe(name) {
2097
2712
  }
2098
2713
  function getParentExe(sessionKey) {
2099
2714
  try {
2100
- const data = JSON.parse(readFileSync9(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2715
+ const data = JSON.parse(readFileSync9(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2101
2716
  return data.parentExe || null;
2102
2717
  } catch {
2103
2718
  return null;
@@ -2140,10 +2755,10 @@ var init_tmux_routing = __esm({
2140
2755
  init_intercom_queue();
2141
2756
  init_plan_limits();
2142
2757
  init_employees();
2143
- SPAWN_LOCK_DIR = path10.join(os6.homedir(), ".exe-os", "spawn-locks");
2144
- SESSION_CACHE = path10.join(os6.homedir(), ".exe-os", "session-cache");
2145
- INTERCOM_LOG2 = path10.join(os6.homedir(), ".exe-os", "intercom.log");
2146
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
2758
+ SPAWN_LOCK_DIR = path11.join(os7.homedir(), ".exe-os", "spawn-locks");
2759
+ SESSION_CACHE = path11.join(os7.homedir(), ".exe-os", "session-cache");
2760
+ INTERCOM_LOG2 = path11.join(os7.homedir(), ".exe-os", "intercom.log");
2761
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2147
2762
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2148
2763
  }
2149
2764
  });
@@ -2184,13 +2799,13 @@ var init_memory = __esm({
2184
2799
  // src/lib/keychain.ts
2185
2800
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2186
2801
  import { existsSync as existsSync9 } from "fs";
2187
- import path11 from "path";
2188
- import os7 from "os";
2802
+ import path12 from "path";
2803
+ import os8 from "os";
2189
2804
  function getKeyDir() {
2190
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path11.join(os7.homedir(), ".exe-os");
2805
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path12.join(os8.homedir(), ".exe-os");
2191
2806
  }
2192
2807
  function getKeyPath() {
2193
- return path11.join(getKeyDir(), "master.key");
2808
+ return path12.join(getKeyDir(), "master.key");
2194
2809
  }
2195
2810
  async function tryKeytar() {
2196
2811
  try {
@@ -2213,7 +2828,7 @@ async function getMasterKey() {
2213
2828
  const keyPath = getKeyPath();
2214
2829
  if (!existsSync9(keyPath)) {
2215
2830
  process.stderr.write(
2216
- `[keychain] Key not found at ${keyPath} (HOME=${os7.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2831
+ `[keychain] Key not found at ${keyPath} (HOME=${os8.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2217
2832
  `
2218
2833
  );
2219
2834
  return null;
@@ -2306,7 +2921,7 @@ __export(shard_manager_exports, {
2306
2921
  listShards: () => listShards,
2307
2922
  shardExists: () => shardExists
2308
2923
  });
2309
- import path12 from "path";
2924
+ import path13 from "path";
2310
2925
  import { existsSync as existsSync10, mkdirSync as mkdirSync6, readdirSync as readdirSync3 } from "fs";
2311
2926
  import { createClient as createClient2 } from "@libsql/client";
2312
2927
  function initShardManager(encryptionKey) {
@@ -2332,7 +2947,7 @@ function getShardClient(projectName) {
2332
2947
  }
2333
2948
  const cached = _shards.get(safeName);
2334
2949
  if (cached) return cached;
2335
- const dbPath = path12.join(SHARDS_DIR, `${safeName}.db`);
2950
+ const dbPath = path13.join(SHARDS_DIR, `${safeName}.db`);
2336
2951
  const client = createClient2({
2337
2952
  url: `file:${dbPath}`,
2338
2953
  encryptionKey: _encryptionKey
@@ -2342,7 +2957,7 @@ function getShardClient(projectName) {
2342
2957
  }
2343
2958
  function shardExists(projectName) {
2344
2959
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2345
- return existsSync10(path12.join(SHARDS_DIR, `${safeName}.db`));
2960
+ return existsSync10(path13.join(SHARDS_DIR, `${safeName}.db`));
2346
2961
  }
2347
2962
  function listShards() {
2348
2963
  if (!existsSync10(SHARDS_DIR)) return [];
@@ -2419,7 +3034,23 @@ async function ensureShardSchema(client) {
2419
3034
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2420
3035
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2421
3036
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2422
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
3037
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3038
+ // Metadata enrichment columns (must match database.ts)
3039
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3040
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3041
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3042
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3043
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3044
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3045
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3046
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3047
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3048
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3049
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3050
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3051
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3052
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3053
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2423
3054
  ]) {
2424
3055
  try {
2425
3056
  await client.execute(col);
@@ -2531,7 +3162,7 @@ var init_shard_manager = __esm({
2531
3162
  "src/lib/shard-manager.ts"() {
2532
3163
  "use strict";
2533
3164
  init_config();
2534
- SHARDS_DIR = path12.join(EXE_AI_DIR, "shards");
3165
+ SHARDS_DIR = path13.join(EXE_AI_DIR, "shards");
2535
3166
  _shards = /* @__PURE__ */ new Map();
2536
3167
  _encryptionKey = null;
2537
3168
  _shardingEnabled = false;