@askexenow/exe-os 0.8.80 → 0.8.82

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 (110) hide show
  1. package/dist/bin/backfill-conversations.js +359 -267
  2. package/dist/bin/backfill-responses.js +357 -265
  3. package/dist/bin/backfill-vectors.js +339 -264
  4. package/dist/bin/cleanup-stale-review-tasks.js +315 -256
  5. package/dist/bin/cli.js +494 -240
  6. package/dist/bin/exe-agent.js +141 -46
  7. package/dist/bin/exe-assign.js +151 -63
  8. package/dist/bin/exe-boot.js +294 -115
  9. package/dist/bin/exe-call.js +76 -51
  10. package/dist/bin/exe-cloud.js +58 -45
  11. package/dist/bin/exe-dispatch.js +434 -277
  12. package/dist/bin/exe-doctor.js +317 -246
  13. package/dist/bin/exe-export-behaviors.js +328 -248
  14. package/dist/bin/exe-forget.js +314 -231
  15. package/dist/bin/exe-gateway.js +2676 -1402
  16. package/dist/bin/exe-heartbeat.js +329 -264
  17. package/dist/bin/exe-kill.js +324 -244
  18. package/dist/bin/exe-launch-agent.js +574 -463
  19. package/dist/bin/exe-link.js +1055 -95
  20. package/dist/bin/exe-new-employee.js +49 -54
  21. package/dist/bin/exe-pending-messages.js +310 -253
  22. package/dist/bin/exe-pending-notifications.js +299 -228
  23. package/dist/bin/exe-pending-reviews.js +314 -245
  24. package/dist/bin/exe-rename.js +259 -195
  25. package/dist/bin/exe-review.js +140 -64
  26. package/dist/bin/exe-search.js +543 -356
  27. package/dist/bin/exe-session-cleanup.js +463 -382
  28. package/dist/bin/exe-settings.js +129 -99
  29. package/dist/bin/exe-start.sh +6 -6
  30. package/dist/bin/exe-status.js +95 -36
  31. package/dist/bin/exe-team.js +116 -51
  32. package/dist/bin/git-sweep.js +482 -307
  33. package/dist/bin/graph-backfill.js +357 -245
  34. package/dist/bin/graph-export.js +324 -244
  35. package/dist/bin/install.js +33 -10
  36. package/dist/bin/scan-tasks.js +481 -307
  37. package/dist/bin/setup.js +1147 -140
  38. package/dist/bin/shard-migrate.js +321 -241
  39. package/dist/bin/update.js +1 -7
  40. package/dist/bin/wiki-sync.js +318 -238
  41. package/dist/gateway/index.js +2656 -1383
  42. package/dist/hooks/bug-report-worker.js +641 -472
  43. package/dist/hooks/commit-complete.js +482 -307
  44. package/dist/hooks/error-recall.js +363 -135
  45. package/dist/hooks/exe-heartbeat-hook.js +97 -27
  46. package/dist/hooks/ingest-worker.js +584 -397
  47. package/dist/hooks/ingest.js +123 -58
  48. package/dist/hooks/instructions-loaded.js +212 -82
  49. package/dist/hooks/notification.js +200 -70
  50. package/dist/hooks/post-compact.js +199 -81
  51. package/dist/hooks/pre-compact.js +352 -140
  52. package/dist/hooks/pre-tool-use.js +416 -278
  53. package/dist/hooks/prompt-ingest-worker.js +376 -299
  54. package/dist/hooks/prompt-submit.js +414 -188
  55. package/dist/hooks/response-ingest-worker.js +408 -338
  56. package/dist/hooks/session-end.js +209 -83
  57. package/dist/hooks/session-start.js +382 -158
  58. package/dist/hooks/stop.js +209 -83
  59. package/dist/hooks/subagent-stop.js +209 -85
  60. package/dist/hooks/summary-worker.js +606 -510
  61. package/dist/index.js +2133 -855
  62. package/dist/lib/cloud-sync.js +1175 -184
  63. package/dist/lib/config.js +1 -9
  64. package/dist/lib/consolidation.js +71 -34
  65. package/dist/lib/database.js +166 -14
  66. package/dist/lib/device-registry.js +189 -117
  67. package/dist/lib/embedder.js +6 -10
  68. package/dist/lib/employee-templates.js +134 -39
  69. package/dist/lib/employees.js +30 -7
  70. package/dist/lib/exe-daemon-client.js +5 -7
  71. package/dist/lib/exe-daemon.js +514 -152
  72. package/dist/lib/hybrid-search.js +543 -356
  73. package/dist/lib/identity-templates.js +15 -15
  74. package/dist/lib/identity.js +19 -15
  75. package/dist/lib/license.js +1 -7
  76. package/dist/lib/messaging.js +157 -135
  77. package/dist/lib/reminders.js +97 -0
  78. package/dist/lib/schedules.js +302 -231
  79. package/dist/lib/skill-learning.js +33 -27
  80. package/dist/lib/status-brief.js +11 -14
  81. package/dist/lib/store.js +326 -237
  82. package/dist/lib/task-router.js +105 -1
  83. package/dist/lib/tasks.js +233 -116
  84. package/dist/lib/tmux-routing.js +173 -56
  85. package/dist/lib/ws-client.js +13 -3
  86. package/dist/mcp/server.js +2009 -1015
  87. package/dist/mcp/tools/complete-reminder.js +97 -0
  88. package/dist/mcp/tools/create-reminder.js +97 -0
  89. package/dist/mcp/tools/create-task.js +426 -262
  90. package/dist/mcp/tools/deactivate-behavior.js +119 -44
  91. package/dist/mcp/tools/list-reminders.js +97 -0
  92. package/dist/mcp/tools/list-tasks.js +56 -57
  93. package/dist/mcp/tools/send-message.js +206 -143
  94. package/dist/mcp/tools/update-task.js +259 -85
  95. package/dist/runtime/index.js +495 -316
  96. package/dist/tui/App.js +1128 -919
  97. package/package.json +2 -10
  98. package/src/commands/exe/afk.md +8 -8
  99. package/src/commands/exe/assign.md +1 -1
  100. package/src/commands/exe/build-adv.md +1 -1
  101. package/src/commands/exe/call.md +10 -10
  102. package/src/commands/exe/employee-heartbeat.md +9 -6
  103. package/src/commands/exe/heartbeat.md +5 -5
  104. package/src/commands/exe/intercom.md +26 -15
  105. package/src/commands/exe/launch.md +2 -2
  106. package/src/commands/exe/new-employee.md +1 -1
  107. package/src/commands/exe/review.md +2 -2
  108. package/src/commands/exe/schedule.md +1 -1
  109. package/src/commands/exe/sessions.md +2 -2
  110. package/src/commands/exe.md +22 -20
@@ -57,7 +57,7 @@ function wrapWithRetry(client) {
57
57
  return (sql) => retryOnBusy(() => target.execute(sql), "execute");
58
58
  }
59
59
  if (prop === "batch") {
60
- return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
60
+ return (stmts, mode) => retryOnBusy(() => target.batch(stmts, mode), "batch");
61
61
  }
62
62
  return Reflect.get(target, prop, receiver);
63
63
  }
@@ -73,6 +73,283 @@ var init_db_retry = __esm({
73
73
  }
74
74
  });
75
75
 
