@askexenow/exe-os 0.8.0 → 0.8.2

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 (107) hide show
  1. package/README.md +178 -79
  2. package/package.json +1 -1
  3. package/dist/bin/backfill-responses.js +0 -1912
  4. package/dist/bin/backfill-vectors.js +0 -1642
  5. package/dist/bin/cleanup-stale-review-tasks.js +0 -1339
  6. package/dist/bin/cli.js +0 -18800
  7. package/dist/bin/exe-agent.js +0 -1858
  8. package/dist/bin/exe-assign.js +0 -1957
  9. package/dist/bin/exe-boot.js +0 -6460
  10. package/dist/bin/exe-call.js +0 -197
  11. package/dist/bin/exe-cloud.js +0 -850
  12. package/dist/bin/exe-dispatch.js +0 -1146
  13. package/dist/bin/exe-doctor.js +0 -1657
  14. package/dist/bin/exe-export-behaviors.js +0 -1494
  15. package/dist/bin/exe-forget.js +0 -1627
  16. package/dist/bin/exe-gateway.js +0 -7732
  17. package/dist/bin/exe-healthcheck.js +0 -207
  18. package/dist/bin/exe-heartbeat.js +0 -1647
  19. package/dist/bin/exe-kill.js +0 -1479
  20. package/dist/bin/exe-launch-agent.js +0 -1704
  21. package/dist/bin/exe-link.js +0 -192
  22. package/dist/bin/exe-new-employee.js +0 -852
  23. package/dist/bin/exe-pending-messages.js +0 -1446
  24. package/dist/bin/exe-pending-notifications.js +0 -1321
  25. package/dist/bin/exe-pending-reviews.js +0 -1468
  26. package/dist/bin/exe-repo-drift.js +0 -95
  27. package/dist/bin/exe-review.js +0 -1590
  28. package/dist/bin/exe-search.js +0 -2651
  29. package/dist/bin/exe-session-cleanup.js +0 -3173
  30. package/dist/bin/exe-settings.js +0 -354
  31. package/dist/bin/exe-status.js +0 -1532
  32. package/dist/bin/exe-team.js +0 -1324
  33. package/dist/bin/git-sweep.js +0 -2185
  34. package/dist/bin/graph-backfill.js +0 -1968
  35. package/dist/bin/graph-export.js +0 -1604
  36. package/dist/bin/install.js +0 -656
  37. package/dist/bin/list-providers.js +0 -140
  38. package/dist/bin/scan-tasks.js +0 -1820
  39. package/dist/bin/setup.js +0 -951
  40. package/dist/bin/shard-migrate.js +0 -1494
  41. package/dist/bin/update.js +0 -95
  42. package/dist/bin/wiki-sync.js +0 -1514
  43. package/dist/gateway/index.js +0 -8848
  44. package/dist/hooks/bug-report-worker.js +0 -2743
  45. package/dist/hooks/commit-complete.js +0 -2108
  46. package/dist/hooks/error-recall.js +0 -2861
  47. package/dist/hooks/exe-heartbeat-hook.js +0 -232
  48. package/dist/hooks/ingest-worker.js +0 -4793
  49. package/dist/hooks/ingest.js +0 -684
  50. package/dist/hooks/instructions-loaded.js +0 -1880
  51. package/dist/hooks/notification.js +0 -1726
  52. package/dist/hooks/post-compact.js +0 -1751
  53. package/dist/hooks/pre-compact.js +0 -1746
  54. package/dist/hooks/pre-tool-use.js +0 -2191
  55. package/dist/hooks/prompt-ingest-worker.js +0 -2126
  56. package/dist/hooks/prompt-submit.js +0 -4693
  57. package/dist/hooks/response-ingest-worker.js +0 -1936
  58. package/dist/hooks/session-end.js +0 -1752
  59. package/dist/hooks/session-start.js +0 -2795
  60. package/dist/hooks/stop.js +0 -1835
  61. package/dist/hooks/subagent-stop.js +0 -1726
  62. package/dist/hooks/summary-worker.js +0 -2661
  63. package/dist/index.js +0 -11834
  64. package/dist/lib/cloud-sync.js +0 -495
  65. package/dist/lib/config.js +0 -222
  66. package/dist/lib/consolidation.js +0 -476
  67. package/dist/lib/crypto.js +0 -51
  68. package/dist/lib/database.js +0 -730
  69. package/dist/lib/device-registry.js +0 -900
  70. package/dist/lib/embedder.js +0 -632
  71. package/dist/lib/employee-templates.js +0 -543
  72. package/dist/lib/employees.js +0 -177
  73. package/dist/lib/error-detector.js +0 -156
  74. package/dist/lib/exe-daemon-client.js +0 -451
  75. package/dist/lib/exe-daemon.js +0 -8285
  76. package/dist/lib/file-grep.js +0 -199
  77. package/dist/lib/hybrid-search.js +0 -1819
  78. package/dist/lib/identity-templates.js +0 -320
  79. package/dist/lib/identity.js +0 -223
  80. package/dist/lib/keychain.js +0 -145
  81. package/dist/lib/license.js +0 -377
  82. package/dist/lib/messaging.js +0 -1376
  83. package/dist/lib/reminders.js +0 -63
  84. package/dist/lib/schedules.js +0 -1396
  85. package/dist/lib/session-registry.js +0 -52
  86. package/dist/lib/skill-learning.js +0 -477
  87. package/dist/lib/status-brief.js +0 -235
  88. package/dist/lib/store.js +0 -1551
  89. package/dist/lib/task-router.js +0 -62
  90. package/dist/lib/tasks.js +0 -2456
  91. package/dist/lib/tmux-routing.js +0 -2836
  92. package/dist/lib/tmux-status.js +0 -261
  93. package/dist/lib/tmux-transport.js +0 -83
  94. package/dist/lib/transport.js +0 -128
  95. package/dist/lib/ws-auth.js +0 -19
  96. package/dist/lib/ws-client.js +0 -160
  97. package/dist/mcp/server.js +0 -10538
  98. package/dist/mcp/tools/complete-reminder.js +0 -67
  99. package/dist/mcp/tools/create-reminder.js +0 -52
  100. package/dist/mcp/tools/create-task.js +0 -1853
  101. package/dist/mcp/tools/deactivate-behavior.js +0 -263
  102. package/dist/mcp/tools/list-reminders.js +0 -62
  103. package/dist/mcp/tools/list-tasks.js +0 -463
  104. package/dist/mcp/tools/send-message.js +0 -1382
  105. package/dist/mcp/tools/update-task.js +0 -1692
  106. package/dist/runtime/index.js +0 -6809
  107. package/dist/tui/App.js +0 -17479
