@askexenow/exe-os 0.9.7 → 0.9.9

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 (101) hide show
  1. package/dist/bin/backfill-conversations.js +953 -105
  2. package/dist/bin/backfill-responses.js +952 -104
  3. package/dist/bin/backfill-vectors.js +956 -108
  4. package/dist/bin/cleanup-stale-review-tasks.js +802 -58
  5. package/dist/bin/cli.js +2292 -1070
  6. package/dist/bin/exe-agent-config.js +157 -101
  7. package/dist/bin/exe-agent.js +55 -29
  8. package/dist/bin/exe-assign.js +940 -92
  9. package/dist/bin/exe-boot.js +1424 -442
  10. package/dist/bin/exe-call.js +240 -141
  11. package/dist/bin/exe-cloud.js +198 -70
  12. package/dist/bin/exe-dispatch.js +951 -192
  13. package/dist/bin/exe-doctor.js +791 -51
  14. package/dist/bin/exe-export-behaviors.js +790 -42
  15. package/dist/bin/exe-forget.js +771 -31
  16. package/dist/bin/exe-gateway.js +1592 -521
  17. package/dist/bin/exe-heartbeat.js +850 -109
  18. package/dist/bin/exe-kill.js +783 -35
  19. package/dist/bin/exe-launch-agent.js +1030 -107
  20. package/dist/bin/exe-link.js +916 -110
  21. package/dist/bin/exe-new-employee.js +526 -217
  22. package/dist/bin/exe-pending-messages.js +1046 -62
  23. package/dist/bin/exe-pending-notifications.js +1318 -111
  24. package/dist/bin/exe-pending-reviews.js +1040 -72
  25. package/dist/bin/exe-rename.js +772 -59
  26. package/dist/bin/exe-review.js +772 -32
  27. package/dist/bin/exe-search.js +982 -128
  28. package/dist/bin/exe-session-cleanup.js +1180 -306
  29. package/dist/bin/exe-settings.js +185 -105
  30. package/dist/bin/exe-start-codex.js +886 -132
  31. package/dist/bin/exe-start-opencode.js +873 -119
  32. package/dist/bin/exe-status.js +803 -59
  33. package/dist/bin/exe-team.js +772 -32
  34. package/dist/bin/git-sweep.js +1046 -223
  35. package/dist/bin/graph-backfill.js +779 -31
  36. package/dist/bin/graph-export.js +785 -37
  37. package/dist/bin/install.js +632 -200
  38. package/dist/bin/scan-tasks.js +1055 -232
  39. package/dist/bin/setup.js +1419 -320
  40. package/dist/bin/shard-migrate.js +783 -35
  41. package/dist/bin/update.js +138 -49
  42. package/dist/bin/wiki-sync.js +782 -34
  43. package/dist/gateway/index.js +1444 -449
  44. package/dist/hooks/bug-report-worker.js +1141 -269
  45. package/dist/hooks/codex-stop-task-finalizer.js +4678 -0
  46. package/dist/hooks/commit-complete.js +1044 -221
  47. package/dist/hooks/error-recall.js +989 -135
  48. package/dist/hooks/exe-heartbeat-hook.js +99 -75
  49. package/dist/hooks/ingest-worker.js +4176 -3226
  50. package/dist/hooks/ingest.js +920 -168
  51. package/dist/hooks/instructions-loaded.js +874 -70
  52. package/dist/hooks/notification.js +860 -56
  53. package/dist/hooks/post-compact.js +881 -73
  54. package/dist/hooks/pre-compact.js +1050 -227
  55. package/dist/hooks/pre-tool-use.js +1084 -159
  56. package/dist/hooks/prompt-ingest-worker.js +1089 -164
  57. package/dist/hooks/prompt-submit.js +1469 -515
  58. package/dist/hooks/response-ingest-worker.js +1104 -179
  59. package/dist/hooks/session-end.js +1085 -251
  60. package/dist/hooks/session-start.js +1241 -231
  61. package/dist/hooks/stop.js +935 -109
  62. package/dist/hooks/subagent-stop.js +881 -73
  63. package/dist/hooks/summary-worker.js +1323 -307
  64. package/dist/index.js +1449 -452
  65. package/dist/lib/agent-config.js +28 -6
  66. package/dist/lib/cloud-sync.js +909 -115
  67. package/dist/lib/config.js +30 -10
  68. package/dist/lib/consolidation.js +42 -9
  69. package/dist/lib/database.js +739 -33
  70. package/dist/lib/db-daemon-client.js +73 -19
  71. package/dist/lib/db.js +2359 -0
  72. package/dist/lib/device-registry.js +760 -47
  73. package/dist/lib/embedder.js +201 -73
  74. package/dist/lib/employee-templates.js +30 -4
  75. package/dist/lib/employees.js +290 -86
  76. package/dist/lib/exe-daemon-client.js +187 -83
  77. package/dist/lib/exe-daemon.js +1696 -616
  78. package/dist/lib/hybrid-search.js +982 -128
  79. package/dist/lib/identity.js +43 -13
  80. package/dist/lib/license.js +133 -48
  81. package/dist/lib/messaging.js +167 -80
  82. package/dist/lib/reminders.js +35 -5
  83. package/dist/lib/schedules.js +772 -32
  84. package/dist/lib/skill-learning.js +54 -7
  85. package/dist/lib/store.js +779 -31
  86. package/dist/lib/task-router.js +94 -73
  87. package/dist/lib/tasks.js +298 -225
  88. package/dist/lib/tmux-routing.js +246 -172
  89. package/dist/lib/token-spend.js +52 -14
  90. package/dist/mcp/server.js +2893 -850
  91. package/dist/mcp/tools/complete-reminder.js +35 -5
  92. package/dist/mcp/tools/create-reminder.js +35 -5
  93. package/dist/mcp/tools/create-task.js +507 -323
  94. package/dist/mcp/tools/deactivate-behavior.js +40 -10
  95. package/dist/mcp/tools/list-reminders.js +35 -5
  96. package/dist/mcp/tools/list-tasks.js +277 -104
  97. package/dist/mcp/tools/send-message.js +129 -56
  98. package/dist/mcp/tools/update-task.js +1864 -188
  99. package/dist/runtime/index.js +1083 -259
  100. package/dist/tui/App.js +1501 -434
  101. package/package.json +3 -2
@@ -19,6 +19,44 @@ var __copyProps = (to, from, except, desc) => {
19
19
  };
20
20
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
21
 
22
+ // src/lib/secure-files.ts
23
+ import { chmodSync, existsSync, mkdirSync } from "fs";
24
+ import { chmod, mkdir } from "fs/promises";
25
+ async function ensurePrivateDir(dirPath) {
26
+ await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
27
+ try {
28
+ await chmod(dirPath, PRIVATE_DIR_MODE);
29
+ } catch {
30
+ }
31
+ }
32
+ function ensurePrivateDirSync(dirPath) {
33
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
34
+ try {
35
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
36
+ } catch {
37
+ }
38
+ }
39
+ async function enforcePrivateFile(filePath) {
40
+ try {
41
+ await chmod(filePath, PRIVATE_FILE_MODE);
42
+ } catch {
43
+ }
44
+ }
45
+ function enforcePrivateFileSync(filePath) {
46
+ try {
47
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
48
+ } catch {
49
+ }
50
+ }
51
+ var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
52
+ var init_secure_files = __esm({
53
+ "src/lib/secure-files.ts"() {
54
+ "use strict";
55
+ PRIVATE_DIR_MODE = 448;
56
+ PRIVATE_FILE_MODE = 384;
57
+ }
58
+ });
59
+
22
60
  // src/lib/config.ts
23
61
  var config_exports = {};