76
+ // src/lib/config.ts
77
+ var config_exports = {};
78
+ __export(config_exports, {
79
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
80
+ CONFIG_PATH: () => CONFIG_PATH,
81
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
82
+ DB_PATH: () => DB_PATH,
83
+ EXE_AI_DIR: () => EXE_AI_DIR,
84
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
85
+ MODELS_DIR: () => MODELS_DIR,
86
+ loadConfig: () => loadConfig,
87
+ loadConfigFrom: () => loadConfigFrom,
88
+ loadConfigSync: () => loadConfigSync,
89
+ migrateConfig: () => migrateConfig,
90
+ saveConfig: () => saveConfig
91
+ });
92
+ import { readFile, writeFile, mkdir, chmod } from "fs/promises";
93
+ import { readFileSync, existsSync, renameSync } from "fs";
94
+ import path from "path";
95
+ import os from "os";
96
+ function resolveDataDir() {
97
+ if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
98
+ if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
99
+ const newDir = path.join(os.homedir(), ".exe-os");
100
+ const legacyDir = path.join(os.homedir(), ".exe-mem");
101
+ if (!existsSync(newDir) && existsSync(legacyDir)) {
102
+ try {
103
+ renameSync(legacyDir, newDir);
104
+ process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
105
+ `);
106
+ } catch {
107
+ return legacyDir;
108
+ }
109
+ }
110
+ return newDir;
111
+ }
112
+ function migrateLegacyConfig(raw) {
113
+ if ("r2" in raw) {
114
+ process.stderr.write(
115
+ "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
116
+ );
117
+ delete raw.r2;
118
+ }
119
+ if ("syncIntervalMs" in raw) {
120
+ delete raw.syncIntervalMs;
121
+ }
122
+ return raw;
123
+ }
124
+ function migrateConfig(raw) {
125
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
126
+ let currentVersion = fromVersion;
127
+ let migrated = false;
128
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
129
+ return { config: raw, migrated: false, fromVersion };
130
+ }
131
+ for (const migration of CONFIG_MIGRATIONS) {
132
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
133
+ raw = migration.migrate(raw);
134
+ currentVersion = migration.to;
135
+ migrated = true;
136
+ }
137
+ }
138
+ return { config: raw, migrated, fromVersion };
139
+ }
140
+ function normalizeScalingRoadmap(raw) {
141
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
142
+ const userRoadmap = raw.scalingRoadmap ?? {};
143
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
144
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
145
+ userAuto.enabled = raw.rerankerEnabled;
146
+ }
147
+ raw.scalingRoadmap = {
148
+ ...userRoadmap,
149
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
150
+ };
151
+ }
152
+ function normalizeSessionLifecycle(raw) {
153
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
154
+ const userSL = raw.sessionLifecycle ?? {};
155
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
156
+ }
157
+ function normalizeAutoUpdate(raw) {
158
+ const defaultAU = DEFAULT_CONFIG.autoUpdate;
159
+ const userAU = raw.autoUpdate ?? {};
160
+ raw.autoUpdate = { ...defaultAU, ...userAU };
161
+ }
162
+ async function loadConfig() {
163
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
164
+ await mkdir(dir, { recursive: true });
165
+ const configPath = path.join(dir, "config.json");
166
+ if (!existsSync(configPath)) {
167
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
168
+ }
169
+ const raw = await readFile(configPath, "utf-8");
170
+ try {
171
+ let parsed = JSON.parse(raw);
172
+ parsed = migrateLegacyConfig(parsed);
173
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
174
+ if (migrated) {
175
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
176
+ `);
177
+ try {
178
+ await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
179
+ } catch {
180
+ }
181
+ }
182
+ normalizeScalingRoadmap(migratedCfg);
183
+ normalizeSessionLifecycle(migratedCfg);
184
+ normalizeAutoUpdate(migratedCfg);
185
+ const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
186
+ if (config.dbPath.startsWith("~")) {
187
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
188
+ }
189
+ return config;
190
+ } catch {
191
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
192
+ }
193
+ }
194
+ function loadConfigSync() {
195
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
196
+ const configPath = path.join(dir, "config.json");
197
+ if (!existsSync(configPath)) {
198
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
199
+ }
200
+ try {
201
+ const raw = readFileSync(configPath, "utf-8");
202
+ let parsed = JSON.parse(raw);
203
+ parsed = migrateLegacyConfig(parsed);
204
+ const { config: migratedCfg } = migrateConfig(parsed);
205
+ normalizeScalingRoadmap(migratedCfg);
206
+ normalizeSessionLifecycle(migratedCfg);
207
+ normalizeAutoUpdate(migratedCfg);
208
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
209
+ } catch {
210
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
211
+ }
212
+ }
213
+ async function saveConfig(config) {
214
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
215
+ await mkdir(dir, { recursive: true });
216
+ const configPath = path.join(dir, "config.json");
217
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
218
+ if (config.cloud?.apiKey) {
219
+ await chmod(configPath, 384);
220
+ }
221
+ }
222
+ async function loadConfigFrom(configPath) {
223
+ const raw = await readFile(configPath, "utf-8");
224
+ try {
225
+ let parsed = JSON.parse(raw);
226
+ parsed = migrateLegacyConfig(parsed);
227
+ const { config: migratedCfg } = migrateConfig(parsed);
228
+ normalizeScalingRoadmap(migratedCfg);
229
+ normalizeSessionLifecycle(migratedCfg);
230
+ normalizeAutoUpdate(migratedCfg);
231
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
232
+ } catch {
233
+ return { ...DEFAULT_CONFIG };
234
+ }
235
+ }
236
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
237
+ var init_config = __esm({
238
+ "src/lib/config.ts"() {
239
+ "use strict";
240
+ EXE_AI_DIR = resolveDataDir();
241
+ DB_PATH = path.join(EXE_AI_DIR, "memories.db");
242
+ MODELS_DIR = path.join(EXE_AI_DIR, "models");
243
+ CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
244
+ LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
245
+ CURRENT_CONFIG_VERSION = 1;
246
+ DEFAULT_CONFIG = {
247
+ config_version: CURRENT_CONFIG_VERSION,
248
+ dbPath: DB_PATH,
249
+ modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
250
+ embeddingDim: 1024,
251
+ batchSize: 20,
252
+ flushIntervalMs: 1e4,
253
+ autoIngestion: true,
254
+ autoRetrieval: true,
255
+ searchMode: "hybrid",
256
+ hookSearchMode: "hybrid",
257
+ fileGrepEnabled: true,
258
+ splashEffect: true,
259
+ consolidationEnabled: true,
260
+ consolidationIntervalMs: 6 * 60 * 60 * 1e3,
261
+ consolidationModel: "claude-haiku-4-5-20251001",
262
+ consolidationMaxCallsPerRun: 20,
263
+ selfQueryRouter: true,
264
+ selfQueryModel: "claude-haiku-4-5-20251001",
265
+ rerankerEnabled: true,
266
+ scalingRoadmap: {
267
+ rerankerAutoTrigger: {
268
+ enabled: true,
269
+ broadQueryMinCardinality: 5e4,
270
+ fetchTopK: 150,
271
+ returnTopK: 5
272
+ }
273
+ },
274
+ graphRagEnabled: true,
275
+ wikiEnabled: false,
276
+ wikiUrl: "",
277
+ wikiApiKey: "",
278
+ wikiSyncIntervalMs: 30 * 60 * 1e3,
279
+ wikiWorkspaceMapping: {},
280
+ wikiAutoUpdate: true,
281
+ wikiAutoUpdateThreshold: 0.5,
282
+ wikiAutoUpdateCreateNew: true,
283
+ skillLearning: true,
284
+ skillThreshold: 3,
285
+ skillModel: "claude-haiku-4-5-20251001",
286
+ exeHeartbeat: {
287
+ enabled: true,
288
+ intervalSeconds: 60,
289
+ staleInProgressThresholdHours: 2
290
+ },
291
+ sessionLifecycle: {
292
+ idleKillEnabled: true,
293
+ idleKillTicksRequired: 3,
294
+ idleKillIntercomAckWindowMs: 1e4,
295
+ maxAutoInstances: 10
296
+ },
297
+ autoUpdate: {
298
+ checkOnBoot: true,
299
+ autoInstall: false,
300
+ checkIntervalMs: 24 * 60 * 60 * 1e3
301
+ }
302
+ };
303
+ CONFIG_MIGRATIONS = [
304
+ {
305
+ from: 0,
306
+ to: 1,
307
+ migrate: (cfg) => {
308
+ cfg.config_version = 1;
309
+ return cfg;
310
+ }
311
+ }
312
+ ];
313
+ }
314
+ });
315
+
316
+ // src/lib/employees.ts
317
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
318
+ import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
319
+ import { execSync } from "child_process";
320
+ import path2 from "path";
321
+ import os2 from "os";
322
+ function normalizeRole(role) {
323
+ return (role ?? "").trim().toLowerCase();
324
+ }
325
+ function isCoordinatorRole(role) {
326
+ return normalizeRole(role) === normalizeRole(COORDINATOR_ROLE);
327
+ }
328
+ function getCoordinatorEmployee(employees) {
329
+ return employees.find((e) => isCoordinatorRole(e.role));
330
+ }
331
+ function getCoordinatorName(employees = loadEmployeesSync()) {
332
+ return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
333
+ }
334
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
335
+ if (!existsSync2(employeesPath)) return [];
336
+ try {
337
+ return JSON.parse(readFileSync2(employeesPath, "utf-8"));
338
+ } catch {
339
+ return [];
340
+ }
341
+ }
342
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
343
+ var init_employees = __esm({
344
+ "src/lib/employees.ts"() {
345
+ "use strict";
346
+ init_config();
347
+ EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
348
+ DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
349
+ COORDINATOR_ROLE = "COO";
350
+ }
351
+ });
352
+
76
353
  // src/lib/database.ts
