@askexenow/exe-os 0.9.6 → 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 +668 -37
  5. package/dist/bin/cli.js +1399 -607
  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 +795 -155
  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 +703 -72
  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 +1064 -273
  17. package/dist/bin/exe-heartbeat.js +676 -45
  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 +845 -152
  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 +668 -37
  33. package/dist/bin/exe-team.js +635 -13
  34. package/dist/bin/git-sweep.js +731 -91
  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 +735 -95
  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 +1038 -247
  43. package/dist/hooks/bug-report-worker.js +902 -172
  44. package/dist/hooks/commit-complete.js +729 -89
  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 +851 -158
  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 +685 -45
  52. package/dist/hooks/pre-compact.js +729 -89
  53. package/dist/hooks/pre-tool-use.js +883 -127
  54. package/dist/hooks/prompt-ingest-worker.js +758 -83
  55. package/dist/hooks/prompt-submit.js +1071 -321
  56. package/dist/hooks/response-ingest-worker.js +758 -83
  57. package/dist/hooks/session-end.js +732 -92
  58. package/dist/hooks/session-start.js +1042 -209
  59. package/dist/hooks/stop.js +691 -51
  60. package/dist/hooks/subagent-stop.js +685 -45
  61. package/dist/hooks/summary-worker.js +827 -134
  62. package/dist/index.js +1026 -234
  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 +905 -164
  73. package/dist/lib/hybrid-search.js +771 -88
  74. package/dist/lib/identity.js +27 -7
  75. package/dist/lib/messaging.js +66 -30
  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 +109 -73
  82. package/dist/lib/tmux-routing.js +98 -62
  83. package/dist/lib/token-spend.js +26 -6
  84. package/dist/mcp/server.js +1807 -472
  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 +301 -166
  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 +206 -40
  91. package/dist/mcp/tools/send-message.js +69 -33
  92. package/dist/mcp/tools/update-task.js +86 -50
  93. package/dist/runtime/index.js +731 -91
  94. package/dist/tui/App.js +864 -125
  95. package/package.json +3 -2
@@ -331,7 +331,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
331
331
  function getEmployee(employees, name) {
332
332
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
333
333
  }