package/dist/lib/tasks.js DELETED
@@ -1,2456 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __esm = (fn, res) => function __init() {
6
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
- };
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
-
22
- // src/lib/database.ts
23
- import { createClient } from "@libsql/client";
24
- function getClient() {
25
- if (!_client) {
26
- throw new Error("Database client not initialized. Call initDatabase() first.");
27
- }
28
- return _client;
29
- }
30
- var _client;
31
- var init_database = __esm({
32
- "src/lib/database.ts"() {
33
- "use strict";
34
- _client = null;
35
- }
36
- });
37
-
38
- // src/lib/config.ts
39
- import { readFile, writeFile, mkdir } from "fs/promises";
40
- import { readFileSync, existsSync, renameSync } from "fs";
41
- import path from "path";
42
- import os from "os";
43
- function resolveDataDir() {
44
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
45
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
46
- const newDir = path.join(os.homedir(), ".exe-os");
47
- const legacyDir = path.join(os.homedir(), ".exe-mem");
48
- if (!existsSync(newDir) && existsSync(legacyDir)) {
49
- try {
50
- renameSync(legacyDir, newDir);
51
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
52
- `);
53
- } catch {
54
- return legacyDir;
55
- }
56
- }
57
- return newDir;
58
- }
59
- function migrateLegacyConfig(raw) {
60
- if ("r2" in raw) {
61
- process.stderr.write(
62
- "[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"
63
- );
64
- delete raw.r2;
65
- }
66
- if ("syncIntervalMs" in raw) {
67
- delete raw.syncIntervalMs;
68
- }
69
- return raw;
70
- }
71
- function migrateConfig(raw) {
72
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
73
- let currentVersion = fromVersion;
74
- let migrated = false;
75
- if (currentVersion > CURRENT_CONFIG_VERSION) {
76
- return { config: raw, migrated: false, fromVersion };
77
- }
78
- for (const migration of CONFIG_MIGRATIONS) {
79
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
80
- raw = migration.migrate(raw);
81
- currentVersion = migration.to;
82
- migrated = true;
83
- }
84
- }
85
- return { config: raw, migrated, fromVersion };
86
- }
87
- function normalizeScalingRoadmap(raw) {
88
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
89
- const userRoadmap = raw.scalingRoadmap ?? {};
90
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
91
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
92
- userAuto.enabled = raw.rerankerEnabled;
93
- }
94
- raw.scalingRoadmap = {
95
- ...userRoadmap,
96
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
97
- };
98
- }
99
- function normalizeSessionLifecycle(raw) {
100
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
101
- const userSL = raw.sessionLifecycle ?? {};
102
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
103
- }
104
- async function loadConfig() {
105
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
106
- await mkdir(dir, { recursive: true });
107
- const configPath = path.join(dir, "config.json");
108
- if (!existsSync(configPath)) {
109
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
110
- }
111
- const raw = await readFile(configPath, "utf-8");
112
- try {
113
- let parsed = JSON.parse(raw);
114
- parsed = migrateLegacyConfig(parsed);
115
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
116
- if (migrated) {
117
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
118
- `);
119
- try {
120
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
121
- } catch {
122
- }
123
- }
124
- normalizeScalingRoadmap(migratedCfg);
125
- normalizeSessionLifecycle(migratedCfg);
126
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
127
- if (config.dbPath.startsWith("~")) {
128
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
129
- }
130
- return config;
131
- } catch {
132
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
133
- }
134
- }
135
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
136
- var init_config = __esm({
137
- "src/lib/config.ts"() {
138
- "use strict";
139
- EXE_AI_DIR = resolveDataDir();
140
- DB_PATH = path.join(EXE_AI_DIR, "memories.db");
141
- MODELS_DIR = path.join(EXE_AI_DIR, "models");
142
- CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
143
- LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
144
- CURRENT_CONFIG_VERSION = 1;
145
- DEFAULT_CONFIG = {
146
- config_version: CURRENT_CONFIG_VERSION,
147
- dbPath: DB_PATH,
148
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
149
- embeddingDim: 1024,
150
- batchSize: 20,
151
- flushIntervalMs: 1e4,
152
- autoIngestion: true,
153
- autoRetrieval: true,
154
- searchMode: "hybrid",
155
- hookSearchMode: "hybrid",
156
- fileGrepEnabled: true,
157
- splashEffect: true,
158
- consolidationEnabled: true,
159
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
160
- consolidationModel: "claude-haiku-4-5-20251001",
161
- consolidationMaxCallsPerRun: 20,
162
- selfQueryRouter: true,
163
- selfQueryModel: "claude-haiku-4-5-20251001",
164
- rerankerEnabled: true,
165
- scalingRoadmap: {
166
- rerankerAutoTrigger: {
167
- enabled: true,
168
- broadQueryMinCardinality: 5e4,
169
- fetchTopK: 150,
170
- returnTopK: 5
171
- }
172
- },
173
- graphRagEnabled: true,
174
- wikiEnabled: false,
175
- wikiUrl: "",
176
- wikiApiKey: "",
177
- wikiSyncIntervalMs: 30 * 60 * 1e3,
178
- wikiWorkspaceMapping: {
179
- exe: "Executive",
180
- yoshi: "Engineering",
181
- mari: "Marketing",
182
- tom: "Engineering",
183
- sasha: "Production"
184
- },
185
- wikiAutoUpdate: true,
186
- wikiAutoUpdateThreshold: 0.5,
187
- wikiAutoUpdateCreateNew: true,
188
- skillLearning: true,
189
- skillThreshold: 3,
190
- skillModel: "claude-haiku-4-5-20251001",
191
- exeHeartbeat: {
192
- enabled: true,
193
- intervalSeconds: 60,
194
- staleInProgressThresholdHours: 2
195
- },
196
- sessionLifecycle: {
197
- idleKillEnabled: true,
198
- idleKillTicksRequired: 3,
199
- idleKillIntercomAckWindowMs: 1e4,
200
- maxAutoInstances: 10
201
- }
202
- };
203
- CONFIG_MIGRATIONS = [
204
- {
205
- from: 0,
206
- to: 1,
207
- migrate: (cfg) => {
208
- cfg.config_version = 1;
209
- return cfg;
210
- }
211
- }
212
- ];
213
- }
214
- });
215
-
216
- // src/lib/notifications.ts
217
- import crypto from "crypto";
218
- import path2 from "path";
219
- import os2 from "os";
220
- import {
221
- readFileSync as readFileSync2,
222
- readdirSync,
223
- unlinkSync,
224
- existsSync as existsSync2,
225
- rmdirSync
226
- } from "fs";
227
- async function writeNotification(notification) {
228
- try {
229
- const client = getClient();
230
- const id = crypto.randomUUID();
231
- const now = (/* @__PURE__ */ new Date()).toISOString();
232
- await client.execute({
233
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
234
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
235
- args: [
236
- id,
237
- notification.agentId,
238
- notification.agentRole,
239
- notification.event,
240
- notification.project,
241
- notification.summary,
242
- notification.taskFile ?? null,
243
- now
244
- ]
245
- });
246
- } catch (err) {
247
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
248
- `);
249
- }
250
- }
251
- async function markAsReadByTaskFile(taskFile) {
252
- try {
253
- const client = getClient();
254
- await client.execute({
255
- sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
256
- args: [taskFile]
257
- });
258
- } catch {
259
- }
260
- }
261
- var init_notifications = __esm({
262
- "src/lib/notifications.ts"() {
263
- "use strict";
264
- init_database();
265
- }
266
- });
267
-
268
- // src/lib/tasks-crud.ts
269
- import crypto2 from "crypto";
270
- import path3 from "path";
271
- import { execSync } from "child_process";
272
- import { mkdir as mkdir2, writeFile as writeFile2, appendFile } from "fs/promises";
273
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
274
- function extractParentFromContext(contextBody) {
275
- if (!contextBody) return null;
276
- const match = contextBody.match(
277
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
278
- );
279
- return match ? match[1].toLowerCase() : null;
280
- }
281
- function slugify(title) {
282
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
283
- }
284
- async function resolveTask(client, identifier) {
285
- let result = await client.execute({
286
- sql: "SELECT * FROM tasks WHERE id = ?",
287
- args: [identifier]
288
- });
289
- if (result.rows.length === 1) return result.rows[0];
290
- result = await client.execute({
291
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
292
- args: [`%${identifier}%`]
293
- });
294
- if (result.rows.length === 1) return result.rows[0];
295
- if (result.rows.length > 1) {
296
- const exact = result.rows.filter(
297
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
298
- );
299
- if (exact.length === 1) return exact[0];
300
- const candidates = exact.length > 1 ? exact : result.rows;
301
- const active = candidates.filter(
302
- (r) => !["done", "cancelled"].includes(String(r.status))
303
- );
304
- if (active.length === 1) return active[0];
305
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
306
- throw new Error(
307
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
308
- );
309
- }
310
- result = await client.execute({
311
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
312
- args: [`%${identifier}%`]
313
- });
314
- if (result.rows.length === 1) return result.rows[0];
315
- if (result.rows.length > 1) {
316
- const active = result.rows.filter(
317
- (r) => !["done", "cancelled"].includes(String(r.status))
318
- );
319
- if (active.length === 1) return active[0];
320
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
321
- throw new Error(
322
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
323
- );
324
- }
325
- throw new Error(`Task not found: ${identifier}`);
326
- }
327
- async function createTaskCore(input) {
328
- const client = getClient();
329
- const id = crypto2.randomUUID();
330
- const now = (/* @__PURE__ */ new Date()).toISOString();
331
- const slug = slugify(input.title);
332
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
333
- let blockedById = null;
334
- const initialStatus = input.blockedBy ? "blocked" : "open";
335
- if (input.blockedBy) {
336
- const blocker = await resolveTask(client, input.blockedBy);
337
- blockedById = String(blocker.id);
338
- }
339
- let parentTaskId = null;
340
- let parentRef = input.parentTaskId;
341
- if (!parentRef) {
342
- const extracted = extractParentFromContext(input.context);
343
- if (extracted) {
344
- parentRef = extracted;
345
- process.stderr.write(
346
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
347
- );
348
- }
349
- }
350
- if (parentRef) {
351
- try {
352
- const parent = await resolveTask(client, parentRef);
353
- parentTaskId = String(parent.id);
354
- } catch (err) {
355
- if (!input.parentTaskId) {
356
- throw new Error(
357
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
358
- );
359
- }
360
- throw err;
361
- }
362
- }
363
- let warning;
364
- const dupCheck = await client.execute({
365
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
366
- args: [input.title, input.assignedTo]
367
- });
368
- if (dupCheck.rows.length > 0) {
369
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
370
- }
371
- if (input.baseDir) {
372
- try {
373
- await mkdir2(path3.join(input.baseDir, "exe", "output"), { recursive: true });
374
- await mkdir2(path3.join(input.baseDir, "exe", "research"), { recursive: true });
375
- await ensureArchitectureDoc(input.baseDir, input.projectName);
376
- await ensureGitignoreExe(input.baseDir);
377
- } catch {
378
- }
379
- }
380
- await client.execute({
381
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, created_at, updated_at)
382
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
383
- args: [
384
- id,
385
- input.title,
386
- input.assignedTo,
387
- input.assignedBy,
388
- input.projectName,
389
- input.priority,
390
- initialStatus,
391
- taskFile,
392
- blockedById,
393
- parentTaskId,
394
- input.reviewer ?? null,
395
- input.context,
396
- now,
397
- now
398
- ]
399
- });
400
- return {
401
- id,
402
- title: input.title,
403
- assignedTo: input.assignedTo,
404
- assignedBy: input.assignedBy,
405
- projectName: input.projectName,
406
- priority: input.priority,
407
- status: initialStatus,
408
- taskFile,
409
- createdAt: now,
410
- updatedAt: now,
411
- warning
412
- };
413
- }
414
- async function listTasks(input) {
415
- const client = getClient();
416
- const conditions = [];
417
- const args = [];
418
- if (input.assignedTo) {
419
- conditions.push("assigned_to = ?");
420
- args.push(input.assignedTo);
421
- }
422
- if (input.status) {
423
- conditions.push("status = ?");
424
- args.push(input.status);
425
- } else {
426
- conditions.push("status IN ('open', 'in_progress', 'blocked')");
427
- }
428
- if (input.projectName) {
429
- conditions.push("project_name = ?");
430
- args.push(input.projectName);
431
- }
432
- if (input.priority) {
433
- conditions.push("priority = ?");
434
- args.push(input.priority);
435
- }
436
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
437
- const result = await client.execute({
438
- sql: `SELECT * FROM tasks ${where} ORDER BY CASE status WHEN 'blocked' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'open' THEN 2 ELSE 3 END, priority ASC, created_at DESC`,
439
- args
440
- });
441
- return result.rows.map((r) => ({
442
- id: String(r.id),
443
- title: String(r.title),
444
- assignedTo: String(r.assigned_to),
445
- assignedBy: String(r.assigned_by),
446
- projectName: String(r.project_name),
447
- priority: String(r.priority),
448
- status: String(r.status),
449
- taskFile: String(r.task_file),
450
- createdAt: String(r.created_at),
451
- updatedAt: String(r.updated_at)
452
- }));
453
- }
454
- function checkStaleCompletion(taskContext, taskCreatedAt) {
455
- if (!taskContext) return null;
456
- if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
457
- try {
458
- const since = new Date(taskCreatedAt).toISOString();
459
- const commitCount = execSync(
460
- `git log --oneline --since="${since}" 2>/dev/null | wc -l`,
461
- { encoding: "utf8", timeout: 5e3 }
462
- ).trim();
463
- const count = parseInt(commitCount, 10);
464
- if (count === 0) {
465
- return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
466
- }
467
- return null;
468
- } catch {
469
- return null;
470
- }
471
- }
472
- async function updateTaskStatus(input) {
473
- const client = getClient();
474
- const now = (/* @__PURE__ */ new Date()).toISOString();
475
- const row = await resolveTask(client, input.taskId);
476
- const taskId = String(row.id);
477
- const taskFile = String(row.task_file);
478
- if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
479
- process.stderr.write(
480
- `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
481
- `
482
- );
483
- }
484
- if (input.status === "done") {
485
- const existingRow = await client.execute({
486
- sql: "SELECT context, created_at FROM tasks WHERE id = ?",
487
- args: [taskId]
488
- });
489
- if (existingRow.rows.length > 0) {
490
- const ctx = existingRow.rows[0];
491
- const warning = checkStaleCompletion(ctx.context, ctx.created_at);
492
- if (warning) {
493
- input.result = input.result ? `\u26A0\uFE0F ${warning}
494
-
495
- ${input.result}` : `\u26A0\uFE0F ${warning}`;
496
- process.stderr.write(`[tasks] ${warning} (task: ${taskId})
497
- `);
498
- }
499
- }
500
- }
501
- if (input.status === "in_progress") {
502
- const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
503
- const claim = await client.execute({
504
- sql: `UPDATE tasks
505
- SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
506
- WHERE id = ? AND status = 'open'`,
507
- args: [tmuxSession, now, taskId]
508
- });
509
- if (claim.rowsAffected === 0) {
510
- const current = await client.execute({
511
- sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
512
- args: [taskId]
513
- });
514
- const cur = current.rows[0];
515
- const status = cur?.status ?? "unknown";
516
- const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
517
- throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
518
- }
519
- return { row, taskFile, now, taskId };
520
- }
521
- if (input.result) {
522
- await client.execute({
523
- sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
524
- args: [input.status, input.result, now, taskId]
525
- });
526
- } else {
527
- await client.execute({
528
- sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
529
- args: [input.status, now, taskId]
530
- });
531
- }
532
- return { row, taskFile, now, taskId };
533
- }
534
- async function deleteTaskCore(taskId, _baseDir) {
535
- const client = getClient();
536
- const row = await resolveTask(client, taskId);
537
- const id = String(row.id);
538
- const taskFile = String(row.task_file);
539
- const assignedTo = String(row.assigned_to);
540
- const assignedBy = String(row.assigned_by);
541
- await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
542
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
543
- return { taskFile, assignedTo, assignedBy, taskSlug };
544
- }
545
- async function ensureArchitectureDoc(baseDir, projectName) {
546
- const archPath = path3.join(baseDir, "exe", "ARCHITECTURE.md");
547
- try {
548
- if (existsSync3(archPath)) return;
549
- const template = [
550
- `# ${projectName} \u2014 System Architecture`,
551
- "",
552
- "> Employees: read this before every task. Update it when you change system structure.",
553
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
554
- "",
555
- "## Overview",
556
- "",
557
- "<!-- Describe what this system does, its main components, and how they connect. -->",
558
- "",
559
- "## Key Components",
560
- "",
561
- "<!-- List the major modules, services, or subsystems. -->",
562
- "",
563
- "## Data Flow",
564
- "",
565
- "<!-- How does data move through the system? What writes where? -->",
566
- "",
567
- "## Invariants",
568
- "",
569
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
570
- "",
571
- "## Dependencies",
572
- "",
573
- "<!-- What depends on what? If I change X, what else is affected? -->",
574
- ""
575
- ].join("\n");
576
- await writeFile2(archPath, template, "utf-8");
577
- } catch {
578
- }
579
- }
580
- async function ensureGitignoreExe(baseDir) {
581
- const gitignorePath = path3.join(baseDir, ".gitignore");
582
- try {
583
- if (existsSync3(gitignorePath)) {
584
- const content = readFileSync3(gitignorePath, "utf-8");
585
- if (/^\/?exe\/?$/m.test(content)) return;
586
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
587
- } else {
588
- await writeFile2(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
589
- }
590
- } catch {
591
- }
592
- }
593
- var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
594
- var init_tasks_crud = __esm({
595
- "src/lib/tasks-crud.ts"() {
596
- "use strict";
597
- init_database();
598
- DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
599
- TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
600
- }
601
- });
602
-
603
- // src/lib/employees.ts
604
- import { readFile as readFile2, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
605
- import { existsSync as existsSync4, symlinkSync, readlinkSync } from "fs";
606
- import { execSync as execSync2 } from "child_process";
607
- import path4 from "path";
608
- var EMPLOYEES_PATH;
609
- var init_employees = __esm({
610
- "src/lib/employees.ts"() {
611
- "use strict";
612
- init_config();
613
- EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
614
- }
615
- });
616
-
617
- // src/lib/session-registry.ts
618
- import { readFileSync as readFileSync4, writeFileSync, mkdirSync, existsSync as existsSync5 } from "fs";
619
- import path5 from "path";
620
- import os3 from "os";
621
- function registerSession(entry) {
622
- const dir = path5.dirname(REGISTRY_PATH);
623
- if (!existsSync5(dir)) {
624
- mkdirSync(dir, { recursive: true });
625
- }
626
- const sessions = listSessions();
627
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
628
- if (idx >= 0) {
629
- sessions[idx] = entry;
630
- } else {
631
- sessions.push(entry);
632
- }
633
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
634
- }
635
- function listSessions() {
636
- try {
637
- const raw = readFileSync4(REGISTRY_PATH, "utf8");
638
- return JSON.parse(raw);
639
- } catch {
640
- return [];
641
- }
642
- }
643
- var REGISTRY_PATH;
644
- var init_session_registry = __esm({
645
- "src/lib/session-registry.ts"() {
646
- "use strict";
647
- REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
648
- }
649
- });
650
-
651
- // src/lib/session-key.ts
652
- import { execSync as execSync3 } from "child_process";
653
- function getSessionKey() {
654
- if (_cached) return _cached;
655
- let pid = process.ppid;
656
- for (let i = 0; i < 10; i++) {
657
- try {
658
- const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
659
- encoding: "utf8",
660
- timeout: 2e3
661
- }).trim();
662
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
663
- if (!match) break;
664
- const [, ppid, cmd] = match;
665
- if (cmd === "claude" || cmd.endsWith("/claude")) {
666
- _cached = String(pid);
667
- return _cached;
668
- }
669
- pid = parseInt(ppid, 10);
670
- if (pid <= 1) break;
671
- } catch {
672
- break;
673
- }
674
- }
675
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
676
- return _cached;
677
- }
678
- var _cached;
679
- var init_session_key = __esm({
680
- "src/lib/session-key.ts"() {
681
- "use strict";
682
- _cached = null;
683
- }
684
- });
685
-
686
- // src/lib/tmux-transport.ts
687
- var tmux_transport_exports = {};
688
- __export(tmux_transport_exports, {
689
- TmuxTransport: () => TmuxTransport
690
- });
691
- import { execFileSync } from "child_process";
692
- var QUIET, TmuxTransport;
693
- var init_tmux_transport = __esm({
694
- "src/lib/tmux-transport.ts"() {
695
- "use strict";
696
- QUIET = {
697
- encoding: "utf8",
698
- stdio: ["pipe", "pipe", "pipe"]
699
- };
700
- TmuxTransport = class {
701
- getMySession() {
702
- try {
703
- return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
704
- } catch {
705
- return null;
706
- }
707
- }
708
- listSessions() {
709
- try {
710
- return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
711
- } catch {
712
- return [];
713
- }
714
- }
715
- isAlive(target) {
716
- try {
717
- const sessions = this.listSessions();
718
- if (!sessions.includes(target)) return false;
719
- const paneStatus = execFileSync(
720
- "tmux",
721
- ["list-panes", "-t", target, "-F", "#{pane_dead}"],
722
- QUIET
723
- ).trim();
724
- return paneStatus !== "1";
725
- } catch {
726
- return false;
727
- }
728
- }
729
- sendKeys(target, keys) {
730
- execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
731
- }
732
- capturePane(target, lines) {
733
- const args = ["capture-pane", "-t", target, "-p"];
734
- if (lines) args.push("-S", `-${lines}`);
735
- return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
736
- }
737
- isPaneInCopyMode(target) {
738
- try {
739
- const result = execFileSync(
740
- "tmux",
741
- ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
742
- { ...QUIET, timeout: 3e3 }
743
- ).trim();
744
- return result === "1";
745
- } catch {
746
- return false;
747
- }
748
- }
749
- spawn(name, config) {
750
- try {
751
- const args = ["new-session", "-d", "-s", name];
752
- if (config.cwd) args.push("-c", config.cwd);
753
- args.push(config.command);
754
- execFileSync("tmux", args);
755
- return { sessionName: name };
756
- } catch (e) {
757
- return { sessionName: name, error: `spawn failed: ${e}` };
758
- }
759
- }
760
- kill(target) {
761
- try {
762
- execFileSync("tmux", ["kill-session", "-t", target], QUIET);
763
- } catch {
764
- }
765
- }
766
- pipeLog(target, logFile) {
767
- try {
768
- const safePath = logFile.replace(/'/g, "'\\''");
769
- execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
770
- } catch {
771
- }
772
- }
773
- };
774
- }
775
- });
776
-
777
- // src/lib/transport.ts
778
- function getTransport() {
779
- if (!_transport) {
780
- const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
781
- _transport = new TmuxTransport2();
782
- }
783
- return _transport;
784
- }
785
- var _transport;
786
- var init_transport = __esm({
787
- "src/lib/transport.ts"() {
788
- "use strict";
789
- _transport = null;
790
- }
791
- });
792
-
793
- // src/lib/cc-agent-support.ts
794
- import { execSync as execSync4 } from "child_process";
795
- function _resetCcAgentSupportCache() {
796
- _cachedSupport = null;
797
- }
798
- function claudeSupportsAgentFlag() {
799
- if (_cachedSupport !== null) return _cachedSupport;
800
- try {
801
- const helpOutput = execSync4("claude --help 2>&1", {
802
- encoding: "utf-8",
803
- timeout: 5e3
804
- });
805
- _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
806
- } catch {
807
- _cachedSupport = false;
808
- }
809
- return _cachedSupport;
810
- }
811
- var _cachedSupport;
812
- var init_cc_agent_support = __esm({
813
- "src/lib/cc-agent-support.ts"() {
814
- "use strict";
815
- _cachedSupport = null;
816
- }
817
- });
818
-
819
- // src/lib/mcp-prefix.ts
820
- function expandDualPrefixTools(shortNames) {
821
- const out = [];
822
- for (const name of shortNames) {
823
- for (const prefix of MCP_TOOL_PREFIXES) {
824
- out.push(prefix + name);
825
- }
826
- }
827
- return out;
828
- }
829
- var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
830
- var init_mcp_prefix = __esm({
831
- "src/lib/mcp-prefix.ts"() {
832
- "use strict";
833
- MCP_PRIMARY_KEY = "exe-os";
834
- MCP_LEGACY_KEY = "exe-mem";
835
- MCP_TOOL_PREFIXES = [
836
- `mcp__${MCP_PRIMARY_KEY}__`,
837
- `mcp__${MCP_LEGACY_KEY}__`
838
- ];
839
- }
840
- });
841
-
842
- // src/lib/provider-table.ts
843
- function detectActiveProvider(env = process.env) {
844
- const baseUrl = env.ANTHROPIC_BASE_URL;
845
- if (!baseUrl) return DEFAULT_PROVIDER;
846
- for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
847
- if (cfg.baseUrl === baseUrl) return name;
848
- }
849
- return DEFAULT_PROVIDER;
850
- }
851
- var PROVIDER_TABLE, DEFAULT_PROVIDER;
852
- var init_provider_table = __esm({
853
- "src/lib/provider-table.ts"() {
854
- "use strict";
855
- PROVIDER_TABLE = {
856
- opencode: {
857
- baseUrl: "https://opencode.ai/zen/go",
858
- apiKeyEnv: "OPENCODE_API_KEY",
859
- defaultModel: "minimax-m2.7"
860
- }
861
- };
862
- DEFAULT_PROVIDER = "default";
863
- }
864
- });
865
-
866
- // src/lib/intercom-queue.ts
867
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
868
- import path6 from "path";
869
- import os4 from "os";
870
- function ensureDir() {
871
- const dir = path6.dirname(QUEUE_PATH);
872
- if (!existsSync6(dir)) mkdirSync2(dir, { recursive: true });
873
- }
874
- function readQueue() {
875
- try {
876
- if (!existsSync6(QUEUE_PATH)) return [];
877
- return JSON.parse(readFileSync5(QUEUE_PATH, "utf8"));
878
- } catch {
879
- return [];
880
- }
881
- }
882
- function writeQueue(queue) {
883
- ensureDir();
884
- const tmp = `${QUEUE_PATH}.tmp`;
885
- writeFileSync2(tmp, JSON.stringify(queue, null, 2));
886
- renameSync2(tmp, QUEUE_PATH);
887
- }
888
- function queueIntercom(targetSession, reason) {
889
- const queue = readQueue();
890
- const existing = queue.find((q) => q.targetSession === targetSession);
891
- if (existing) {
892
- existing.attempts++;
893
- existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
894
- existing.reason = reason;
895
- } else {
896
- queue.push({
897
- targetSession,
898
- queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
899
- attempts: 0,
900
- reason
901
- });
902
- }
903
- writeQueue(queue);
904
- }
905
- var QUEUE_PATH, INTERCOM_LOG;
906
- var init_intercom_queue = __esm({
907
- "src/lib/intercom-queue.ts"() {
908
- "use strict";
909
- QUEUE_PATH = path6.join(os4.homedir(), ".exe-os", "intercom-queue.json");
910
- INTERCOM_LOG = path6.join(os4.homedir(), ".exe-os", "intercom.log");
911
- }
912
- });
913
-
914
- // src/lib/license.ts
915
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
916
- import { randomUUID } from "crypto";
917
- import path7 from "path";
918
- import { jwtVerify, importSPKI } from "jose";
919
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
920
- var init_license = __esm({
921
- "src/lib/license.ts"() {
922
- "use strict";
923
- init_config();
924
- LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
925
- CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
926
- DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
927
- PLAN_LIMITS = {
928
- free: { devices: 1, employees: 1, memories: 5e3 },
929
- pro: { devices: 2, employees: 5, memories: 1e5 },
930
- team: { devices: 10, employees: 20, memories: 1e6 },
931
- agency: { devices: 50, employees: 100, memories: 1e7 },
932
- enterprise: { devices: -1, employees: -1, memories: -1 }
933
- };
934
- }
935
- });
936
-
937
- // src/lib/plan-limits.ts
938
- import { readFileSync as readFileSync7, existsSync as existsSync8 } from "fs";
939
- import path8 from "path";
940
- function getLicenseSync() {
941
- try {
942
- if (!existsSync8(CACHE_PATH2)) return freeLicense();
943
- const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
944
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
945
- const parts = raw.token.split(".");
946
- if (parts.length !== 3) return freeLicense();
947
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
948
- const plan = payload.plan ?? "free";
949
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
950
- return {
951
- valid: true,
952
- plan,
953
- email: payload.sub ?? "",
954
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
955
- deviceLimit: limits.devices,
956
- employeeLimit: limits.employees,
957
- memoryLimit: limits.memories
958
- };
959
- } catch {
960
- return freeLicense();
961
- }
962
- }
963
- function freeLicense() {
964
- const limits = PLAN_LIMITS.free;
965
- return {
966
- valid: true,
967
- plan: "free",
968
- email: "",
969
- expiresAt: null,
970
- deviceLimit: limits.devices,
971
- employeeLimit: limits.employees,
972
- memoryLimit: limits.memories
973
- };
974
- }
975
- function assertEmployeeLimitSync(rosterPath) {
976
- const license = getLicenseSync();
977
- if (license.employeeLimit < 0) return;
978
- const filePath = rosterPath ?? EMPLOYEES_PATH;
979
- let count = 0;
980
- try {
981
- if (existsSync8(filePath)) {
982
- const raw = readFileSync7(filePath, "utf8");
983
- const employees = JSON.parse(raw);
984
- count = Array.isArray(employees) ? employees.length : 0;
985
- }
986
- } catch {
987
- throw new PlanLimitError(
988
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
989
- );
990
- }
991
- if (count >= license.employeeLimit) {
992
- throw new PlanLimitError(
993
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
994
- );
995
- }
996
- }
997
- var PlanLimitError, CACHE_PATH2;
998
- var init_plan_limits = __esm({
999
- "src/lib/plan-limits.ts"() {
1000
- "use strict";
1001
- init_database();
1002
- init_employees();
1003
- init_license();
1004
- init_config();
1005
- PlanLimitError = class extends Error {
1006
- constructor(message) {
1007
- super(message);
1008
- this.name = "PlanLimitError";
1009
- }
1010
- };
1011
- CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
1012
- }
1013
- });
1014
-
1015
- // src/lib/worktree.ts
1016
- import { execSync as execSync5 } from "child_process";
1017
- import { existsSync as existsSync9, readFileSync as readFileSync8, appendFileSync, mkdirSync as mkdirSync4, realpathSync } from "fs";
1018
- import path9 from "path";
1019
- function getGitRoot(dir) {
1020
- try {
1021
- const root = execSync5("git rev-parse --show-toplevel", {
1022
- cwd: dir,
1023
- encoding: "utf-8",
1024
- timeout: GIT_TIMEOUT_MS,
1025
- stdio: ["pipe", "pipe", "pipe"]
1026
- }).trim();
1027
- return realpath(root);
1028
- } catch {
1029
- return null;
1030
- }
1031
- }
1032
- function worktreePath(repoRoot, employeeName, instance) {
1033
- const label = instanceLabel(employeeName, instance);
1034
- return path9.join(repoRoot, ".worktrees", label);
1035
- }
1036
- function worktreeBranch(employeeName, instance) {
1037
- return `${instanceLabel(employeeName, instance)}-work`;
1038
- }
1039
- function instanceLabel(name, instance) {
1040
- return instance != null && instance > 0 ? `${name}${instance}` : name;
1041
- }
1042
- function ensureWorktree(projectDir, employeeName, instance) {
1043
- const repoRoot = getGitRoot(projectDir);
1044
- if (!repoRoot) return null;
1045
- const wtPath = worktreePath(repoRoot, employeeName, instance);
1046
- const branch = worktreeBranch(employeeName, instance);
1047
- if (existsSync9(path9.join(wtPath, ".git"))) {
1048
- return wtPath;
1049
- }
1050
- const worktreesDir = path9.join(repoRoot, ".worktrees");
1051
- mkdirSync4(worktreesDir, { recursive: true });
1052
- ensureGitignoreEntry(repoRoot, "/.worktrees/");
1053
- try {
1054
- execSync5("git worktree prune", {
1055
- cwd: repoRoot,
1056
- encoding: "utf-8",
1057
- timeout: GIT_TIMEOUT_MS,
1058
- stdio: ["pipe", "pipe", "pipe"]
1059
- });
1060
- } catch {
1061
- }
1062
- const branchExists = branchExistsLocally(repoRoot, branch);
1063
- try {
1064
- if (branchExists) {
1065
- execSync5(`git worktree add "${wtPath}" "${branch}"`, {
1066
- cwd: repoRoot,
1067
- encoding: "utf-8",
1068
- timeout: GIT_TIMEOUT_MS,
1069
- stdio: ["pipe", "pipe", "pipe"]
1070
- });
1071
- } else {
1072
- execSync5(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
1073
- cwd: repoRoot,
1074
- encoding: "utf-8",
1075
- timeout: GIT_TIMEOUT_MS,
1076
- stdio: ["pipe", "pipe", "pipe"]
1077
- });
1078
- }
1079
- return wtPath;
1080
- } catch (err) {
1081
- process.stderr.write(
1082
- `[worktree] Failed to create worktree for ${employeeName}: ${err instanceof Error ? err.message : String(err)}
1083
- `
1084
- );
1085
- return null;
1086
- }
1087
- }
1088
- function branchExistsLocally(repoRoot, branch) {
1089
- try {
1090
- execSync5(`git rev-parse --verify "refs/heads/${branch}"`, {
1091
- cwd: repoRoot,
1092
- encoding: "utf-8",
1093
- timeout: GIT_TIMEOUT_MS,
1094
- stdio: ["pipe", "pipe", "pipe"]
1095
- });
1096
- return true;
1097
- } catch {
1098
- return false;
1099
- }
1100
- }
1101
- function realpath(p) {
1102
- try {
1103
- return realpathSync(p);
1104
- } catch {
1105
- return p;
1106
- }
1107
- }
1108
- function ensureGitignoreEntry(repoRoot, entry) {
1109
- try {
1110
- const gitignorePath = path9.join(repoRoot, ".gitignore");
1111
- if (existsSync9(gitignorePath)) {
1112
- const content = readFileSync8(gitignorePath, "utf-8");
1113
- if (content.includes(entry)) return;
1114
- appendFileSync(gitignorePath, `
1115
- # Agent worktrees (exe-os)
1116
- ${entry}
1117
- `);
1118
- } else {
1119
- }
1120
- } catch {
1121
- }
1122
- }
1123
- var GIT_TIMEOUT_MS;
1124
- var init_worktree = __esm({
1125
- "src/lib/worktree.ts"() {
1126
- "use strict";
1127
- GIT_TIMEOUT_MS = 1e4;
1128
- }
1129
- });
1130
-
1131
- // src/lib/tmux-routing.ts
1132
- import { execFileSync as execFileSync2, execSync as execSync6 } from "child_process";
1133
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync as appendFileSync2 } from "fs";
1134
- import path10 from "path";
1135
- import os5 from "os";
1136
- import { fileURLToPath } from "url";
1137
- function resolveBehaviorsExporterScript() {
1138
- try {
1139
- const thisFile = fileURLToPath(import.meta.url);
1140
- const scriptPath = path10.join(
1141
- path10.dirname(thisFile),
1142
- "..",
1143
- "bin",
1144
- "exe-export-behaviors.js"
1145
- );
1146
- return existsSync10(scriptPath) ? scriptPath : null;
1147
- } catch {
1148
- return null;
1149
- }
1150
- }
1151
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
1152
- const script = resolveBehaviorsExporterScript();
1153
- if (!script) return null;
1154
- try {
1155
- const output = execFileSync2(
1156
- process.execPath,
1157
- [script, agentId, projectName, sessionKey],
1158
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
1159
- ).trim();
1160
- return output.length > 0 ? output : null;
1161
- } catch (err) {
1162
- process.stderr.write(
1163
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
1164
- `
1165
- );
1166
- return null;
1167
- }
1168
- }
1169
- function getMySession() {
1170
- return getTransport().getMySession();
1171
- }
1172
- function employeeSessionName(employee, exeSession, instance) {
1173
- const suffix = instance != null && instance > 0 ? String(instance) : "";
1174
- return `${employee}${suffix}-${exeSession}`;
1175
- }
1176
- function extractRootExe(name) {
1177
- const match = name.match(/(exe\d+)$/);
1178
- return match?.[1] ?? null;
1179
- }
1180
- function getParentExe(sessionKey) {
1181
- try {
1182
- const data = JSON.parse(readFileSync9(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
1183
- return data.parentExe || null;
1184
- } catch {
1185
- return null;
1186
- }
1187
- }
1188
- function getDispatchedBy(sessionKey) {
1189
- try {
1190
- const data = JSON.parse(readFileSync9(
1191
- path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
1192
- "utf8"
1193
- ));
1194
- return data.dispatchedBy ?? data.parentExe ?? null;
1195
- } catch {
1196
- return null;
1197
- }
1198
- }
1199
- function resolveExeSession() {
1200
- const mySession = getMySession();
1201
- if (!mySession) return null;
1202
- try {
1203
- const key = getSessionKey();
1204
- const parentExe = getParentExe(key);
1205
- if (parentExe) {
1206
- return extractRootExe(parentExe) ?? parentExe;
1207
- }
1208
- } catch {
1209
- }
1210
- return extractRootExe(mySession) ?? mySession;
1211
- }
1212
- function isEmployeeAlive(sessionName) {
1213
- return getTransport().isAlive(sessionName);
1214
- }
1215
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
1216
- const base = employeeSessionName(employeeName, exeSession);
1217
- if (!isAlive(base)) return 0;
1218
- for (let i = 2; i <= maxInstances; i++) {
1219
- const candidate = employeeSessionName(employeeName, exeSession, i);
1220
- if (!isAlive(candidate)) return i;
1221
- }
1222
- return null;
1223
- }
1224
- function readDebounceState() {
1225
- try {
1226
- if (!existsSync10(DEBOUNCE_FILE)) return {};
1227
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
1228
- } catch {
1229
- return {};
1230
- }
1231
- }
1232
- function writeDebounceState(state) {
1233
- try {
1234
- if (!existsSync10(SESSION_CACHE)) mkdirSync5(SESSION_CACHE, { recursive: true });
1235
- writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
1236
- } catch {
1237
- }
1238
- }
1239
- function isDebounced(targetSession) {
1240
- const state = readDebounceState();
1241
- const lastSent = state[targetSession] ?? 0;
1242
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
1243
- }
1244
- function recordDebounce(targetSession) {
1245
- const state = readDebounceState();
1246
- state[targetSession] = Date.now();
1247
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
1248
- for (const key of Object.keys(state)) {
1249
- if ((state[key] ?? 0) < cutoff) delete state[key];
1250
- }
1251
- writeDebounceState(state);
1252
- }
1253
- function logIntercom(msg) {
1254
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
1255
- `;
1256
- process.stderr.write(`[intercom] ${msg}
1257
- `);
1258
- try {
1259
- appendFileSync2(INTERCOM_LOG2, line);
1260
- } catch {
1261
- }
1262
- }
1263
- function getSessionState(sessionName) {
1264
- const transport = getTransport();
1265
- if (!transport.isAlive(sessionName)) return "offline";
1266
- try {
1267
- const pane = transport.capturePane(sessionName, 5);
1268
- if (/Running…/.test(pane)) return "tool";
1269
- if (BUSY_PATTERN.test(pane)) return "thinking";
1270
- return "idle";
1271
- } catch {
1272
- return "offline";
1273
- }
1274
- }
1275
- function isSessionBusy(sessionName) {
1276
- const state = getSessionState(sessionName);
1277
- return state === "thinking" || state === "tool";
1278
- }
1279
- function isExeSession(sessionName) {
1280
- return /^exe\d*$/.test(sessionName);
1281
- }
1282
- function sendIntercom(targetSession) {
1283
- const transport = getTransport();
1284
- if (isExeSession(targetSession)) {
1285
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
1286
- return "skipped_exe";
1287
- }
1288
- if (isDebounced(targetSession)) {
1289
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
1290
- return "debounced";
1291
- }
1292
- try {
1293
- const sessions = transport.listSessions();
1294
- if (!sessions.includes(targetSession)) {
1295
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
1296
- return "failed";
1297
- }
1298
- if (isSessionBusy(targetSession)) {
1299
- queueIntercom(targetSession, "session busy at send time");
1300
- recordDebounce(targetSession);
1301
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
1302
- return "queued";
1303
- }
1304
- if (transport.isPaneInCopyMode(targetSession)) {
1305
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
1306
- transport.sendKeys(targetSession, "q");
1307
- }
1308
- transport.sendKeys(targetSession, "/exe-intercom");
1309
- recordDebounce(targetSession);
1310
- for (let i = 0; i < INTERCOM_POLL_MAX_ATTEMPTS; i++) {
1311
- try {
1312
- execSync6(`sleep ${INTERCOM_POLL_INTERVAL_S}`);
1313
- } catch {
1314
- }
1315
- const state = getSessionState(targetSession);
1316
- if (state === "thinking" || state === "tool") {
1317
- logIntercom(`ACKNOWLEDGED \u2192 ${targetSession} (state=${state}, poll=${i + 1})`);
1318
- return "acknowledged";
1319
- }
1320
- }
1321
- logIntercom(`DELIVERED \u2192 ${targetSession} (no state transition after ${INTERCOM_POLL_MAX_ATTEMPTS}s)`);
1322
- return "delivered";
1323
- } catch {
1324
- logIntercom(`FAIL \u2192 ${targetSession}`);
1325
- return "failed";
1326
- }
1327
- }
1328
- function notifyParentExe(sessionKey) {
1329
- const target = getDispatchedBy(sessionKey);
1330
- if (!target) {
1331
- process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
1332
- `);
1333
- return false;
1334
- }
1335
- process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
1336
- `);
1337
- const result = sendIntercom(target);
1338
- return result !== "failed";
1339
- }
1340
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
1341
- if (employeeName === "exe") {
1342
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
1343
- }
1344
- try {
1345
- assertEmployeeLimitSync();
1346
- } catch (err) {
1347
- if (err instanceof PlanLimitError) {
1348
- return { status: "failed", sessionName: "", error: err.message };
1349
- }
1350
- }
1351
- if (/-exe\d*$/.test(employeeName)) {
1352
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
1353
- return {
1354
- status: "failed",
1355
- sessionName: "",
1356
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
1357
- };
1358
- }
1359
- let effectiveInstance = opts?.instance;
1360
- if (effectiveInstance === void 0 && opts?.autoInstance) {
1361
- const free = findFreeInstance(
1362
- employeeName,
1363
- exeSession,
1364
- opts.maxAutoInstances ?? 10
1365
- );
1366
- if (free === null) {
1367
- return {
1368
- status: "failed",
1369
- sessionName: employeeSessionName(employeeName, exeSession),
1370
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
1371
- };
1372
- }
1373
- effectiveInstance = free === 0 ? void 0 : free;
1374
- }
1375
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
1376
- if (isEmployeeAlive(sessionName)) {
1377
- const result2 = sendIntercom(sessionName);
1378
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
1379
- return { status: "intercom_sent", sessionName };
1380
- }
1381
- if (result2 === "delivered") {
1382
- return { status: "intercom_unprocessed", sessionName };
1383
- }
1384
- return { status: "failed", sessionName, error: "intercom delivery failed" };
1385
- }
1386
- const spawnOpts = { ...opts, instance: effectiveInstance };
1387
- const wtPath = ensureWorktree(projectDir, employeeName, effectiveInstance);
1388
- if (wtPath) {
1389
- spawnOpts.cwd = wtPath;
1390
- }
1391
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
1392
- if (result.error) {
1393
- return { status: "failed", sessionName, error: result.error };
1394
- }
1395
- return { status: "spawned", sessionName };
1396
- }
1397
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
1398
- const transport = getTransport();
1399
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
1400
- const instanceLabel2 = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
1401
- const logDir = path10.join(os5.homedir(), ".exe-os", "session-logs");
1402
- const logFile = path10.join(logDir, `${instanceLabel2}-${Date.now()}.log`);
1403
- if (!existsSync10(logDir)) {
1404
- mkdirSync5(logDir, { recursive: true });
1405
- }
1406
- transport.kill(sessionName);
1407
- let cleanupSuffix = "";
1408
- try {
1409
- const thisFile = fileURLToPath(import.meta.url);
1410
- const cleanupScript = path10.join(path10.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
1411
- if (existsSync10(cleanupScript)) {
1412
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
1413
- }
1414
- } catch {
1415
- }
1416
- try {
1417
- const claudeJsonPath = path10.join(os5.homedir(), ".claude.json");
1418
- let claudeJson = {};
1419
- try {
1420
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
1421
- } catch {
1422
- }
1423
- if (!claudeJson.projects) claudeJson.projects = {};
1424
- const projects = claudeJson.projects;
1425
- const trustDir = opts?.cwd ?? projectDir;
1426
- if (!projects[trustDir]) projects[trustDir] = {};
1427
- projects[trustDir].hasTrustDialogAccepted = true;
1428
- writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
1429
- } catch {
1430
- }
1431
- try {
1432
- const settingsDir = path10.join(os5.homedir(), ".claude", "projects");
1433
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
1434
- const projSettingsDir = path10.join(settingsDir, normalizedKey);
1435
- const settingsPath = path10.join(projSettingsDir, "settings.json");
1436
- let settings = {};
1437
- try {
1438
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
1439
- } catch {
1440
- }
1441
- const perms = settings.permissions ?? {};
1442
- const allow = perms.allow ?? [];
1443
- const toolNames = [
1444
- "recall_my_memory",
1445
- "store_memory",
1446
- "create_task",
1447
- "update_task",
1448
- "list_tasks",
1449
- "get_task",
1450
- "ask_team_memory",
1451
- "store_behavior",
1452
- "get_identity",
1453
- "send_message"
1454
- ];
1455
- const requiredTools = expandDualPrefixTools(toolNames);
1456
- let changed = false;
1457
- for (const tool of requiredTools) {
1458
- if (!allow.includes(tool)) {
1459
- allow.push(tool);
1460
- changed = true;
1461
- }
1462
- }
1463
- if (changed) {
1464
- perms.allow = allow;
1465
- settings.permissions = perms;
1466
- mkdirSync5(projSettingsDir, { recursive: true });
1467
- writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
1468
- }
1469
- } catch {
1470
- }
1471
- const spawnCwd = opts?.cwd ?? projectDir;
1472
- const useExeAgent = !!(opts?.model && opts?.provider);
1473
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
1474
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
1475
- let identityFlag = "";
1476
- let behaviorsFlag = "";
1477
- let legacyFallbackWarned = false;
1478
- if (!useExeAgent && !useBinSymlink) {
1479
- const identityPath = path10.join(
1480
- os5.homedir(),
1481
- ".exe-os",
1482
- "identity",
1483
- `${employeeName}.md`
1484
- );
1485
- _resetCcAgentSupportCache();
1486
- const hasAgentFlag = claudeSupportsAgentFlag();
1487
- if (hasAgentFlag) {
1488
- identityFlag = ` --agent ${employeeName}`;
1489
- } else if (existsSync10(identityPath)) {
1490
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
1491
- legacyFallbackWarned = true;
1492
- }
1493
- const behaviorsFile = exportBehaviorsSync(
1494
- employeeName,
1495
- path10.basename(spawnCwd),
1496
- sessionName
1497
- );
1498
- if (behaviorsFile) {
1499
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
1500
- }
1501
- }
1502
- if (legacyFallbackWarned) {
1503
- process.stderr.write(
1504
- `[tmux-routing] claude --agent not supported by installed CC. Falling back to --append-system-prompt-file for ${employeeName}. Upgrade Claude Code to enable native --agent launch.
1505
- `
1506
- );
1507
- }
1508
- let sessionContextFlag = "";
1509
- try {
1510
- const ctxDir = path10.join(os5.homedir(), ".exe-os", "session-cache");
1511
- mkdirSync5(ctxDir, { recursive: true });
1512
- const ctxFile = path10.join(ctxDir, `session-context-${sessionName}.md`);
1513
- const ctxContent = [
1514
- `## Session Context`,
1515
- `You are running in tmux session: ${sessionName}.`,
1516
- `Your parent exe session is ${exeSession}.`,
1517
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
1518
- ].join("\n");
1519
- writeFileSync4(ctxFile, ctxContent);
1520
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
1521
- } catch {
1522
- }
1523
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
1524
- if (ccProvider !== DEFAULT_PROVIDER) {
1525
- const cfg = PROVIDER_TABLE[ccProvider];
1526
- if (cfg?.apiKeyEnv) {
1527
- const keyVal = process.env[cfg.apiKeyEnv];
1528
- if (keyVal) {
1529
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
1530
- }
1531
- }
1532
- }
1533
- let spawnCommand;
1534
- if (useExeAgent) {
1535
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
1536
- } else if (useBinSymlink) {
1537
- const binName = `${employeeName}-${ccProvider}`;
1538
- process.stderr.write(
1539
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
1540
- `
1541
- );
1542
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
1543
- } else {
1544
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
1545
- }
1546
- const spawnResult = transport.spawn(sessionName, {
1547
- cwd: spawnCwd,
1548
- command: spawnCommand
1549
- });
1550
- if (spawnResult.error) {
1551
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
1552
- }
1553
- transport.pipeLog(sessionName, logFile);
1554
- try {
1555
- const mySession = getMySession();
1556
- const dispatchInfo = path10.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
1557
- writeFileSync4(dispatchInfo, JSON.stringify({
1558
- dispatchedBy: mySession,
1559
- rootExe: exeSession,
1560
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
1561
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1562
- }));
1563
- } catch {
1564
- }
1565
- let booted = false;
1566
- for (let i = 0; i < 30; i++) {
1567
- try {
1568
- execSync6("sleep 1");
1569
- } catch {
1570
- }
1571
- try {
1572
- const pane = transport.capturePane(sessionName);
1573
- if (useExeAgent) {
1574
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
1575
- booted = true;
1576
- break;
1577
- }
1578
- } else {
1579
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
1580
- booted = true;
1581
- break;
1582
- }
1583
- }
1584
- } catch {
1585
- }
1586
- }
1587
- if (!booted) {
1588
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 30s` };
1589
- }
1590
- if (!useExeAgent) {
1591
- try {
1592
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
1593
- } catch {
1594
- }
1595
- }
1596
- registerSession({
1597
- windowName: sessionName,
1598
- agentId: employeeName,
1599
- projectDir: spawnCwd,
1600
- parentExe: exeSession,
1601
- pid: 0,
1602
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1603
- });
1604
- return { sessionName };
1605
- }
1606
- var SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN, INTERCOM_POLL_INTERVAL_S, INTERCOM_POLL_MAX_ATTEMPTS;
1607
- var init_tmux_routing = __esm({
1608
- "src/lib/tmux-routing.ts"() {
1609
- "use strict";
1610
- init_session_registry();
1611
- init_session_key();
1612
- init_transport();
1613
- init_cc_agent_support();
1614
- init_mcp_prefix();
1615
- init_provider_table();
1616
- init_intercom_queue();
1617
- init_plan_limits();
1618
- init_worktree();
1619
- SESSION_CACHE = path10.join(os5.homedir(), ".exe-os", "session-cache");
1620
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
1621
- INTERCOM_DEBOUNCE_MS = 3e4;
1622
- INTERCOM_LOG2 = path10.join(os5.homedir(), ".exe-os", "intercom.log");
1623
- DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
1624
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1625
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
1626
- INTERCOM_POLL_INTERVAL_S = 1;
1627
- INTERCOM_POLL_MAX_ATTEMPTS = 8;
1628
- }
1629
- });
1630
-
1631
- // src/lib/tasks-review.ts
1632
- import path11 from "path";
1633
- import { existsSync as existsSync11, readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
1634
- async function countPendingReviews() {
1635
- const client = getClient();
1636
- const result = await client.execute({
1637
- sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
1638
- args: []
1639
- });
1640
- return Number(result.rows[0]?.cnt) || 0;
1641
- }
1642
- async function countNewPendingReviewsSince(sinceIso) {
1643
- const client = getClient();
1644
- const result = await client.execute({
1645
- sql: `SELECT COUNT(*) as cnt FROM tasks
1646
- WHERE status = 'needs_review' AND updated_at > ?`,
1647
- args: [sinceIso]
1648
- });
1649
- return Number(result.rows[0]?.cnt) || 0;
1650
- }
1651
- async function listPendingReviews(limit) {
1652
- const client = getClient();
1653
- const result = await client.execute({
1654
- sql: `SELECT title, assigned_to, project_name FROM tasks
1655
- WHERE status = 'needs_review'
1656
- ORDER BY priority ASC, created_at DESC LIMIT ?`,
1657
- args: [limit]
1658
- });
1659
- return result.rows;
1660
- }
1661
- function getReviewChecklist(role, agent, taskSlug) {
1662
- const roleLower = role.toLowerCase();
1663
- if (roleLower.includes("engineer") || roleLower === "principal engineer") {
1664
- return {
1665
- lens: "Code Quality (Engineer)",
1666
- checklist: [
1667
- "1. Do all tests pass? Any new tests needed?",
1668
- "2. Is the code clean \u2014 no dead code, no TODOs left?",
1669
- "3. Does it follow existing patterns and conventions in the codebase?",
1670
- "4. Any regressions in the test suite?"
1671
- ]
1672
- };
1673
- }
1674
- if (roleLower === "cto" || roleLower.includes("architect")) {
1675
- return {
1676
- lens: "Architecture (CTO)",
1677
- checklist: [
1678
- "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
1679
- "2. Is it backward compatible? Any breaking changes?",
1680
- "3. Does it introduce technical debt? Is that debt justified?",
1681
- "4. Security implications? Any new attack surface?",
1682
- "5. Does it scale? Performance considerations?",
1683
- "6. Coordination: does this affect other employees' work or other projects?"
1684
- ]
1685
- };
1686
- }
1687
- if (roleLower === "coo" || roleLower.includes("operations")) {
1688
- return {
1689
- lens: "Strategic (COO)",
1690
- checklist: [
1691
- "1. Does this serve the project mission?",
1692
- "2. Is this the right work at the right time?",
1693
- "3. Does the architectural assessment make sense for the business?",
1694
- "4. Any cross-project implications?"
1695
- ]
1696
- };
1697
- }
1698
- return {
1699
- lens: "General",
1700
- checklist: [
1701
- "1. Read the original task's acceptance criteria",
1702
- `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
1703
- "3. Verify code changes match requirements",
1704
- "4. Check if tests were added/updated",
1705
- `5. Look for output files in exe/output/${agent}-${taskSlug}*`
1706
- ]
1707
- };
1708
- }
1709
- async function cleanupReviewFile(row, taskFile, _baseDir) {
1710
- if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
1711
- try {
1712
- const client = getClient();
1713
- const fileName = taskFile.split("/").pop() ?? "";
1714
- const reviewPrefix = fileName.replace(".md", "");
1715
- const parts = reviewPrefix.split("-");
1716
- if (parts.length >= 3 && parts[0] === "review") {
1717
- const agent = parts[1];
1718
- const slug = parts.slice(2).join("-");
1719
- const originalTaskFile = `exe/${agent}/${slug}.md`;
1720
- const result = await client.execute({
1721
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
1722
- args: [(/* @__PURE__ */ new Date()).toISOString(), originalTaskFile]
1723
- });
1724
- if (result.rowsAffected > 0) {
1725
- process.stderr.write(
1726
- `[review-cleanup] Cascaded original task to done: ${originalTaskFile}
1727
- `
1728
- );
1729
- }
1730
- }
1731
- } catch (err) {
1732
- process.stderr.write(
1733
- `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
1734
- `
1735
- );
1736
- }
1737
- try {
1738
- const cacheDir = path11.join(EXE_AI_DIR, "session-cache");
1739
- if (existsSync11(cacheDir)) {
1740
- for (const f of readdirSync2(cacheDir)) {
1741
- if (f.startsWith("review-notified-")) {
1742
- unlinkSync2(path11.join(cacheDir, f));
1743
- }
1744
- }
1745
- }
1746
- } catch {
1747
- }
1748
- }
1749
- var init_tasks_review = __esm({
1750
- "src/lib/tasks-review.ts"() {
1751
- "use strict";
1752
- init_database();
1753
- init_config();
1754
- init_employees();
1755
- init_notifications();
1756
- init_tasks_crud();
1757
- init_tmux_routing();
1758
- init_session_key();
1759
- }
1760
- });
1761
-
1762
- // src/lib/tasks-chain.ts
1763
- import path12 from "path";
1764
- import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
1765
- async function cascadeUnblock(taskId, baseDir, now) {
1766
- const client = getClient();
1767
- const unblocked = await client.execute({
1768
- sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
1769
- WHERE blocked_by = ? AND status = 'blocked'`,
1770
- args: [now, taskId]
1771
- });
1772
- if (baseDir && unblocked.rowsAffected > 0) {
1773
- const unblockedRows = await client.execute({
1774
- sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
1775
- args: [now]
1776
- });
1777
- for (const ur of unblockedRows.rows) {
1778
- try {
1779
- const ubFile = path12.join(baseDir, String(ur.task_file));
1780
- let ubContent = await readFile3(ubFile, "utf-8");
1781
- ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
1782
- ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
1783
- await writeFile4(ubFile, ubContent, "utf-8");
1784
- } catch {
1785
- }
1786
- }
1787
- }
1788
- }
1789
- async function findNextTask(assignedTo) {
1790
- const client = getClient();
1791
- const nextResult = await client.execute({
1792
- sql: `SELECT title, task_file, priority FROM tasks
1793
- WHERE assigned_to = ? AND status = 'open'
1794
- ORDER BY priority ASC, created_at ASC
1795
- LIMIT 1`,
1796
- args: [assignedTo]
1797
- });
1798
- if (nextResult.rows.length === 1) {
1799
- const nr = nextResult.rows[0];
1800
- return {
1801
- title: String(nr.title),
1802
- priority: String(nr.priority),
1803
- taskFile: String(nr.task_file)
1804
- };
1805
- }
1806
- return void 0;
1807
- }
1808
- async function checkSubtaskCompletion(parentTaskId, projectName) {
1809
- const client = getClient();
1810
- const remaining = await client.execute({
1811
- sql: `SELECT COUNT(*) as cnt FROM tasks
1812
- WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
1813
- args: [parentTaskId]
1814
- });
1815
- const cnt = Number(remaining.rows[0]?.cnt ?? 1);
1816
- if (cnt === 0) {
1817
- const parentRow = await client.execute({
1818
- sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
1819
- args: [parentTaskId]
1820
- });
1821
- if (parentRow.rows.length === 1) {
1822
- const pr = parentRow.rows[0];
1823
- const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
1824
- await writeNotification({
1825
- agentId: String(pr.assigned_to),
1826
- agentRole: "system",
1827
- event: "subtasks_complete",
1828
- project: parentProject,
1829
- summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
1830
- taskFile: String(pr.task_file)
1831
- });
1832
- }
1833
- }
1834
- }
1835
- var init_tasks_chain = __esm({
1836
- "src/lib/tasks-chain.ts"() {
1837
- "use strict";
1838
- init_database();
1839
- init_notifications();
1840
- }
1841
- });
1842
-
1843
- // src/lib/project-name.ts
1844
- import { execSync as execSync7 } from "child_process";
1845
- import path13 from "path";
1846
- function getProjectName(cwd) {
1847
- const dir = cwd ?? process.cwd();
1848
- if (_cached2 && _cachedCwd === dir) return _cached2;
1849
- try {
1850
- const repoRoot = execSync7("git rev-parse --show-toplevel", {
1851
- cwd: dir,
1852
- encoding: "utf8",
1853
- timeout: 2e3,
1854
- stdio: ["pipe", "pipe", "pipe"]
1855
- }).trim();
1856
- _cached2 = path13.basename(repoRoot);
1857
- _cachedCwd = dir;
1858
- return _cached2;
1859
- } catch {
1860
- _cached2 = path13.basename(dir);
1861
- _cachedCwd = dir;
1862
- return _cached2;
1863
- }
1864
- }
1865
- var _cached2, _cachedCwd;
1866
- var init_project_name = __esm({
1867
- "src/lib/project-name.ts"() {
1868
- "use strict";
1869
- _cached2 = null;
1870
- _cachedCwd = null;
1871
- }
1872
- });
1873
-
1874
- // src/lib/session-scope.ts
1875
- var session_scope_exports = {};
1876
- __export(session_scope_exports, {
1877
- assertSessionScope: () => assertSessionScope,
1878
- findSessionForProject: () => findSessionForProject,
1879
- getSessionProject: () => getSessionProject
1880
- });
1881
- function getSessionProject(sessionName) {
1882
- const sessions = listSessions();
1883
- const entry = sessions.find((s) => s.windowName === sessionName);
1884
- if (!entry) return null;
1885
- const parts = entry.projectDir.split("/").filter(Boolean);
1886
- return parts[parts.length - 1] ?? null;
1887
- }
1888
- function findSessionForProject(projectName) {
1889
- const sessions = listSessions();
1890
- for (const s of sessions) {
1891
- const proj = s.projectDir.split("/").filter(Boolean).pop();
1892
- if (proj === projectName && s.agentId === "exe") return s;
1893
- }
1894
- return null;
1895
- }
1896
- function assertSessionScope(actionType, targetProject) {
1897
- try {
1898
- const currentProject = getProjectName();
1899
- const exeSession = resolveExeSession();
1900
- if (!exeSession) {
1901
- return { allowed: true, reason: "no_session" };
1902
- }
1903
- if (currentProject === targetProject) {
1904
- return {
1905
- allowed: true,
1906
- reason: "same_session",
1907
- currentProject,
1908
- targetProject
1909
- };
1910
- }
1911
- process.stderr.write(
1912
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
1913
- `
1914
- );
1915
- return {
1916
- allowed: true,
1917
- // v1: warn-only, don't block
1918
- reason: "cross_session_granted",
1919
- currentProject,
1920
- targetProject,
1921
- targetSession: findSessionForProject(targetProject)?.windowName
1922
- };
1923
- } catch {
1924
- return { allowed: true, reason: "no_session" };
1925
- }
1926
- }
1927
- var init_session_scope = __esm({
1928
- "src/lib/session-scope.ts"() {
1929
- "use strict";
1930
- init_session_registry();
1931
- init_project_name();
1932
- init_tmux_routing();
1933
- }
1934
- });
1935
-
1936
- // src/lib/tasks-notify.ts
1937
- async function dispatchTaskToEmployee(input) {
1938
- if (input.assignedTo === "exe") return { dispatched: "skipped" };
1939
- let crossProject = false;
1940
- if (input.projectName) {
1941
- try {
1942
- const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
1943
- const check = assertSessionScope2("dispatch_task", input.projectName);
1944
- if (check.reason === "cross_session_granted") {
1945
- crossProject = true;
1946
- }
1947
- } catch {
1948
- }
1949
- }
1950
- try {
1951
- const transport = getTransport();
1952
- const exeSession = resolveExeSession();
1953
- if (!exeSession) return { dispatched: "session_missing" };
1954
- const sessionName = employeeSessionName(input.assignedTo, exeSession);
1955
- if (transport.isAlive(sessionName)) {
1956
- const result = sendIntercom(sessionName);
1957
- const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
1958
- return { dispatched, session: sessionName, crossProject };
1959
- } else {
1960
- const projectDir = input.projectDir ?? process.cwd();
1961
- const result = ensureEmployee(input.assignedTo, exeSession, projectDir);
1962
- if (result.status === "failed") {
1963
- process.stderr.write(
1964
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
1965
- `
1966
- );
1967
- return { dispatched: "session_missing" };
1968
- }
1969
- return { dispatched: "spawned", session: result.sessionName, crossProject };
1970
- }
1971
- } catch {
1972
- return { dispatched: "session_missing" };
1973
- }
1974
- }
1975
- function notifyTaskDone() {
1976
- try {
1977
- const key = getSessionKey();
1978
- if (key && !process.env.VITEST) notifyParentExe(key);
1979
- } catch {
1980
- }
1981
- }
1982
- async function markTaskNotificationsRead(taskFile) {
1983
- try {
1984
- await markAsReadByTaskFile(taskFile);
1985
- } catch {
1986
- }
1987
- }
1988
- var init_tasks_notify = __esm({
1989
- "src/lib/tasks-notify.ts"() {
1990
- "use strict";
1991
- init_tmux_routing();
1992
- init_session_key();
1993
- init_notifications();
1994
- init_transport();
1995
- }
1996
- });
1997
-
1998
- // src/lib/behaviors.ts
1999
- import crypto3 from "crypto";
2000
- async function storeBehavior(opts) {
2001
- const client = getClient();
2002
- const id = crypto3.randomUUID();
2003
- const now = (/* @__PURE__ */ new Date()).toISOString();
2004
- await client.execute({
2005
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
2006
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
2007
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
2008
- });
2009
- return id;
2010
- }
2011
- var init_behaviors = __esm({
2012
- "src/lib/behaviors.ts"() {
2013
- "use strict";
2014
- init_database();
2015
- }
2016
- });
2017
-
2018
- // src/lib/skill-learning.ts
2019
- var skill_learning_exports = {};
2020
- __export(skill_learning_exports, {
2021
- captureAndLearn: () => captureAndLearn,
2022
- captureTrajectory: () => captureTrajectory,
2023
- editDistance: () => editDistance,
2024
- extractSkill: () => extractSkill,
2025
- extractTrajectory: () => extractTrajectory,
2026
- findSimilarTrajectories: () => findSimilarTrajectories,
2027
- hashSignature: () => hashSignature,
2028
- storeTrajectory: () => storeTrajectory,
2029
- sweepTrajectories: () => sweepTrajectories
2030
- });
2031
- import crypto4 from "crypto";
2032
- async function extractTrajectory(taskId, agentId) {
2033
- const client = getClient();
2034
- const result = await client.execute({
2035
- sql: `SELECT tool_name, raw_text
2036
- FROM memories
2037
- WHERE task_id = ? AND agent_id = ?
2038
- ORDER BY timestamp ASC`,
2039
- args: [taskId, agentId]
2040
- });
2041
- if (result.rows.length === 0) return [];
2042
- const rawTools = result.rows.map((r) => {
2043
- const toolName = String(r.tool_name);
2044
- if (toolName === "Bash") {
2045
- const text = String(r.raw_text);
2046
- const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
2047
- return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
2048
- }
2049
- return toolName;
2050
- });
2051
- const signature = [];
2052
- for (const tool of rawTools) {
2053
- if (signature.length === 0 || signature[signature.length - 1] !== tool) {
2054
- signature.push(tool);
2055
- }
2056
- }
2057
- return signature;
2058
- }
2059
- function hashSignature(signature) {
2060
- return crypto4.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
2061
- }
2062
- async function storeTrajectory(opts) {
2063
- const client = getClient();
2064
- const id = crypto4.randomUUID();
2065
- const now = (/* @__PURE__ */ new Date()).toISOString();
2066
- const signatureHash = hashSignature(opts.signature);
2067
- await client.execute({
2068
- sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
2069
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2070
- args: [
2071
- id,
2072
- opts.taskId,
2073
- opts.agentId,
2074
- opts.projectName,
2075
- opts.taskTitle,
2076
- JSON.stringify(opts.signature),
2077
- signatureHash,
2078
- opts.signature.length,
2079
- now
2080
- ]
2081
- });
2082
- return id;
2083
- }
2084
- async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
2085
- const client = getClient();
2086
- const hash = hashSignature(signature);
2087
- const result = await client.execute({
2088
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2089
- FROM trajectories
2090
- WHERE signature_hash = ?
2091
- ORDER BY created_at DESC
2092
- LIMIT 20`,
2093
- args: [hash]
2094
- });
2095
- const mapRow = (r) => ({
2096
- id: String(r.id),
2097
- taskId: String(r.task_id),
2098
- agentId: String(r.agent_id),
2099
- projectName: String(r.project_name),
2100
- taskTitle: String(r.task_title),
2101
- signature: JSON.parse(String(r.signature)),
2102
- signatureHash: String(r.signature_hash),
2103
- toolCount: Number(r.tool_count),
2104
- skillId: r.skill_id ? String(r.skill_id) : null,
2105
- createdAt: String(r.created_at)
2106
- });
2107
- const matches = result.rows.map(mapRow);
2108
- if (matches.length >= threshold) return matches;
2109
- const nearResult = await client.execute({
2110
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2111
- FROM trajectories
2112
- WHERE tool_count BETWEEN ? AND ?
2113
- AND signature_hash != ?
2114
- ORDER BY created_at DESC
2115
- LIMIT 50`,
2116
- args: [
2117
- Math.max(1, signature.length - 3),
2118
- signature.length + 3,
2119
- hash
2120
- ]
2121
- });
2122
- for (const r of nearResult.rows) {
2123
- const candidateSig = JSON.parse(String(r.signature));
2124
- if (editDistance(signature, candidateSig) <= 2) {
2125
- matches.push(mapRow(r));
2126
- }
2127
- }
2128
- return matches;
2129
- }
2130
- async function captureTrajectory(opts) {
2131
- const signature = await extractTrajectory(opts.taskId, opts.agentId);
2132
- if (signature.length < 3) {
2133
- return { trajectoryId: "", similarCount: 0, similar: [] };
2134
- }
2135
- const trajectoryId = await storeTrajectory({
2136
- taskId: opts.taskId,
2137
- agentId: opts.agentId,
2138
- projectName: opts.projectName,
2139
- taskTitle: opts.taskTitle,
2140
- signature
2141
- });
2142
- const similar = await findSimilarTrajectories(
2143
- signature,
2144
- opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
2145
- );
2146
- return { trajectoryId, similarCount: similar.length, similar };
2147
- }
2148
- function buildExtractionPrompt(trajectories) {
2149
- const items = trajectories.map((t, i) => {
2150
- const sig = t.signature.join(" \u2192 ");
2151
- return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
2152
- Signature: ${sig}`;
2153
- }).join("\n\n");
2154
- return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
2155
-
2156
- ${items}
2157
-
2158
- Extract the reusable procedure. Format your response EXACTLY like this:
2159
-
2160
- SKILL: {name \u2014 short, descriptive}
2161
- TRIGGER: {when to use this \u2014 one sentence}
2162
- STEPS:
2163
- 1. ...
2164
- 2. ...
2165
- PITFALLS: {common mistakes to avoid}
2166
-
2167
- Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
2168
- }
2169
- async function extractSkill(trajectories, model) {
2170
- if (trajectories.length === 0) return null;
2171
- const config = await loadConfig();
2172
- const skillModel = model ?? config.skillModel;
2173
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
2174
- const client = new Anthropic();
2175
- const prompt = buildExtractionPrompt(trajectories);
2176
- const response = await client.messages.create({
2177
- model: skillModel,
2178
- max_tokens: 500,
2179
- messages: [{ role: "user", content: prompt }]
2180
- });
2181
- const textBlock = response.content.find((b) => b.type === "text");
2182
- const skillText = textBlock?.text;
2183
- if (!skillText) return null;
2184
- const agentId = trajectories[0].agentId;
2185
- const projectName = trajectories[0].projectName;
2186
- const skillId = await storeBehavior({
2187
- agentId,
2188
- content: skillText,
2189
- domain: "skill",
2190
- projectName
2191
- });
2192
- const dbClient = getClient();
2193
- for (const t of trajectories) {
2194
- await dbClient.execute({
2195
- sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
2196
- args: [skillId, t.id]
2197
- });
2198
- }
2199
- process.stderr.write(
2200
- `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
2201
- `
2202
- );
2203
- return skillId;
2204
- }
2205
- async function captureAndLearn(opts) {
2206
- try {
2207
- const config = await loadConfig();
2208
- if (!config.skillLearning) return;
2209
- const { trajectoryId, similarCount, similar } = await captureTrajectory({
2210
- ...opts,
2211
- skillThreshold: config.skillThreshold
2212
- });
2213
- if (!trajectoryId) return;
2214
- if (similarCount >= config.skillThreshold) {
2215
- const unprocessed = similar.filter((t) => !t.skillId);
2216
- if (unprocessed.length >= config.skillThreshold) {
2217
- extractSkill(unprocessed, config.skillModel).catch((err) => {
2218
- process.stderr.write(
2219
- `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
2220
- `
2221
- );
2222
- });
2223
- }
2224
- }
2225
- } catch (err) {
2226
- process.stderr.write(
2227
- `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
2228
- `
2229
- );
2230
- }
2231
- }
2232
- async function sweepTrajectories(threshold, model) {
2233
- const config = await loadConfig();
2234
- if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
2235
- const t = threshold ?? config.skillThreshold;
2236
- const client = getClient();
2237
- const result = await client.execute({
2238
- sql: `SELECT signature_hash, COUNT(*) as cnt
2239
- FROM trajectories
2240
- WHERE skill_id IS NULL
2241
- GROUP BY signature_hash
2242
- HAVING cnt >= ?
2243
- ORDER BY cnt DESC
2244
- LIMIT 10`,
2245
- args: [t]
2246
- });
2247
- let clustersProcessed = 0;
2248
- let skillsExtracted = 0;
2249
- for (const row of result.rows) {
2250
- const hash = String(row.signature_hash);
2251
- const trajResult = await client.execute({
2252
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
2253
- FROM trajectories
2254
- WHERE signature_hash = ? AND skill_id IS NULL
2255
- ORDER BY created_at DESC
2256
- LIMIT 10`,
2257
- args: [hash]
2258
- });
2259
- const trajectories = trajResult.rows.map((r) => ({
2260
- id: String(r.id),
2261
- taskId: String(r.task_id),
2262
- agentId: String(r.agent_id),
2263
- projectName: String(r.project_name),
2264
- taskTitle: String(r.task_title),
2265
- signature: JSON.parse(String(r.signature)),
2266
- signatureHash: String(r.signature_hash),
2267
- toolCount: Number(r.tool_count),
2268
- skillId: null,
2269
- createdAt: String(r.created_at)
2270
- }));
2271
- if (trajectories.length >= t) {
2272
- clustersProcessed++;
2273
- const skillId = await extractSkill(trajectories, model ?? config.skillModel);
2274
- if (skillId) skillsExtracted++;
2275
- }
2276
- }
2277
- return { clustersProcessed, skillsExtracted };
2278
- }
2279
- function editDistance(a, b) {
2280
- const m = a.length;
2281
- const n = b.length;
2282
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
2283
- for (let i = 0; i <= m; i++) dp[i][0] = i;
2284
- for (let j = 0; j <= n; j++) dp[0][j] = j;
2285
- for (let i = 1; i <= m; i++) {
2286
- for (let j = 1; j <= n; j++) {
2287
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2288
- dp[i][j] = Math.min(
2289
- dp[i - 1][j] + 1,
2290
- dp[i][j - 1] + 1,
2291
- dp[i - 1][j - 1] + cost
2292
- );
2293
- }
2294
- }
2295
- return dp[m][n];
2296
- }
2297
- var DEFAULT_SKILL_THRESHOLD;
2298
- var init_skill_learning = __esm({
2299
- "src/lib/skill-learning.ts"() {
2300
- "use strict";
2301
- init_database();
2302
- init_behaviors();
2303
- init_config();
2304
- DEFAULT_SKILL_THRESHOLD = 3;
2305
- }
2306
- });
2307
-
2308
- // src/lib/tasks.ts
2309
- import path14 from "path";
2310
- import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, unlinkSync as unlinkSync3 } from "fs";
2311
- async function createTask(input) {
2312
- const result = await createTaskCore(input);
2313
- if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
2314
- dispatchTaskToEmployee({
2315
- assignedTo: input.assignedTo,
2316
- title: input.title,
2317
- priority: input.priority,
2318
- taskFile: result.taskFile,
2319
- initialStatus: result.status,
2320
- projectName: input.projectName
2321
- });
2322
- }
2323
- return result;
2324
- }
2325
- async function updateTask(input) {
2326
- const { row, taskFile, now, taskId } = await updateTaskStatus(input);
2327
- try {
2328
- const agent = String(row.assigned_to);
2329
- const cacheDir = path14.join(EXE_AI_DIR, "session-cache");
2330
- const cachePath = path14.join(cacheDir, `current-task-${agent}.json`);
2331
- if (input.status === "in_progress") {
2332
- mkdirSync6(cacheDir, { recursive: true });
2333
- writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
2334
- } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
2335
- try {
2336
- unlinkSync3(cachePath);
2337
- } catch {
2338
- }
2339
- }
2340
- } catch {
2341
- }
2342
- if (input.status === "done") {
2343
- await cleanupReviewFile(row, taskFile, input.baseDir);
2344
- }
2345
- if (input.status === "done" || input.status === "cancelled") {
2346
- try {
2347
- const client = getClient();
2348
- const taskTitle = String(row.title);
2349
- await client.execute({
2350
- sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
2351
- WHERE title LIKE ? AND status IN ('open', 'in_progress')`,
2352
- args: [now, `%left%${taskTitle}%in_progress`]
2353
- });
2354
- } catch {
2355
- }
2356
- }
2357
- const isTerminal = input.status === "done" || input.status === "needs_review";
2358
- if (isTerminal) {
2359
- const isExe = String(row.assigned_to) === "exe";
2360
- if (!isExe) {
2361
- notifyTaskDone();
2362
- }
2363
- await markTaskNotificationsRead(taskFile);
2364
- if (input.status === "done") {
2365
- try {
2366
- await cascadeUnblock(taskId, input.baseDir, now);
2367
- } catch {
2368
- }
2369
- if (row.parent_task_id) {
2370
- try {
2371
- await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
2372
- } catch {
2373
- }
2374
- }
2375
- }
2376
- }
2377
- if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
2378
- Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
2379
- ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
2380
- taskId,
2381
- agentId: String(row.assigned_to),
2382
- projectName: String(row.project_name),
2383
- taskTitle: String(row.title)
2384
- })
2385
- ).catch((err) => {
2386
- process.stderr.write(
2387
- `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
2388
- `
2389
- );
2390
- });
2391
- }
2392
- let nextTask;
2393
- if (isTerminal && String(row.assigned_to) !== "exe") {
2394
- try {
2395
- nextTask = await findNextTask(String(row.assigned_to));
2396
- } catch {
2397
- }
2398
- }
2399
- return {
2400
- id: String(row.id),
2401
- title: String(row.title),
2402
- assignedTo: String(row.assigned_to),
2403
- assignedBy: String(row.assigned_by),
2404
- projectName: String(row.project_name),
2405
- priority: String(row.priority),
2406
- status: input.status,
2407
- taskFile,
2408
- createdAt: String(row.created_at),
2409
- updatedAt: now,
2410
- nextTask
2411
- };
2412
- }
2413
- async function deleteTask(taskId, baseDir) {
2414
- const client = getClient();
2415
- const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
2416
- const reviewer = assignedBy || "exe";
2417
- const reviewSlug = `review-${assignedTo}-${taskSlug}`;
2418
- const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
2419
- await client.execute({
2420
- sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
2421
- args: [reviewFile, `exe/exe/${reviewSlug}.md`]
2422
- });
2423
- await markAsReadByTaskFile(taskFile);
2424
- await markAsReadByTaskFile(reviewFile);
2425
- }
2426
- var init_tasks = __esm({
2427
- "src/lib/tasks.ts"() {
2428
- init_database();
2429
- init_config();
2430
- init_notifications();
2431
- init_tasks_crud();
2432
- init_tasks_review();
2433
- init_tasks_crud();
2434
- init_tasks_chain();
2435
- init_tasks_review();
2436
- init_tasks_notify();
2437
- }
2438
- });
2439
- init_tasks();
2440
- export {
2441
- countNewPendingReviewsSince,
2442
- countPendingReviews,
2443
- createTask,
2444
- createTaskCore,
2445
- deleteTask,
2446
- deleteTaskCore,
2447
- ensureArchitectureDoc,
2448
- ensureGitignoreExe,
2449
- getReviewChecklist,
2450
- listPendingReviews,
2451
- listTasks,
2452
- resolveTask,
2453
- slugify,
2454
- updateTask,
2455
- updateTaskStatus
2456
- };