77
354
  import { createClient } from "@libsql/client";
78
355
  async function initDatabase(config) {
@@ -206,22 +483,24 @@ async function ensureSchema() {
206
483
  ON behaviors(agent_id, active);
207
484
  `);
208
485
  try {
486
+ const coordinatorName = getCoordinatorName();
209
487
  const existing = await client.execute({
210
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
211
- args: []
488
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
489
+ args: [coordinatorName]
212
490
  });
213
491
  if (Number(existing.rows[0]?.cnt) === 0) {
214
- await client.executeMultiple(`
215
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
216
- VALUES
217
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
218
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
219
- VALUES
220
- (hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
221
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
222
- VALUES
223
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
224
- `);
492
+ const seededAt = "2026-03-25T00:00:00Z";
493
+ for (const [domain, content] of [
494
+ ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
495
+ ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
496
+ ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
497
+ ]) {
498
+ await client.execute({
499
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
500
+ VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
501
+ args: [coordinatorName, domain, content, seededAt, seededAt]
502
+ });
503
+ }
225
504
  }
226
505
  } catch {
227
506
  }
@@ -913,6 +1192,39 @@ async function ensureSchema() {
913
1192
  } catch {
914
1193
  }
915
1194
  }
1195
+ try {
1196
+ await client.execute({
1197
+ sql: `ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0`,
1198
+ args: []
1199
+ });
1200
+ } catch {
1201
+ }
1202
+ try {
1203
+ await client.execute(
1204
+ `CREATE INDEX IF NOT EXISTS idx_memories_draft ON memories(draft) WHERE draft = 1`
1205
+ );
1206
+ } catch {
1207
+ }
1208
+ try {
1209
+ await client.execute({
1210
+ sql: `ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'`,
1211
+ args: []
1212
+ });
1213
+ } catch {
1214
+ }
1215
+ try {
1216
+ await client.execute(
1217
+ `CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(memory_type)`
1218
+ );
1219
+ } catch {
1220
+ }
1221
+ try {
1222
+ await client.execute({
1223
+ sql: `ALTER TABLE memories ADD COLUMN trajectory TEXT`,
1224
+ args: []
1225
+ });
1226
+ } catch {
1227
+ }
916
1228
  }
