@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
@@ -277,7 +277,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
277
277
  return [];
278
278
  }
279
279
  }
280
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
280
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
281
281
  var init_employees = __esm({
282
282
  "src/lib/employees.ts"() {
283
283
  "use strict";
@@ -285,12 +285,609 @@ var init_employees = __esm({
285
285
  EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
286
286
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
287
287
  COORDINATOR_ROLE = "COO";
288
+ IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
289
+ }
290
+ });
291
+
292
+ // src/lib/database-adapter.ts
293
+ import os3 from "os";
294
+ import path3 from "path";
295
+ import { createRequire } from "module";
296
+ import { pathToFileURL } from "url";
297
+ function quotedIdentifier(identifier) {
298
+ return `"${identifier.replace(/"/g, '""')}"`;
299
+ }
300
+ function unqualifiedTableName(name) {
301
+ const raw = name.trim().replace(/^"|"$/g, "");
302
+ const parts = raw.split(".");
303
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
304
+ }
305
+ function stripTrailingSemicolon(sql) {
306
+ return sql.trim().replace(/;+\s*$/u, "");
307
+ }
308
+ function appendClause(sql, clause) {
309
+ const trimmed = stripTrailingSemicolon(sql);
310
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
311
+ if (!returningMatch) {
312
+ return `${trimmed}${clause}`;
313
+ }
314
+ const idx = returningMatch.index;
315
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
316
+ }
317
+ function normalizeStatement(stmt) {
318
+ if (typeof stmt === "string") {
319
+ return { kind: "positional", sql: stmt, args: [] };
320
+ }
321
+ const sql = stmt.sql;
322
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
323
+ return { kind: "positional", sql, args: stmt.args ?? [] };
324
+ }
325
+ return { kind: "named", sql, args: stmt.args };
326
+ }
327
+ function rewriteBooleanLiterals(sql) {
328
+ let out = sql;
329
+ for (const column of BOOLEAN_COLUMN_NAMES) {
330
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
331
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
332
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
333
+ 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
+ }
338
+ return out;
339
+ }
340
+ function rewriteInsertOrIgnore(sql) {
341
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
342
+ return sql;
343
+ }
344
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
345
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
346
+ }
347
+ function rewriteInsertOrReplace(sql) {
348
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
349
+ if (!match) {
350
+ return sql;
351
+ }
352
+ const rawTable = match[1];
353
+ const rawColumns = match[2];
354
+ const remainder = match[3];
355
+ const tableName = unqualifiedTableName(rawTable);
356
+ const conflictKeys = UPSERT_KEYS[tableName];
357
+ if (!conflictKeys?.length) {
358
+ return sql;
359
+ }
360
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
361
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
362
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
363
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
364
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
365
+ }
366
+ function rewriteSql(sql) {
367
+ let out = sql;
368
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
369
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
370
+ out = rewriteBooleanLiterals(out);
371
+ out = rewriteInsertOrReplace(out);
372
+ out = rewriteInsertOrIgnore(out);
373
+ return stripTrailingSemicolon(out);
374
+ }
375
+ function toBoolean(value) {
376
+ if (value === null || value === void 0) return value;
377
+ if (typeof value === "boolean") return value;
378
+ if (typeof value === "number") return value !== 0;
379
+ if (typeof value === "bigint") return value !== 0n;
380
+ if (typeof value === "string") {
381
+ const normalized = value.trim().toLowerCase();
382
+ if (normalized === "0" || normalized === "false") return false;
383
+ if (normalized === "1" || normalized === "true") return true;
384
+ }
385
+ return Boolean(value);
386
+ }
387
+ function countQuestionMarks(sql, end) {
388
+ let count = 0;
389
+ let inSingle = false;
390
+ let inDouble = false;
391
+ let inLineComment = false;
392
+ let inBlockComment = false;
393
+ for (let i = 0; i < end; i++) {
394
+ const ch = sql[i];
395
+ const next = sql[i + 1];
396
+ if (inLineComment) {
397
+ if (ch === "\n") inLineComment = false;
398
+ continue;
399
+ }
400
+ if (inBlockComment) {
401
+ if (ch === "*" && next === "/") {
402
+ inBlockComment = false;
403
+ i += 1;
404
+ }
405
+ continue;
406
+ }
407
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
408
+ inLineComment = true;
409
+ i += 1;
410
+ continue;
411
+ }
412
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
413
+ inBlockComment = true;
414
+ i += 1;
415
+ continue;
416
+ }
417
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
418
+ inSingle = !inSingle;
419
+ continue;
420
+ }
421
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
422
+ inDouble = !inDouble;
423
+ continue;
424
+ }
425
+ if (!inSingle && !inDouble && ch === "?") {
426
+ count += 1;
427
+ }
428
+ }
429
+ return count;
430
+ }
431
+ function findBooleanPlaceholderIndexes(sql) {
432
+ const indexes = /* @__PURE__ */ new Set();
433
+ for (const column of BOOLEAN_COLUMN_NAMES) {
434
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
435
+ for (const match of sql.matchAll(pattern)) {
436
+ const matchText = match[0];
437
+ const qIndex = match.index + matchText.lastIndexOf("?");
438
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
439
+ }
440
+ }
441
+ return indexes;
442
+ }
443
+ function coerceInsertBooleanArgs(sql, args) {
444
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
445
+ if (!match) return;
446
+ const rawTable = match[1];
447
+ const rawColumns = match[2];
448
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
449
+ if (!boolColumns?.size) return;
450
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
451
+ for (const [index, column] of columns.entries()) {
452
+ if (boolColumns.has(column) && index < args.length) {
453
+ args[index] = toBoolean(args[index]);
454
+ }
455
+ }
456
+ }
457
+ function coerceUpdateBooleanArgs(sql, args) {
458
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
459
+ if (!match) return;
460
+ const rawTable = match[1];
461
+ const setClause = match[2];
462
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
463
+ if (!boolColumns?.size) return;
464
+ const assignments = setClause.split(",");
465
+ let placeholderIndex = 0;
466
+ for (const assignment of assignments) {
467
+ if (!assignment.includes("?")) continue;
468
+ placeholderIndex += 1;
469
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
470
+ if (colMatch && boolColumns.has(colMatch[1])) {
471
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
472
+ }
473
+ }
474
+ }
475
+ function coerceBooleanArgs(sql, args) {
476
+ const nextArgs = [...args];
477
+ coerceInsertBooleanArgs(sql, nextArgs);
478
+ coerceUpdateBooleanArgs(sql, nextArgs);
479
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
480
+ for (const index of placeholderIndexes) {
481
+ if (index > 0 && index <= nextArgs.length) {
482
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
483
+ }
484
+ }
485
+ return nextArgs;
486
+ }
487
+ function convertQuestionMarksToDollarParams(sql) {
488
+ let out = "";
489
+ let placeholder = 0;
490
+ let inSingle = false;
491
+ let inDouble = false;
492
+ let inLineComment = false;
493
+ let inBlockComment = false;
494
+ for (let i = 0; i < sql.length; i++) {
495
+ const ch = sql[i];
496
+ const next = sql[i + 1];
497
+ if (inLineComment) {
498
+ out += ch;
499
+ if (ch === "\n") inLineComment = false;
500
+ continue;
501
+ }
502
+ if (inBlockComment) {
503
+ out += ch;
504
+ if (ch === "*" && next === "/") {
505
+ out += next;
506
+ inBlockComment = false;
507
+ i += 1;
508
+ }
509
+ continue;
510
+ }
511
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
512
+ out += ch + next;
513
+ inLineComment = true;
514
+ i += 1;
515
+ continue;
516
+ }
517
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
518
+ out += ch + next;
519
+ inBlockComment = true;
520
+ i += 1;
521
+ continue;
522
+ }
523
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
524
+ inSingle = !inSingle;
525
+ out += ch;
526
+ continue;
527
+ }
528
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
529
+ inDouble = !inDouble;
530
+ out += ch;
531
+ continue;
532
+ }
533
+ if (!inSingle && !inDouble && ch === "?") {
534
+ placeholder += 1;
535
+ out += `$${placeholder}`;
536
+ continue;
537
+ }
538
+ out += ch;
539
+ }
540
+ return out;
541
+ }
542
+ function translateStatementForPostgres(stmt) {
543
+ const normalized = normalizeStatement(stmt);
544
+ if (normalized.kind === "named") {
545
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
546
+ }
547
+ const rewrittenSql = rewriteSql(normalized.sql);
548
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
549
+ return {
550
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
551
+ args: coercedArgs
552
+ };
553
+ }
554
+ function shouldBypassPostgres(stmt) {
555
+ const normalized = normalizeStatement(stmt);
556
+ if (normalized.kind === "named") {
557
+ return true;
558
+ }
559
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
560
+ }
561
+ function shouldFallbackOnError(error) {
562
+ const message = error instanceof Error ? error.message : String(error);
563
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
564
+ }
565
+ function isReadQuery(sql) {
566
+ const trimmed = sql.trimStart();
567
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
568
+ }
569
+ function buildRow(row, columns) {
570
+ const values = columns.map((column) => row[column]);
571
+ return Object.assign(values, row);
572
+ }
573
+ function buildResultSet(rows, rowsAffected = 0) {
574
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
575
+ const resultRows = rows.map((row) => buildRow(row, columns));
576
+ return {
577
+ columns,
578
+ columnTypes: columns.map(() => ""),
579
+ rows: resultRows,
580
+ rowsAffected,
581
+ lastInsertRowid: void 0,
582
+ toJSON() {
583
+ return {
584
+ columns,
585
+ columnTypes: columns.map(() => ""),
586
+ rows,
587
+ rowsAffected,
588
+ lastInsertRowid: void 0
589
+ };
590
+ }
591
+ };
592
+ }
593
+ async function loadPrismaClient() {
594
+ if (!prismaClientPromise) {
595
+ prismaClientPromise = (async () => {
596
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
597
+ if (explicitPath) {
598
+ const module2 = await import(pathToFileURL(explicitPath).href);
599
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
600
+ if (!PrismaClient2) {
601
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
602
+ }
603
+ return new PrismaClient2();
604
+ }
605
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
606
+ const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
607
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
608
+ const module = await import(pathToFileURL(prismaEntry).href);
609
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
610
+ if (!PrismaClient) {
611
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
612
+ }
613
+ return new PrismaClient();
614
+ })();
615
+ }
616
+ return prismaClientPromise;
617
+ }
618
+ async function ensureCompatibilityViews(prisma) {
619
+ if (!compatibilityBootstrapPromise) {
620
+ compatibilityBootstrapPromise = (async () => {
621
+ for (const mapping of VIEW_MAPPINGS) {
622
+ const relation = mapping.source.replace(/"/g, "");
623
+ const rows = await prisma.$queryRawUnsafe(
624
+ "SELECT to_regclass($1) AS regclass",
625
+ relation
626
+ );
627
+ if (!rows[0]?.regclass) {
628
+ continue;
629
+ }
630
+ await prisma.$executeRawUnsafe(
631
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
632
+ );
633
+ }
634
+ })();
635
+ }
636
+ return compatibilityBootstrapPromise;
637
+ }
638
+ async function executeOnPrisma(executor, stmt) {
639
+ const translated = translateStatementForPostgres(stmt);
640
+ if (isReadQuery(translated.sql)) {
641
+ const rows = await executor.$queryRawUnsafe(
642
+ translated.sql,
643
+ ...translated.args
644
+ );
645
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
646
+ }
647
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
648
+ return buildResultSet([], rowsAffected);
649
+ }
650
+ function splitSqlStatements(sql) {
651
+ const parts = [];
652
+ let current = "";
653
+ let inSingle = false;
654
+ let inDouble = false;
655
+ let inLineComment = false;
656
+ let inBlockComment = false;
657
+ for (let i = 0; i < sql.length; i++) {
658
+ const ch = sql[i];
659
+ const next = sql[i + 1];
660
+ if (inLineComment) {
661
+ current += ch;
662
+ if (ch === "\n") inLineComment = false;
663
+ continue;
664
+ }
665
+ if (inBlockComment) {
666
+ current += ch;
667
+ if (ch === "*" && next === "/") {
668
+ current += next;
669
+ inBlockComment = false;
670
+ i += 1;
671
+ }
672
+ continue;
673
+ }
674
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
675
+ current += ch + next;
676
+ inLineComment = true;
677
+ i += 1;
678
+ continue;
679
+ }
680
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
681
+ current += ch + next;
682
+ inBlockComment = true;
683
+ i += 1;
684
+ continue;
685
+ }
686
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
687
+ inSingle = !inSingle;
688
+ current += ch;
689
+ continue;
690
+ }
691
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
692
+ inDouble = !inDouble;
693
+ current += ch;
694
+ continue;
695
+ }
696
+ if (!inSingle && !inDouble && ch === ";") {
697
+ if (current.trim()) {
698
+ parts.push(current.trim());
699
+ }
700
+ current = "";
701
+ continue;
702
+ }
703
+ current += ch;
704
+ }
705
+ if (current.trim()) {
706
+ parts.push(current.trim());
707
+ }
708
+ return parts;
709
+ }
710
+ async function createPrismaDbAdapter(fallbackClient) {
711
+ const prisma = await loadPrismaClient();
712
+ await ensureCompatibilityViews(prisma);
713
+ let closed = false;
714
+ let adapter;
715
+ const fallbackExecute = async (stmt, error) => {
716
+ if (!fallbackClient) {
717
+ if (error) throw error;
718
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
719
+ }
720
+ if (error) {
721
+ process.stderr.write(
722
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
723
+ `
724
+ );
725
+ }
726
+ return fallbackClient.execute(stmt);
727
+ };
728
+ adapter = {
729
+ async execute(stmt) {
730
+ if (shouldBypassPostgres(stmt)) {
731
+ return fallbackExecute(stmt);
732
+ }
733
+ try {
734
+ return await executeOnPrisma(prisma, stmt);
735
+ } catch (error) {
736
+ if (shouldFallbackOnError(error)) {
737
+ return fallbackExecute(stmt, error);
738
+ }
739
+ throw error;
740
+ }
741
+ },
742
+ async batch(stmts, mode) {
743
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
744
+ if (!fallbackClient) {
745
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
746
+ }
747
+ return fallbackClient.batch(stmts, mode);
748
+ }
749
+ try {
750
+ if (prisma.$transaction) {
751
+ return await prisma.$transaction(async (tx) => {
752
+ const results2 = [];
753
+ for (const stmt of stmts) {
754
+ results2.push(await executeOnPrisma(tx, stmt));
755
+ }
756
+ return results2;
757
+ });
758
+ }
759
+ const results = [];
760
+ for (const stmt of stmts) {
761
+ results.push(await executeOnPrisma(prisma, stmt));
762
+ }
763
+ return results;
764
+ } catch (error) {
765
+ if (fallbackClient && shouldFallbackOnError(error)) {
766
+ process.stderr.write(
767
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
768
+ `
769
+ );
770
+ return fallbackClient.batch(stmts, mode);
771
+ }
772
+ throw error;
773
+ }
774
+ },
775
+ async migrate(stmts) {
776
+ if (fallbackClient) {
777
+ return fallbackClient.migrate(stmts);
778
+ }
779
+ return adapter.batch(stmts, "deferred");
780
+ },
781
+ async transaction(mode) {
782
+ if (!fallbackClient) {
783
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
784
+ }
785
+ return fallbackClient.transaction(mode);
786
+ },
787
+ async executeMultiple(sql) {
788
+ if (fallbackClient && shouldBypassPostgres(sql)) {
789
+ return fallbackClient.executeMultiple(sql);
790
+ }
791
+ for (const statement of splitSqlStatements(sql)) {
792
+ await adapter.execute(statement);
793
+ }
794
+ },
795
+ async sync() {
796
+ if (fallbackClient) {
797
+ return fallbackClient.sync();
798
+ }
799
+ return { frame_no: 0, frames_synced: 0 };
800
+ },
801
+ close() {
802
+ closed = true;
803
+ prismaClientPromise = null;
804
+ compatibilityBootstrapPromise = null;
805
+ void prisma.$disconnect?.();
806
+ },
807
+ get closed() {
808
+ return closed;
809
+ },
810
+ get protocol() {
811
+ return "prisma-postgres";
812
+ }
813
+ };
814
+ return adapter;
815
+ }
816
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
817
+ var init_database_adapter = __esm({
818
+ "src/lib/database-adapter.ts"() {
819
+ "use strict";
820
+ VIEW_MAPPINGS = [
821
+ { view: "memories", source: "memory.memory_records" },
822
+ { view: "tasks", source: "memory.tasks" },
823
+ { view: "behaviors", source: "memory.behaviors" },
824
+ { view: "entities", source: "memory.entities" },
825
+ { view: "relationships", source: "memory.relationships" },
826
+ { view: "entity_memories", source: "memory.entity_memories" },
827
+ { view: "entity_aliases", source: "memory.entity_aliases" },
828
+ { view: "notifications", source: "memory.notifications" },
829
+ { view: "messages", source: "memory.messages" },
830
+ { view: "users", source: "wiki.users" },
831
+ { view: "workspaces", source: "wiki.workspaces" },
832
+ { view: "workspace_users", source: "wiki.workspace_users" },
833
+ { view: "documents", source: "wiki.workspace_documents" },
834
+ { view: "chats", source: "wiki.workspace_chats" }
835
+ ];
836
+ UPSERT_KEYS = {
837
+ memories: ["id"],
838
+ tasks: ["id"],
839
+ behaviors: ["id"],
840
+ entities: ["id"],
841
+ relationships: ["id"],
842
+ entity_aliases: ["alias"],
843
+ notifications: ["id"],
844
+ messages: ["id"],
845
+ users: ["id"],
846
+ workspaces: ["id"],
847
+ workspace_users: ["id"],
848
+ documents: ["id"],
849
+ chats: ["id"]
850
+ };
851
+ BOOLEAN_COLUMNS_BY_TABLE = {
852
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
853
+ behaviors: /* @__PURE__ */ new Set(["active"]),
854
+ notifications: /* @__PURE__ */ new Set(["read"]),
855
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
856
+ };
857
+ BOOLEAN_COLUMN_NAMES = new Set(
858
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
859
+ );
860
+ IMMEDIATE_FALLBACK_PATTERNS = [
861
+ /\bPRAGMA\b/i,
862
+ /\bsqlite_master\b/i,
863
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
864
+ /\bMATCH\b/i,
865
+ /\bvector_distance_cos\s*\(/i,
866
+ /\bjson_extract\s*\(/i,
867
+ /\bjulianday\s*\(/i,
868
+ /\bstrftime\s*\(/i,
869
+ /\blast_insert_rowid\s*\(/i
870
+ ];
871
+ prismaClientPromise = null;
872
+ compatibilityBootstrapPromise = null;
288
873
  }
289
874
  });
290
875
 
291
876
  // src/lib/database.ts
292
877
  import { createClient } from "@libsql/client";
293
878
  async function initDatabase(config) {
879
+ if (_walCheckpointTimer) {
880
+ clearInterval(_walCheckpointTimer);
881
+ _walCheckpointTimer = null;
882
+ }
883
+ if (_daemonClient) {
884
+ _daemonClient.close();
885
+ _daemonClient = null;
886
+ }
887
+ if (_adapterClient && _adapterClient !== _resilientClient) {
888
+ _adapterClient.close();
889
+ }
890
+ _adapterClient = null;
294
891
  if (_client) {
295
892
  _client.close();
296
893
  _client = null;
@@ -304,6 +901,7 @@ async function initDatabase(config) {
304
901
  }
305
902
  _client = createClient(opts);
306
903
  _resilientClient = wrapWithRetry(_client);
904
+ _adapterClient = _resilientClient;
307
905
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
308
906
  });
309
907
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -314,11 +912,17 @@ async function initDatabase(config) {
314
912
  });
315
913
  }, 3e4);
316
914
  _walCheckpointTimer.unref();
915
+ if (process.env.DATABASE_URL) {
916
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
917
+ }
317
918
  }
318
919
  function getClient() {
319
- if (!_resilientClient) {
920
+ if (!_adapterClient) {
320
921
  throw new Error("Database client not initialized. Call initDatabase() first.");
321
922
  }
923
+ if (process.env.DATABASE_URL) {
924
+ return _adapterClient;
925
+ }
322
926
  if (process.env.EXE_IS_DAEMON === "1") {
323
927
  return _resilientClient;
324
928
  }
@@ -1258,16 +1862,18 @@ async function ensureSchema() {
1258
1862
  }
1259
1863
  }
1260
1864
  }
1261
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
1865
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1262
1866
  var init_database = __esm({
1263
1867
  "src/lib/database.ts"() {
1264
1868
  "use strict";
1265
1869
  init_db_retry();
1266
1870
  init_employees();
1871
+ init_database_adapter();
1267
1872
  _client = null;
1268
1873
  _resilientClient = null;
1269
1874
  _walCheckpointTimer = null;
1270
1875
  _daemonClient = null;
1876
+ _adapterClient = null;
1271
1877
  initTurso = initDatabase;
1272
1878
  }
1273
1879
  });
@@ -1285,7 +1891,7 @@ __export(shard_manager_exports, {
1285
1891
  listShards: () => listShards,
1286
1892
  shardExists: () => shardExists
1287
1893
  });
1288
- import path4 from "path";
1894
+ import path5 from "path";
1289
1895
  import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1290
1896
  import { createClient as createClient2 } from "@libsql/client";
1291
1897
  function initShardManager(encryptionKey) {
@@ -1311,7 +1917,7 @@ function getShardClient(projectName) {
1311
1917
  }
1312
1918
  const cached = _shards.get(safeName);
1313
1919
  if (cached) return cached;
1314
- const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1920
+ const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
1315
1921
  const client = createClient2({
1316
1922
  url: `file:${dbPath}`,
1317
1923
  encryptionKey: _encryptionKey
@@ -1321,7 +1927,7 @@ function getShardClient(projectName) {
1321
1927
  }
1322
1928
  function shardExists(projectName) {
1323
1929
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1324
- return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1930
+ return existsSync4(path5.join(SHARDS_DIR, `${safeName}.db`));
1325
1931
  }
1326
1932
  function listShards() {
1327
1933
  if (!existsSync4(SHARDS_DIR)) return [];
@@ -1398,7 +2004,23 @@ async function ensureShardSchema(client) {
1398
2004
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1399
2005
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1400
2006
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1401
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
2007
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2008
+ // Metadata enrichment columns (must match database.ts)
2009
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
2010
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
2011
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
2012
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2013
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2014
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2015
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
2016
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2017
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2018
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2019
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2020
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
2021
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
2022
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
2023
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1402
2024
  ]) {
1403
2025
  try {
1404
2026
  await client.execute(col);
@@ -1510,7 +2132,7 @@ var init_shard_manager = __esm({
1510
2132
  "src/lib/shard-manager.ts"() {
1511
2133
  "use strict";
1512
2134
  init_config();
1513
- SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
2135
+ SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
1514
2136
  _shards = /* @__PURE__ */ new Map();
1515
2137
  _encryptionKey = null;
1516
2138
  _shardingEnabled = false;
@@ -1706,11 +2328,11 @@ ${p.content}`).join("\n\n");
1706
2328
 
1707
2329
  // src/lib/exe-daemon-client.ts
1708
2330
  import net from "net";
1709
- import os4 from "os";
2331
+ import os5 from "os";
1710
2332
  import { spawn } from "child_process";
1711
2333
  import { randomUUID as randomUUID2 } from "crypto";
1712
2334
  import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
1713
- import path5 from "path";
2335
+ import path6 from "path";
1714
2336
  import { fileURLToPath } from "url";
1715
2337
  function handleData(chunk) {
1716
2338
  _buffer += chunk.toString();
@@ -1761,17 +2383,17 @@ function cleanupStaleFiles() {
1761
2383
  }
1762
2384
  }
1763
2385
  function findPackageRoot() {
1764
- let dir = path5.dirname(fileURLToPath(import.meta.url));
1765
- const { root } = path5.parse(dir);
2386
+ let dir = path6.dirname(fileURLToPath(import.meta.url));
2387
+ const { root } = path6.parse(dir);
1766
2388
  while (dir !== root) {
1767
- if (existsSync5(path5.join(dir, "package.json"))) return dir;
1768
- dir = path5.dirname(dir);
2389
+ if (existsSync5(path6.join(dir, "package.json"))) return dir;
2390
+ dir = path6.dirname(dir);
1769
2391
  }
1770
2392
  return null;
1771
2393
  }
1772
2394
  function spawnDaemon() {
1773
- const freeGB = os4.freemem() / (1024 * 1024 * 1024);
1774
- const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
2395
+ const freeGB = os5.freemem() / (1024 * 1024 * 1024);
2396
+ const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
1775
2397
  if (totalGB <= 8) {
1776
2398
  process.stderr.write(
1777
2399
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -1791,7 +2413,7 @@ function spawnDaemon() {
1791
2413
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
1792
2414
  return;
1793
2415
  }
1794
- const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
2416
+ const daemonPath = path6.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1795
2417
  if (!existsSync5(daemonPath)) {
1796
2418
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1797
2419
  `);
@@ -1800,7 +2422,7 @@ function spawnDaemon() {
1800
2422
  const resolvedPath = daemonPath;
1801
2423
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1802
2424
  `);
1803
- const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
2425
+ const logPath = path6.join(path6.dirname(SOCKET_PATH), "exed.log");
1804
2426
  let stderrFd = "ignore";
1805
2427
  try {
1806
2428
  stderrFd = openSync(logPath, "a");
@@ -1951,83 +2573,132 @@ async function pingDaemon() {
1951
2573
  return null;
1952
2574
  }
1953
2575
  function killAndRespawnDaemon() {
1954
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
1955
- if (existsSync5(PID_PATH)) {
1956
- try {
1957
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
1958
- if (pid > 0) {
1959
- try {
1960
- process.kill(pid, "SIGKILL");
1961
- } catch {
2576
+ if (!acquireSpawnLock()) {
2577
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
2578
+ if (_socket) {
2579
+ _socket.destroy();
2580
+ _socket = null;
2581
+ }
2582
+ _connected = false;
2583
+ _buffer = "";
2584
+ return;
2585
+ }
2586
+ try {
2587
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
2588
+ if (existsSync5(PID_PATH)) {
2589
+ try {
2590
+ const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
2591
+ if (pid > 0) {
2592
+ try {
2593
+ process.kill(pid, "SIGKILL");
2594
+ } catch {
2595
+ }
1962
2596
  }
2597
+ } catch {
1963
2598
  }
2599
+ }
2600
+ if (_socket) {
2601
+ _socket.destroy();
2602
+ _socket = null;
2603
+ }
2604
+ _connected = false;
2605
+ _buffer = "";
2606
+ try {
2607
+ unlinkSync2(PID_PATH);
1964
2608
  } catch {
1965
2609
  }
2610
+ try {
2611
+ unlinkSync2(SOCKET_PATH);
2612
+ } catch {
2613
+ }
2614
+ spawnDaemon();
2615
+ } finally {
2616
+ releaseSpawnLock();
1966
2617
  }
1967
- if (_socket) {
1968
- _socket.destroy();
1969
- _socket = null;
1970
- }
1971
- _connected = false;
1972
- _buffer = "";
2618
+ }
2619
+ function isDaemonTooYoung() {
1973
2620
  try {
1974
- unlinkSync2(PID_PATH);
2621
+ const stat2 = statSync(PID_PATH);
2622
+ return Date.now() - stat2.mtimeMs < MIN_DAEMON_AGE_MS;
1975
2623
  } catch {
2624
+ return false;
1976
2625
  }
1977
- try {
1978
- unlinkSync2(SOCKET_PATH);
1979
- } catch {
2626
+ }
2627
+ async function retryThenRestart(doRequest, label) {
2628
+ const result = await doRequest();
2629
+ if (!result.error) {
2630
+ _consecutiveFailures = 0;
2631
+ return result;
2632
+ }
2633
+ _consecutiveFailures++;
2634
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
2635
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
2636
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
2637
+ `);
2638
+ await new Promise((r) => setTimeout(r, delayMs));
2639
+ if (!_connected) {
2640
+ if (!await connectToSocket()) continue;
2641
+ }
2642
+ const retry = await doRequest();
2643
+ if (!retry.error) {
2644
+ _consecutiveFailures = 0;
2645
+ return retry;
2646
+ }
2647
+ _consecutiveFailures++;
2648
+ }
2649
+ if (isDaemonTooYoung()) {
2650
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
2651
+ `);
2652
+ return { error: result.error };
2653
+ }
2654
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
2655
+ `);
2656
+ killAndRespawnDaemon();
2657
+ const start = Date.now();
2658
+ let delay2 = 200;
2659
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2660
+ await new Promise((r) => setTimeout(r, delay2));
2661
+ if (await connectToSocket()) break;
2662
+ delay2 = Math.min(delay2 * 2, 3e3);
1980
2663
  }
1981
- spawnDaemon();
2664
+ if (!_connected) return { error: "Daemon restart failed" };
2665
+ const final = await doRequest();
2666
+ if (!final.error) _consecutiveFailures = 0;
2667
+ return final;
1982
2668
  }
1983
2669
  async function embedViaClient(text, priority = "high") {
1984
2670
  if (!_connected && !await connectEmbedDaemon()) return null;
1985
2671
  _requestCount++;
1986
2672
  if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1987
2673
  const health = await pingDaemon();
1988
- if (!health) {
2674
+ if (!health && !isDaemonTooYoung()) {
1989
2675
  process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1990
2676
  `);
1991
2677
  killAndRespawnDaemon();
1992
2678
  const start = Date.now();
1993
- let delay2 = 200;
2679
+ let d = 200;
1994
2680
  while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1995
- await new Promise((r) => setTimeout(r, delay2));
2681
+ await new Promise((r) => setTimeout(r, d));
1996
2682
  if (await connectToSocket()) break;
1997
- delay2 = Math.min(delay2 * 2, 3e3);
2683
+ d = Math.min(d * 2, 3e3);
1998
2684
  }
1999
2685
  if (!_connected) return null;
2000
2686
  }
2001
2687
  }
2002
- const result = await sendRequest([text], priority);
2003
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
2004
- if (result.error) {
2005
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
2006
- `);
2007
- killAndRespawnDaemon();
2008
- const start = Date.now();
2009
- let delay2 = 200;
2010
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
2011
- await new Promise((r) => setTimeout(r, delay2));
2012
- if (await connectToSocket()) break;
2013
- delay2 = Math.min(delay2 * 2, 3e3);
2014
- }
2015
- if (!_connected) return null;
2016
- const retry = await sendRequest([text], priority);
2017
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
2018
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
2019
- `);
2020
- }
2021
- return null;
2688
+ const result = await retryThenRestart(
2689
+ () => sendRequest([text], priority),
2690
+ "Embed"
2691
+ );
2692
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
2022
2693
  }
2023
- var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending, MAX_BUFFER;
2694
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
2024
2695
  var init_exe_daemon_client = __esm({
2025
2696
  "src/lib/exe-daemon-client.ts"() {
2026
2697
  "use strict";
2027
2698
  init_config();
2028
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
2029
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
2030
- SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
2699
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path6.join(EXE_AI_DIR, "exed.sock");
2700
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path6.join(EXE_AI_DIR, "exed.pid");
2701
+ SPAWN_LOCK_PATH = path6.join(EXE_AI_DIR, "exed-spawn.lock");
2031
2702
  SPAWN_LOCK_STALE_MS = 3e4;
2032
2703
  CONNECT_TIMEOUT_MS = 15e3;
2033
2704
  REQUEST_TIMEOUT_MS = 3e4;
@@ -2035,7 +2706,11 @@ var init_exe_daemon_client = __esm({
2035
2706
  _connected = false;
2036
2707
  _buffer = "";
2037
2708
  _requestCount = 0;
2709
+ _consecutiveFailures = 0;
2038
2710
  HEALTH_CHECK_INTERVAL = 100;
2711
+ MAX_RETRIES_BEFORE_RESTART = 3;
2712
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
2713
+ MIN_DAEMON_AGE_MS = 3e4;
2039
2714
  _pending = /* @__PURE__ */ new Map();
2040
2715
  MAX_BUFFER = 1e7;
2041
2716
  }
@@ -2045,7 +2720,7 @@ var init_exe_daemon_client = __esm({
2045
2720
  import crypto from "crypto";
2046
2721
  import { createReadStream } from "fs";
2047
2722
  import { readdir, stat } from "fs/promises";
2048
- import path6 from "path";
2723
+ import path7 from "path";
2049
2724
  import { createInterface } from "readline";
2050
2725
  import { homedir } from "os";
2051
2726
 
@@ -2061,15 +2736,15 @@ init_database();
2061
2736
  // src/lib/keychain.ts
2062
2737
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2063
2738
  import { existsSync as existsSync3 } from "fs";
2064
- import path3 from "path";
2065
- import os3 from "os";
2739
+ import path4 from "path";
2740
+ import os4 from "os";
2066
2741
  var SERVICE = "exe-mem";
2067
2742
  var ACCOUNT = "master-key";
2068
2743
  function getKeyDir() {
2069
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
2744
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2070
2745
  }
2071
2746
  function getKeyPath() {
2072
- return path3.join(getKeyDir(), "master.key");
2747
+ return path4.join(getKeyDir(), "master.key");
2073
2748
  }
2074
2749
  async function tryKeytar() {
2075
2750
  try {
@@ -2092,7 +2767,7 @@ async function getMasterKey() {
2092
2767
  const keyPath = getKeyPath();
2093
2768
  if (!existsSync3(keyPath)) {
2094
2769
  process.stderr.write(
2095
- `[keychain] Key not found at ${keyPath} (HOME=${os3.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2770
+ `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2096
2771
  `
2097
2772
  );
2098
2773
  return null;
@@ -2540,7 +3215,7 @@ var SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1e3;
2540
3215
  process.env.EXE_EMBED_PRIORITY = "low";
2541
3216
  var MAX_WALK_DEPTH = 10;
2542
3217
  async function findRecentJsonlFiles() {
2543
- const projectsDir = path6.join(homedir(), ".claude", "projects");
3218
+ const projectsDir = path7.join(homedir(), ".claude", "projects");
2544
3219
  const cutoff = Date.now() - SEVEN_DAYS_MS;
2545
3220
  const files = [];
2546
3221
  async function walk(dir, depth = 0) {
@@ -2552,7 +3227,7 @@ async function findRecentJsonlFiles() {
2552
3227
  return;
2553
3228
  }
2554
3229
  for (const entry of entries) {
2555
- const full = path6.join(dir, entry.name);
3230
+ const full = path7.join(dir, entry.name);
2556
3231
  if (entry.isDirectory()) {
2557
3232
  await walk(full, depth + 1);
2558
3233
  } else if (entry.name.endsWith(".jsonl")) {
@@ -2568,9 +3243,9 @@ async function findRecentJsonlFiles() {
2568
3243
  return files;
2569
3244
  }
2570
3245
  function projectNameFromPath(filePath) {
2571
- const projectsDir = path6.join(homedir(), ".claude", "projects");
2572
- const relative = path6.relative(projectsDir, filePath);
2573
- const projectDir = relative.split(path6.sep)[0] ?? "";
3246
+ const projectsDir = path7.join(homedir(), ".claude", "projects");
3247
+ const relative = path7.relative(projectsDir, filePath);
3248
+ const projectDir = relative.split(path7.sep)[0] ?? "";
2574
3249
  const homeEncoded = homedir().replaceAll("/", "-");
2575
3250
  if (projectDir.startsWith(homeEncoded + "-")) {
2576
3251
  return projectDir.slice(homeEncoded.length + 1);
@@ -2646,7 +3321,7 @@ async function processFile(filePath, seenHashes, daemonConnected, stats) {
2646
3321
  continue;
2647
3322
  }
2648
3323
  seenHashes.add(hash);
2649
- const resolvedProject = fileCwd ? path6.basename(fileCwd) : fallbackProject;
3324
+ const resolvedProject = fileCwd ? path7.basename(fileCwd) : fallbackProject;
2650
3325
  let vector = null;
2651
3326
  if (daemonConnected) {
2652
3327
  try {