334
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
334
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
335
335
  var init_employees = __esm({
336
336
  "src/lib/employees.ts"() {
337
337
  "use strict";
@@ -339,6 +339,7 @@ var init_employees = __esm({
339
339
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
340
340
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
341
341
  COORDINATOR_ROLE = "COO";
342
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
342
343
  }
343
344
  });
344
345
 
@@ -602,13 +603,597 @@ var init_db_retry = __esm({
602
603
  }
603
604
  });
604
605
 
606
+ // src/lib/database-adapter.ts
607
+ import os5 from "os";
608
+ import path7 from "path";
609
+ import { createRequire } from "module";
610
+ import { pathToFileURL } from "url";
611
+ function quotedIdentifier(identifier) {
612
+ return `"${identifier.replace(/"/g, '""')}"`;
613
+ }
614
+ function unqualifiedTableName(name) {
615
+ const raw = name.trim().replace(/^"|"$/g, "");
616
+ const parts = raw.split(".");
617
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
618
+ }
619
+ function stripTrailingSemicolon(sql) {
620
+ return sql.trim().replace(/;+\s*$/u, "");
621
+ }
622
+ function appendClause(sql, clause) {
623
+ const trimmed = stripTrailingSemicolon(sql);
624
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
625
+ if (!returningMatch) {
626
+ return `${trimmed}${clause}`;
627
+ }
628
+ const idx = returningMatch.index;
629
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
630
+ }
631
+ function normalizeStatement(stmt) {
632
+ if (typeof stmt === "string") {
633
+ return { kind: "positional", sql: stmt, args: [] };
634
+ }
635
+ const sql = stmt.sql;
636
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
637
+ return { kind: "positional", sql, args: stmt.args ?? [] };
638
+ }
639
+ return { kind: "named", sql, args: stmt.args };
640
+ }
641
+ function rewriteBooleanLiterals(sql) {
642
+ let out = sql;
643
+ for (const column of BOOLEAN_COLUMN_NAMES) {
644
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
645
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
646
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
647
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
648
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
649
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
650
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
651
+ }
652
+ return out;
653
+ }
654
+ function rewriteInsertOrIgnore(sql) {
655
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
656
+ return sql;
657
+ }
658
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
659
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
660
+ }
661
+ function rewriteInsertOrReplace(sql) {
662
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
663
+ if (!match) {
664
+ return sql;
665
+ }
666
+ const rawTable = match[1];
667
+ const rawColumns = match[2];
668
+ const remainder = match[3];
669
+ const tableName = unqualifiedTableName(rawTable);
670
+ const conflictKeys = UPSERT_KEYS[tableName];
671
+ if (!conflictKeys?.length) {
672
+ return sql;
673
+ }
674
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
675
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
676
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
677
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
678
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
679
+ }
680
+ function rewriteSql(sql) {
681
+ let out = sql;
682
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
683
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
684
+ out = rewriteBooleanLiterals(out);
685
+ out = rewriteInsertOrReplace(out);
686
+ out = rewriteInsertOrIgnore(out);
687
+ return stripTrailingSemicolon(out);
688
+ }
689
+ function toBoolean(value) {
690
+ if (value === null || value === void 0) return value;
691
+ if (typeof value === "boolean") return value;
692
+ if (typeof value === "number") return value !== 0;
693
+ if (typeof value === "bigint") return value !== 0n;
694
+ if (typeof value === "string") {
695
+ const normalized = value.trim().toLowerCase();
696
+ if (normalized === "0" || normalized === "false") return false;
697
+ if (normalized === "1" || normalized === "true") return true;
698
+ }
699
+ return Boolean(value);
700
+ }
701
+ function countQuestionMarks(sql, end) {
702
+ let count = 0;
703
+ let inSingle = false;
704
+ let inDouble = false;
705
+ let inLineComment = false;
706
+ let inBlockComment = false;
707
+ for (let i = 0; i < end; i++) {
708
+ const ch = sql[i];
709
+ const next = sql[i + 1];
710
+ if (inLineComment) {
711
+ if (ch === "\n") inLineComment = false;
712
+ continue;
713
+ }
714
+ if (inBlockComment) {
715
+ if (ch === "*" && next === "/") {
716
+ inBlockComment = false;
717
+ i += 1;
718
+ }
719
+ continue;
720
+ }
721
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
722
+ inLineComment = true;
723
+ i += 1;
724
+ continue;
725
+ }
726
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
727
+ inBlockComment = true;
728
+ i += 1;
729
+ continue;
730
+ }
731
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
732
+ inSingle = !inSingle;
733
+ continue;
734
+ }
735
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
736
+ inDouble = !inDouble;
737
+ continue;
738
+ }
739
+ if (!inSingle && !inDouble && ch === "?") {
740
+ count += 1;
741
+ }
742
+ }
743
+ return count;
744
+ }
745
+ function findBooleanPlaceholderIndexes(sql) {
746
+ const indexes = /* @__PURE__ */ new Set();
747
+ for (const column of BOOLEAN_COLUMN_NAMES) {
748
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
749
+ for (const match of sql.matchAll(pattern)) {
750
+ const matchText = match[0];
751
+ const qIndex = match.index + matchText.lastIndexOf("?");
752
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
753
+ }
754
+ }
755
+ return indexes;
756
+ }
757
+ function coerceInsertBooleanArgs(sql, args) {
758
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
759
+ if (!match) return;
760
+ const rawTable = match[1];
761
+ const rawColumns = match[2];
762
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
763
+ if (!boolColumns?.size) return;
764
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
765
+ for (const [index, column] of columns.entries()) {
766
+ if (boolColumns.has(column) && index < args.length) {
767
+ args[index] = toBoolean(args[index]);
768
+ }
769
+ }
770
+ }
771
+ function coerceUpdateBooleanArgs(sql, args) {
772
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
773
+ if (!match) return;
774
+ const rawTable = match[1];
775
+ const setClause = match[2];
776
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
777
+ if (!boolColumns?.size) return;
778
+ const assignments = setClause.split(",");
779
+ let placeholderIndex = 0;
780
+ for (const assignment of assignments) {
781
+ if (!assignment.includes("?")) continue;
782
+ placeholderIndex += 1;
783
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
784
+ if (colMatch && boolColumns.has(colMatch[1])) {
785
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
786
+ }
787
+ }
788
+ }
789
+ function coerceBooleanArgs(sql, args) {
790
+ const nextArgs = [...args];
791
+ coerceInsertBooleanArgs(sql, nextArgs);
792
+ coerceUpdateBooleanArgs(sql, nextArgs);
793
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
794
+ for (const index of placeholderIndexes) {
795
+ if (index > 0 && index <= nextArgs.length) {
796
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
797
+ }
798
+ }
799
+ return nextArgs;
800
+ }
801
+ function convertQuestionMarksToDollarParams(sql) {
802
+ let out = "";
803
+ let placeholder = 0;
804
+ let inSingle = false;
805
+ let inDouble = false;
806
+ let inLineComment = false;
807
+ let inBlockComment = false;
808
+ for (let i = 0; i < sql.length; i++) {
809
+ const ch = sql[i];
810
+ const next = sql[i + 1];
811
+ if (inLineComment) {
812
+ out += ch;
813
+ if (ch === "\n") inLineComment = false;
814
+ continue;
815
+ }
816
+ if (inBlockComment) {
817
+ out += ch;
818
+ if (ch === "*" && next === "/") {
819
+ out += next;
820
+ inBlockComment = false;
821
+ i += 1;
822
+ }
823
+ continue;
824
+ }
825
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
826
+ out += ch + next;
827
+ inLineComment = true;
828
+ i += 1;
829
+ continue;
830
+ }
831
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
832
+ out += ch + next;
833
+ inBlockComment = true;
834
+ i += 1;
835
+ continue;
836
+ }
837
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
838
+ inSingle = !inSingle;
839
+ out += ch;
840
+ continue;
841
+ }
842
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
843
+ inDouble = !inDouble;
844
+ out += ch;
845
+ continue;
846
+ }
847
+ if (!inSingle && !inDouble && ch === "?") {
848
+ placeholder += 1;
849
+ out += `$${placeholder}`;
850
+ continue;
851
+ }
852
+ out += ch;
853
+ }
854
+ return out;
855
+ }
856
+ function translateStatementForPostgres(stmt) {
857
+ const normalized = normalizeStatement(stmt);
858
+ if (normalized.kind === "named") {
859
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
860
+ }
861
+ const rewrittenSql = rewriteSql(normalized.sql);
862
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
863
+ return {
864
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
865
+ args: coercedArgs
866
+ };
867
+ }
868
+ function shouldBypassPostgres(stmt) {
869
+ const normalized = normalizeStatement(stmt);
870
+ if (normalized.kind === "named") {
871
+ return true;
872
+ }
873
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
874
+ }
875
+ function shouldFallbackOnError(error) {
876
+ const message = error instanceof Error ? error.message : String(error);
877
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
878
+ }
879
+ function isReadQuery(sql) {
880
+ const trimmed = sql.trimStart();
881
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
882
+ }
883
+ function buildRow(row, columns) {
884
+ const values = columns.map((column) => row[column]);
885
+ return Object.assign(values, row);
886
+ }
887
+ function buildResultSet(rows, rowsAffected = 0) {
888
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
889
+ const resultRows = rows.map((row) => buildRow(row, columns));
890
+ return {
891
+ columns,
892
+ columnTypes: columns.map(() => ""),
893
+ rows: resultRows,
894
+ rowsAffected,
895
+ lastInsertRowid: void 0,
896
+ toJSON() {
897
+ return {
898
+ columns,
899
+ columnTypes: columns.map(() => ""),
900
+ rows,
901
+ rowsAffected,
902
+ lastInsertRowid: void 0
903
+ };
904
+ }
905
+ };
906
+ }
907
+ async function loadPrismaClient() {
908
+ if (!prismaClientPromise) {
909
+ prismaClientPromise = (async () => {
910
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
911
+ if (explicitPath) {
912
+ const module2 = await import(pathToFileURL(explicitPath).href);
913
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
914
+ if (!PrismaClient2) {
915
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
916
+ }
917
+ return new PrismaClient2();
918
+ }
919
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path7.join(os5.homedir(), "exe-db");
920
+ const requireFromExeDb = createRequire(path7.join(exeDbRoot, "package.json"));
921
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
922
+ const module = await import(pathToFileURL(prismaEntry).href);
923
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
924
+ if (!PrismaClient) {
925
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
926
+ }
927
+ return new PrismaClient();
928
+ })();
929
+ }
930
+ return prismaClientPromise;
931
+ }
932
+ async function ensureCompatibilityViews(prisma) {
933
+ if (!compatibilityBootstrapPromise) {
934
+ compatibilityBootstrapPromise = (async () => {
935
+ for (const mapping of VIEW_MAPPINGS) {
936
+ const relation = mapping.source.replace(/"/g, "");
937
+ const rows = await prisma.$queryRawUnsafe(
938
+ "SELECT to_regclass($1) AS regclass",
939
+ relation
940
+ );
941
+ if (!rows[0]?.regclass) {
942
+ continue;
943
+ }
944
+ await prisma.$executeRawUnsafe(
945
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
946
+ );
947
+ }
948
+ })();
949
+ }
950
+ return compatibilityBootstrapPromise;
951
+ }
952
+ async function executeOnPrisma(executor, stmt) {
953
+ const translated = translateStatementForPostgres(stmt);
954
+ if (isReadQuery(translated.sql)) {
955
+ const rows = await executor.$queryRawUnsafe(
956
+ translated.sql,
957
+ ...translated.args
958
+ );
959
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
960
+ }
961
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
962
+ return buildResultSet([], rowsAffected);
963
+ }
964
+ function splitSqlStatements(sql) {
965
+ const parts = [];
966
+ let current = "";
967
+ let inSingle = false;
968
+ let inDouble = false;
969
+ let inLineComment = false;
970
+ let inBlockComment = false;
971
+ for (let i = 0; i < sql.length; i++) {
972
+ const ch = sql[i];
973
+ const next = sql[i + 1];
974
+ if (inLineComment) {
975
+ current += ch;
976
+ if (ch === "\n") inLineComment = false;
977
+ continue;
978
+ }
979
+ if (inBlockComment) {
980
+ current += ch;
981
+ if (ch === "*" && next === "/") {
982
+ current += next;
983
+ inBlockComment = false;
984
+ i += 1;
985
+ }
986
+ continue;
987
+ }
988
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
989
+ current += ch + next;
990
+ inLineComment = true;
991
+ i += 1;
992
+ continue;
993
+ }
994
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
995
+ current += ch + next;
996
+ inBlockComment = true;
997
+ i += 1;
998
+ continue;
999
+ }
1000
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
1001
+ inSingle = !inSingle;
1002
+ current += ch;
1003
+ continue;
1004
+ }
1005
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
1006
+ inDouble = !inDouble;
1007
+ current += ch;
1008
+ continue;
1009
+ }
1010
+ if (!inSingle && !inDouble && ch === ";") {
1011
+ if (current.trim()) {
1012
+ parts.push(current.trim());
1013
+ }
1014
+ current = "";
1015
+ continue;
1016
+ }
1017
+ current += ch;
1018
+ }
1019
+ if (current.trim()) {
1020
+ parts.push(current.trim());
1021
+ }
1022
+ return parts;
1023
+ }
1024
+ async function createPrismaDbAdapter(fallbackClient) {
1025
+ const prisma = await loadPrismaClient();
1026
+ await ensureCompatibilityViews(prisma);
1027
+ let closed = false;
1028
+ let adapter;
1029
+ const fallbackExecute = async (stmt, error) => {
1030
+ if (!fallbackClient) {
1031
+ if (error) throw error;
1032
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
1033
+ }
1034
+ if (error) {
1035
+ process.stderr.write(
1036
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
1037
+ `
1038
+ );
1039
+ }
1040
+ return fallbackClient.execute(stmt);
1041
+ };
1042
+ adapter = {
1043
+ async execute(stmt) {
1044
+ if (shouldBypassPostgres(stmt)) {
1045
+ return fallbackExecute(stmt);
1046
+ }
1047
+ try {
1048
+ return await executeOnPrisma(prisma, stmt);
1049
+ } catch (error) {
1050
+ if (shouldFallbackOnError(error)) {
1051
+ return fallbackExecute(stmt, error);
1052
+ }
1053
+ throw error;
1054
+ }
1055
+ },
1056
+ async batch(stmts, mode) {
1057
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
1058
+ if (!fallbackClient) {
1059
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
1060
+ }
1061
+ return fallbackClient.batch(stmts, mode);
1062
+ }
1063
+ try {
1064
+ if (prisma.$transaction) {
1065
+ return await prisma.$transaction(async (tx) => {
1066
+ const results2 = [];
1067
+ for (const stmt of stmts) {
1068
+ results2.push(await executeOnPrisma(tx, stmt));
1069
+ }
1070
+ return results2;
1071
+ });
1072
+ }
1073
+ const results = [];
1074
+ for (const stmt of stmts) {
1075
+ results.push(await executeOnPrisma(prisma, stmt));
1076
+ }
1077
+ return results;
1078
+ } catch (error) {
1079
+ if (fallbackClient && shouldFallbackOnError(error)) {
1080
+ process.stderr.write(
1081
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
1082
+ `
1083
+ );
1084
+ return fallbackClient.batch(stmts, mode);
1085
+ }
1086
+ throw error;
1087
+ }
1088
+ },
1089
+ async migrate(stmts) {
1090
+ if (fallbackClient) {
1091
+ return fallbackClient.migrate(stmts);
1092
+ }
1093
+ return adapter.batch(stmts, "deferred");
1094
+ },
1095
+ async transaction(mode) {
1096
+ if (!fallbackClient) {
1097
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
1098
+ }
1099
+ return fallbackClient.transaction(mode);
1100
+ },
1101
+ async executeMultiple(sql) {
1102
+ if (fallbackClient && shouldBypassPostgres(sql)) {
1103
+ return fallbackClient.executeMultiple(sql);
1104
+ }
1105
+ for (const statement of splitSqlStatements(sql)) {
1106
+ await adapter.execute(statement);
1107
+ }
1108
+ },
1109
+ async sync() {
1110
+ if (fallbackClient) {
1111
+ return fallbackClient.sync();
1112
+ }
1113
+ return { frame_no: 0, frames_synced: 0 };
1114
+ },
1115
+ close() {
1116
+ closed = true;
1117
+ prismaClientPromise = null;
1118
+ compatibilityBootstrapPromise = null;
1119
+ void prisma.$disconnect?.();
1120
+ },
1121
+ get closed() {
1122
+ return closed;
1123
+ },
1124
+ get protocol() {
1125
+ return "prisma-postgres";
1126
+ }
1127
+ };
1128
+ return adapter;
1129
+ }
1130
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
1131
+ var init_database_adapter = __esm({
1132
+ "src/lib/database-adapter.ts"() {
1133
+ "use strict";
1134
+ VIEW_MAPPINGS = [
1135
+ { view: "memories", source: "memory.memory_records" },
1136
+ { view: "tasks", source: "memory.tasks" },
1137
+ { view: "behaviors", source: "memory.behaviors" },
1138
+ { view: "entities", source: "memory.entities" },
1139
+ { view: "relationships", source: "memory.relationships" },
1140
+ { view: "entity_memories", source: "memory.entity_memories" },
1141
+ { view: "entity_aliases", source: "memory.entity_aliases" },
1142
+ { view: "notifications", source: "memory.notifications" },
1143
+ { view: "messages", source: "memory.messages" },
1144
+ { view: "users", source: "wiki.users" },
1145
+ { view: "workspaces", source: "wiki.workspaces" },
1146
+ { view: "workspace_users", source: "wiki.workspace_users" },
1147
+ { view: "documents", source: "wiki.workspace_documents" },
1148
+ { view: "chats", source: "wiki.workspace_chats" }
1149
+ ];
1150
+ UPSERT_KEYS = {
1151
+ memories: ["id"],
1152
+ tasks: ["id"],
1153
+ behaviors: ["id"],
1154
+ entities: ["id"],
1155
+ relationships: ["id"],
1156
+ entity_aliases: ["alias"],
1157
+ notifications: ["id"],
1158
+ messages: ["id"],
1159
+ users: ["id"],
1160
+ workspaces: ["id"],
1161
+ workspace_users: ["id"],
1162
+ documents: ["id"],
1163
+ chats: ["id"]
1164
+ };
1165
+ BOOLEAN_COLUMNS_BY_TABLE = {
1166
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
1167
+ behaviors: /* @__PURE__ */ new Set(["active"]),
1168
+ notifications: /* @__PURE__ */ new Set(["read"]),
1169
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
1170
+ };
1171
+ BOOLEAN_COLUMN_NAMES = new Set(
1172
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
1173
+ );
1174
+ IMMEDIATE_FALLBACK_PATTERNS = [
1175
+ /\bPRAGMA\b/i,
1176
+ /\bsqlite_master\b/i,
1177
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
1178
+ /\bMATCH\b/i,
1179
+ /\bvector_distance_cos\s*\(/i,
1180
+ /\bjson_extract\s*\(/i,
1181
+ /\bjulianday\s*\(/i,
1182
+ /\bstrftime\s*\(/i,
1183
+ /\blast_insert_rowid\s*\(/i
1184
+ ];
1185
+ prismaClientPromise = null;
1186
+ compatibilityBootstrapPromise = null;
1187
+ }
1188
+ });
1189
+
605
1190
  // src/lib/exe-daemon-client.ts
606
1191
  import net from "net";
607
- import os5 from "os";
1192
+ import os6 from "os";
608
1193
  import { spawn } from "child_process";
609
1194
  import { randomUUID } from "crypto";
610
1195
  import { existsSync as existsSync5, unlinkSync as unlinkSync3, readFileSync as readFileSync6, openSync, closeSync, statSync } from "fs";
611
- import path7 from "path";
1196
+ import path8 from "path";
612
1197
  import { fileURLToPath } from "url";
613
1198
  function handleData(chunk) {
614
1199
  _buffer += chunk.toString();
@@ -659,17 +1244,17 @@ function cleanupStaleFiles() {
659
1244
  }
660
1245
  }
661
1246
  function findPackageRoot() {
662
- let dir = path7.dirname(fileURLToPath(import.meta.url));
663
- const { root } = path7.parse(dir);
1247
+ let dir = path8.dirname(fileURLToPath(import.meta.url));
1248
+ const { root } = path8.parse(dir);
664
1249
  while (dir !== root) {
665
- if (existsSync5(path7.join(dir, "package.json"))) return dir;
666
- dir = path7.dirname(dir);
1250
+ if (existsSync5(path8.join(dir, "package.json"))) return dir;
1251
+ dir = path8.dirname(dir);
667
1252
  }
668
1253
  return null;
669
1254
  }
670
1255
  function spawnDaemon() {
671
- const freeGB = os5.freemem() / (1024 * 1024 * 1024);
672
- const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
1256
+ const freeGB = os6.freemem() / (1024 * 1024 * 1024);
1257
+ const totalGB = os6.totalmem() / (1024 * 1024 * 1024);
673
1258
  if (totalGB <= 8) {
674
1259
  process.stderr.write(
675
1260
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -689,7 +1274,7 @@ function spawnDaemon() {
689
1274
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
690
1275
  return;
691
1276
  }
692
- const daemonPath = path7.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1277
+ const daemonPath = path8.join(pkgRoot, "dist", "lib", "exe-daemon.js");
693
1278
  if (!existsSync5(daemonPath)) {
694
1279
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
695
1280
  `);
@@ -698,7 +1283,7 @@ function spawnDaemon() {
698
1283
  const resolvedPath = daemonPath;
699
1284
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
700
1285
  `);
701
- const logPath = path7.join(path7.dirname(SOCKET_PATH), "exed.log");
1286
+ const logPath = path8.join(path8.dirname(SOCKET_PATH), "exed.log");
702
1287
  let stderrFd = "ignore";
703
1288
  try {
704
1289
  stderrFd = openSync(logPath, "a");
@@ -845,9 +1430,9 @@ var init_exe_daemon_client = __esm({
845
1430
  "src/lib/exe-daemon-client.ts"() {
846
1431
  "use strict";
847
1432
  init_config();
848
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path7.join(EXE_AI_DIR, "exed.sock");
849
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path7.join(EXE_AI_DIR, "exed.pid");
850
- SPAWN_LOCK_PATH = path7.join(EXE_AI_DIR, "exed-spawn.lock");
1433
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path8.join(EXE_AI_DIR, "exed.sock");
1434
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path8.join(EXE_AI_DIR, "exed.pid");
1435
+ SPAWN_LOCK_PATH = path8.join(EXE_AI_DIR, "exed-spawn.lock");
851
1436
  SPAWN_LOCK_STALE_MS = 3e4;
852
1437
  CONNECT_TIMEOUT_MS = 15e3;
853
1438
  REQUEST_TIMEOUT_MS = 3e4;
@@ -929,7 +1514,7 @@ __export(db_daemon_client_exports, {
929
1514
  createDaemonDbClient: () => createDaemonDbClient,
930
1515
  initDaemonDbClient: () => initDaemonDbClient
931
1516
  });
932
- function normalizeStatement(stmt) {
1517
+ function normalizeStatement2(stmt) {
933
1518
  if (typeof stmt === "string") {
934
1519
  return { sql: stmt, args: [] };
935
1520
  }
@@ -953,7 +1538,7 @@ function createDaemonDbClient(fallbackClient) {
953
1538
  if (!_useDaemon || !isClientConnected()) {
954
1539
  return fallbackClient.execute(stmt);
955
1540
  }
956
- const { sql, args } = normalizeStatement(stmt);
1541
+ const { sql, args } = normalizeStatement2(stmt);
957
1542
  const response = await sendDaemonRequest({
958
1543
  type: "db-execute",
959
1544
  sql,
@@ -978,7 +1563,7 @@ function createDaemonDbClient(fallbackClient) {
978
1563
  if (!_useDaemon || !isClientConnected()) {
979
1564
  return fallbackClient.batch(stmts, mode);
980
1565
  }
981
- const statements = stmts.map(normalizeStatement);
1566
+ const statements = stmts.map(normalizeStatement2);
982
1567
  const response = await sendDaemonRequest({
983
1568
  type: "db-batch",
984
1569
  statements,
@@ -1073,6 +1658,18 @@ __export(database_exports, {
1073
1658
  });
1074
1659
  import { createClient } from "@libsql/client";
1075
1660
  async function initDatabase(config) {
1661
+ if (_walCheckpointTimer) {
1662
+ clearInterval(_walCheckpointTimer);
1663
+ _walCheckpointTimer = null;
1664
+ }
1665
+ if (_daemonClient) {
1666
+ _daemonClient.close();
1667
+ _daemonClient = null;
1668
+ }
1669
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1670
+ _adapterClient.close();
1671
+ }
1672
+ _adapterClient = null;
1076
1673
  if (_client) {
1077
1674
  _client.close();
1078
1675
  _client = null;
@@ -1086,6 +1683,7 @@ async function initDatabase(config) {
1086
1683
  }
1087
1684
  _client = createClient(opts);
1088
1685
  _resilientClient = wrapWithRetry(_client);
1686
+ _adapterClient = _resilientClient;
1089
1687
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1090
1688
  });
1091
1689
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -1096,14 +1694,20 @@ async function initDatabase(config) {
1096
1694
  });
1097
1695
  }, 3e4);
1098
1696
  _walCheckpointTimer.unref();
1697
+ if (process.env.DATABASE_URL) {
1698
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1699
+ }
1099
1700
  }
1100
1701
  function isInitialized() {
1101
- return _client !== null;
1702
+ return _adapterClient !== null || _client !== null;
1102
1703
  }
1103
1704
  function getClient() {
1104
- if (!_resilientClient) {
1705
+ if (!_adapterClient) {
1105
1706
  throw new Error("Database client not initialized. Call initDatabase() first.");
1106
1707
  }
1708
+ if (process.env.DATABASE_URL) {
1709
+ return _adapterClient;
1710
+ }
1107
1711
  if (process.env.EXE_IS_DAEMON === "1") {
1108
1712
  return _resilientClient;
1109
1713
  }
@@ -1113,6 +1717,7 @@ function getClient() {
1113
1717
  return _resilientClient;
1114
1718
  }
1115
1719
  async function initDaemonClient() {
1720
+ if (process.env.DATABASE_URL) return;
1116
1721
  if (process.env.EXE_IS_DAEMON === "1") return;
1117
1722
  if (!_resilientClient) return;
1118
1723
  try {
@@ -2057,26 +2662,36 @@ async function ensureSchema() {
2057
2662
  }
2058
2663
  }
2059
2664
  async function disposeDatabase() {
2665
+ if (_walCheckpointTimer) {
2666
+ clearInterval(_walCheckpointTimer);
2667
+ _walCheckpointTimer = null;
2668
+ }
2060
2669
  if (_daemonClient) {
2061
2670
  _daemonClient.close();
2062
2671
  _daemonClient = null;
2063
2672
  }
2673
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2674
+ _adapterClient.close();
2675
+ }
2676
+ _adapterClient = null;
2064
2677
  if (_client) {
2065
2678
  _client.close();
2066
2679
  _client = null;
2067
2680
  _resilientClient = null;
2068
2681
  }
2069
2682
  }
2070
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
2683
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2071
2684
  var init_database = __esm({
2072
2685
  "src/lib/database.ts"() {
2073
2686
  "use strict";
2074
2687
  init_db_retry();
2075
2688
  init_employees();
2689
+ init_database_adapter();
2076
2690
  _client = null;
2077
2691
  _resilientClient = null;
2078
2692
  _walCheckpointTimer = null;
2079
2693
  _daemonClient = null;
2694
+ _adapterClient = null;
2080
2695
  initTurso = initDatabase;
2081
2696
  disposeTurso = disposeDatabase;
2082
2697
  }
@@ -2085,22 +2700,22 @@ var init_database = __esm({
2085
2700
  // src/lib/license.ts
2086
2701
  import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync6, mkdirSync as mkdirSync4 } from "fs";
2087
2702
  import { randomUUID as randomUUID2 } from "crypto";
2088
- import path8 from "path";
2703
+ import path9 from "path";
2089
2704
  import { jwtVerify, importSPKI } from "jose";
2090
2705
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2091
2706
  var init_license = __esm({
2092
2707
  "src/lib/license.ts"() {
2093
2708
  "use strict";
2094
2709
  init_config();
2095
- LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
2096
- CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
2097
- DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
2710
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2711
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2712
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2098
2713
  }
2099
2714
  });
2100
2715
 
2101
2716
  // src/lib/plan-limits.ts
2102
2717
  import { readFileSync as readFileSync8, existsSync as existsSync7 } from "fs";
2103
- import path9 from "path";
2718
+ import path10 from "path";
2104
2719
  var CACHE_PATH2;
2105
2720
  var init_plan_limits = __esm({
2106
2721
  "src/lib/plan-limits.ts"() {
@@ -2109,14 +2724,14 @@ var init_plan_limits = __esm({
2109
2724
  init_employees();
2110
2725
  init_license();
2111
2726
  init_config();
2112
- CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2727
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2113
2728
  }
2114
2729
  });
2115
2730
 
2116
2731
  // src/lib/tmux-routing.ts
2117
2732
  import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync5, existsSync as existsSync8, appendFileSync, readdirSync as readdirSync2 } from "fs";
2118
- import path10 from "path";
2119
- import os6 from "os";
2733
+ import path11 from "path";
2734
+ import os7 from "os";
2120
2735
  import { fileURLToPath as fileURLToPath2 } from "url";
2121
2736
  function getMySession() {
2122
2737
  return getTransport().getMySession();
@@ -2129,7 +2744,7 @@ function extractRootExe(name) {
2129
2744
  }
2130
2745
  function getParentExe(sessionKey) {
2131
2746
  try {
2132
- const data = JSON.parse(readFileSync9(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2747
+ const data = JSON.parse(readFileSync9(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2133
2748
  return data.parentExe || null;
2134
2749
  } catch {
2135
2750
  return null;
@@ -2138,15 +2753,24 @@ function getParentExe(sessionKey) {
2138
2753
  function resolveExeSession() {
2139
2754
  const mySession = getMySession();
2140
2755
  if (!mySession) return null;
2756
+ const fromSessionName = extractRootExe(mySession);
2141
2757
  try {
2142
2758
  const key = getSessionKey();
2143
2759
  const parentExe = getParentExe(key);
2144
2760
  if (parentExe) {
2145
- return extractRootExe(parentExe) ?? parentExe;
2761
+ const fromCache = extractRootExe(parentExe) ?? parentExe;
2762
+ if (fromSessionName && fromCache !== fromSessionName) {
2763
+ process.stderr.write(
2764
+ `[tmux-routing] WARN: cache says "${fromCache}" but session name says "${fromSessionName}". Trusting session name.
2765
+ `
2766
+ );
2767
+ return fromSessionName;
2768
+ }
2769
+ return fromCache;
2146
2770
  }
2147
2771
  } catch {
2148
2772
  }
2149
- return extractRootExe(mySession) ?? mySession;
2773
+ return fromSessionName ?? mySession;
2150
2774
  }
2151
2775
  var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
2152
2776
  var init_tmux_routing = __esm({
@@ -2163,10 +2787,10 @@ var init_tmux_routing = __esm({
2163
2787
  init_intercom_queue();
2164
2788
  init_plan_limits();
2165
2789
  init_employees();
2166
- SPAWN_LOCK_DIR = path10.join(os6.homedir(), ".exe-os", "spawn-locks");
2167
- SESSION_CACHE = path10.join(os6.homedir(), ".exe-os", "session-cache");
2168
- INTERCOM_LOG2 = path10.join(os6.homedir(), ".exe-os", "intercom.log");
2169
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
2790
+ SPAWN_LOCK_DIR = path11.join(os7.homedir(), ".exe-os", "spawn-locks");
2791
+ SESSION_CACHE = path11.join(os7.homedir(), ".exe-os", "session-cache");
2792
+ INTERCOM_LOG2 = path11.join(os7.homedir(), ".exe-os", "intercom.log");
2793
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2170
2794
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2171
2795
  }
2172
2796
  });
@@ -2207,13 +2831,13 @@ var init_memory = __esm({
2207
2831
  // src/lib/keychain.ts
2208
2832
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2209
2833
  import { existsSync as existsSync9 } from "fs";
2210
- import path11 from "path";
2211
- import os7 from "os";
2834
+ import path12 from "path";
2835
+ import os8 from "os";
2212
2836
  function getKeyDir() {
2213
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path11.join(os7.homedir(), ".exe-os");
2837
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path12.join(os8.homedir(), ".exe-os");
2214
2838
  }
2215
2839
  function getKeyPath() {
2216
- return path11.join(getKeyDir(), "master.key");
2840
+ return path12.join(getKeyDir(), "master.key");
2217
2841
  }
2218
2842
  async function tryKeytar() {
2219
2843
  try {
@@ -2236,7 +2860,7 @@ async function getMasterKey() {
2236
2860
  const keyPath = getKeyPath();
2237
2861
  if (!existsSync9(keyPath)) {
2238
2862
  process.stderr.write(
2239
- `[keychain] Key not found at ${keyPath} (HOME=${os7.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2863
+ `[keychain] Key not found at ${keyPath} (HOME=${os8.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2240
2864
  `
2241
2865
  );
2242
2866
  return null;
@@ -2329,7 +2953,7 @@ __export(shard_manager_exports, {
2329
2953
  listShards: () => listShards,
2330
2954
  shardExists: () => shardExists
2331
2955
  });
2332
- import path12 from "path";
2956
+ import path13 from "path";
2333
2957
  import { existsSync as existsSync10, mkdirSync as mkdirSync6, readdirSync as readdirSync3 } from "fs";
2334
2958
  import { createClient as createClient2 } from "@libsql/client";
2335
2959
  function initShardManager(encryptionKey) {
@@ -2355,7 +2979,7 @@ function getShardClient(projectName) {
2355
2979
  }
2356
2980
  const cached = _shards.get(safeName);
2357
2981
  if (cached) return cached;
2358
- const dbPath = path12.join(SHARDS_DIR, `${safeName}.db`);
2982
+ const dbPath = path13.join(SHARDS_DIR, `${safeName}.db`);
2359
2983
  const client = createClient2({
2360
2984
  url: `file:${dbPath}`,
2361
2985
  encryptionKey: _encryptionKey
@@ -2365,7 +2989,7 @@ function getShardClient(projectName) {
2365
2989
  }
2366
2990
  function shardExists(projectName) {
2367
2991
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2368
- return existsSync10(path12.join(SHARDS_DIR, `${safeName}.db`));
2992
+ return existsSync10(path13.join(SHARDS_DIR, `${safeName}.db`));
2369
2993
  }
2370
2994
  function listShards() {
2371
2995
  if (!existsSync10(SHARDS_DIR)) return [];
@@ -2442,7 +3066,23 @@ async function ensureShardSchema(client) {
2442
3066
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2443
3067
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2444
3068
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2445
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
3069
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3070
+ // Metadata enrichment columns (must match database.ts)
3071
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3072
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3073
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3074
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3075
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3076
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3077
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3078
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3079
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3080
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3081
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3082
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3083
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3084
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3085
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2446
3086
  ]) {
2447
3087
  try {
2448
3088
  await client.execute(col);
@@ -2554,7 +3194,7 @@ var init_shard_manager = __esm({
2554
3194
  "src/lib/shard-manager.ts"() {
2555
3195
  "use strict";
2556
3196
  init_config();
2557
- SHARDS_DIR = path12.join(EXE_AI_DIR, "shards");
3197
+ SHARDS_DIR = path13.join(EXE_AI_DIR, "shards");
2558
3198
  _shards = /* @__PURE__ */ new Map();
2559
3199
  _encryptionKey = null;
2560
3200
  _shardingEnabled = false;
@@ -3323,7 +3963,7 @@ init_config();
3323
3963
  init_config();
3324
3964
  import { spawn as spawn2 } from "child_process";
3325
3965
  import { existsSync as existsSync11, openSync as openSync2, closeSync as closeSync2 } from "fs";
3326
- import path13 from "path";
3966
+ import path14 from "path";
3327
3967
  import { fileURLToPath as fileURLToPath3 } from "url";
3328
3968
 
3329
3969
  // src/lib/active-agent.ts
@@ -3433,7 +4073,7 @@ if (!process.env.AGENT_ID) {
3433
4073
  if (!loadConfigSync().autoIngestion) {
3434
4074
  process.exit(0);
3435
4075
  }
3436
- var WORKER_LOG_PATH = path13.join(EXE_AI_DIR, "workers.log");
4076
+ var WORKER_LOG_PATH = path14.join(EXE_AI_DIR, "workers.log");
3437
4077
  function openWorkerLog() {
3438
4078
  try {
3439
4079
  return openSync2(WORKER_LOG_PATH, "a");
@@ -3456,9 +4096,9 @@ process.stdin.on("end", () => {
3456
4096
  try {
3457
4097
  if (process.env.EXE_DEBUG_HOOKS || process.env.EXE_RUNTIME === "codex") {
3458
4098
  try {
3459
- const debugPath = path13.join(EXE_AI_DIR, "logs", "hook-stdin-stop.log");
4099
+ const debugPath = path14.join(EXE_AI_DIR, "logs", "hook-stdin-stop.log");
3460
4100
  const { mkdirSync: mkdirSync7, writeFileSync: writeFileSync7 } = __require("fs");
3461
- mkdirSync7(path13.dirname(debugPath), { recursive: true });
4101
+ mkdirSync7(path14.dirname(debugPath), { recursive: true });
3462
4102
  const ts = (/* @__PURE__ */ new Date()).toISOString();
3463
4103
  const snippet = input.length > 500 ? input.slice(0, 500) + "...[truncated]" : input;
3464
4104
  writeFileSync7(debugPath, `[${ts}] len=${input.length} ${snippet}
@@ -3537,8 +4177,8 @@ process.stdin.on("end", () => {
3537
4177
  }).catch(() => {
3538
4178
  });
3539
4179
  }
3540
- const workerPath = path13.resolve(
3541
- path13.dirname(fileURLToPath3(import.meta.url)),
4180
+ const workerPath = path14.resolve(
4181
+ path14.dirname(fileURLToPath3(import.meta.url)),
3542
4182
  "response-ingest-worker.js"
3543
4183
  );
3544
4184
  if (!existsSync11(workerPath)) {