917
1229
  async function disposeDatabase() {
918
1230
  if (_client) {
@@ -926,6 +1238,7 @@ var init_database = __esm({
926
1238
  "src/lib/database.ts"() {
927
1239
  "use strict";
928
1240
  init_db_retry();
1241
+ init_employees();
929
1242
  _client = null;
930
1243
  _resilientClient = null;
931
1244
  initTurso = initDatabase;
@@ -934,15 +1247,15 @@ var init_database = __esm({
934
1247
  });
935
1248
 
936
1249
  // src/lib/keychain.ts
937
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
938
- import { existsSync } from "fs";
939
- import path from "path";
940
- import os from "os";
1250
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1251
+ import { existsSync as existsSync3 } from "fs";
1252
+ import path3 from "path";
1253
+ import os3 from "os";
941
1254
  function getKeyDir() {
942
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(os.homedir(), ".exe-os");
1255
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
943
1256
  }
944
1257
  function getKeyPath() {
945
- return path.join(getKeyDir(), "master.key");
1258
+ return path3.join(getKeyDir(), "master.key");
946
1259
  }
947
1260
  async function tryKeytar() {
948
1261
  try {
@@ -963,11 +1276,11 @@ async function getMasterKey() {
963
1276
  }
964
1277
  }
965
1278
  const keyPath = getKeyPath();
966
- if (!existsSync(keyPath)) {
1279
+ if (!existsSync3(keyPath)) {
967
1280
  return null;
968
1281
  }
969
1282
  try {
970
- const content = await readFile(keyPath, "utf-8");
1283
+ const content = await readFile3(keyPath, "utf-8");
971
1284
  return Buffer.from(content.trim(), "base64");
972
1285
  } catch {
973
1286
  return null;
@@ -982,254 +1295,6 @@ var init_keychain = __esm({
982
1295
  }
983
1296
  });
984
1297
 
985
- // src/lib/config.ts
986
- var config_exports = {};
987
- __export(config_exports, {
988
- CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
989
- CONFIG_PATH: () => CONFIG_PATH,
990
- COO_AGENT_NAME: () => COO_AGENT_NAME,
991
- CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
992
- DB_PATH: () => DB_PATH,
993
- EXE_AI_DIR: () => EXE_AI_DIR,
994
- LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
995
- MODELS_DIR: () => MODELS_DIR,
996
- loadConfig: () => loadConfig,
997
- loadConfigFrom: () => loadConfigFrom,
998
- loadConfigSync: () => loadConfigSync,
999
- migrateConfig: () => migrateConfig,
1000
- saveConfig: () => saveConfig
1001
- });
1002
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
1003
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
1004
- import path2 from "path";
1005
- import os2 from "os";
1006
- function resolveDataDir() {
1007
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
1008
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
1009
- const newDir = path2.join(os2.homedir(), ".exe-os");
1010
- const legacyDir = path2.join(os2.homedir(), ".exe-mem");
1011
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
1012
- try {
1013
- renameSync(legacyDir, newDir);
1014
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
1015
- `);
1016
- } catch {
1017
- return legacyDir;
1018
- }
1019
- }
1020
- return newDir;
1021
- }
1022
- function migrateLegacyConfig(raw) {
1023
- if ("r2" in raw) {
1024
- process.stderr.write(
1025
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
1026
- );
1027
- delete raw.r2;
1028
- }
1029
- if ("syncIntervalMs" in raw) {
1030
- delete raw.syncIntervalMs;
1031
- }
1032
- return raw;
1033
- }
1034
- function migrateConfig(raw) {
1035
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
1036
- let currentVersion = fromVersion;
1037
- let migrated = false;
1038
- if (currentVersion > CURRENT_CONFIG_VERSION) {
1039
- return { config: raw, migrated: false, fromVersion };
1040
- }
1041
- for (const migration of CONFIG_MIGRATIONS) {
1042
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
1043
- raw = migration.migrate(raw);
1044
- currentVersion = migration.to;
1045
- migrated = true;
1046
- }
1047
- }
1048
- return { config: raw, migrated, fromVersion };
1049
- }
1050
- function normalizeScalingRoadmap(raw) {
1051
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
1052
- const userRoadmap = raw.scalingRoadmap ?? {};
1053
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
1054
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
1055
- userAuto.enabled = raw.rerankerEnabled;
1056
- }
1057
- raw.scalingRoadmap = {
1058
- ...userRoadmap,
1059
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
1060
- };
1061
- }
1062
- function normalizeSessionLifecycle(raw) {
1063
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
1064
- const userSL = raw.sessionLifecycle ?? {};
1065
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
1066
- }
1067
- function normalizeAutoUpdate(raw) {
1068
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
1069
- const userAU = raw.autoUpdate ?? {};
1070
- raw.autoUpdate = { ...defaultAU, ...userAU };
1071
- }
1072
- async function loadConfig() {
1073
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1074
- await mkdir2(dir, { recursive: true });
1075
- const configPath = path2.join(dir, "config.json");
1076
- if (!existsSync2(configPath)) {
1077
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1078
- }
1079
- const raw = await readFile2(configPath, "utf-8");
1080
- try {
1081
- let parsed = JSON.parse(raw);
1082
- parsed = migrateLegacyConfig(parsed);
1083
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
1084
- if (migrated) {
1085
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
1086
- `);
1087
- try {
1088
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
1089
- } catch {
1090
- }
1091
- }
1092
- normalizeScalingRoadmap(migratedCfg);
1093
- normalizeSessionLifecycle(migratedCfg);
1094
- normalizeAutoUpdate(migratedCfg);
1095
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1096
- if (config.dbPath.startsWith("~")) {
1097
- config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
1098
- }
1099
- return config;
1100
- } catch {
1101
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1102
- }
1103
- }
1104
- function loadConfigSync() {
1105
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1106
- const configPath = path2.join(dir, "config.json");
1107
- if (!existsSync2(configPath)) {
1108
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1109
- }
1110
- try {
1111
- const raw = readFileSync(configPath, "utf-8");
1112
- let parsed = JSON.parse(raw);
1113
- parsed = migrateLegacyConfig(parsed);
1114
- const { config: migratedCfg } = migrateConfig(parsed);
1115
- normalizeScalingRoadmap(migratedCfg);
1116
- normalizeSessionLifecycle(migratedCfg);
1117
- normalizeAutoUpdate(migratedCfg);
1118
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1119
- } catch {
1120
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1121
- }
1122
- }
1123
- async function saveConfig(config) {
1124
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1125
- await mkdir2(dir, { recursive: true });
1126
- const configPath = path2.join(dir, "config.json");
1127
- await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
1128
- if (config.cloud?.apiKey) {
1129
- await chmod2(configPath, 384);
1130
- }
1131
- }
1132
- async function loadConfigFrom(configPath) {
1133
- const raw = await readFile2(configPath, "utf-8");
1134
- try {
1135
- let parsed = JSON.parse(raw);
1136
- parsed = migrateLegacyConfig(parsed);
1137
- const { config: migratedCfg } = migrateConfig(parsed);
1138
- normalizeScalingRoadmap(migratedCfg);
1139
- normalizeSessionLifecycle(migratedCfg);
1140
- normalizeAutoUpdate(migratedCfg);
1141
- return { ...DEFAULT_CONFIG, ...migratedCfg };
1142
- } catch {
1143
- return { ...DEFAULT_CONFIG };
1144
- }
1145
- }
1146
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, COO_AGENT_NAME, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
1147
- var init_config = __esm({
1148
- "src/lib/config.ts"() {
1149
- "use strict";
1150
- EXE_AI_DIR = resolveDataDir();
1151
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
1152
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
1153
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
1154
- COO_AGENT_NAME = "exe";
1155
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
1156
- CURRENT_CONFIG_VERSION = 1;
1157
- DEFAULT_CONFIG = {
1158
- config_version: CURRENT_CONFIG_VERSION,
1159
- dbPath: DB_PATH,
1160
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
1161
- embeddingDim: 1024,
1162
- batchSize: 20,
1163
- flushIntervalMs: 1e4,
1164
- autoIngestion: true,
1165
- autoRetrieval: true,
1166
- searchMode: "hybrid",
1167
- hookSearchMode: "hybrid",
1168
- fileGrepEnabled: true,
1169
- splashEffect: true,
1170
- consolidationEnabled: true,
1171
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
1172
- consolidationModel: "claude-haiku-4-5-20251001",
1173
- consolidationMaxCallsPerRun: 20,
1174
- selfQueryRouter: true,
1175
- selfQueryModel: "claude-haiku-4-5-20251001",
1176
- rerankerEnabled: true,
1177
- scalingRoadmap: {
1178
- rerankerAutoTrigger: {
1179
- enabled: true,
1180
- broadQueryMinCardinality: 5e4,
1181
- fetchTopK: 150,
1182
- returnTopK: 5
1183
- }
1184
- },
1185
- graphRagEnabled: true,
1186
- wikiEnabled: false,
1187
- wikiUrl: "",
1188
- wikiApiKey: "",
1189
- wikiSyncIntervalMs: 30 * 60 * 1e3,
1190
- wikiWorkspaceMapping: {
1191
- exe: "Executive",
1192
- yoshi: "Engineering",
1193
- mari: "Marketing",
1194
- tom: "Engineering",
1195
- sasha: "Production"
1196
- },
1197
- wikiAutoUpdate: true,
1198
- wikiAutoUpdateThreshold: 0.5,
1199
- wikiAutoUpdateCreateNew: true,
1200
- skillLearning: true,
1201
- skillThreshold: 3,
1202
- skillModel: "claude-haiku-4-5-20251001",
1203
- exeHeartbeat: {
1204
- enabled: true,
1205
- intervalSeconds: 60,
1206
- staleInProgressThresholdHours: 2
1207
- },
1208
- sessionLifecycle: {
1209
- idleKillEnabled: true,
1210
- idleKillTicksRequired: 3,
1211
- idleKillIntercomAckWindowMs: 1e4,
1212
- maxAutoInstances: 10
1213
- },
1214
- autoUpdate: {
1215
- checkOnBoot: true,
1216
- autoInstall: false,
1217
- checkIntervalMs: 24 * 60 * 60 * 1e3
1218
- }
1219
- };
1220
- CONFIG_MIGRATIONS = [
1221
- {
1222
- from: 0,
1223
- to: 1,
1224
- migrate: (cfg) => {
1225
- cfg.config_version = 1;
1226
- return cfg;
1227
- }
1228
- }
1229
- ];
1230
- }
1231
- });
1232
-
1233
1298
  // src/lib/state-bus.ts
1234
1299
  var StateBus, orgBus;
1235
1300
  var init_state_bus = __esm({
@@ -1298,12 +1363,12 @@ __export(shard_manager_exports, {
1298
1363
  listShards: () => listShards,
1299
1364
  shardExists: () => shardExists
1300
1365
  });
1301
- import path3 from "path";
1302
- import { existsSync as existsSync3, mkdirSync, readdirSync } from "fs";
1366
+ import path4 from "path";
1367
+ import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1303
1368
  import { createClient as createClient2 } from "@libsql/client";
1304
1369
  function initShardManager(encryptionKey) {
1305
1370
  _encryptionKey = encryptionKey;
1306
- if (!existsSync3(SHARDS_DIR)) {
1371
+ if (!existsSync4(SHARDS_DIR)) {
1307
1372
  mkdirSync(SHARDS_DIR, { recursive: true });
1308
1373
  }
1309
1374
  _shardingEnabled = true;
@@ -1324,7 +1389,7 @@ function getShardClient(projectName) {
1324
1389
  }
1325
1390
  const cached = _shards.get(safeName);
1326
1391
  if (cached) return cached;
1327
- const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
1392
+ const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1328
1393
  const client = createClient2({
1329
1394
  url: `file:${dbPath}`,
1330
1395
  encryptionKey: _encryptionKey
@@ -1334,10 +1399,10 @@ function getShardClient(projectName) {
1334
1399
  }
1335
1400
  function shardExists(projectName) {
1336
1401
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1337
- return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
1402
+ return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1338
1403
  }
1339
1404
  function listShards() {
1340
- if (!existsSync3(SHARDS_DIR)) return [];
1405
+ if (!existsSync4(SHARDS_DIR)) return [];
1341
1406
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1342
1407
  }
1343
1408
  async function ensureShardSchema(client) {
@@ -1407,7 +1472,11 @@ async function ensureShardSchema(client) {
1407
1472
  "ALTER TABLE memories ADD COLUMN source_path TEXT",
1408
1473
  "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1409
1474
  "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1410
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1475
+ "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
1476
+ // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1477
+ "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1478
+ "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1479
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT"
1411
1480
  ]) {
1412
1481
  try {
1413
1482
  await client.execute(col);
@@ -1519,7 +1588,7 @@ var init_shard_manager = __esm({
1519
1588
  "src/lib/shard-manager.ts"() {
1520
1589
  "use strict";
1521
1590
  init_config();
1522
- SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
1591
+ SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
1523
1592
  _shards = /* @__PURE__ */ new Map();
1524
1593
  _encryptionKey = null;
1525
1594
  _shardingEnabled = false;
@@ -1537,26 +1606,26 @@ var init_platform_procedures = __esm({
1537
1606
  title: "What is exe-os \u2014 the operating model every agent must understand",
1538
1607
  domain: "architecture",
1539
1608
  priority: "p0",
1540
- content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO (exe), CTO (yoshi), CMO (mari), engineers (tom), content (sasha). Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
1609
+ content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO, CTO, CMO, engineers, and content production specialists. Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
1541
1610
  },
1542
1611
  {
1543
1612
  title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
1544
1613
  domain: "architecture",
1545
1614
  priority: "p0",
1546
- content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code. The founder opens CC, runs /exe to boot the COO. exe manages employees in tmux sessions. Each exeN is a separate CC window/project. Employees (yoshi, tom, mari) run in their own tmux panes via create_task auto-spawn. The founder talks to exe; exe orchestrates the team. CC is the shell, exe-os is the brain."
1615
+ content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code. The founder opens CC and boots the COO. The COO manages employees in tmux sessions. Each coordinator session is a separate CC window/project. Employees run in their own tmux panes via create_task auto-spawn. The founder talks to the COO; the COO orchestrates the team. CC is the shell, exe-os is the brain."
1547
1616
  },
1548
1617
  {
1549
- title: "Sessions explained \u2014 what exeN means and how projects work",
1618
+ title: "Sessions explained \u2014 coordinator session names and projects",
1550
1619
  domain: "architecture",
1551
1620
  priority: "p0",
1552
- content: "Each exeN (exe1, exe2, exe3) is an isolated project session. exe1 might be exe-os development, exe2 might be exe-wiki. Each session spawns its own employees: exe1\u2192yoshi-exe1\u2192tom-exe1. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
1621
+ content: "Each coordinator session is an isolated project session. One might be exe-os development, another might be exe-wiki. Each session spawns its own employees using {employee}-{coordinatorSession}. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
1553
1622
  },
1554
1623
  // --- Hierarchy and dispatch ---
1555
1624
  {
1556
1625
  title: "Chain of command \u2014 who talks to whom",
1557
1626
  domain: "workflow",
1558
1627
  priority: "p0",
1559
- content: "Founder \u2192 exe (COO) \u2192 yoshi (CTO) / mari (CMO). Yoshi \u2192 tom (engineer). Mari \u2192 sasha (content). Never skip levels: exe never assigns directly to tom. Tom never reports directly to exe. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
1628
+ content: "Founder -> COO -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the COO does not bypass managers for specialist work. Specialists report to their manager. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
1560
1629
  },
1561
1630
  {
1562
1631
  title: "Single dispatch path \u2014 create_task only",
@@ -1566,30 +1635,30 @@ var init_platform_procedures = __esm({
1566
1635
  },
1567
1636
  // --- Session isolation ---
1568
1637
  {
1569
- title: "Session scoping \u2014 stay in your exe boundary",
1638
+ title: "Session scoping \u2014 stay in your coordinator boundary",
1570
1639
  domain: "security",
1571
1640
  priority: "p0",
1572
- content: "Session scoping is mandatory. Managers dispatch to workers within their own exe session ONLY. exe1\u2192yoshi-exe1\u2192tom-exe1. exe2\u2192yoshi-exe2\u2192tom2-exe2. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating exe session."
1641
+ content: "Session scoping is mandatory. Managers dispatch to workers within their own coordinator session ONLY. Employee sessions use {employee}-{coordinatorSession}. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating coordinator session."
1573
1642
  },
1574
1643
  {
1575
1644
  title: "Session isolation \u2014 never touch another session's work",
1576
1645
  domain: "workflow",
1577
1646
  priority: "p0",
1578
- content: `Sessions are isolated. exeN owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another exe session. (2) Never review work from a different session \u2014 report "belongs to exeN" and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: yoshi-exe1 works ONLY on exe1 tasks. Cross-session work is a system violation.`
1647
+ content: "Sessions are isolated. A coordinator session owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another coordinator session. (2) Never review work from a different session \u2014 report that it belongs to another session and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: employee sessions work ONLY on their parent coordinator session's tasks. Cross-session work is a system violation."
1579
1648
  },
1580
1649
  // --- Engineering: session scoping in code ---
1581
1650
  {
1582
1651
  title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
1583
1652
  domain: "architecture",
1584
1653
  priority: "p0",
1585
- content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching current exeN. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ exe sessions simultaneously."
1654
+ content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching the current coordinator session. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ coordinator sessions simultaneously."
1586
1655
  },
1587
1656
  // --- Hard constraints ---
1588
1657
  {
1589
1658
  title: "What you CANNOT do in exe-os \u2014 hard constraints",
1590
1659
  domain: "security",
1591
1660
  priority: "p0",
1592
- content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 exe reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
1661
+ content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 the COO reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
1593
1662
  },
1594
1663
  // --- Operations ---
1595
1664
  {
@@ -1829,7 +1898,10 @@ async function writeMemory(record) {
1829
1898
  source_path: record.source_path ?? null,
1830
1899
  source_type: record.source_type ?? null,
1831
1900
  tier: record.tier ?? classifyTier(record),
1832
- supersedes_id: record.supersedes_id ?? null
1901
+ supersedes_id: record.supersedes_id ?? null,
1902
+ draft: record.draft ? 1 : 0,
1903
+ memory_type: record.memory_type ?? "raw",
1904
+ trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null
1833
1905
  };
1834
1906
  _pendingRecords.push(dbRow);
1835
1907
  orgBus.emit({
@@ -1884,6 +1956,9 @@ async function flushBatch() {
1884
1956
  const sourceType = row.source_type ?? null;
1885
1957
  const tier = row.tier ?? 3;
1886
1958
  const supersedesId = row.supersedes_id ?? null;
1959
+ const draft = row.draft ? 1 : 0;
1960
+ const memoryType = row.memory_type ?? "raw";
1961
+ const trajectory = row.trajectory ?? null;
1887
1962
  return {
1888
1963
  sql: hasVector ? `INSERT OR IGNORE INTO memories
1889
1964
  (id, agent_id, agent_role, session_id, timestamp,
@@ -1891,15 +1966,15 @@ async function flushBatch() {
1891
1966
  has_error, raw_text, vector, version, task_id, importance, status,
1892
1967
  confidence, last_accessed,
1893
1968
  workspace_id, document_id, user_id, char_offset, page_number,
1894
- source_path, source_type, tier, supersedes_id)
1895
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1969
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory)
1970
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1896
1971
  (id, agent_id, agent_role, session_id, timestamp,
1897
1972
  tool_name, project_name,
1898
1973
  has_error, raw_text, vector, version, task_id, importance, status,
1899
1974
  confidence, last_accessed,
1900
1975
  workspace_id, document_id, user_id, char_offset, page_number,
1901
- source_path, source_type, tier, supersedes_id)
1902
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1976
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory)
1977
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1903
1978
  args: hasVector ? [
1904
1979
  row.id,
1905
1980
  row.agent_id,
@@ -1925,7 +2000,10 @@ async function flushBatch() {
1925
2000
  sourcePath,
1926
2001
  sourceType,
1927
2002
  tier,
1928
- supersedesId
2003
+ supersedesId,
2004
+ draft,
2005
+ memoryType,
2006
+ trajectory
1929
2007
  ] : [
1930
2008
  row.id,
1931
2009
  row.agent_id,
@@ -1950,7 +2028,10 @@ async function flushBatch() {
1950
2028
  sourcePath,
1951
2029
  sourceType,
1952
2030
  tier,
1953
- supersedesId
2031
+ supersedesId,
2032
+ draft,
2033
+ memoryType,
2034
+ trajectory
1954
2035
  ]
1955
2036
  };
1956
2037
  };
@@ -2019,6 +2100,8 @@ async function searchMemories(queryVector, agentId, options) {
2019
2100
  const limit = options?.limit ?? 10;
2020
2101
  const statusFilter = options?.includeArchived ? "" : `
2021
2102
  AND COALESCE(status, 'active') = 'active'`;
2103
+ const draftFilter = options?.includeDrafts ? "" : `
2104
+ AND (draft = 0 OR draft IS NULL)`;
2022
2105
  let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
2023
2106
  tool_name, project_name,
2024
2107
  has_error, raw_text, vector, importance, status,
@@ -2028,7 +2111,7 @@ async function searchMemories(queryVector, agentId, options) {
2028
2111
  source_path, source_type
2029
2112
  FROM memories
2030
2113
  WHERE agent_id = ?
2031
- AND vector IS NOT NULL${statusFilter}
2114
+ AND vector IS NOT NULL${statusFilter}${draftFilter}
2032
2115
  AND COALESCE(confidence, 0.7) >= 0.3`;
2033
2116
  const args = [agentId];
2034
2117
  const scope = buildWikiScopeFilter(options, "");
@@ -2050,6 +2133,10 @@ async function searchMemories(queryVector, agentId, options) {
2050
2133
  sql += ` AND timestamp >= ?`;
2051
2134
  args.push(options.since);
2052
2135
  }
2136
+ if (options?.memoryType) {
2137
+ sql += ` AND memory_type = ?`;
2138
+ args.push(options.memoryType);
2139
+ }
2053
2140
  sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
2054
2141
  args.push(vectorToBlob(queryVector));
2055
2142
  sql += ` LIMIT ?`;
@@ -2275,7 +2362,7 @@ var init_self_query_router = __esm({
2275
2362
  },
2276
2363
  is_broad_query: {
2277
2364
  type: "boolean",
2278
- description: "True if the query is exploratory/broad (e.g., 'what has yoshi been working on', 'summarize recent activity'). False if targeted (e.g., 'how did we fix the auth bug')."
2365
+ description: "True if the query is exploratory/broad (e.g., 'what has the CTO been working on', 'summarize recent activity'). False if targeted (e.g., 'how did we fix the auth bug')."
2279
2366
  }
2280
2367
  },
2281
2368
  required: ["semantic_query", "project_filter", "role_filter", "time_filter", "is_broad_query"]
@@ -2288,8 +2375,8 @@ var init_self_query_router = __esm({
2288
2375
  import net from "net";
2289
2376
  import { spawn } from "child_process";
2290
2377
  import { randomUUID as randomUUID2 } from "crypto";
2291
- import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
2292
- import path4 from "path";
2378
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync3, openSync, closeSync, statSync } from "fs";
2379
+ import path5 from "path";
2293
2380
  import { fileURLToPath } from "url";
2294
2381
  function handleData(chunk) {
2295
2382
  _buffer += chunk.toString();
@@ -2315,9 +2402,9 @@ function handleData(chunk) {
2315
2402
  }
2316
2403
  }
2317
2404
  function cleanupStaleFiles() {
2318
- if (existsSync4(PID_PATH)) {
2405
+ if (existsSync5(PID_PATH)) {
2319
2406
  try {
2320
- const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
2407
+ const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
2321
2408
  if (pid > 0) {
2322
2409
  try {
2323
2410
  process.kill(pid, 0);
@@ -2328,21 +2415,21 @@ function cleanupStaleFiles() {
2328
2415
  } catch {
2329
2416
  }
2330
2417
  try {
2331
- unlinkSync(PID_PATH);
2418
+ unlinkSync2(PID_PATH);
2332
2419
  } catch {
2333
2420
  }
2334
2421
  try {
2335
- unlinkSync(SOCKET_PATH);
2422
+ unlinkSync2(SOCKET_PATH);
2336
2423
  } catch {
2337
2424
  }
2338
2425
  }
2339
2426
  }
2340
2427
  function findPackageRoot() {
2341
- let dir = path4.dirname(fileURLToPath(import.meta.url));
2342
- const { root } = path4.parse(dir);
2428
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
2429
+ const { root } = path5.parse(dir);
2343
2430
  while (dir !== root) {
2344
- if (existsSync4(path4.join(dir, "package.json"))) return dir;
2345
- dir = path4.dirname(dir);
2431
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
2432
+ dir = path5.dirname(dir);
2346
2433
  }
2347
2434
  return null;
2348
2435
  }
@@ -2352,8 +2439,8 @@ function spawnDaemon() {
2352
2439
  process.stderr.write("[exed-client] WARN: cannot find package root\n");
2353
2440
  return;
2354
2441
  }
2355
- const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
2356
- if (!existsSync4(daemonPath)) {
2442
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
2443
+ if (!existsSync5(daemonPath)) {
2357
2444
  process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
2358
2445
  `);
2359
2446
  return;
@@ -2361,7 +2448,7 @@ function spawnDaemon() {
2361
2448
  const resolvedPath = daemonPath;
2362
2449
  process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
2363
2450
  `);
2364
- const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
2451
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
2365
2452
  let stderrFd = "ignore";
2366
2453
  try {
2367
2454
  stderrFd = openSync(logPath, "a");
@@ -2372,6 +2459,10 @@ function spawnDaemon() {
2372
2459
  stdio: ["ignore", "ignore", stderrFd],
2373
2460
  env: {
2374
2461
  ...process.env,
2462
+ TMUX: void 0,
2463
+ // Daemon is global — must not inherit session scope
2464
+ TMUX_PANE: void 0,
2465
+ // Prevents resolveExeSession() from scoping to one session
2375
2466
  EXE_DAEMON_SOCK: SOCKET_PATH,
2376
2467
  EXE_DAEMON_PID: PID_PATH
2377
2468
  }
@@ -2394,7 +2485,7 @@ function acquireSpawnLock() {
2394
2485
  const stat = statSync(SPAWN_LOCK_PATH);
2395
2486
  if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
2396
2487
  try {
2397
- unlinkSync(SPAWN_LOCK_PATH);
2488
+ unlinkSync2(SPAWN_LOCK_PATH);
2398
2489
  } catch {
2399
2490
  }
2400
2491
  try {
@@ -2411,7 +2502,7 @@ function acquireSpawnLock() {
2411
2502
  }
2412
2503
  function releaseSpawnLock() {
2413
2504
  try {
2414
- unlinkSync(SPAWN_LOCK_PATH);
2505
+ unlinkSync2(SPAWN_LOCK_PATH);
2415
2506
  } catch {
2416
2507
  }
2417
2508
  }
@@ -2523,9 +2614,9 @@ async function pingDaemon() {
2523
2614
  }
2524
2615
  function killAndRespawnDaemon() {
2525
2616
  process.stderr.write("[exed-client] Killing daemon for restart...\n");
2526
- if (existsSync4(PID_PATH)) {
2617
+ if (existsSync5(PID_PATH)) {
2527
2618
  try {
2528
- const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
2619
+ const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
2529
2620
  if (pid > 0) {
2530
2621
  try {
2531
2622
  process.kill(pid, "SIGKILL");
@@ -2542,11 +2633,11 @@ function killAndRespawnDaemon() {
2542
2633
  _connected = false;
2543
2634
  _buffer = "";
2544
2635
  try {
2545
- unlinkSync(PID_PATH);
2636
+ unlinkSync2(PID_PATH);
2546
2637
  } catch {
2547
2638
  }
2548
2639
  try {
2549
- unlinkSync(SOCKET_PATH);
2640
+ unlinkSync2(SOCKET_PATH);
2550
2641
  } catch {
2551
2642
  }
2552
2643
  spawnDaemon();
@@ -2609,9 +2700,9 @@ var init_exe_daemon_client = __esm({
2609
2700
  "src/lib/exe-daemon-client.ts"() {
2610
2701
  "use strict";
2611
2702
  init_config();
2612
- SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
2613
- PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
2614
- SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
2703
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
2704
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
2705
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
2615
2706
  SPAWN_LOCK_STALE_MS = 3e4;
2616
2707
  CONNECT_TIMEOUT_MS = 15e3;
2617
2708
  REQUEST_TIMEOUT_MS = 3e4;
@@ -2662,10 +2753,10 @@ async function disposeEmbedder() {
2662
2753
  async function embedDirect(text) {
2663
2754
  const llamaCpp = await import("node-llama-cpp");
2664
2755
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2665
- const { existsSync: existsSync7 } = await import("fs");
2666
- const path8 = await import("path");
2667
- const modelPath = path8.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
2668
- if (!existsSync7(modelPath)) {
2756
+ const { existsSync: existsSync8 } = await import("fs");
2757
+ const path9 = await import("path");
2758
+ const modelPath = path9.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
2759
+ if (!existsSync8(modelPath)) {
2669
2760
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
2670
2761
  }
2671
2762
  const llama = await llamaCpp.getLlama();
@@ -2699,34 +2790,34 @@ __export(project_name_exports, {
2699
2790
  _resetCache: () => _resetCache,
2700
2791
  getProjectName: () => getProjectName
2701
2792
  });
2702
- import { execSync } from "child_process";
2703
- import path5 from "path";
2793
+ import { execSync as execSync2 } from "child_process";
2794
+ import path6 from "path";
2704
2795
  function getProjectName(cwd) {
2705
2796
  const dir = cwd ?? process.cwd();
2706
2797
  if (_cached && _cachedCwd === dir) return _cached;
2707
2798
  try {
2708
2799
  let repoRoot;
2709
2800
  try {
2710
- const gitCommonDir = execSync("git rev-parse --path-format=absolute --git-common-dir", {
2801
+ const gitCommonDir = execSync2("git rev-parse --path-format=absolute --git-common-dir", {
2711
2802
  cwd: dir,
2712
2803
  encoding: "utf8",
2713
2804
  timeout: 2e3,
2714
2805
  stdio: ["pipe", "pipe", "pipe"]
2715
2806
  }).trim();
2716
- repoRoot = path5.dirname(gitCommonDir);
2807
+ repoRoot = path6.dirname(gitCommonDir);
2717
2808
  } catch {
2718
- repoRoot = execSync("git rev-parse --show-toplevel", {
2809
+ repoRoot = execSync2("git rev-parse --show-toplevel", {
2719
2810
  cwd: dir,
2720
2811
  encoding: "utf8",
2721
2812
  timeout: 2e3,
2722
2813
  stdio: ["pipe", "pipe", "pipe"]
2723
2814
  }).trim();
2724
2815
  }
2725
- _cached = path5.basename(repoRoot);
2816
+ _cached = path6.basename(repoRoot);
2726
2817
  _cachedCwd = dir;
2727
2818
  return _cached;
2728
2819
  } catch {
2729
- _cached = path5.basename(dir);
2820
+ _cached = path6.basename(dir);
2730
2821
  _cachedCwd = dir;
2731
2822
  return _cached;
2732
2823
  }
@@ -2749,14 +2840,14 @@ var file_grep_exports = {};
2749
2840
  __export(file_grep_exports, {
2750
2841
  grepProjectFiles: () => grepProjectFiles
2751
2842
  });
2752
- import { execSync as execSync2 } from "child_process";
2753
- import { readFileSync as readFileSync3, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync5 } from "fs";
2754
- import path6 from "path";
2843
+ import { execSync as execSync3 } from "child_process";
2844
+ import { readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync6 } from "fs";
2845
+ import path7 from "path";
2755
2846
  import crypto from "crypto";
2756
2847
  function hasRipgrep() {
2757
2848
  if (_hasRg === null) {
2758
2849
  try {
2759
- execSync2("rg --version", { stdio: "ignore", timeout: 2e3 });
2850
+ execSync3("rg --version", { stdio: "ignore", timeout: 2e3 });
2760
2851
  _hasRg = true;
2761
2852
  } catch {
2762
2853
  _hasRg = false;
@@ -2791,7 +2882,7 @@ async function grepProjectFiles(query, projectRoot, options) {
2791
2882
  session_id: "file-grep",
2792
2883
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2793
2884
  tool_name: "file_grep",
2794
- project_name: path6.basename(projectRoot),
2885
+ project_name: path7.basename(projectRoot),
2795
2886
  has_error: false,
2796
2887
  raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
2797
2888
  vector: null,
@@ -2803,7 +2894,7 @@ function getChunkContext(filePath, lineNumber) {
2803
2894
  try {
2804
2895
  const ext = filePath.split(".").pop()?.toLowerCase();
2805
2896
  if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
2806
- const source = readFileSync3(filePath, "utf8");
2897
+ const source = readFileSync4(filePath, "utf8");
2807
2898
  const lines = source.split("\n");
2808
2899
  for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
2809
2900
  const line = lines[i];
@@ -2822,7 +2913,7 @@ function grepWithRipgrep(pattern, projectRoot, patterns) {
2822
2913
  const globs = (patterns ?? DEFAULT_PATTERNS).map((p) => `--glob '${p}'`).join(" ");
2823
2914
  const excludes = EXCLUDE_DIRS.map((d) => `--glob '!${d}'`).join(" ");
2824
2915
  const cmd = `rg -i -c --hidden --no-config --no-ignore '${pattern.replace(/'/g, "\\'")}' . ${globs} ${excludes} --max-filesize ${MAX_FILE_SIZE} 2>/dev/null || true`;
2825
- const output = execSync2(cmd, {
2916
+ const output = execSync3(cmd, {
2826
2917
  cwd: projectRoot,
2827
2918
  encoding: "utf8",
2828
2919
  timeout: 3e3,
@@ -2837,12 +2928,12 @@ function grepWithRipgrep(pattern, projectRoot, patterns) {
2837
2928
  const matchCount = parseInt(line.slice(colonIdx + 1));
2838
2929
  if (isNaN(matchCount) || matchCount === 0) continue;
2839
2930
  try {
2840
- const firstMatch = execSync2(
2931
+ const firstMatch = execSync3(
2841
2932
  `rg -i -n --hidden '${pattern.replace(/'/g, "\\'")}' '${filePath}' --max-count 1 2>/dev/null | head -1`,
2842
2933
  { cwd: projectRoot, encoding: "utf8", timeout: 1e3 }
2843
2934
  ).trim();
2844
2935
  const lineNum = parseInt(firstMatch.split(":")[0] ?? "1");
2845
- const totalLines = execSync2(`wc -l < '${filePath}'`, {
2936
+ const totalLines = execSync3(`wc -l < '${filePath}'`, {
2846
2937
  cwd: projectRoot,
2847
2938
  encoding: "utf8",
2848
2939
  timeout: 1e3
@@ -2865,11 +2956,11 @@ function grepWithNodeFs(pattern, projectRoot, patterns) {
2865
2956
  const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
2866
2957
  const hits = [];
2867
2958
  for (const filePath of files.slice(0, MAX_FILES)) {
2868
- const absPath = path6.join(projectRoot, filePath);
2959
+ const absPath = path7.join(projectRoot, filePath);
2869
2960
  try {
2870
2961
  const stat = statSync2(absPath);
2871
2962
  if (stat.size > MAX_FILE_SIZE) continue;
2872
- const content = readFileSync3(absPath, "utf8");
2963
+ const content = readFileSync4(absPath, "utf8");
2873
2964
  const lines = content.split("\n");
2874
2965
  const matches = content.match(regex);
2875
2966
  if (!matches || matches.length === 0) continue;
@@ -2892,15 +2983,15 @@ function collectFiles(root, patterns) {
2892
2983
  const files = [];
2893
2984
  function walk(dir, relative) {
2894
2985
  if (files.length >= MAX_FILES) return;
2895
- const basename = path6.basename(dir);
2986
+ const basename = path7.basename(dir);
2896
2987
  if (EXCLUDE_DIRS.includes(basename)) return;
2897
2988
  try {
2898
2989
  const entries = readdirSync2(dir, { withFileTypes: true });
2899
2990
  for (const entry of entries) {
2900
2991
  if (files.length >= MAX_FILES) return;
2901
- const rel = path6.join(relative, entry.name);
2992
+ const rel = path7.join(relative, entry.name);
2902
2993
  if (entry.isDirectory()) {
2903
- walk(path6.join(dir, entry.name), rel);
2994
+ walk(path7.join(dir, entry.name), rel);
2904
2995
  } else if (entry.isFile()) {
2905
2996
  for (const pat of patterns) {
2906
2997
  if (matchGlob(rel, pat)) {
@@ -2932,7 +3023,7 @@ function matchGlob(filePath, pattern) {
2932
3023
  if (slashIdx !== -1) {
2933
3024
  const dir = pattern.slice(0, slashIdx);
2934
3025
  const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
2935
- const fileDir = path6.dirname(filePath);
3026
+ const fileDir = path7.dirname(filePath);
2936
3027
  return fileDir === dir && filePath.endsWith(ext2);
2937
3028
  }
2938
3029
  const ext = pattern.replace("*", "");
@@ -2940,9 +3031,9 @@ function matchGlob(filePath, pattern) {
2940
3031
  }
2941
3032
  function buildSnippet(hit, projectRoot) {
2942
3033
  try {
2943
- const absPath = path6.join(projectRoot, hit.filePath);
2944
- if (!existsSync5(absPath)) return hit.matchLine;
2945
- const lines = readFileSync3(absPath, "utf8").split("\n");
3034
+ const absPath = path7.join(projectRoot, hit.filePath);
3035
+ if (!existsSync6(absPath)) return hit.matchLine;
3036
+ const lines = readFileSync4(absPath, "utf8").split("\n");
2946
3037
  const start = Math.max(0, hit.lineNumber - 3);
2947
3038
  const end = Math.min(lines.length, hit.lineNumber + 2);
2948
3039
  return lines.slice(start, end).join("\n").slice(0, 500);
@@ -2976,8 +3067,8 @@ __export(reranker_exports, {
2976
3067
  rerank: () => rerank,
2977
3068
  rerankWithScores: () => rerankWithScores
2978
3069
  });
2979
- import path7 from "path";
2980
- import { existsSync as existsSync6 } from "fs";
3070
+ import path8 from "path";
3071
+ import { existsSync as existsSync7 } from "fs";
2981
3072
  function resetIdleTimer() {
2982
3073
  if (_idleTimer) clearTimeout(_idleTimer);
2983
3074
  _idleTimer = setTimeout(() => {
@@ -2988,18 +3079,18 @@ function resetIdleTimer() {
2988
3079
  }
2989
3080
  }
2990
3081
  function isRerankerAvailable() {
2991
- return existsSync6(path7.join(MODELS_DIR, RERANKER_MODEL_FILE));
3082
+ return existsSync7(path8.join(MODELS_DIR, RERANKER_MODEL_FILE));
2992
3083
  }
2993
3084
  function getRerankerModelPath() {
2994
- return path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
3085
+ return path8.join(MODELS_DIR, RERANKER_MODEL_FILE);
2995
3086
  }
2996
3087
  async function ensureLoaded() {
2997
3088
  if (_rerankerContext) {
2998
3089
  resetIdleTimer();
2999
3090
  return;
3000
3091
  }
3001
- const modelPath = path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
3002
- if (!existsSync6(modelPath)) {
3092
+ const modelPath = path8.join(MODELS_DIR, RERANKER_MODEL_FILE);
3093
+ if (!existsSync7(modelPath)) {
3003
3094
  throw new Error(
3004
3095
  `Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
3005
3096
  );
@@ -3089,6 +3180,8 @@ async function hybridSearch(queryText, agentId, options) {
3089
3180
  return lightweightSearch(queryText, agentId, options);
3090
3181
  }
3091
3182
  const limit = options?.limit ?? 10;
3183
+ const trajectoryResults = await trajectoryBypass(queryText, agentId, options, limit);
3184
+ if (trajectoryResults !== null) return trajectoryResults;
3092
3185
  let effectiveQuery = queryText;
3093
3186
  let effectiveOptions = { ...options };
3094
3187
  let _isBroadQuery = false;
@@ -3312,6 +3405,8 @@ async function lightweightSearch(queryText, agentId, options) {
3312
3405
  async function ftsQuery(client, matchExpr, agentId, options, limit) {
3313
3406
  const statusFilter = options?.includeArchived ? "" : `
3314
3407
  AND COALESCE(m.status, 'active') = 'active'`;
3408
+ const draftFilter = options?.includeDrafts ? "" : `
3409
+ AND (m.draft = 0 OR m.draft IS NULL)`;
3315
3410
  let sql = `SELECT m.id, m.agent_id, m.agent_role, m.session_id, m.timestamp,
3316
3411
  m.tool_name, m.project_name,
3317
3412
  m.has_error, m.raw_text, m.vector, m.task_id,
@@ -3322,7 +3417,7 @@ async function ftsQuery(client, matchExpr, agentId, options, limit) {
3322
3417
  FROM memories m
3323
3418
  JOIN memories_fts fts ON m.rowid = fts.rowid
3324
3419
  WHERE memories_fts MATCH ?
3325
- AND m.agent_id = ?${statusFilter}
3420
+ AND m.agent_id = ?${statusFilter}${draftFilter}
3326
3421
  AND COALESCE(m.confidence, 0.7) >= 0.3`;
3327
3422
  const args = [matchExpr, agentId];
3328
3423
  const scope = buildWikiScopeFilter(options, "m.");
@@ -3344,6 +3439,10 @@ async function ftsQuery(client, matchExpr, agentId, options, limit) {
3344
3439
  sql += ` AND m.timestamp >= ?`;
3345
3440
  args.push(options.since);
3346
3441
  }
3442
+ if (options?.memoryType) {
3443
+ sql += ` AND m.memory_type = ?`;
3444
+ args.push(options.memoryType);
3445
+ }
3347
3446
  sql += ` ORDER BY rank LIMIT ?`;
3348
3447
  args.push(limit);
3349
3448
  const result = await client.execute({ sql, args });
@@ -3376,6 +3475,8 @@ async function recentRecords(agentId, options, limit) {
3376
3475
  const client = getClient();
3377
3476
  const statusFilter = options?.includeArchived ? "" : `
3378
3477
  AND COALESCE(status, 'active') = 'active'`;
3478
+ const draftFilter = options?.includeDrafts ? "" : `
3479
+ AND (draft = 0 OR draft IS NULL)`;
3379
3480
  let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
3380
3481
  tool_name, project_name,
3381
3482
  has_error, raw_text, vector, task_id,
@@ -3384,7 +3485,7 @@ async function recentRecords(agentId, options, limit) {
3384
3485
  char_offset, page_number,
3385
3486
  source_path, source_type
3386
3487
  FROM memories
3387
- WHERE agent_id = ?${statusFilter}
3488
+ WHERE agent_id = ?${statusFilter}${draftFilter}
3388
3489
  AND COALESCE(confidence, 0.7) >= 0.3`;
3389
3490
  const args = [agentId];
3390
3491
  const scope = buildWikiScopeFilter(options, "");
@@ -3406,6 +3507,10 @@ async function recentRecords(agentId, options, limit) {
3406
3507
  sql += ` AND timestamp >= ?`;
3407
3508
  args.push(options.since);
3408
3509
  }
3510
+ if (options?.memoryType) {
3511
+ sql += ` AND memory_type = ?`;
3512
+ args.push(options.memoryType);
3513
+ }
3409
3514
  sql += ` ORDER BY timestamp DESC LIMIT ?`;
3410
3515
  args.push(limit);
3411
3516
  const result = await client.execute({ sql, args });
@@ -3434,6 +3539,88 @@ async function recentRecords(agentId, options, limit) {
3434
3539
  source_type: row.source_type ?? null
3435
3540
  }));
3436
3541
  }
3542
+ var KNOWN_TOOLS = /* @__PURE__ */ new Set([
3543
+ "Bash",
3544
+ "Read",
3545
+ "Write",
3546
+ "Edit",
3547
+ "Grep",
3548
+ "Glob",
3549
+ "Agent",
3550
+ "Skill",
3551
+ "WebSearch",
3552
+ "WebFetch"
3553
+ ]);
3554
+ function detectToolQuery(query) {
3555
+ const lower = query.toLowerCase().trim();
3556
+ for (const tool of KNOWN_TOOLS) {
3557
+ if (lower === tool.toLowerCase()) return tool;
3558
+ if (lower.startsWith(tool.toLowerCase() + " ")) return tool;
3559
+ if (lower.includes(`tool:${tool.toLowerCase()}`)) return tool;
3560
+ }
3561
+ return null;
3562
+ }
3563
+ async function trajectoryBypass(queryText, agentId, options, limit) {
3564
+ const toolName = detectToolQuery(queryText);
3565
+ if (!toolName) return null;
3566
+ try {
3567
+ const client = getClient();
3568
+ const statusFilter = options?.includeArchived ? "" : `
3569
+ AND COALESCE(status, 'active') = 'active'`;
3570
+ const draftFilter = options?.includeDrafts ? "" : `
3571
+ AND (draft = 0 OR draft IS NULL)`;
3572
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
3573
+ tool_name, project_name,
3574
+ has_error, raw_text, vector, task_id,
3575
+ importance, status, confidence, last_accessed,
3576
+ workspace_id, document_id, user_id,
3577
+ char_offset, page_number,
3578
+ source_path, source_type
3579
+ FROM memories
3580
+ WHERE trajectory IS NOT NULL
3581
+ AND json_extract(trajectory, '$.tool') = ?
3582
+ AND agent_id = ?${statusFilter}${draftFilter}`;
3583
+ const args = [toolName, agentId];
3584
+ if (options?.projectName) {
3585
+ sql += ` AND project_name = ?`;
3586
+ args.push(options.projectName);
3587
+ }
3588
+ if (options?.since) {
3589
+ sql += ` AND timestamp >= ?`;
3590
+ args.push(options.since);
3591
+ }
3592
+ sql += ` ORDER BY timestamp DESC LIMIT ?`;
3593
+ args.push(limit);
3594
+ const result = await client.execute({ sql, args });
3595
+ if (result.rows.length < 3) return null;
3596
+ return result.rows.map((row) => ({
3597
+ id: row.id,
3598
+ agent_id: row.agent_id,
3599
+ agent_role: row.agent_role,
3600
+ session_id: row.session_id,
3601
+ timestamp: row.timestamp,
3602
+ tool_name: row.tool_name,
3603
+ project_name: row.project_name,
3604
+ has_error: row.has_error === 1,
3605
+ raw_text: row.raw_text,
3606
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
3607
+ task_id: row.task_id ?? null,
3608
+ importance: row.importance ?? 5,
3609
+ status: row.status ?? "active",
3610
+ confidence: row.confidence ?? 0.7,
3611
+ last_accessed: row.last_accessed ?? row.timestamp,
3612
+ workspace_id: row.workspace_id ?? null,
3613
+ document_id: row.document_id ?? null,
3614
+ user_id: row.user_id ?? null,
3615
+ char_offset: row.char_offset ?? null,
3616
+ page_number: row.page_number ?? null,
3617
+ source_path: row.source_path ?? null,
3618
+ source_type: row.source_type ?? null
3619
+ }));
3620
+ } catch {
3621
+ return null;
3622
+ }
3623
+ }
3437
3624
 
3438
3625
  // src/bin/exe-search.ts
3439
3626
  init_config();