24
62
  __export(config_exports, {
@@ -35,8 +73,8 @@ __export(config_exports, {
35
73
  migrateConfig: () => migrateConfig,
36
74
  saveConfig: () => saveConfig
37
75
  });
38
- import { readFile, writeFile, mkdir, chmod } from "fs/promises";
39
- import { readFileSync, existsSync, renameSync } from "fs";
76
+ import { readFile, writeFile } from "fs/promises";
77
+ import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
40
78
  import path from "path";
41
79
  import os from "os";
42
80
  function resolveDataDir() {
@@ -44,7 +82,7 @@ function resolveDataDir() {
44
82
  if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
45
83
  const newDir = path.join(os.homedir(), ".exe-os");
46
84
  const legacyDir = path.join(os.homedir(), ".exe-mem");
47
- if (!existsSync(newDir) && existsSync(legacyDir)) {
85
+ if (!existsSync2(newDir) && existsSync2(legacyDir)) {
48
86
  try {
49
87
  renameSync(legacyDir, newDir);
50
88
  process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
@@ -107,9 +145,9 @@ function normalizeAutoUpdate(raw) {
107
145
  }
108
146
  async function loadConfig() {
109
147
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
110
- await mkdir(dir, { recursive: true });
148
+ await ensurePrivateDir(dir);
111
149
  const configPath = path.join(dir, "config.json");
112
- if (!existsSync(configPath)) {
150
+ if (!existsSync2(configPath)) {
113
151
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
114
152
  }
115
153
  const raw = await readFile(configPath, "utf-8");
@@ -122,6 +160,7 @@ async function loadConfig() {
122
160
  `);
123
161
  try {
124
162
  await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
163
+ await enforcePrivateFile(configPath);
125
164
  } catch {
126
165
  }
127
166
  }
@@ -140,7 +179,7 @@ async function loadConfig() {
140
179
  function loadConfigSync() {
141
180
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
142
181
  const configPath = path.join(dir, "config.json");
143
- if (!existsSync(configPath)) {
182
+ if (!existsSync2(configPath)) {
144
183
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
145
184
  }
146
185
  try {
@@ -158,12 +197,10 @@ function loadConfigSync() {
158
197
  }
159
198
  async function saveConfig(config) {
160
199
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
161
- await mkdir(dir, { recursive: true });
200
+ await ensurePrivateDir(dir);
162
201
  const configPath = path.join(dir, "config.json");
163
202
  await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
164
- if (config.cloud?.apiKey) {
165
- await chmod(configPath, 384);
166
- }
203
+ await enforcePrivateFile(configPath);
167
204
  }
168
205
  async function loadConfigFrom(configPath) {
169
206
  const raw = await readFile(configPath, "utf-8");
@@ -183,6 +220,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
183
220
  var init_config = __esm({
184
221
  "src/lib/config.ts"() {
185
222
  "use strict";
223
+ init_secure_files();
186
224
  EXE_AI_DIR = resolveDataDir();
187
225
  DB_PATH = path.join(EXE_AI_DIR, "memories.db");
188
226
  MODELS_DIR = path.join(EXE_AI_DIR, "models");
@@ -323,6 +361,120 @@ var init_db_retry = __esm({
323
361
  }
324
362
  });
325
363
 
364
+ // src/lib/runtime-table.ts
365
+ var RUNTIME_TABLE, DEFAULT_RUNTIME;
366
+ var init_runtime_table = __esm({
367
+ "src/lib/runtime-table.ts"() {
368
+ "use strict";
369
+ RUNTIME_TABLE = {
370
+ codex: {
371
+ binary: "codex",
372
+ launchMode: "interactive",
373
+ autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
374
+ inlineFlag: "--no-alt-screen",
375
+ apiKeyEnv: "OPENAI_API_KEY",
376
+ defaultModel: "gpt-5.4"
377
+ },
378
+ opencode: {
379
+ binary: "opencode",
380
+ launchMode: "exec",
381
+ autoApproveFlag: "--dangerously-skip-permissions",
382
+ inlineFlag: "",
383
+ apiKeyEnv: "ANTHROPIC_API_KEY",
384
+ defaultModel: "anthropic/claude-sonnet-4-6"
385
+ }
386
+ };
387
+ DEFAULT_RUNTIME = "claude";
388
+ }
389
+ });
390
+
391
+ // src/lib/agent-config.ts
392
+ var agent_config_exports = {};
393
+ __export(agent_config_exports, {
394
+ AGENT_CONFIG_PATH: () => AGENT_CONFIG_PATH,
395
+ DEFAULT_MODELS: () => DEFAULT_MODELS,
396
+ KNOWN_RUNTIMES: () => KNOWN_RUNTIMES,
397
+ RUNTIME_LABELS: () => RUNTIME_LABELS,
398
+ clearAgentRuntime: () => clearAgentRuntime,
399
+ getAgentRuntime: () => getAgentRuntime,
400
+ loadAgentConfig: () => loadAgentConfig,
401
+ saveAgentConfig: () => saveAgentConfig,
402
+ setAgentRuntime: () => setAgentRuntime
403
+ });
404
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync3 } from "fs";
405
+ import path2 from "path";
406
+ function loadAgentConfig() {
407
+ if (!existsSync3(AGENT_CONFIG_PATH)) return {};
408
+ try {
409
+ return JSON.parse(readFileSync2(AGENT_CONFIG_PATH, "utf-8"));
410
+ } catch {
411
+ return {};
412
+ }
413
+ }
414
+ function saveAgentConfig(config) {
415
+ const dir = path2.dirname(AGENT_CONFIG_PATH);
416
+ ensurePrivateDirSync(dir);
417
+ writeFileSync(AGENT_CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", "utf-8");
418
+ enforcePrivateFileSync(AGENT_CONFIG_PATH);
419
+ }
420
+ function getAgentRuntime(agentId) {
421
+ const config = loadAgentConfig();
422
+ const entry = config[agentId];
423
+ if (entry) return entry;
424
+ const orgDefault = config["default"];
425
+ if (orgDefault) return orgDefault;
426
+ return { runtime: DEFAULT_RUNTIME, model: DEFAULT_MODELS[DEFAULT_RUNTIME] };
427
+ }
428
+ function setAgentRuntime(agentId, runtime, model) {
429
+ const knownModels = KNOWN_RUNTIMES[runtime];
430
+ if (!knownModels) {
431
+ return {
432
+ ok: false,
433
+ error: `Unknown runtime "${runtime}". Valid: ${Object.keys(KNOWN_RUNTIMES).join(", ")}`
434
+ };
435
+ }
436
+ if (!knownModels.includes(model)) {
437
+ return {
438
+ ok: false,
439
+ error: `Unknown model "${model}" for runtime "${runtime}". Valid: ${knownModels.join(", ")}`
440
+ };
441
+ }
442
+ const config = loadAgentConfig();
443
+ config[agentId] = { runtime, model };
444
+ saveAgentConfig(config);
445
+ return { ok: true };
446
+ }
447
+ function clearAgentRuntime(agentId) {
448
+ const config = loadAgentConfig();
449
+ delete config[agentId];
450
+ saveAgentConfig(config);
451
+ }
452
+ var AGENT_CONFIG_PATH, KNOWN_RUNTIMES, RUNTIME_LABELS, DEFAULT_MODELS;
453
+ var init_agent_config = __esm({
454
+ "src/lib/agent-config.ts"() {
455
+ "use strict";
456
+ init_config();
457
+ init_runtime_table();
458
+ init_secure_files();
459
+ AGENT_CONFIG_PATH = path2.join(EXE_AI_DIR, "agent-config.json");
460
+ KNOWN_RUNTIMES = {
461
+ claude: ["claude-opus-4", "claude-sonnet-4", "claude-haiku-4.5"],
462
+ codex: ["gpt-5.4", "gpt-5.5", "gpt-5.3-codex-spark", "o3", "o4-mini"],
463
+ opencode: ["anthropic/claude-sonnet-4-6", "openai/gpt-5.4", "google/gemini-2.5-pro", "deepseek/deepseek-r3", "minimax/minimax-m2.5"]
464
+ };
465
+ RUNTIME_LABELS = {
466
+ claude: "Claude Code (Anthropic)",
467
+ codex: "Codex (OpenAI)",
468
+ opencode: "OpenCode (open source)"
469
+ };
470
+ DEFAULT_MODELS = {
471
+ claude: "claude-opus-4",
472
+ codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
473
+ opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
474
+ };
475
+ }
476
+ });
477
+
326
478
  // src/lib/employees.ts
327
479
  var employees_exports = {};
328
480
  __export(employees_exports, {
@@ -338,6 +490,7 @@ __export(employees_exports, {
338
490
  getEmployeeByRole: () => getEmployeeByRole,
339
491
  getEmployeeNamesByRole: () => getEmployeeNamesByRole,
340
492
  hasRole: () => hasRole,
493
+ hireEmployee: () => hireEmployee,
341
494
  isCoordinatorName: () => isCoordinatorName,
342
495
  isCoordinatorRole: () => isCoordinatorRole,
343
496
  isMultiInstance: () => isMultiInstance,
@@ -350,9 +503,9 @@ __export(employees_exports, {
350
503
  validateEmployeeName: () => validateEmployeeName
351
504
  });
352
505
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
353
- import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
506
+ import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync3, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
354
507
  import { execSync } from "child_process";
355
- import path2 from "path";
508
+ import path3 from "path";
356
509
  import os2 from "os";
357
510
  function normalizeRole(role) {
358
511
  return (role ?? "").trim().toLowerCase();
@@ -389,7 +542,7 @@ function validateEmployeeName(name) {
389
542
  return { valid: true };
390
543
  }
391
544
  async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
392
- if (!existsSync2(employeesPath)) {
545
+ if (!existsSync4(employeesPath)) {
393
546
  return [];
394
547
  }
395
548
  const raw = await readFile2(employeesPath, "utf-8");
@@ -400,13 +553,13 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
400
553
  }
401
554
  }
402
555
  async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
403
- await mkdir2(path2.dirname(employeesPath), { recursive: true });
556
+ await mkdir2(path3.dirname(employeesPath), { recursive: true });
404
557
  await writeFile2(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
405
558
  }
406
559
  function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
407
- if (!existsSync2(employeesPath)) return [];
560
+ if (!existsSync4(employeesPath)) return [];
408
561
  try {
409
- return JSON.parse(readFileSync2(employeesPath, "utf-8"));
562
+ return JSON.parse(readFileSync3(employeesPath, "utf-8"));
410
563
  } catch {
411
564
  return [];
412
565
  }
@@ -448,6 +601,52 @@ function addEmployee(employees, employee) {
448
601
  }
449
602
  return [...employees, normalized];
450
603
  }
604
+ function appendToCoordinatorTeam(employee) {
605
+ const coordinator = getCoordinatorEmployee(loadEmployeesSync());
606
+ if (!coordinator) return;
607
+ const idPath = path3.join(IDENTITY_DIR, `${coordinator.name}.md`);
608
+ if (!existsSync4(idPath)) return;
609
+ const content = readFileSync3(idPath, "utf-8");
610
+ if (content.includes(`**${capitalize(employee.name)}`)) return;
611
+ const teamMatch = content.match(TEAM_SECTION_RE);
612
+ if (!teamMatch || teamMatch.index === void 0) return;
613
+ const afterTeam = content.slice(teamMatch.index + teamMatch[0].length);
614
+ const nextHeading = afterTeam.match(/\n## /);
615
+ const entry = `
616
+ **${capitalize(employee.name)} (${employee.role}):** Newly hired. Update this description as the role develops.
617
+ `;
618
+ let updated;
619
+ if (nextHeading && nextHeading.index !== void 0) {
620
+ const insertAt = teamMatch.index + teamMatch[0].length + nextHeading.index;
621
+ updated = content.slice(0, insertAt) + entry + content.slice(insertAt);
622
+ } else {
623
+ updated = content.trimEnd() + "\n" + entry;
624
+ }
625
+ writeFileSync2(idPath, updated, "utf-8");
626
+ }
627
+ function capitalize(s) {
628
+ return s.charAt(0).toUpperCase() + s.slice(1);
629
+ }
630
+ async function hireEmployee(employee) {
631
+ const employees = await loadEmployees();
632
+ const updated = addEmployee(employees, employee);
633
+ await saveEmployees(updated);
634
+ try {
635
+ appendToCoordinatorTeam(employee);
636
+ } catch {
637
+ }
638
+ try {
639
+ const { loadAgentConfig: loadAgentConfig2, saveAgentConfig: saveAgentConfig2 } = await Promise.resolve().then(() => (init_agent_config(), agent_config_exports));
640
+ const config = loadAgentConfig2();
641
+ const name = employee.name.toLowerCase();
642
+ if (!config[name] && config["default"]) {
643
+ config[name] = { ...config["default"] };
644
+ saveAgentConfig2(config);
645
+ }
646
+ } catch {
647
+ }
648
+ return updated;
649
+ }
451
650
  async function normalizeRosterCase(rosterPath) {
452
651
  const employees = await loadEmployees(rosterPath);
453
652
  let changed = false;
@@ -457,14 +656,14 @@ async function normalizeRosterCase(rosterPath) {
457
656
  emp.name = emp.name.toLowerCase();
458
657
  changed = true;
459
658
  try {
460
- const identityDir = path2.join(os2.homedir(), ".exe-os", "identity");
461
- const oldPath = path2.join(identityDir, `${oldName}.md`);
462
- const newPath = path2.join(identityDir, `${emp.name}.md`);
463
- if (existsSync2(oldPath) && !existsSync2(newPath)) {
659
+ const identityDir = path3.join(os2.homedir(), ".exe-os", "identity");
660
+ const oldPath = path3.join(identityDir, `${oldName}.md`);
661
+ const newPath = path3.join(identityDir, `${emp.name}.md`);
662
+ if (existsSync4(oldPath) && !existsSync4(newPath)) {
464
663
  renameSync2(oldPath, newPath);
465
- } else if (existsSync2(oldPath) && oldPath !== newPath) {
466
- const content = readFileSync2(oldPath, "utf-8");
467
- writeFileSync(newPath, content, "utf-8");
664
+ } else if (existsSync4(oldPath) && oldPath !== newPath) {
665
+ const content = readFileSync3(oldPath, "utf-8");
666
+ writeFileSync2(newPath, content, "utf-8");
468
667
  if (oldPath.toLowerCase() !== newPath.toLowerCase()) {
469
668
  unlinkSync(oldPath);
470
669
  }
@@ -494,7 +693,7 @@ function registerBinSymlinks(name) {
494
693
  errors.push("Could not find 'exe-os' in PATH");
495
694
  return { created, skipped, errors };
496
695
  }
497
- const binDir = path2.dirname(exeBinPath);
696
+ const binDir = path3.dirname(exeBinPath);
498
697
  let target;
499
698
  try {
500
699
  target = readlinkSync(exeBinPath);
@@ -504,8 +703,8 @@ function registerBinSymlinks(name) {
504
703
  }
505
704
  for (const suffix of ["", "-opencode"]) {
506
705
  const linkName = `${name}${suffix}`;
507
- const linkPath = path2.join(binDir, linkName);
508
- if (existsSync2(linkPath)) {
706
+ const linkPath = path3.join(binDir, linkName);
707
+ if (existsSync4(linkPath)) {
509
708
  skipped.push(linkName);
510
709
  continue;
511
710
  }
@@ -518,25 +717,648 @@ function registerBinSymlinks(name) {
518
717
  }
519
718
  return { created, skipped, errors };
520
719
  }
521
- var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, MULTI_INSTANCE_ROLES;
720
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, MULTI_INSTANCE_ROLES, IDENTITY_DIR, TEAM_SECTION_RE;
522
721
  var init_employees = __esm({
523
722
  "src/lib/employees.ts"() {
524
723
  "use strict";
525
724
  init_config();
526
- EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
725
+ EMPLOYEES_PATH = path3.join(EXE_AI_DIR, "exe-employees.json");
527
726
  DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
528
727
  COORDINATOR_ROLE = "COO";
529
728
  MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
729
+ IDENTITY_DIR = path3.join(EXE_AI_DIR, "identity");
730
+ TEAM_SECTION_RE = /^## Team\b.*$/m;
731
+ }
732
+ });
733
+
734
+ // src/lib/database-adapter.ts
735
+ import os3 from "os";
736
+ import path4 from "path";
737
+ import { createRequire } from "module";
738
+ import { pathToFileURL } from "url";
739
+ function quotedIdentifier(identifier) {
740
+ return `"${identifier.replace(/"/g, '""')}"`;
741
+ }
742
+ function unqualifiedTableName(name) {
743
+ const raw = name.trim().replace(/^"|"$/g, "");
744
+ const parts = raw.split(".");
745
+ return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
746
+ }
747
+ function stripTrailingSemicolon(sql) {
748
+ return sql.trim().replace(/;+\s*$/u, "");
749
+ }
750
+ function appendClause(sql, clause) {
751
+ const trimmed = stripTrailingSemicolon(sql);
752
+ const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
753
+ if (!returningMatch) {
754
+ return `${trimmed}${clause}`;
755
+ }
756
+ const idx = returningMatch.index;
757
+ return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
758
+ }
759
+ function normalizeStatement(stmt) {
760
+ if (typeof stmt === "string") {
761
+ return { kind: "positional", sql: stmt, args: [] };
762
+ }
763
+ const sql = stmt.sql;
764
+ if (Array.isArray(stmt.args) || stmt.args === void 0) {
765
+ return { kind: "positional", sql, args: stmt.args ?? [] };
766
+ }
767
+ return { kind: "named", sql, args: stmt.args };
768
+ }
769
+ function rewriteBooleanLiterals(sql) {
770
+ let out = sql;
771
+ for (const column of BOOLEAN_COLUMN_NAMES) {
772
+ const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
773
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
774
+ out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
775
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
776
+ out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
777
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
778
+ out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
779
+ }
780
+ return out;
781
+ }
782
+ function rewriteInsertOrIgnore(sql) {
783
+ if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
784
+ return sql;
785
+ }
786
+ const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
787
+ return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
788
+ }
789
+ function rewriteInsertOrReplace(sql) {
790
+ const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
791
+ if (!match) {
792
+ return sql;
793
+ }
794
+ const rawTable = match[1];
795
+ const rawColumns = match[2];
796
+ const remainder = match[3];
797
+ const tableName = unqualifiedTableName(rawTable);
798
+ const conflictKeys = UPSERT_KEYS[tableName];
799
+ if (!conflictKeys?.length) {
800
+ return sql;
801
+ }
802
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
803
+ const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
804
+ const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
805
+ const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
806
+ return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
807
+ }
808
+ function rewriteSql(sql) {
809
+ let out = sql;
810
+ out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
811
+ out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
812
+ out = rewriteBooleanLiterals(out);
813
+ out = rewriteInsertOrReplace(out);
814
+ out = rewriteInsertOrIgnore(out);
815
+ return stripTrailingSemicolon(out);
816
+ }
817
+ function toBoolean(value) {
818
+ if (value === null || value === void 0) return value;
819
+ if (typeof value === "boolean") return value;
820
+ if (typeof value === "number") return value !== 0;
821
+ if (typeof value === "bigint") return value !== 0n;
822
+ if (typeof value === "string") {
823
+ const normalized = value.trim().toLowerCase();
824
+ if (normalized === "0" || normalized === "false") return false;
825
+ if (normalized === "1" || normalized === "true") return true;
826
+ }
827
+ return Boolean(value);
828
+ }
829
+ function countQuestionMarks(sql, end) {
830
+ let count = 0;
831
+ let inSingle = false;
832
+ let inDouble = false;
833
+ let inLineComment = false;
834
+ let inBlockComment = false;
835
+ for (let i = 0; i < end; i++) {
836
+ const ch = sql[i];
837
+ const next = sql[i + 1];
838
+ if (inLineComment) {
839
+ if (ch === "\n") inLineComment = false;
840
+ continue;
841
+ }
842
+ if (inBlockComment) {
843
+ if (ch === "*" && next === "/") {
844
+ inBlockComment = false;
845
+ i += 1;
846
+ }
847
+ continue;
848
+ }
849
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
850
+ inLineComment = true;
851
+ i += 1;
852
+ continue;
853
+ }
854
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
855
+ inBlockComment = true;
856
+ i += 1;
857
+ continue;
858
+ }
859
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
860
+ inSingle = !inSingle;
861
+ continue;
862
+ }
863
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
864
+ inDouble = !inDouble;
865
+ continue;
866
+ }
867
+ if (!inSingle && !inDouble && ch === "?") {
868
+ count += 1;
869
+ }
870
+ }
871
+ return count;
872
+ }
873
+ function findBooleanPlaceholderIndexes(sql) {
874
+ const indexes = /* @__PURE__ */ new Set();
875
+ for (const column of BOOLEAN_COLUMN_NAMES) {
876
+ const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
877
+ for (const match of sql.matchAll(pattern)) {
878
+ const matchText = match[0];
879
+ const qIndex = match.index + matchText.lastIndexOf("?");
880
+ indexes.add(countQuestionMarks(sql, qIndex + 1));
881
+ }
882
+ }
883
+ return indexes;
884
+ }
885
+ function coerceInsertBooleanArgs(sql, args) {
886
+ const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
887
+ if (!match) return;
888
+ const rawTable = match[1];
889
+ const rawColumns = match[2];
890
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
891
+ if (!boolColumns?.size) return;
892
+ const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
893
+ for (const [index, column] of columns.entries()) {
894
+ if (boolColumns.has(column) && index < args.length) {
895
+ args[index] = toBoolean(args[index]);
896
+ }
897
+ }
898
+ }
899
+ function coerceUpdateBooleanArgs(sql, args) {
900
+ const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
901
+ if (!match) return;
902
+ const rawTable = match[1];
903
+ const setClause = match[2];
904
+ const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
905
+ if (!boolColumns?.size) return;
906
+ const assignments = setClause.split(",");
907
+ let placeholderIndex = 0;
908
+ for (const assignment of assignments) {
909
+ if (!assignment.includes("?")) continue;
910
+ placeholderIndex += 1;
911
+ const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
912
+ if (colMatch && boolColumns.has(colMatch[1])) {
913
+ args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
914
+ }
915
+ }
916
+ }
917
+ function coerceBooleanArgs(sql, args) {
918
+ const nextArgs = [...args];
919
+ coerceInsertBooleanArgs(sql, nextArgs);
920
+ coerceUpdateBooleanArgs(sql, nextArgs);
921
+ const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
922
+ for (const index of placeholderIndexes) {
923
+ if (index > 0 && index <= nextArgs.length) {
924
+ nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
925
+ }
926
+ }
927
+ return nextArgs;
928
+ }
929
+ function convertQuestionMarksToDollarParams(sql) {
930
+ let out = "";
931
+ let placeholder = 0;
932
+ let inSingle = false;
933
+ let inDouble = false;
934
+ let inLineComment = false;
935
+ let inBlockComment = false;
936
+ for (let i = 0; i < sql.length; i++) {
937
+ const ch = sql[i];
938
+ const next = sql[i + 1];
939
+ if (inLineComment) {
940
+ out += ch;
941
+ if (ch === "\n") inLineComment = false;
942
+ continue;
943
+ }
944
+ if (inBlockComment) {
945
+ out += ch;
946
+ if (ch === "*" && next === "/") {
947
+ out += next;
948
+ inBlockComment = false;
949
+ i += 1;
950
+ }
951
+ continue;
952
+ }
953
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
954
+ out += ch + next;
955
+ inLineComment = true;
956
+ i += 1;
957
+ continue;
958
+ }
959
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
960
+ out += ch + next;
961
+ inBlockComment = true;
962
+ i += 1;
963
+ continue;
964
+ }
965
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
966
+ inSingle = !inSingle;
967
+ out += ch;
968
+ continue;
969
+ }
970
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
971
+ inDouble = !inDouble;
972
+ out += ch;
973
+ continue;
974
+ }
975
+ if (!inSingle && !inDouble && ch === "?") {
976
+ placeholder += 1;
977
+ out += `$${placeholder}`;
978
+ continue;
979
+ }
980
+ out += ch;
981
+ }
982
+ return out;
983
+ }
984
+ function translateStatementForPostgres(stmt) {
985
+ const normalized = normalizeStatement(stmt);
986
+ if (normalized.kind === "named") {
987
+ throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
988
+ }
989
+ const rewrittenSql = rewriteSql(normalized.sql);
990
+ const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
991
+ return {
992
+ sql: convertQuestionMarksToDollarParams(rewrittenSql),
993
+ args: coercedArgs
994
+ };
995
+ }
996
+ function shouldBypassPostgres(stmt) {
997
+ const normalized = normalizeStatement(stmt);
998
+ if (normalized.kind === "named") {
999
+ return true;
1000
+ }
1001
+ return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
1002
+ }
1003
+ function shouldFallbackOnError(error) {
1004
+ const message = error instanceof Error ? error.message : String(error);
1005
+ return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
1006
+ }
1007
+ function isReadQuery(sql) {
1008
+ const trimmed = sql.trimStart();
1009
+ return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
1010
+ }
1011
+ function buildRow(row, columns) {
1012
+ const values = columns.map((column) => row[column]);
1013
+ return Object.assign(values, row);
1014
+ }
1015
+ function buildResultSet(rows, rowsAffected = 0) {
1016
+ const columns = rows[0] ? Object.keys(rows[0]) : [];
1017
+ const resultRows = rows.map((row) => buildRow(row, columns));
1018
+ return {
1019
+ columns,
1020
+ columnTypes: columns.map(() => ""),
1021
+ rows: resultRows,
1022
+ rowsAffected,
1023
+ lastInsertRowid: void 0,
1024
+ toJSON() {
1025
+ return {
1026
+ columns,
1027
+ columnTypes: columns.map(() => ""),
1028
+ rows,
1029
+ rowsAffected,
1030
+ lastInsertRowid: void 0
1031
+ };
1032
+ }
1033
+ };
1034
+ }
1035
+ async function loadPrismaClient() {
1036
+ if (!prismaClientPromise) {
1037
+ prismaClientPromise = (async () => {
1038
+ const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
1039
+ if (explicitPath) {
1040
+ const module2 = await import(pathToFileURL(explicitPath).href);
1041
+ const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
1042
+ if (!PrismaClient2) {
1043
+ throw new Error(`No PrismaClient export found at ${explicitPath}`);
1044
+ }
1045
+ return new PrismaClient2();
1046
+ }
1047
+ const exeDbRoot = process.env.EXE_DB_ROOT ?? path4.join(os3.homedir(), "exe-db");
1048
+ const requireFromExeDb = createRequire(path4.join(exeDbRoot, "package.json"));
1049
+ const prismaEntry = requireFromExeDb.resolve("@prisma/client");
1050
+ const module = await import(pathToFileURL(prismaEntry).href);
1051
+ const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
1052
+ if (!PrismaClient) {
1053
+ throw new Error(`No PrismaClient export found in ${prismaEntry}`);
1054
+ }
1055
+ return new PrismaClient();
1056
+ })();
1057
+ }
1058
+ return prismaClientPromise;
1059
+ }
1060
+ async function ensureCompatibilityViews(prisma) {
1061
+ if (!compatibilityBootstrapPromise) {
1062
+ compatibilityBootstrapPromise = (async () => {
1063
+ for (const mapping of VIEW_MAPPINGS) {
1064
+ const relation = mapping.source.replace(/"/g, "");
1065
+ const rows = await prisma.$queryRawUnsafe(
1066
+ "SELECT to_regclass($1) AS regclass",
1067
+ relation
1068
+ );
1069
+ if (!rows[0]?.regclass) {
1070
+ continue;
1071
+ }
1072
+ await prisma.$executeRawUnsafe(
1073
+ `CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
1074
+ );
1075
+ }
1076
+ })();
1077
+ }
1078
+ return compatibilityBootstrapPromise;
1079
+ }
1080
+ async function executeOnPrisma(executor, stmt) {
1081
+ const translated = translateStatementForPostgres(stmt);
1082
+ if (isReadQuery(translated.sql)) {
1083
+ const rows = await executor.$queryRawUnsafe(
1084
+ translated.sql,
1085
+ ...translated.args
1086
+ );
1087
+ return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
1088
+ }
1089
+ const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
1090
+ return buildResultSet([], rowsAffected);
1091
+ }
1092
+ function splitSqlStatements(sql) {
1093
+ const parts = [];
1094
+ let current = "";
1095
+ let inSingle = false;
1096
+ let inDouble = false;
1097
+ let inLineComment = false;
1098
+ let inBlockComment = false;
1099
+ for (let i = 0; i < sql.length; i++) {
1100
+ const ch = sql[i];
1101
+ const next = sql[i + 1];
1102
+ if (inLineComment) {
1103
+ current += ch;
1104
+ if (ch === "\n") inLineComment = false;
1105
+ continue;
1106
+ }
1107
+ if (inBlockComment) {
1108
+ current += ch;
1109
+ if (ch === "*" && next === "/") {
1110
+ current += next;
1111
+ inBlockComment = false;
1112
+ i += 1;
1113
+ }
1114
+ continue;
1115
+ }
1116
+ if (!inSingle && !inDouble && ch === "-" && next === "-") {
1117
+ current += ch + next;
1118
+ inLineComment = true;
1119
+ i += 1;
1120
+ continue;
1121
+ }
1122
+ if (!inSingle && !inDouble && ch === "/" && next === "*") {
1123
+ current += ch + next;
1124
+ inBlockComment = true;
1125
+ i += 1;
1126
+ continue;
1127
+ }
1128
+ if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
1129
+ inSingle = !inSingle;
1130
+ current += ch;
1131
+ continue;
1132
+ }
1133
+ if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
1134
+ inDouble = !inDouble;
1135
+ current += ch;
1136
+ continue;
1137
+ }
1138
+ if (!inSingle && !inDouble && ch === ";") {
1139
+ if (current.trim()) {
1140
+ parts.push(current.trim());
1141
+ }
1142
+ current = "";
1143
+ continue;
1144
+ }
1145
+ current += ch;
1146
+ }
1147
+ if (current.trim()) {
1148
+ parts.push(current.trim());
1149
+ }
1150
+ return parts;
1151
+ }
1152
+ async function createPrismaDbAdapter(fallbackClient) {
1153
+ const prisma = await loadPrismaClient();
1154
+ await ensureCompatibilityViews(prisma);
1155
+ let closed = false;
1156
+ let adapter;
1157
+ const fallbackExecute = async (stmt, error) => {
1158
+ if (!fallbackClient) {
1159
+ if (error) throw error;
1160
+ throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
1161
+ }
1162
+ if (error) {
1163
+ process.stderr.write(
1164
+ `[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
1165
+ `
1166
+ );
1167
+ }
1168
+ return fallbackClient.execute(stmt);
1169
+ };
1170
+ adapter = {
1171
+ async execute(stmt) {
1172
+ if (shouldBypassPostgres(stmt)) {
1173
+ return fallbackExecute(stmt);
1174
+ }
1175
+ try {
1176
+ return await executeOnPrisma(prisma, stmt);
1177
+ } catch (error) {
1178
+ if (shouldFallbackOnError(error)) {
1179
+ return fallbackExecute(stmt, error);
1180
+ }
1181
+ throw error;
1182
+ }
1183
+ },
1184
+ async batch(stmts, mode) {
1185
+ if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
1186
+ if (!fallbackClient) {
1187
+ throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
1188
+ }
1189
+ return fallbackClient.batch(stmts, mode);
1190
+ }
1191
+ try {
1192
+ if (prisma.$transaction) {
1193
+ return await prisma.$transaction(async (tx) => {
1194
+ const results2 = [];
1195
+ for (const stmt of stmts) {
1196
+ results2.push(await executeOnPrisma(tx, stmt));
1197
+ }
1198
+ return results2;
1199
+ });
1200
+ }
1201
+ const results = [];
1202
+ for (const stmt of stmts) {
1203
+ results.push(await executeOnPrisma(prisma, stmt));
1204
+ }
1205
+ return results;
1206
+ } catch (error) {
1207
+ if (fallbackClient && shouldFallbackOnError(error)) {
1208
+ process.stderr.write(
1209
+ `[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
1210
+ `
1211
+ );
1212
+ return fallbackClient.batch(stmts, mode);
1213
+ }
1214
+ throw error;
1215
+ }
1216
+ },
1217
+ async migrate(stmts) {
1218
+ if (fallbackClient) {
1219
+ return fallbackClient.migrate(stmts);
1220
+ }
1221
+ return adapter.batch(stmts, "deferred");
1222
+ },
1223
+ async transaction(mode) {
1224
+ if (!fallbackClient) {
1225
+ throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
1226
+ }
1227
+ return fallbackClient.transaction(mode);
1228
+ },
1229
+ async executeMultiple(sql) {
1230
+ if (fallbackClient && shouldBypassPostgres(sql)) {
1231
+ return fallbackClient.executeMultiple(sql);
1232
+ }
1233
+ for (const statement of splitSqlStatements(sql)) {
1234
+ await adapter.execute(statement);
1235
+ }
1236
+ },
1237
+ async sync() {
1238
+ if (fallbackClient) {
1239
+ return fallbackClient.sync();
1240
+ }
1241
+ return { frame_no: 0, frames_synced: 0 };
1242
+ },
1243
+ close() {
1244
+ closed = true;
1245
+ prismaClientPromise = null;
1246
+ compatibilityBootstrapPromise = null;
1247
+ void prisma.$disconnect?.();
1248
+ },
1249
+ get closed() {
1250
+ return closed;
1251
+ },
1252
+ get protocol() {
1253
+ return "prisma-postgres";
1254
+ }
1255
+ };
1256
+ return adapter;
1257
+ }
1258
+ var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
1259
+ var init_database_adapter = __esm({
1260
+ "src/lib/database-adapter.ts"() {
1261
+ "use strict";
1262
+ VIEW_MAPPINGS = [
1263
+ { view: "memories", source: "memory.memory_records" },
1264
+ { view: "tasks", source: "memory.tasks" },
1265
+ { view: "behaviors", source: "memory.behaviors" },
1266
+ { view: "entities", source: "memory.entities" },
1267
+ { view: "relationships", source: "memory.relationships" },
1268
+ { view: "entity_memories", source: "memory.entity_memories" },
1269
+ { view: "entity_aliases", source: "memory.entity_aliases" },
1270
+ { view: "notifications", source: "memory.notifications" },
1271
+ { view: "messages", source: "memory.messages" },
1272
+ { view: "users", source: "wiki.users" },
1273
+ { view: "workspaces", source: "wiki.workspaces" },
1274
+ { view: "workspace_users", source: "wiki.workspace_users" },
1275
+ { view: "documents", source: "wiki.workspace_documents" },
1276
+ { view: "chats", source: "wiki.workspace_chats" }
1277
+ ];
1278
+ UPSERT_KEYS = {
1279
+ memories: ["id"],
1280
+ tasks: ["id"],
1281
+ behaviors: ["id"],
1282
+ entities: ["id"],
1283
+ relationships: ["id"],
1284
+ entity_aliases: ["alias"],
1285
+ notifications: ["id"],
1286
+ messages: ["id"],
1287
+ users: ["id"],
1288
+ workspaces: ["id"],
1289
+ workspace_users: ["id"],
1290
+ documents: ["id"],
1291
+ chats: ["id"]
1292
+ };
1293
+ BOOLEAN_COLUMNS_BY_TABLE = {
1294
+ memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
1295
+ behaviors: /* @__PURE__ */ new Set(["active"]),
1296
+ notifications: /* @__PURE__ */ new Set(["read"]),
1297
+ users: /* @__PURE__ */ new Set(["has_personal_memory"])
1298
+ };
1299
+ BOOLEAN_COLUMN_NAMES = new Set(
1300
+ Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
1301
+ );
1302
+ IMMEDIATE_FALLBACK_PATTERNS = [
1303
+ /\bPRAGMA\b/i,
1304
+ /\bsqlite_master\b/i,
1305
+ /(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
1306
+ /\bMATCH\b/i,
1307
+ /\bvector_distance_cos\s*\(/i,
1308
+ /\bjson_extract\s*\(/i,
1309
+ /\bjulianday\s*\(/i,
1310
+ /\bstrftime\s*\(/i,
1311
+ /\blast_insert_rowid\s*\(/i
1312
+ ];
1313
+ prismaClientPromise = null;
1314
+ compatibilityBootstrapPromise = null;
1315
+ }
1316
+ });
1317
+
1318
+ // src/lib/daemon-auth.ts
1319
+ import crypto from "crypto";
1320
+ import path5 from "path";
1321
+ import { existsSync as existsSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
1322
+ function normalizeToken(token) {
1323
+ if (!token) return null;
1324
+ const trimmed = token.trim();
1325
+ return trimmed.length > 0 ? trimmed : null;
1326
+ }
1327
+ function readDaemonToken() {
1328
+ try {
1329
+ if (!existsSync5(DAEMON_TOKEN_PATH)) return null;
1330
+ return normalizeToken(readFileSync4(DAEMON_TOKEN_PATH, "utf8"));
1331
+ } catch {
1332
+ return null;
1333
+ }
1334
+ }
1335
+ function ensureDaemonToken(seed) {
1336
+ const existing = readDaemonToken();
1337
+ if (existing) return existing;
1338
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
1339
+ ensurePrivateDirSync(EXE_AI_DIR);
1340
+ writeFileSync3(DAEMON_TOKEN_PATH, `${token}
1341
+ `, "utf8");
1342
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
1343
+ return token;
1344
+ }
1345
+ var DAEMON_TOKEN_PATH;
1346
+ var init_daemon_auth = __esm({
1347
+ "src/lib/daemon-auth.ts"() {
1348
+ "use strict";
1349
+ init_config();
1350
+ init_secure_files();
1351
+ DAEMON_TOKEN_PATH = path5.join(EXE_AI_DIR, "exed.token");
530
1352
  }
531
1353
  });
532
1354
 
533
1355
  // src/lib/exe-daemon-client.ts
534
1356
  import net from "net";
535
- import os3 from "os";
1357
+ import os4 from "os";
536
1358
  import { spawn } from "child_process";
537
1359
  import { randomUUID } from "crypto";
538
- import { existsSync as existsSync3, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
539
- import path3 from "path";
1360
+ import { existsSync as existsSync6, unlinkSync as unlinkSync2, readFileSync as readFileSync5, openSync, closeSync, statSync } from "fs";
1361
+ import path6 from "path";
540
1362
  import { fileURLToPath } from "url";
541
1363
  function handleData(chunk) {
542
1364
  _buffer += chunk.toString();
@@ -564,9 +1386,9 @@ function handleData(chunk) {
564
1386
  }
565
1387
  }
566
1388
  function cleanupStaleFiles() {
567
- if (existsSync3(PID_PATH)) {
1389
+ if (existsSync6(PID_PATH)) {
568
1390
  try {
569
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
1391
+ const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
570
1392
  if (pid > 0) {
571
1393
  try {
572
1394
  process.kill(pid, 0);
@@ -587,17 +1409,17 @@ function cleanupStaleFiles() {
587
1409
  }
588
1410
  }
589
1411
  function findPackageRoot() {
590
- let dir = path3.dirname(fileURLToPath(import.meta.url));
591
- const { root } = path3.parse(dir);
1412
+ let dir = path6.dirname(fileURLToPath(import.meta.url));
1413
+ const { root } = path6.parse(dir);
592
1414
  while (dir !== root) {
593
- if (existsSync3(path3.join(dir, "package.json"))) return dir;
594
- dir = path3.dirname(dir);
1415
+ if (existsSync6(path6.join(dir, "package.json"))) return dir;
1416
+ dir = path6.dirname(dir);
595
1417
  }
596
1418
  return null;
597
1419
  }
598
1420
  function spawnDaemon() {
599
- const freeGB = os3.freemem() / (1024 * 1024 * 1024);
600
- const totalGB = os3.totalmem() / (1024 * 1024 * 1024);
1421
+ const freeGB = os4.freemem() / (1024 * 1024 * 1024);
1422
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
601
1423
  if (totalGB <= 8) {
602
1424
  process.stderr.write(
603
1425
  `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
@@ -617,16 +1439,17 @@ function spawnDaemon() {
617
1439
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
618
1440
  return;
619
1441
  }
620
- const daemonPath = path3.join(pkgRoot, "dist", "lib", "exe-daemon.js");
621
- if (!existsSync3(daemonPath)) {
1442
+ const daemonPath = path6.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1443
+ if (!existsSync6(daemonPath)) {
622
1444
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
623
1445
  `);
624
1446
  return;
625
1447
  }
626
1448
  const resolvedPath = daemonPath;
1449
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
627
1450
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
628
1451
  `);
629
- const logPath = path3.join(path3.dirname(SOCKET_PATH), "exed.log");
1452
+ const logPath = path6.join(path6.dirname(SOCKET_PATH), "exed.log");
630
1453
  let stderrFd = "ignore";
631
1454
  try {
632
1455
  stderrFd = openSync(logPath, "a");
@@ -644,7 +1467,8 @@ function spawnDaemon() {
644
1467
  TMUX_PANE: void 0,
645
1468
  // Prevents resolveExeSession() from scoping to one session
646
1469
  EXE_DAEMON_SOCK: SOCKET_PATH,
647
- EXE_DAEMON_PID: PID_PATH
1470
+ EXE_DAEMON_PID: PID_PATH,
1471
+ [DAEMON_TOKEN_ENV]: daemonToken
648
1472
  }
649
1473
  });
650
1474
  child.unref();
@@ -754,13 +1578,14 @@ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
754
1578
  return;
755
1579
  }
756
1580
  const id = randomUUID();
1581
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
757
1582
  const timer = setTimeout(() => {
758
1583
  _pending.delete(id);
759
1584
  resolve({ error: "Request timeout" });
760
1585
  }, timeoutMs);
761
1586
  _pending.set(id, { resolve, timer });
762
1587
  try {
763
- _socket.write(JSON.stringify({ id, ...payload }) + "\n");
1588
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
764
1589
  } catch {
765
1590
  clearTimeout(timer);
766
1591
  _pending.delete(id);
@@ -777,74 +1602,123 @@ async function pingDaemon() {
777
1602
  return null;
778
1603
  }
779
1604
  function killAndRespawnDaemon() {
780
- process.stderr.write("[exed-client] Killing daemon for restart...\n");
781
- if (existsSync3(PID_PATH)) {
782
- try {
783
- const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
784
- if (pid > 0) {
785
- try {
786
- process.kill(pid, "SIGKILL");
787
- } catch {
1605
+ if (!acquireSpawnLock()) {
1606
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1607
+ if (_socket) {
1608
+ _socket.destroy();
1609
+ _socket = null;
1610
+ }
1611
+ _connected = false;
1612
+ _buffer = "";
1613
+ return;
1614
+ }
1615
+ try {
1616
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1617
+ if (existsSync6(PID_PATH)) {
1618
+ try {
1619
+ const pid = parseInt(readFileSync5(PID_PATH, "utf8").trim(), 10);
1620
+ if (pid > 0) {
1621
+ try {
1622
+ process.kill(pid, "SIGKILL");
1623
+ } catch {
1624
+ }
788
1625
  }
1626
+ } catch {
789
1627
  }
1628
+ }
1629
+ if (_socket) {
1630
+ _socket.destroy();
1631
+ _socket = null;
1632
+ }
1633
+ _connected = false;
1634
+ _buffer = "";
1635
+ try {
1636
+ unlinkSync2(PID_PATH);
790
1637
  } catch {
791
1638
  }
1639
+ try {
1640
+ unlinkSync2(SOCKET_PATH);
1641
+ } catch {
1642
+ }
1643
+ spawnDaemon();
1644
+ } finally {
1645
+ releaseSpawnLock();
792
1646
  }
793
- if (_socket) {
794
- _socket.destroy();
795
- _socket = null;
796
- }
797
- _connected = false;
798
- _buffer = "";
1647
+ }
1648
+ function isDaemonTooYoung() {
799
1649
  try {
800
- unlinkSync2(PID_PATH);
1650
+ const stat = statSync(PID_PATH);
1651
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
801
1652
  } catch {
1653
+ return false;
802
1654
  }
803
- try {
804
- unlinkSync2(SOCKET_PATH);
805
- } catch {
1655
+ }
1656
+ async function retryThenRestart(doRequest, label) {
1657
+ const result = await doRequest();
1658
+ if (!result.error) {
1659
+ _consecutiveFailures = 0;
1660
+ return result;
806
1661
  }
807
- spawnDaemon();
1662
+ _consecutiveFailures++;
1663
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1664
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1665
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1666
+ `);
1667
+ await new Promise((r) => setTimeout(r, delayMs));
1668
+ if (!_connected) {
1669
+ if (!await connectToSocket()) continue;
1670
+ }
1671
+ const retry = await doRequest();
1672
+ if (!retry.error) {
1673
+ _consecutiveFailures = 0;
1674
+ return retry;
1675
+ }
1676
+ _consecutiveFailures++;
1677
+ }
1678
+ if (isDaemonTooYoung()) {
1679
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1680
+ `);
1681
+ return { error: result.error };
1682
+ }
1683
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1684
+ `);
1685
+ killAndRespawnDaemon();
1686
+ const start = Date.now();
1687
+ let delay2 = 200;
1688
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1689
+ await new Promise((r) => setTimeout(r, delay2));
1690
+ if (await connectToSocket()) break;
1691
+ delay2 = Math.min(delay2 * 2, 3e3);
1692
+ }
1693
+ if (!_connected) return { error: "Daemon restart failed" };
1694
+ const final = await doRequest();
1695
+ if (!final.error) _consecutiveFailures = 0;
1696
+ return final;
808
1697
  }
809
1698
  async function embedViaClient(text, priority = "high") {
810
1699
  if (!_connected && !await connectEmbedDaemon()) return null;
811
1700
  _requestCount++;
812
1701
  if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
813
1702
  const health = await pingDaemon();
814
- if (!health) {
1703
+ if (!health && !isDaemonTooYoung()) {
815
1704
  process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
816
1705
  `);
817
1706
  killAndRespawnDaemon();
818
1707
  const start = Date.now();
819
- let delay2 = 200;
1708
+ let d = 200;
820
1709
  while (Date.now() - start < CONNECT_TIMEOUT_MS) {
821
- await new Promise((r) => setTimeout(r, delay2));
1710
+ await new Promise((r) => setTimeout(r, d));
822
1711
  if (await connectToSocket()) break;
823
- delay2 = Math.min(delay2 * 2, 3e3);
1712
+ d = Math.min(d * 2, 3e3);
824
1713
  }
825
1714
  if (!_connected) return null;
826
1715
  }
827
1716
  }
828
- const result = await sendRequest([text], priority);
829
- if (!result.error && result.vectors?.[0]) return result.vectors[0];
830
- if (result.error) {
831
- process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
832
- `);
833
- killAndRespawnDaemon();
834
- const start = Date.now();
835
- let delay2 = 200;
836
- while (Date.now() - start < CONNECT_TIMEOUT_MS) {
837
- await new Promise((r) => setTimeout(r, delay2));
838
- if (await connectToSocket()) break;
839
- delay2 = Math.min(delay2 * 2, 3e3);
840
- }
841
- if (!_connected) return null;
842
- const retry = await sendRequest([text], priority);
843
- if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
844
- process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
845
- `);
846
- }
847
- return null;
1717
+ const result = await retryThenRestart(
1718
+ () => sendRequest([text], priority),
1719
+ "Embed"
1720
+ );
1721
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
848
1722
  }
849
1723
  function disconnectClient() {
850
1724
  if (_socket) {
@@ -862,22 +1736,28 @@ function disconnectClient() {
862
1736
  function isClientConnected() {
863
1737
  return _connected;
864
1738
  }
865
- 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;
1739
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
866
1740
  var init_exe_daemon_client = __esm({
867
1741
  "src/lib/exe-daemon-client.ts"() {
868
1742
  "use strict";
869
1743
  init_config();
870
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path3.join(EXE_AI_DIR, "exed.sock");
871
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path3.join(EXE_AI_DIR, "exed.pid");
872
- SPAWN_LOCK_PATH = path3.join(EXE_AI_DIR, "exed-spawn.lock");
1744
+ init_daemon_auth();
1745
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path6.join(EXE_AI_DIR, "exed.sock");
1746
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path6.join(EXE_AI_DIR, "exed.pid");
1747
+ SPAWN_LOCK_PATH = path6.join(EXE_AI_DIR, "exed-spawn.lock");
873
1748
  SPAWN_LOCK_STALE_MS = 3e4;
874
1749
  CONNECT_TIMEOUT_MS = 15e3;
875
1750
  REQUEST_TIMEOUT_MS = 3e4;
1751
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
876
1752
  _socket = null;
877
1753
  _connected = false;
878
1754
  _buffer = "";
879
1755
  _requestCount = 0;
1756
+ _consecutiveFailures = 0;
880
1757
  HEALTH_CHECK_INTERVAL = 100;
1758
+ MAX_RETRIES_BEFORE_RESTART = 3;
1759
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1760
+ MIN_DAEMON_AGE_MS = 3e4;
881
1761
  _pending = /* @__PURE__ */ new Map();
882
1762
  MAX_BUFFER = 1e7;
883
1763
  }
@@ -953,7 +1833,7 @@ __export(db_daemon_client_exports, {
953
1833
  createDaemonDbClient: () => createDaemonDbClient,
954
1834
  initDaemonDbClient: () => initDaemonDbClient
955
1835
  });
956
- function normalizeStatement(stmt) {
1836
+ function normalizeStatement2(stmt) {
957
1837
  if (typeof stmt === "string") {
958
1838
  return { sql: stmt, args: [] };
959
1839
  }
@@ -977,7 +1857,7 @@ function createDaemonDbClient(fallbackClient) {
977
1857
  if (!_useDaemon || !isClientConnected()) {
978
1858
  return fallbackClient.execute(stmt);
979
1859
  }
980
- const { sql, args } = normalizeStatement(stmt);
1860
+ const { sql, args } = normalizeStatement2(stmt);
981
1861
  const response = await sendDaemonRequest({
982
1862
  type: "db-execute",
983
1863
  sql,
@@ -1002,7 +1882,7 @@ function createDaemonDbClient(fallbackClient) {
1002
1882
  if (!_useDaemon || !isClientConnected()) {
1003
1883
  return fallbackClient.batch(stmts, mode);
1004
1884
  }
1005
- const statements = stmts.map(normalizeStatement);
1885
+ const statements = stmts.map(normalizeStatement2);
1006
1886
  const response = await sendDaemonRequest({
1007
1887
  type: "db-batch",
1008
1888
  statements,
@@ -1097,6 +1977,18 @@ __export(database_exports, {
1097
1977
  });
1098
1978
  import { createClient } from "@libsql/client";
1099
1979
  async function initDatabase(config) {
1980
+ if (_walCheckpointTimer) {
1981
+ clearInterval(_walCheckpointTimer);
1982
+ _walCheckpointTimer = null;
1983
+ }
1984
+ if (_daemonClient) {
1985
+ _daemonClient.close();
1986
+ _daemonClient = null;
1987
+ }
1988
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1989
+ _adapterClient.close();
1990
+ }
1991
+ _adapterClient = null;
1100
1992
  if (_client) {
1101
1993
  _client.close();
1102
1994
  _client = null;
@@ -1110,6 +2002,7 @@ async function initDatabase(config) {
1110
2002
  }
1111
2003
  _client = createClient(opts);
1112
2004
  _resilientClient = wrapWithRetry(_client);
2005
+ _adapterClient = _resilientClient;
1113
2006
  _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1114
2007
  });
1115
2008
  _client.execute("PRAGMA journal_mode = WAL").catch(() => {
@@ -1120,14 +2013,20 @@ async function initDatabase(config) {
1120
2013
  });
1121
2014
  }, 3e4);
1122
2015
  _walCheckpointTimer.unref();
2016
+ if (process.env.DATABASE_URL) {
2017
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
2018
+ }
1123
2019
  }
1124
2020
  function isInitialized() {
1125
- return _client !== null;
2021
+ return _adapterClient !== null || _client !== null;
1126
2022
  }
1127
2023
  function getClient() {
1128
- if (!_resilientClient) {
2024
+ if (!_adapterClient) {
1129
2025
  throw new Error("Database client not initialized. Call initDatabase() first.");
1130
2026
  }
2027
+ if (process.env.DATABASE_URL) {
2028
+ return _adapterClient;
2029
+ }
1131
2030
  if (process.env.EXE_IS_DAEMON === "1") {
1132
2031
  return _resilientClient;
1133
2032
  }
@@ -1137,6 +2036,7 @@ function getClient() {
1137
2036
  return _resilientClient;
1138
2037
  }
1139
2038
  async function initDaemonClient() {
2039
+ if (process.env.DATABASE_URL) return;
1140
2040
  if (process.env.EXE_IS_DAEMON === "1") return;
1141
2041
  if (!_resilientClient) return;
1142
2042
  try {
@@ -1433,6 +2333,7 @@ async function ensureSchema() {
1433
2333
  project TEXT NOT NULL,
1434
2334
  summary TEXT NOT NULL,
1435
2335
  task_file TEXT,
2336
+ session_scope TEXT,
1436
2337
  read INTEGER NOT NULL DEFAULT 0,
1437
2338
  created_at TEXT NOT NULL
1438
2339
  );
@@ -1441,7 +2342,7 @@ async function ensureSchema() {
1441
2342
  ON notifications(read);
1442
2343
 
1443
2344
  CREATE INDEX IF NOT EXISTS idx_notifications_agent
1444
- ON notifications(agent_id);
2345
+ ON notifications(agent_id, session_scope);
1445
2346
 
1446
2347
  CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1447
2348
  ON notifications(task_file);
@@ -1479,6 +2380,7 @@ async function ensureSchema() {
1479
2380
  target_agent TEXT NOT NULL,
1480
2381
  target_project TEXT,
1481
2382
  target_device TEXT NOT NULL DEFAULT 'local',
2383
+ session_scope TEXT,
1482
2384
  content TEXT NOT NULL,
1483
2385
  priority TEXT DEFAULT 'normal',
1484
2386
  status TEXT DEFAULT 'pending',
@@ -1492,10 +2394,31 @@ async function ensureSchema() {
1492
2394
  );
1493
2395
 
1494
2396
  CREATE INDEX IF NOT EXISTS idx_messages_target
1495
- ON messages(target_agent, status);
2397
+ ON messages(target_agent, session_scope, status);
1496
2398
 
1497
2399
  CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
1498
- ON messages(target_agent, from_agent, server_seq);
2400
+ ON messages(target_agent, session_scope, from_agent, server_seq);
2401
+ `);
2402
+ try {
2403
+ await client.execute({
2404
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
2405
+ args: []
2406
+ });
2407
+ } catch {
2408
+ }
2409
+ try {
2410
+ await client.execute({
2411
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
2412
+ args: []
2413
+ });
2414
+ } catch {
2415
+ }
2416
+ await client.executeMultiple(`
2417
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
2418
+ ON notifications(agent_id, session_scope, read, created_at);
2419
+
2420
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
2421
+ ON messages(target_agent, session_scope, status, created_at);
1499
2422
  `);
1500
2423
  try {
1501
2424
  await client.execute({
@@ -2079,28 +3002,45 @@ async function ensureSchema() {
2079
3002
  } catch {
2080
3003
  }
2081
3004
  }
3005
+ try {
3006
+ await client.execute({
3007
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
3008
+ args: []
3009
+ });
3010
+ } catch {
3011
+ }
2082
3012
  }
2083
3013
  async function disposeDatabase() {
3014
+ if (_walCheckpointTimer) {
3015
+ clearInterval(_walCheckpointTimer);
3016
+ _walCheckpointTimer = null;
3017
+ }
2084
3018
  if (_daemonClient) {
2085
3019
  _daemonClient.close();
2086
3020
  _daemonClient = null;
2087
3021
  }
3022
+ if (_adapterClient && _adapterClient !== _resilientClient) {
3023
+ _adapterClient.close();
3024
+ }
3025
+ _adapterClient = null;
2088
3026
  if (_client) {
2089
3027
  _client.close();
2090
3028
  _client = null;
2091
3029
  _resilientClient = null;
2092
3030
  }
2093
3031
  }
2094
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso, disposeTurso;
3032
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2095
3033
  var init_database = __esm({
2096
3034
  "src/lib/database.ts"() {
2097
3035
  "use strict";
2098
3036
  init_db_retry();
2099
3037
  init_employees();
3038
+ init_database_adapter();
2100
3039
  _client = null;
2101
3040
  _resilientClient = null;
2102
3041
  _walCheckpointTimer = null;
2103
3042
  _daemonClient = null;
3043
+ _adapterClient = null;
2104
3044
  initTurso = initDatabase;
2105
3045
  disposeTurso = disposeDatabase;
2106
3046
  }
@@ -2108,14 +3048,14 @@ var init_database = __esm({
2108
3048
 
2109
3049
  // src/lib/keychain.ts
2110
3050
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2111
- import { existsSync as existsSync4 } from "fs";
2112
- import path4 from "path";
2113
- import os4 from "os";
3051
+ import { existsSync as existsSync7 } from "fs";
3052
+ import path7 from "path";
3053
+ import os5 from "os";
2114
3054
  function getKeyDir() {
2115
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
3055
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path7.join(os5.homedir(), ".exe-os");
2116
3056
  }
2117
3057
  function getKeyPath() {
2118
- return path4.join(getKeyDir(), "master.key");
3058
+ return path7.join(getKeyDir(), "master.key");
2119
3059
  }
2120
3060
  async function tryKeytar() {
2121
3061
  try {
@@ -2136,9 +3076,9 @@ async function getMasterKey() {
2136
3076
  }
2137
3077
  }
2138
3078
  const keyPath = getKeyPath();
2139
- if (!existsSync4(keyPath)) {
3079
+ if (!existsSync7(keyPath)) {
2140
3080
  process.stderr.write(
2141
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3081
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2142
3082
  `
2143
3083
  );
2144
3084
  return null;
@@ -2223,6 +3163,7 @@ var shard_manager_exports = {};
2223
3163
  __export(shard_manager_exports, {
2224
3164
  disposeShards: () => disposeShards,
2225
3165
  ensureShardSchema: () => ensureShardSchema,
3166
+ getOpenShardCount: () => getOpenShardCount,
2226
3167
  getReadyShardClient: () => getReadyShardClient,
2227
3168
  getShardClient: () => getShardClient,
2228
3169
  getShardsDir: () => getShardsDir,
@@ -2231,15 +3172,18 @@ __export(shard_manager_exports, {
2231
3172
  listShards: () => listShards,
2232
3173
  shardExists: () => shardExists
2233
3174
  });
2234
- import path5 from "path";
2235
- import { existsSync as existsSync5, mkdirSync, readdirSync } from "fs";
3175
+ import path8 from "path";
3176
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readdirSync } from "fs";
2236
3177
  import { createClient as createClient2 } from "@libsql/client";
2237
3178
  function initShardManager(encryptionKey) {
2238
3179
  _encryptionKey = encryptionKey;
2239
- if (!existsSync5(SHARDS_DIR)) {
2240
- mkdirSync(SHARDS_DIR, { recursive: true });
3180
+ if (!existsSync8(SHARDS_DIR)) {
3181
+ mkdirSync2(SHARDS_DIR, { recursive: true });
2241
3182
  }
2242
3183
  _shardingEnabled = true;
3184
+ if (_evictionTimer) clearInterval(_evictionTimer);
3185
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
3186
+ _evictionTimer.unref();
2243
3187
  }
2244
3188
  function isShardingEnabled() {
2245
3189
  return _shardingEnabled;
@@ -2256,21 +3200,28 @@ function getShardClient(projectName) {
2256
3200
  throw new Error(`Invalid project name for shard: "${projectName}"`);
2257
3201
  }
2258
3202
  const cached = _shards.get(safeName);
2259
- if (cached) return cached;
2260
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
3203
+ if (cached) {
3204
+ _shardLastAccess.set(safeName, Date.now());
3205
+ return cached;
3206
+ }
3207
+ while (_shards.size >= MAX_OPEN_SHARDS) {
3208
+ evictLRU();
3209
+ }
3210
+ const dbPath = path8.join(SHARDS_DIR, `${safeName}.db`);
2261
3211
  const client = createClient2({
2262
3212
  url: `file:${dbPath}`,
2263
3213
  encryptionKey: _encryptionKey
2264
3214
  });
2265
3215
  _shards.set(safeName, client);
3216
+ _shardLastAccess.set(safeName, Date.now());
2266
3217
  return client;
2267
3218
  }
2268
3219
  function shardExists(projectName) {
2269
3220
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2270
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
3221
+ return existsSync8(path8.join(SHARDS_DIR, `${safeName}.db`));
2271
3222
  }
2272
3223
  function listShards() {
2273
- if (!existsSync5(SHARDS_DIR)) return [];
3224
+ if (!existsSync8(SHARDS_DIR)) return [];
2274
3225
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2275
3226
  }
2276
3227
  async function ensureShardSchema(client) {
@@ -2322,6 +3273,8 @@ async function ensureShardSchema(client) {
2322
3273
  for (const col of [
2323
3274
  "ALTER TABLE memories ADD COLUMN task_id TEXT",
2324
3275
  "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
3276
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
3277
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
2325
3278
  "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
2326
3279
  "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
2327
3280
  "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
@@ -2344,7 +3297,23 @@ async function ensureShardSchema(client) {
2344
3297
  // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2345
3298
  "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2346
3299
  "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2347
- "ALTER TABLE memories ADD COLUMN trajectory TEXT"
3300
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3301
+ // Metadata enrichment columns (must match database.ts)
3302
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3303
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3304
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3305
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3306
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3307
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3308
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3309
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3310
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3311
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3312
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3313
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3314
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3315
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3316
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2348
3317
  ]) {
2349
3318
  try {
2350
3319
  await client.execute(col);
@@ -2443,21 +3412,69 @@ async function getReadyShardClient(projectName) {
2443
3412
  await ensureShardSchema(client);
2444
3413
  return client;
2445
3414
  }
3415
+ function evictLRU() {
3416
+ let oldest = null;
3417
+ let oldestTime = Infinity;
3418
+ for (const [name, time] of _shardLastAccess) {
3419
+ if (time < oldestTime) {
3420
+ oldestTime = time;
3421
+ oldest = name;
3422
+ }
3423
+ }
3424
+ if (oldest) {
3425
+ const client = _shards.get(oldest);
3426
+ if (client) {
3427
+ client.close();
3428
+ }
3429
+ _shards.delete(oldest);
3430
+ _shardLastAccess.delete(oldest);
3431
+ }
3432
+ }
3433
+ function evictIdleShards() {
3434
+ const now = Date.now();
3435
+ const toEvict = [];
3436
+ for (const [name, lastAccess] of _shardLastAccess) {
3437
+ if (now - lastAccess > SHARD_IDLE_MS) {
3438
+ toEvict.push(name);
3439
+ }
3440
+ }
3441
+ for (const name of toEvict) {
3442
+ const client = _shards.get(name);
3443
+ if (client) {
3444
+ client.close();
3445
+ }
3446
+ _shards.delete(name);
3447
+ _shardLastAccess.delete(name);
3448
+ }
3449
+ }
3450
+ function getOpenShardCount() {
3451
+ return _shards.size;
3452
+ }
2446
3453
  function disposeShards() {
3454
+ if (_evictionTimer) {
3455
+ clearInterval(_evictionTimer);
3456
+ _evictionTimer = null;
3457
+ }
2447
3458
  for (const [, client] of _shards) {
2448
3459
  client.close();
2449
3460
  }
2450
3461
  _shards.clear();
3462
+ _shardLastAccess.clear();
2451
3463
  _shardingEnabled = false;
2452
3464
  _encryptionKey = null;
2453
3465
  }
2454
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
3466
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
2455
3467
  var init_shard_manager = __esm({
2456
3468
  "src/lib/shard-manager.ts"() {
2457
3469
  "use strict";
2458
3470
  init_config();
2459
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
3471
+ SHARDS_DIR = path8.join(EXE_AI_DIR, "shards");
3472
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
3473
+ MAX_OPEN_SHARDS = 10;
3474
+ EVICTION_INTERVAL_MS = 60 * 1e3;
2460
3475
  _shards = /* @__PURE__ */ new Map();
3476
+ _shardLastAccess = /* @__PURE__ */ new Map();
3477
+ _evictionTimer = null;
2461
3478
  _encryptionKey = null;
2462
3479
  _shardingEnabled = false;
2463
3480
  }
@@ -3319,8 +4336,8 @@ __export(reranker_exports, {
3319
4336
  rerankWithContext: () => rerankWithContext,
3320
4337
  rerankWithScores: () => rerankWithScores
3321
4338
  });
3322
- import path6 from "path";
3323
- import { existsSync as existsSync6 } from "fs";
4339
+ import path9 from "path";
4340
+ import { existsSync as existsSync9 } from "fs";
3324
4341
  function resetIdleTimer() {
3325
4342
  if (_idleTimer) clearTimeout(_idleTimer);
3326
4343
  _idleTimer = setTimeout(() => {
@@ -3331,18 +4348,18 @@ function resetIdleTimer() {
3331
4348
  }
3332
4349
  }
3333
4350
  function isRerankerAvailable() {
3334
- return existsSync6(path6.join(MODELS_DIR, RERANKER_MODEL_FILE));
4351
+ return existsSync9(path9.join(MODELS_DIR, RERANKER_MODEL_FILE));
3335
4352
  }
3336
4353
  function getRerankerModelPath() {
3337
- return path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
4354
+ return path9.join(MODELS_DIR, RERANKER_MODEL_FILE);
3338
4355
  }
3339
4356
  async function ensureLoaded() {
3340
4357
  if (_rerankerContext) {
3341
4358
  resetIdleTimer();
3342
4359
  return;
3343
4360
  }
3344
- const modelPath = path6.join(MODELS_DIR, RERANKER_MODEL_FILE);
3345
- if (!existsSync6(modelPath)) {
4361
+ const modelPath = path9.join(MODELS_DIR, RERANKER_MODEL_FILE);
4362
+ if (!existsSync9(modelPath)) {
3346
4363
  throw new Error(
3347
4364
  `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
3348
4365
  );
@@ -3475,10 +4492,10 @@ async function disposeEmbedder() {
3475
4492
  async function embedDirect(text) {
3476
4493
  const llamaCpp = await import("node-llama-cpp");
3477
4494
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
3478
- const { existsSync: existsSync13 } = await import("fs");
3479
- const path17 = await import("path");
3480
- const modelPath = path17.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
3481
- if (!existsSync13(modelPath)) {
4495
+ const { existsSync: existsSync16 } = await import("fs");
4496
+ const path19 = await import("path");
4497
+ const modelPath = path19.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
4498
+ if (!existsSync16(modelPath)) {
3482
4499
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
3483
4500
  }
3484
4501
  const llama = await llamaCpp.getLlama();
@@ -3513,7 +4530,7 @@ __export(project_name_exports, {
3513
4530
  getProjectName: () => getProjectName
3514
4531
  });
3515
4532
  import { execSync as execSync2 } from "child_process";
3516
- import path7 from "path";
4533
+ import path10 from "path";
3517
4534
  function getProjectName(cwd) {
3518
4535
  const dir = cwd ?? process.cwd();
3519
4536
  if (_cached && _cachedCwd === dir) return _cached;
@@ -3526,7 +4543,7 @@ function getProjectName(cwd) {
3526
4543
  timeout: 2e3,
3527
4544
  stdio: ["pipe", "pipe", "pipe"]
3528
4545
  }).trim();
3529
- repoRoot = path7.dirname(gitCommonDir);
4546
+ repoRoot = path10.dirname(gitCommonDir);
3530
4547
  } catch {
3531
4548
  repoRoot = execSync2("git rev-parse --show-toplevel", {
3532
4549
  cwd: dir,
@@ -3535,11 +4552,11 @@ function getProjectName(cwd) {
3535
4552
  stdio: ["pipe", "pipe", "pipe"]
3536
4553
  }).trim();
3537
4554
  }
3538
- _cached = path7.basename(repoRoot);
4555
+ _cached = path10.basename(repoRoot);
3539
4556
  _cachedCwd = dir;
3540
4557
  return _cached;
3541
4558
  } catch {
3542
- _cached = path7.basename(dir);
4559
+ _cached = path10.basename(dir);
3543
4560
  _cachedCwd = dir;
3544
4561
  return _cached;
3545
4562
  }
@@ -3563,9 +4580,9 @@ __export(file_grep_exports, {
3563
4580
  grepProjectFiles: () => grepProjectFiles
3564
4581
  });
3565
4582
  import { execSync as execSync3 } from "child_process";
3566
- import { readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync7 } from "fs";
3567
- import path8 from "path";
3568
- import crypto from "crypto";
4583
+ import { readFileSync as readFileSync6, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync10 } from "fs";
4584
+ import path11 from "path";
4585
+ import crypto2 from "crypto";
3569
4586
  function hasRipgrep() {
3570
4587
  if (_hasRg === null) {
3571
4588
  try {
@@ -3598,13 +4615,13 @@ async function grepProjectFiles(query, projectRoot, options) {
3598
4615
  const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
3599
4616
  const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
3600
4617
  return {
3601
- id: crypto.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
4618
+ id: crypto2.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
3602
4619
  agent_id: "project",
3603
4620
  agent_role: "file",
3604
4621
  session_id: "file-grep",
3605
4622
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3606
4623
  tool_name: "file_grep",
3607
- project_name: path8.basename(projectRoot),
4624
+ project_name: path11.basename(projectRoot),
3608
4625
  has_error: false,
3609
4626
  raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
3610
4627
  vector: null,
@@ -3616,7 +4633,7 @@ function getChunkContext(filePath, lineNumber) {
3616
4633
  try {
3617
4634
  const ext = filePath.split(".").pop()?.toLowerCase();
3618
4635
  if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
3619
- const source = readFileSync4(filePath, "utf8");
4636
+ const source = readFileSync6(filePath, "utf8");
3620
4637
  const lines = source.split("\n");
3621
4638
  for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
3622
4639
  const line = lines[i];
@@ -3678,11 +4695,11 @@ function grepWithNodeFs(pattern, projectRoot, patterns) {
3678
4695
  const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
3679
4696
  const hits = [];
3680
4697
  for (const filePath of files.slice(0, MAX_FILES)) {
3681
- const absPath = path8.join(projectRoot, filePath);
4698
+ const absPath = path11.join(projectRoot, filePath);
3682
4699
  try {
3683
4700
  const stat = statSync2(absPath);
3684
4701
  if (stat.size > MAX_FILE_SIZE) continue;
3685
- const content = readFileSync4(absPath, "utf8");
4702
+ const content = readFileSync6(absPath, "utf8");
3686
4703
  const lines = content.split("\n");
3687
4704
  const matches = content.match(regex);
3688
4705
  if (!matches || matches.length === 0) continue;
@@ -3705,15 +4722,15 @@ function collectFiles(root, patterns) {
3705
4722
  const files = [];
3706
4723
  function walk(dir, relative) {
3707
4724
  if (files.length >= MAX_FILES) return;
3708
- const basename = path8.basename(dir);
4725
+ const basename = path11.basename(dir);
3709
4726
  if (EXCLUDE_DIRS.includes(basename)) return;
3710
4727
  try {
3711
4728
  const entries = readdirSync2(dir, { withFileTypes: true });
3712
4729
  for (const entry of entries) {
3713
4730
  if (files.length >= MAX_FILES) return;
3714
- const rel = path8.join(relative, entry.name);
4731
+ const rel = path11.join(relative, entry.name);
3715
4732
  if (entry.isDirectory()) {
3716
- walk(path8.join(dir, entry.name), rel);
4733
+ walk(path11.join(dir, entry.name), rel);
3717
4734
  } else if (entry.isFile()) {
3718
4735
  for (const pat of patterns) {
3719
4736
  if (matchGlob(rel, pat)) {
@@ -3745,7 +4762,7 @@ function matchGlob(filePath, pattern) {
3745
4762
  if (slashIdx !== -1) {
3746
4763
  const dir = pattern.slice(0, slashIdx);
3747
4764
  const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
3748
- const fileDir = path8.dirname(filePath);
4765
+ const fileDir = path11.dirname(filePath);
3749
4766
  return fileDir === dir && filePath.endsWith(ext2);
3750
4767
  }
3751
4768
  const ext = pattern.replace("*", "");
@@ -3753,9 +4770,9 @@ function matchGlob(filePath, pattern) {
3753
4770
  }
3754
4771
  function buildSnippet(hit, projectRoot) {
3755
4772
  try {
3756
- const absPath = path8.join(projectRoot, hit.filePath);
3757
- if (!existsSync7(absPath)) return hit.matchLine;
3758
- const lines = readFileSync4(absPath, "utf8").split("\n");
4773
+ const absPath = path11.join(projectRoot, hit.filePath);
4774
+ if (!existsSync10(absPath)) return hit.matchLine;
4775
+ const lines = readFileSync6(absPath, "utf8").split("\n");
3759
4776
  const start = Math.max(0, hit.lineNumber - 3);
3760
4777
  const end = Math.min(lines.length, hit.lineNumber + 2);
3761
4778
  return lines.slice(start, end).join("\n").slice(0, 500);
@@ -4971,9 +5988,9 @@ var init_session_key = __esm({
4971
5988
  });
4972
5989
 
4973
5990
  // src/lib/active-agent.ts
4974
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync3, readdirSync as readdirSync3 } from "fs";
5991
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, unlinkSync as unlinkSync3, readdirSync as readdirSync3 } from "fs";
4975
5992
  import { execSync as execSync5 } from "child_process";
4976
- import path9 from "path";
5993
+ import path12 from "path";
4977
5994
  function isNameWithOptionalInstance(candidate, baseName) {
4978
5995
  if (candidate === baseName) return true;
4979
5996
  if (!candidate.startsWith(baseName)) return false;
@@ -5017,12 +6034,12 @@ function resolveActiveAgentFromTmuxSession(sessionName) {
5017
6034
  return null;
5018
6035
  }
5019
6036
  function getMarkerPath() {
5020
- return path9.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
6037
+ return path12.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
5021
6038
  }
5022
6039
  function writeActiveAgent(agentId, agentRole) {
5023
6040
  try {
5024
- mkdirSync2(CACHE_DIR, { recursive: true });
5025
- writeFileSync2(
6041
+ mkdirSync3(CACHE_DIR, { recursive: true });
6042
+ writeFileSync4(
5026
6043
  getMarkerPath(),
5027
6044
  JSON.stringify({ agentId, agentRole, startedAt: (/* @__PURE__ */ new Date()).toISOString() })
5028
6045
  );
@@ -5038,7 +6055,7 @@ function clearActiveAgent() {
5038
6055
  function getActiveAgent() {
5039
6056
  try {
5040
6057
  const markerPath = getMarkerPath();
5041
- const raw = readFileSync5(markerPath, "utf8");
6058
+ const raw = readFileSync7(markerPath, "utf8");
5042
6059
  const data = JSON.parse(raw);
5043
6060
  if (data.agentId) {
5044
6061
  if (data.startedAt) {
@@ -5086,14 +6103,14 @@ function getAllActiveAgents() {
5086
6103
  const key = file.slice("active-agent-".length, -".json".length);
5087
6104
  if (key === "undefined") continue;
5088
6105
  try {
5089
- const raw = readFileSync5(path9.join(CACHE_DIR, file), "utf8");
6106
+ const raw = readFileSync7(path12.join(CACHE_DIR, file), "utf8");
5090
6107
  const data = JSON.parse(raw);
5091
6108
  if (!data.agentId) continue;
5092
6109
  if (data.startedAt) {
5093
6110
  const age = Date.now() - new Date(data.startedAt).getTime();
5094
6111
  if (age > STALE_MS) {
5095
6112
  try {
5096
- unlinkSync3(path9.join(CACHE_DIR, file));
6113
+ unlinkSync3(path12.join(CACHE_DIR, file));
5097
6114
  } catch {
5098
6115
  }
5099
6116
  continue;
@@ -5116,11 +6133,11 @@ function getAllActiveAgents() {
5116
6133
  function cleanupSessionMarkers() {
5117
6134
  const key = getSessionKey();
5118
6135
  try {
5119
- unlinkSync3(path9.join(CACHE_DIR, `active-agent-${key}.json`));
6136
+ unlinkSync3(path12.join(CACHE_DIR, `active-agent-${key}.json`));
5120
6137
  } catch {
5121
6138
  }
5122
6139
  try {
5123
- unlinkSync3(path9.join(CACHE_DIR, "active-agent-undefined.json"));
6140
+ unlinkSync3(path12.join(CACHE_DIR, "active-agent-undefined.json"));
5124
6141
  } catch {
5125
6142
  }
5126
6143
  }
@@ -5131,7 +6148,7 @@ var init_active_agent = __esm({
5131
6148
  init_config();
5132
6149
  init_session_key();
5133
6150
  init_employees();
5134
- CACHE_DIR = path9.join(EXE_AI_DIR, "session-cache");
6151
+ CACHE_DIR = path12.join(EXE_AI_DIR, "session-cache");
5135
6152
  STALE_MS = 24 * 60 * 60 * 1e3;
5136
6153
  }
5137
6154
  });
@@ -5154,13 +6171,13 @@ var init_active_agent2 = __esm({
5154
6171
  });
5155
6172
 
5156
6173
  // src/lib/session-registry.ts
5157
- import path10 from "path";
5158
- import os5 from "os";
6174
+ import path13 from "path";
6175
+ import os6 from "os";
5159
6176
  var REGISTRY_PATH;
5160
6177
  var init_session_registry = __esm({
5161
6178
  "src/lib/session-registry.ts"() {
5162
6179
  "use strict";
5163
- REGISTRY_PATH = path10.join(os5.homedir(), ".exe-os", "session-registry.json");
6180
+ REGISTRY_PATH = path13.join(os6.homedir(), ".exe-os", "session-registry.json");
5164
6181
  }
5165
6182
  });
5166
6183
 
@@ -5300,83 +6317,42 @@ var init_provider_table = __esm({
5300
6317
  }
5301
6318
  });
5302
6319
 
5303
- // src/lib/runtime-table.ts
5304
- var RUNTIME_TABLE;
5305
- var init_runtime_table = __esm({
5306
- "src/lib/runtime-table.ts"() {
5307
- "use strict";
5308
- RUNTIME_TABLE = {
5309
- codex: {
5310
- binary: "codex",
5311
- launchMode: "interactive",
5312
- autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
5313
- inlineFlag: "--no-alt-screen",
5314
- apiKeyEnv: "OPENAI_API_KEY",
5315
- defaultModel: "gpt-5.4"
5316
- },
5317
- opencode: {
5318
- binary: "opencode",
5319
- launchMode: "exec",
5320
- autoApproveFlag: "--dangerously-skip-permissions",
5321
- inlineFlag: "",
5322
- apiKeyEnv: "ANTHROPIC_API_KEY",
5323
- defaultModel: "anthropic/claude-sonnet-4-6"
5324
- }
5325
- };
5326
- }
5327
- });
5328
-
5329
- // src/lib/agent-config.ts
5330
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
5331
- import path11 from "path";
5332
- var AGENT_CONFIG_PATH, DEFAULT_MODELS;
5333
- var init_agent_config = __esm({
5334
- "src/lib/agent-config.ts"() {
5335
- "use strict";
5336
- init_config();
5337
- init_runtime_table();
5338
- AGENT_CONFIG_PATH = path11.join(EXE_AI_DIR, "agent-config.json");
5339
- DEFAULT_MODELS = {
5340
- claude: "claude-opus-4",
5341
- codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
5342
- opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
5343
- };
5344
- }
5345
- });
5346
-
5347
6320
  // src/lib/intercom-queue.ts
5348
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync4, renameSync as renameSync3, existsSync as existsSync9, mkdirSync as mkdirSync4 } from "fs";
5349
- import path12 from "path";
5350
- import os6 from "os";
6321
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync5, renameSync as renameSync3, existsSync as existsSync11, mkdirSync as mkdirSync4 } from "fs";
6322
+ import path14 from "path";
6323
+ import os7 from "os";
5351
6324
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
5352
6325
  var init_intercom_queue = __esm({
5353
6326
  "src/lib/intercom-queue.ts"() {
5354
6327
  "use strict";
5355
- QUEUE_PATH = path12.join(os6.homedir(), ".exe-os", "intercom-queue.json");
6328
+ QUEUE_PATH = path14.join(os7.homedir(), ".exe-os", "intercom-queue.json");
5356
6329
  TTL_MS = 60 * 60 * 1e3;
5357
- INTERCOM_LOG = path12.join(os6.homedir(), ".exe-os", "intercom.log");
6330
+ INTERCOM_LOG = path14.join(os7.homedir(), ".exe-os", "intercom.log");
5358
6331
  }
5359
6332
  });
5360
6333
 
5361
6334
  // src/lib/license.ts
5362
- import { readFileSync as readFileSync8, writeFileSync as writeFileSync5, existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
6335
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, existsSync as existsSync12, mkdirSync as mkdirSync5 } from "fs";
5363
6336
  import { randomUUID as randomUUID3 } from "crypto";
5364
- import path13 from "path";
6337
+ import { createRequire as createRequire2 } from "module";
6338
+ import { pathToFileURL as pathToFileURL2 } from "url";
6339
+ import os8 from "os";
6340
+ import path15 from "path";
5365
6341
  import { jwtVerify, importSPKI } from "jose";
5366
6342
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
5367
6343
  var init_license = __esm({
5368
6344
  "src/lib/license.ts"() {
5369
6345
  "use strict";
5370
6346
  init_config();
5371
- LICENSE_PATH = path13.join(EXE_AI_DIR, "license.key");
5372
- CACHE_PATH = path13.join(EXE_AI_DIR, "license-cache.json");
5373
- DEVICE_ID_PATH = path13.join(EXE_AI_DIR, "device-id");
6347
+ LICENSE_PATH = path15.join(EXE_AI_DIR, "license.key");
6348
+ CACHE_PATH = path15.join(EXE_AI_DIR, "license-cache.json");
6349
+ DEVICE_ID_PATH = path15.join(EXE_AI_DIR, "device-id");
5374
6350
  }
5375
6351
  });
5376
6352
 
5377
6353
  // src/lib/plan-limits.ts
5378
- import { readFileSync as readFileSync9, existsSync as existsSync11 } from "fs";
5379
- import path14 from "path";
6354
+ import { readFileSync as readFileSync10, existsSync as existsSync13 } from "fs";
6355
+ import path16 from "path";
5380
6356
  var CACHE_PATH2;
5381
6357
  var init_plan_limits = __esm({
5382
6358
  "src/lib/plan-limits.ts"() {
@@ -5385,14 +6361,14 @@ var init_plan_limits = __esm({
5385
6361
  init_employees();
5386
6362
  init_license();
5387
6363
  init_config();
5388
- CACHE_PATH2 = path14.join(EXE_AI_DIR, "license-cache.json");
6364
+ CACHE_PATH2 = path16.join(EXE_AI_DIR, "license-cache.json");
5389
6365
  }
5390
6366
  });
5391
6367
 
5392
6368
  // src/lib/tmux-routing.ts
5393
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync6, mkdirSync as mkdirSync6, existsSync as existsSync12, appendFileSync, readdirSync as readdirSync4 } from "fs";
5394
- import path15 from "path";
5395
- import os7 from "os";
6369
+ import { readFileSync as readFileSync11, writeFileSync as writeFileSync7, mkdirSync as mkdirSync6, existsSync as existsSync14, appendFileSync, readdirSync as readdirSync4 } from "fs";
6370
+ import path17 from "path";
6371
+ import os9 from "os";
5396
6372
  import { fileURLToPath as fileURLToPath2 } from "url";
5397
6373
  function getMySession() {
5398
6374
  return getTransport().getMySession();
@@ -5405,7 +6381,7 @@ function extractRootExe(name) {
5405
6381
  }
5406
6382
  function getParentExe(sessionKey) {
5407
6383
  try {
5408
- const data = JSON.parse(readFileSync10(path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
6384
+ const data = JSON.parse(readFileSync11(path17.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
5409
6385
  return data.parentExe || null;
5410
6386
  } catch {
5411
6387
  return null;
@@ -5448,10 +6424,10 @@ var init_tmux_routing = __esm({
5448
6424
  init_intercom_queue();
5449
6425
  init_plan_limits();
5450
6426
  init_employees();
5451
- SPAWN_LOCK_DIR = path15.join(os7.homedir(), ".exe-os", "spawn-locks");
5452
- SESSION_CACHE = path15.join(os7.homedir(), ".exe-os", "session-cache");
5453
- INTERCOM_LOG2 = path15.join(os7.homedir(), ".exe-os", "intercom.log");
5454
- DEBOUNCE_FILE = path15.join(SESSION_CACHE, "intercom-debounce.json");
6427
+ SPAWN_LOCK_DIR = path17.join(os9.homedir(), ".exe-os", "spawn-locks");
6428
+ SESSION_CACHE = path17.join(os9.homedir(), ".exe-os", "session-cache");
6429
+ INTERCOM_LOG2 = path17.join(os9.homedir(), ".exe-os", "intercom.log");
6430
+ DEBOUNCE_FILE = path17.join(SESSION_CACHE, "intercom-debounce.json");
5455
6431
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
5456
6432
  }
5457
6433
  });
@@ -5460,7 +6436,8 @@ var init_tmux_routing = __esm({
5460
6436
  var task_scope_exports = {};
5461
6437
  __export(task_scope_exports, {
5462
6438
  getCurrentSessionScope: () => getCurrentSessionScope,
5463
- sessionScopeFilter: () => sessionScopeFilter
6439
+ sessionScopeFilter: () => sessionScopeFilter,
6440
+ strictSessionScopeFilter: () => strictSessionScopeFilter
5464
6441
  });
5465
6442
  function getCurrentSessionScope() {
5466
6443
  try {
@@ -5478,6 +6455,15 @@ function sessionScopeFilter(sessionScope, tableAlias) {
5478
6455
  args: [scope]
5479
6456
  };
5480
6457
  }
6458
+ function strictSessionScopeFilter(sessionScope, tableAlias) {
6459
+ const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
6460
+ if (!scope) return { sql: "", args: [] };
6461
+ const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
6462
+ return {
6463
+ sql: ` AND ${col} = ?`,
6464
+ args: [scope]
6465
+ };
6466
+ }
5481
6467
  var init_task_scope = __esm({
5482
6468
  "src/lib/task-scope.ts"() {
5483
6469
  "use strict";
@@ -5487,8 +6473,8 @@ var init_task_scope = __esm({
5487
6473
 
5488
6474
  // src/adapters/claude/hooks/session-start.ts
5489
6475
  init_config();
5490
- import path16 from "path";
5491
- import { unlinkSync as unlinkSync4 } from "fs";
6476
+ import path18 from "path";
6477
+ import { unlinkSync as unlinkSync4, existsSync as existsSync15, readFileSync as readFileSync12 } from "fs";
5492
6478
  if (!process.env.AGENT_ID) {
5493
6479
  process.env.AGENT_ID = "default";
5494
6480
  process.env.AGENT_ROLE = "employee";
@@ -5521,8 +6507,8 @@ process.stdin.on("end", async () => {
5521
6507
  const source = data.source ?? "startup";
5522
6508
  if (source === "startup") {
5523
6509
  try {
5524
- const undefinedPath = path16.join(
5525
- process.env.EXE_OS_DIR ?? path16.join(process.env.HOME ?? "", ".exe-os"),
6510
+ const undefinedPath = path18.join(
6511
+ process.env.EXE_OS_DIR ?? path18.join(process.env.HOME ?? "", ".exe-os"),
5526
6512
  "session-cache",
5527
6513
  "active-agent-undefined.json"
5528
6514
  );
@@ -5533,6 +6519,30 @@ process.stdin.on("end", async () => {
5533
6519
  await initStore2({ dbPath: hookConfig.dbPath, lightweight: true });
5534
6520
  const agent = getActiveAgent2();
5535
6521
  const agentId = agent.agentId;
6522
+ if (agentId !== "default") {
6523
+ try {
6524
+ const cacheDir = path18.join(
6525
+ process.env.EXE_OS_DIR ?? path18.join(process.env.HOME ?? "", ".exe-os"),
6526
+ "session-cache"
6527
+ );
6528
+ const markerPath = path18.join(cacheDir, `current-task-${agentId}.json`);
6529
+ if (existsSync15(markerPath)) {
6530
+ const marker = JSON.parse(readFileSync12(markerPath, "utf-8"));
6531
+ if (marker.taskId) {
6532
+ const client = getClient2();
6533
+ const result = await client.execute({
6534
+ sql: "SELECT status FROM tasks WHERE id = ? LIMIT 1",
6535
+ args: [marker.taskId]
6536
+ });
6537
+ const status = result.rows[0]?.status;
6538
+ if (!status || status !== "in_progress") {
6539
+ unlinkSync4(markerPath);
6540
+ }
6541
+ }
6542
+ }
6543
+ } catch {
6544
+ }
6545
+ }
5536
6546
  try {
5537
6547
  const sessionId = data.session_id;
5538
6548
  if (sessionId && agentId !== "default") {