@askexenow/exe-os 0.8.41 → 0.8.43

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 (76) hide show
  1. package/dist/bin/backfill-conversations.js +805 -642
  2. package/dist/bin/backfill-responses.js +804 -641
  3. package/dist/bin/backfill-vectors.js +791 -634
  4. package/dist/bin/cleanup-stale-review-tasks.js +788 -631
  5. package/dist/bin/cli.js +1345 -660
  6. package/dist/bin/exe-agent.js +20 -1
  7. package/dist/bin/exe-assign.js +1503 -1343
  8. package/dist/bin/exe-boot.js +2518 -1798
  9. package/dist/bin/exe-call.js +39 -1
  10. package/dist/bin/exe-cloud.js +15 -1
  11. package/dist/bin/exe-dispatch.js +39 -2
  12. package/dist/bin/exe-doctor.js +790 -633
  13. package/dist/bin/exe-export-behaviors.js +792 -637
  14. package/dist/bin/exe-forget.js +145 -0
  15. package/dist/bin/exe-gateway.js +2500 -1877
  16. package/dist/bin/exe-heartbeat.js +147 -1
  17. package/dist/bin/exe-kill.js +795 -640
  18. package/dist/bin/exe-launch-agent.js +2168 -2008
  19. package/dist/bin/exe-link.js +28 -2
  20. package/dist/bin/exe-new-employee.js +25 -3
  21. package/dist/bin/exe-pending-messages.js +146 -1
  22. package/dist/bin/exe-pending-notifications.js +788 -631
  23. package/dist/bin/exe-pending-reviews.js +147 -1
  24. package/dist/bin/exe-rename.js +23 -0
  25. package/dist/bin/exe-review.js +490 -327
  26. package/dist/bin/exe-search.js +154 -3
  27. package/dist/bin/exe-session-cleanup.js +2466 -413
  28. package/dist/bin/exe-status.js +474 -317
  29. package/dist/bin/exe-team.js +474 -317
  30. package/dist/bin/git-sweep.js +2690 -150
  31. package/dist/bin/graph-backfill.js +794 -637
  32. package/dist/bin/graph-export.js +798 -641
  33. package/dist/bin/scan-tasks.js +2951 -44
  34. package/dist/bin/setup.js +62 -26
  35. package/dist/bin/shard-migrate.js +792 -637
  36. package/dist/bin/wiki-sync.js +794 -637
  37. package/dist/gateway/index.js +2504 -1895
  38. package/dist/hooks/bug-report-worker.js +2118 -576
  39. package/dist/hooks/commit-complete.js +2689 -149
  40. package/dist/hooks/error-recall.js +154 -3
  41. package/dist/hooks/ingest-worker.js +1439 -815
  42. package/dist/hooks/instructions-loaded.js +151 -0
  43. package/dist/hooks/notification.js +153 -2
  44. package/dist/hooks/post-compact.js +164 -0
  45. package/dist/hooks/pre-compact.js +3073 -101
  46. package/dist/hooks/pre-tool-use.js +151 -0
  47. package/dist/hooks/prompt-ingest-worker.js +1714 -1537
  48. package/dist/hooks/prompt-submit.js +2658 -1113
  49. package/dist/hooks/response-ingest-worker.js +170 -6
  50. package/dist/hooks/session-end.js +153 -2
  51. package/dist/hooks/session-start.js +154 -3
  52. package/dist/hooks/stop.js +151 -0
  53. package/dist/hooks/subagent-stop.js +151 -0
  54. package/dist/hooks/summary-worker.js +179 -7
  55. package/dist/index.js +278 -100
  56. package/dist/lib/cloud-sync.js +28 -2
  57. package/dist/lib/consolidation.js +69 -2
  58. package/dist/lib/database.js +19 -0
  59. package/dist/lib/device-registry.js +19 -0
  60. package/dist/lib/employee-templates.js +20 -1
  61. package/dist/lib/exe-daemon.js +236 -16
  62. package/dist/lib/hybrid-search.js +154 -3
  63. package/dist/lib/license.js +15 -1
  64. package/dist/lib/messaging.js +39 -2
  65. package/dist/lib/schedules.js +792 -637
  66. package/dist/lib/store.js +796 -636
  67. package/dist/lib/tasks.js +1614 -1091
  68. package/dist/lib/tmux-routing.js +149 -9
  69. package/dist/mcp/server.js +1825 -1138
  70. package/dist/mcp/tools/create-task.js +2280 -828
  71. package/dist/mcp/tools/list-tasks.js +2788 -159
  72. package/dist/mcp/tools/send-message.js +39 -2
  73. package/dist/mcp/tools/update-task.js +64 -0
  74. package/dist/runtime/index.js +235 -67
  75. package/dist/tui/App.js +1452 -644
  76. package/package.json +3 -2
@@ -302,6 +302,40 @@ import {
302
302
  existsSync as existsSync2,
303
303
  rmdirSync
304
304
  } from "fs";
305
+ async function writeNotification(notification) {
306
+ try {
307
+ const client = getClient();
308
+ const id = crypto.randomUUID();
309
+ const now = (/* @__PURE__ */ new Date()).toISOString();
310
+ await client.execute({
311
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
312
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
313
+ args: [
314
+ id,
315
+ notification.agentId,
316
+ notification.agentRole,
317
+ notification.event,
318
+ notification.project,
319
+ notification.summary,
320
+ notification.taskFile ?? null,
321
+ now
322
+ ]
323
+ });
324
+ } catch (err) {
325
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
326
+ `);
327
+ }
328
+ }
329
+ async function markAsReadByTaskFile(taskFile) {
330
+ try {
331
+ const client = getClient();
332
+ await client.execute({
333
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
334
+ args: [taskFile]
335
+ });
336
+ } catch {
337
+ }
338
+ }
305
339
  var init_notifications = __esm({
306
340
  "src/lib/notifications.ts"() {
307
341
  "use strict";
@@ -309,396 +343,103 @@ var init_notifications = __esm({
309
343
  }
310
344
  });
311
345
 
312
- // src/lib/tasks-crud.ts
313
- import crypto2 from "crypto";
314
- import path3 from "path";
315
- import { execSync } from "child_process";
316
- import { mkdir as mkdir2, writeFile as writeFile2, appendFile } from "fs/promises";
317
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
318
- function extractParentFromContext(contextBody) {
319
- if (!contextBody) return null;
320
- const match = contextBody.match(
321
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
322
- );
323
- return match ? match[1].toLowerCase() : null;
324
- }
325
- function slugify(title) {
326
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
327
- }
328
- async function resolveTask(client, identifier) {
329
- let result = await client.execute({
330
- sql: "SELECT * FROM tasks WHERE id = ?",
331
- args: [identifier]
332
- });
333
- if (result.rows.length === 1) return result.rows[0];
334
- result = await client.execute({
335
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
336
- args: [`%${identifier}%`]
337
- });
338
- if (result.rows.length === 1) return result.rows[0];
339
- if (result.rows.length > 1) {
340
- const exact = result.rows.filter(
341
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
342
- );
343
- if (exact.length === 1) return exact[0];
344
- const candidates = exact.length > 1 ? exact : result.rows;
345
- const active = candidates.filter(
346
- (r) => !["done", "cancelled"].includes(String(r.status))
347
- );
348
- if (active.length === 1) return active[0];
349
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
350
- throw new Error(
351
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
352
- );
353
- }
354
- result = await client.execute({
355
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
356
- args: [`%${identifier}%`]
357
- });
358
- if (result.rows.length === 1) return result.rows[0];
359
- if (result.rows.length > 1) {
360
- const active = result.rows.filter(
361
- (r) => !["done", "cancelled"].includes(String(r.status))
362
- );
363
- if (active.length === 1) return active[0];
364
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
365
- throw new Error(
366
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
367
- );
368
- }
369
- throw new Error(`Task not found: ${identifier}`);
370
- }
371
- async function createTaskCore(input) {
372
- const client = getClient();
373
- const id = crypto2.randomUUID();
374
- const now = (/* @__PURE__ */ new Date()).toISOString();
375
- const slug = slugify(input.title);
376
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
377
- let blockedById = null;
378
- const initialStatus = input.blockedBy ? "blocked" : "open";
379
- if (input.blockedBy) {
380
- const blocker = await resolveTask(client, input.blockedBy);
381
- blockedById = String(blocker.id);
382
- }
383
- let parentTaskId = null;
384
- let parentRef = input.parentTaskId;
385
- if (!parentRef) {
386
- const extracted = extractParentFromContext(input.context);
387
- if (extracted) {
388
- parentRef = extracted;
389
- process.stderr.write(
390
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
391
- );
392
- }
393
- }
394
- if (parentRef) {
395
- try {
396
- const parent = await resolveTask(client, parentRef);
397
- parentTaskId = String(parent.id);
398
- } catch (err) {
399
- if (!input.parentTaskId) {
400
- throw new Error(
401
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
402
- );
346
+ // src/lib/state-bus.ts
347
+ var StateBus, orgBus;
348
+ var init_state_bus = __esm({
349
+ "src/lib/state-bus.ts"() {
350
+ "use strict";
351
+ StateBus = class {
352
+ handlers = /* @__PURE__ */ new Map();
353
+ globalHandlers = /* @__PURE__ */ new Set();
354
+ /** Emit an event to all subscribers */
355
+ emit(event) {
356
+ const typeHandlers = this.handlers.get(event.type);
357
+ if (typeHandlers) {
358
+ for (const handler of typeHandlers) {
359
+ try {
360
+ handler(event);
361
+ } catch {
362
+ }
363
+ }
364
+ }
365
+ for (const handler of this.globalHandlers) {
366
+ try {
367
+ handler(event);
368
+ } catch {
369
+ }
370
+ }
403
371
  }
404
- throw err;
405
- }
406
- }
407
- let warning;
408
- const dupCheck = await client.execute({
409
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
410
- args: [input.title, input.assignedTo]
411
- });
412
- if (dupCheck.rows.length > 0) {
413
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
372
+ /** Subscribe to a specific event type */
373
+ on(type, handler) {
374
+ if (!this.handlers.has(type)) {
375
+ this.handlers.set(type, /* @__PURE__ */ new Set());
376
+ }
377
+ this.handlers.get(type).add(handler);
378
+ }
379
+ /** Subscribe to ALL events */
380
+ onAny(handler) {
381
+ this.globalHandlers.add(handler);
382
+ }
383
+ /** Unsubscribe from a specific event type */
384
+ off(type, handler) {
385
+ this.handlers.get(type)?.delete(handler);
386
+ }
387
+ /** Unsubscribe from ALL events */
388
+ offAny(handler) {
389
+ this.globalHandlers.delete(handler);
390
+ }
391
+ /** Remove all listeners */
392
+ clear() {
393
+ this.handlers.clear();
394
+ this.globalHandlers.clear();
395
+ }
396
+ };
397
+ orgBus = new StateBus();
414
398
  }
415
- if (input.baseDir) {
416
- try {
417
- await mkdir2(path3.join(input.baseDir, "exe", "output"), { recursive: true });
418
- await mkdir2(path3.join(input.baseDir, "exe", "research"), { recursive: true });
419
- await ensureArchitectureDoc(input.baseDir, input.projectName);
420
- await ensureGitignoreExe(input.baseDir);
421
- } catch {
422
- }
399
+ });
400
+
401
+ // src/lib/session-registry.ts
402
+ import { readFileSync as readFileSync3, writeFileSync, mkdirSync, existsSync as existsSync3 } from "fs";
403
+ import path3 from "path";
404
+ import os3 from "os";
405
+ function registerSession(entry) {
406
+ const dir = path3.dirname(REGISTRY_PATH);
407
+ if (!existsSync3(dir)) {
408
+ mkdirSync(dir, { recursive: true });
423
409
  }
424
- const complexity = input.complexity ?? "standard";
425
- await client.execute({
426
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, created_at, updated_at)
427
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
428
- args: [
429
- id,
430
- input.title,
431
- input.assignedTo,
432
- input.assignedBy,
433
- input.projectName,
434
- input.priority,
435
- initialStatus,
436
- taskFile,
437
- blockedById,
438
- parentTaskId,
439
- input.reviewer ?? null,
440
- input.context,
441
- complexity,
442
- input.budgetTokens ?? null,
443
- input.budgetFallbackModel ?? null,
444
- 0,
445
- null,
446
- now,
447
- now
448
- ]
449
- });
450
- return {
451
- id,
452
- title: input.title,
453
- assignedTo: input.assignedTo,
454
- assignedBy: input.assignedBy,
455
- projectName: input.projectName,
456
- priority: input.priority,
457
- status: initialStatus,
458
- taskFile,
459
- createdAt: now,
460
- updatedAt: now,
461
- warning,
462
- budgetTokens: input.budgetTokens ?? null,
463
- budgetFallbackModel: input.budgetFallbackModel ?? null,
464
- tokensUsed: 0,
465
- tokensWarnedAt: null
466
- };
467
- }
468
- async function ensureArchitectureDoc(baseDir, projectName) {
469
- const archPath = path3.join(baseDir, "exe", "ARCHITECTURE.md");
470
- try {
471
- if (existsSync3(archPath)) return;
472
- const template = [
473
- `# ${projectName} \u2014 System Architecture`,
474
- "",
475
- "> Employees: read this before every task. Update it when you change system structure.",
476
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
477
- "",
478
- "## Overview",
479
- "",
480
- "<!-- Describe what this system does, its main components, and how they connect. -->",
481
- "",
482
- "## Key Components",
483
- "",
484
- "<!-- List the major modules, services, or subsystems. -->",
485
- "",
486
- "## Data Flow",
487
- "",
488
- "<!-- How does data move through the system? What writes where? -->",
489
- "",
490
- "## Invariants",
491
- "",
492
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
493
- "",
494
- "## Dependencies",
495
- "",
496
- "<!-- What depends on what? If I change X, what else is affected? -->",
497
- ""
498
- ].join("\n");
499
- await writeFile2(archPath, template, "utf-8");
500
- } catch {
410
+ const sessions = listSessions();
411
+ const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
412
+ if (idx >= 0) {
413
+ sessions[idx] = entry;
414
+ } else {
415
+ sessions.push(entry);
501
416
  }
417
+ writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
502
418
  }
503
- async function ensureGitignoreExe(baseDir) {
504
- const gitignorePath = path3.join(baseDir, ".gitignore");
419
+ function listSessions() {
505
420
  try {
506
- if (existsSync3(gitignorePath)) {
507
- const content = readFileSync3(gitignorePath, "utf-8");
508
- if (/^\/?exe\/?$/m.test(content)) return;
509
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
510
- } else {
511
- await writeFile2(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
512
- }
421
+ const raw = readFileSync3(REGISTRY_PATH, "utf8");
422
+ return JSON.parse(raw);
513
423
  } catch {
424
+ return [];
514
425
  }
515
426
  }
516
- var init_tasks_crud = __esm({
517
- "src/lib/tasks-crud.ts"() {
427
+ var REGISTRY_PATH;
428
+ var init_session_registry = __esm({
429
+ "src/lib/session-registry.ts"() {
518
430
  "use strict";
519
- init_database();
520
- }
521
- });
522
-
523
- // src/lib/employees.ts
524
- var employees_exports = {};
525
- __export(employees_exports, {
526
- EMPLOYEES_PATH: () => EMPLOYEES_PATH,
527
- addEmployee: () => addEmployee,
528
- getEmployee: () => getEmployee,
529
- getEmployeeByRole: () => getEmployeeByRole,
530
- getEmployeeNamesByRole: () => getEmployeeNamesByRole,
531
- hasRole: () => hasRole,
532
- isMultiInstance: () => isMultiInstance,
533
- loadEmployees: () => loadEmployees,
534
- loadEmployeesSync: () => loadEmployeesSync,
535
- registerBinSymlinks: () => registerBinSymlinks,
536
- saveEmployees: () => saveEmployees,
537
- validateEmployeeName: () => validateEmployeeName
538
- });
539
- import { readFile as readFile2, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
540
- import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
541
- import { execSync as execSync2 } from "child_process";
542
- import path4 from "path";
543
- function validateEmployeeName(name) {
544
- if (!name) {
545
- return { valid: false, error: "Name is required" };
546
- }
547
- if (name.length > 32) {
548
- return { valid: false, error: "Name must be 32 characters or fewer" };
549
- }
550
- if (!/^[a-z][a-z0-9]*$/.test(name)) {
551
- return {
552
- valid: false,
553
- error: "Name must start with a letter and contain only lowercase alphanumeric characters"
554
- };
555
- }
556
- return { valid: true };
557
- }
558
- async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
559
- if (!existsSync4(employeesPath)) {
560
- return [];
561
- }
562
- const raw = await readFile2(employeesPath, "utf-8");
563
- try {
564
- return JSON.parse(raw);
565
- } catch {
566
- return [];
567
- }
568
- }
569
- async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
570
- await mkdir3(path4.dirname(employeesPath), { recursive: true });
571
- await writeFile3(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
572
- }
573
- function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
574
- if (!existsSync4(employeesPath)) return [];
575
- try {
576
- return JSON.parse(readFileSync4(employeesPath, "utf-8"));
577
- } catch {
578
- return [];
579
- }
580
- }
581
- function getEmployee(employees, name) {
582
- return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
583
- }
584
- function getEmployeeByRole(employees, role) {
585
- const lower = role.toLowerCase();
586
- return employees.find((e) => e.role.toLowerCase() === lower);
587
- }
588
- function getEmployeeNamesByRole(employees, role) {
589
- const lower = role.toLowerCase();
590
- return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
591
- }
592
- function hasRole(agentName, role) {
593
- const employees = loadEmployeesSync();
594
- const emp = getEmployee(employees, agentName);
595
- return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
596
- }
597
- function isMultiInstance(agentName, employees) {
598
- const roster = employees ?? loadEmployeesSync();
599
- const emp = getEmployee(roster, agentName);
600
- if (!emp) return false;
601
- return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
602
- }
603
- function addEmployee(employees, employee) {
604
- const normalized = { ...employee, name: employee.name.toLowerCase() };
605
- if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
606
- throw new Error(`Employee '${normalized.name}' already exists`);
607
- }
608
- return [...employees, normalized];
609
- }
610
- function findExeBin() {
611
- try {
612
- return execSync2(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
613
- } catch {
614
- return null;
615
- }
616
- }
617
- function registerBinSymlinks(name) {
618
- const created = [];
619
- const skipped = [];
620
- const errors = [];
621
- const exeBinPath = findExeBin();
622
- if (!exeBinPath) {
623
- errors.push("Could not find 'exe-os' in PATH");
624
- return { created, skipped, errors };
625
- }
626
- const binDir = path4.dirname(exeBinPath);
627
- let target;
628
- try {
629
- target = readlinkSync(exeBinPath);
630
- } catch {
631
- errors.push("Could not read 'exe' symlink");
632
- return { created, skipped, errors };
633
- }
634
- for (const suffix of ["", "-opencode"]) {
635
- const linkName = `${name}${suffix}`;
636
- const linkPath = path4.join(binDir, linkName);
637
- if (existsSync4(linkPath)) {
638
- skipped.push(linkName);
639
- continue;
640
- }
641
- try {
642
- symlinkSync(target, linkPath);
643
- created.push(linkName);
644
- } catch (err) {
645
- errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
646
- }
647
- }
648
- return { created, skipped, errors };
649
- }
650
- var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
651
- var init_employees = __esm({
652
- "src/lib/employees.ts"() {
653
- "use strict";
654
- init_config();
655
- EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
656
- MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
657
- }
658
- });
659
-
660
- // src/lib/session-registry.ts
661
- import { readFileSync as readFileSync5, writeFileSync, mkdirSync, existsSync as existsSync5 } from "fs";
662
- import path5 from "path";
663
- import os3 from "os";
664
- function registerSession(entry) {
665
- const dir = path5.dirname(REGISTRY_PATH);
666
- if (!existsSync5(dir)) {
667
- mkdirSync(dir, { recursive: true });
668
- }
669
- const sessions = listSessions();
670
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
671
- if (idx >= 0) {
672
- sessions[idx] = entry;
673
- } else {
674
- sessions.push(entry);
675
- }
676
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
677
- }
678
- function listSessions() {
679
- try {
680
- const raw = readFileSync5(REGISTRY_PATH, "utf8");
681
- return JSON.parse(raw);
682
- } catch {
683
- return [];
684
- }
685
- }
686
- var REGISTRY_PATH;
687
- var init_session_registry = __esm({
688
- "src/lib/session-registry.ts"() {
689
- "use strict";
690
- REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
431
+ REGISTRY_PATH = path3.join(os3.homedir(), ".exe-os", "session-registry.json");
691
432
  }
692
433
  });
693
434
 
694
435
  // src/lib/session-key.ts
695
- import { execSync as execSync3 } from "child_process";
436
+ import { execSync } from "child_process";
696
437
  function getSessionKey() {
697
438
  if (_cached) return _cached;
698
439
  let pid = process.ppid;
699
440
  for (let i = 0; i < 10; i++) {
700
441
  try {
701
- const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
442
+ const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
702
443
  encoding: "utf8",
703
444
  timeout: 2e3
704
445
  }).trim();
@@ -834,14 +575,14 @@ var init_transport = __esm({
834
575
  });
835
576
 
836
577
  // src/lib/cc-agent-support.ts
837
- import { execSync as execSync4 } from "child_process";
578
+ import { execSync as execSync2 } from "child_process";
838
579
  function _resetCcAgentSupportCache() {
839
580
  _cachedSupport = null;
840
581
  }
841
582
  function claudeSupportsAgentFlag() {
842
583
  if (_cachedSupport !== null) return _cachedSupport;
843
584
  try {
844
- const helpOutput = execSync4("claude --help 2>&1", {
585
+ const helpOutput = execSync2("claude --help 2>&1", {
845
586
  encoding: "utf-8",
846
587
  timeout: 5e3
847
588
  });
@@ -907,17 +648,17 @@ var init_provider_table = __esm({
907
648
  });
908
649
 
909
650
  // src/lib/intercom-queue.ts
910
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
911
- import path6 from "path";
651
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
652
+ import path4 from "path";
912
653
  import os4 from "os";
913
654
  function ensureDir() {
914
- const dir = path6.dirname(QUEUE_PATH);
915
- if (!existsSync6(dir)) mkdirSync2(dir, { recursive: true });
655
+ const dir = path4.dirname(QUEUE_PATH);
656
+ if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
916
657
  }
917
658
  function readQueue() {
918
659
  try {
919
- if (!existsSync6(QUEUE_PATH)) return [];
920
- return JSON.parse(readFileSync6(QUEUE_PATH, "utf8"));
660
+ if (!existsSync4(QUEUE_PATH)) return [];
661
+ return JSON.parse(readFileSync4(QUEUE_PATH, "utf8"));
921
662
  } catch {
922
663
  return [];
923
664
  }
@@ -949,249 +690,798 @@ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
949
690
  var init_intercom_queue = __esm({
950
691
  "src/lib/intercom-queue.ts"() {
951
692
  "use strict";
952
- QUEUE_PATH = path6.join(os4.homedir(), ".exe-os", "intercom-queue.json");
693
+ QUEUE_PATH = path4.join(os4.homedir(), ".exe-os", "intercom-queue.json");
953
694
  TTL_MS = 60 * 60 * 1e3;
954
- INTERCOM_LOG = path6.join(os4.homedir(), ".exe-os", "intercom.log");
695
+ INTERCOM_LOG = path4.join(os4.homedir(), ".exe-os", "intercom.log");
955
696
  }
956
697
  });
957
698
 
958
- // src/lib/license.ts
959
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
960
- import { randomUUID } from "crypto";
961
- import path7 from "path";
962
- import { jwtVerify, importSPKI } from "jose";
963
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
964
- var init_license = __esm({
965
- "src/lib/license.ts"() {
966
- "use strict";
967
- init_config();
968
- LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
969
- CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
970
- DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
971
- PLAN_LIMITS = {
972
- free: { devices: 1, employees: 1, memories: 5e3 },
973
- pro: { devices: 2, employees: 5, memories: 1e5 },
974
- team: { devices: 10, employees: 20, memories: 1e6 },
975
- agency: { devices: 50, employees: 100, memories: 1e7 },
976
- enterprise: { devices: -1, employees: -1, memories: -1 }
977
- };
978
- }
699
+ // src/lib/employees.ts
700
+ var employees_exports = {};
701
+ __export(employees_exports, {
702
+ EMPLOYEES_PATH: () => EMPLOYEES_PATH,
703
+ addEmployee: () => addEmployee,
704
+ getEmployee: () => getEmployee,
705
+ getEmployeeByRole: () => getEmployeeByRole,
706
+ getEmployeeNamesByRole: () => getEmployeeNamesByRole,
707
+ hasRole: () => hasRole,
708
+ isMultiInstance: () => isMultiInstance,
709
+ loadEmployees: () => loadEmployees,
710
+ loadEmployeesSync: () => loadEmployeesSync,
711
+ registerBinSymlinks: () => registerBinSymlinks,
712
+ saveEmployees: () => saveEmployees,
713
+ validateEmployeeName: () => validateEmployeeName
979
714
  });
980
-
981
- // src/lib/plan-limits.ts
982
- import { readFileSync as readFileSync8, existsSync as existsSync8 } from "fs";
983
- import path8 from "path";
984
- function getLicenseSync() {
985
- try {
986
- if (!existsSync8(CACHE_PATH2)) return freeLicense();
987
- const raw = JSON.parse(readFileSync8(CACHE_PATH2, "utf8"));
988
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
989
- const parts = raw.token.split(".");
990
- if (parts.length !== 3) return freeLicense();
991
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
992
- const plan = payload.plan ?? "free";
993
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
715
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
716
+ import { existsSync as existsSync5, symlinkSync, readlinkSync, readFileSync as readFileSync5 } from "fs";
717
+ import { execSync as execSync3 } from "child_process";
718
+ import path5 from "path";
719
+ function validateEmployeeName(name) {
720
+ if (!name) {
721
+ return { valid: false, error: "Name is required" };
722
+ }
723
+ if (name.length > 32) {
724
+ return { valid: false, error: "Name must be 32 characters or fewer" };
725
+ }
726
+ if (!/^[a-z][a-z0-9]*$/.test(name)) {
994
727
  return {
995
- valid: true,
996
- plan,
997
- email: payload.sub ?? "",
998
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
999
- deviceLimit: limits.devices,
1000
- employeeLimit: limits.employees,
1001
- memoryLimit: limits.memories
728
+ valid: false,
729
+ error: "Name must start with a letter and contain only lowercase alphanumeric characters"
1002
730
  };
731
+ }
732
+ return { valid: true };
733
+ }
734
+ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
735
+ if (!existsSync5(employeesPath)) {
736
+ return [];
737
+ }
738
+ const raw = await readFile2(employeesPath, "utf-8");
739
+ try {
740
+ return JSON.parse(raw);
1003
741
  } catch {
1004
- return freeLicense();
742
+ return [];
1005
743
  }
1006
744
  }
1007
- function freeLicense() {
1008
- const limits = PLAN_LIMITS.free;
1009
- return {
1010
- valid: true,
1011
- plan: "free",
1012
- email: "",
1013
- expiresAt: null,
1014
- deviceLimit: limits.devices,
1015
- employeeLimit: limits.employees,
1016
- memoryLimit: limits.memories
1017
- };
745
+ async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
746
+ await mkdir2(path5.dirname(employeesPath), { recursive: true });
747
+ await writeFile2(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
1018
748
  }
1019
- function assertEmployeeLimitSync(rosterPath) {
1020
- const license = getLicenseSync();
1021
- if (license.employeeLimit < 0) return;
1022
- const filePath = rosterPath ?? EMPLOYEES_PATH;
1023
- let count = 0;
749
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
750
+ if (!existsSync5(employeesPath)) return [];
1024
751
  try {
1025
- if (existsSync8(filePath)) {
1026
- const raw = readFileSync8(filePath, "utf8");
1027
- const employees = JSON.parse(raw);
1028
- count = Array.isArray(employees) ? employees.length : 0;
1029
- }
752
+ return JSON.parse(readFileSync5(employeesPath, "utf-8"));
1030
753
  } catch {
1031
- throw new PlanLimitError(
1032
- `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
1033
- );
1034
- }
1035
- if (count >= license.employeeLimit) {
1036
- throw new PlanLimitError(
1037
- `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
1038
- );
754
+ return [];
1039
755
  }
1040
756
  }
1041
- var PlanLimitError, CACHE_PATH2;
1042
- var init_plan_limits = __esm({
1043
- "src/lib/plan-limits.ts"() {
1044
- "use strict";
1045
- init_database();
1046
- init_employees();
1047
- init_license();
1048
- init_config();
1049
- PlanLimitError = class extends Error {
1050
- constructor(message) {
1051
- super(message);
1052
- this.name = "PlanLimitError";
1053
- }
1054
- };
1055
- CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
1056
- }
1057
- });
1058
-
1059
- // src/lib/tmux-routing.ts
1060
- import { execFileSync as execFileSync2, execSync as execSync5 } from "child_process";
1061
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync9, appendFileSync } from "fs";
1062
- import path9 from "path";
1063
- import os5 from "os";
1064
- import { fileURLToPath } from "url";
1065
- import { unlinkSync as unlinkSync2 } from "fs";
1066
- function spawnLockPath(sessionName) {
1067
- return path9.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
757
+ function getEmployee(employees, name) {
758
+ return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
1068
759
  }
1069
- function isProcessAlive(pid) {
760
+ function getEmployeeByRole(employees, role) {
761
+ const lower = role.toLowerCase();
762
+ return employees.find((e) => e.role.toLowerCase() === lower);
763
+ }
764
+ function getEmployeeNamesByRole(employees, role) {
765
+ const lower = role.toLowerCase();
766
+ return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
767
+ }
768
+ function hasRole(agentName, role) {
769
+ const employees = loadEmployeesSync();
770
+ const emp = getEmployee(employees, agentName);
771
+ return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
772
+ }
773
+ function isMultiInstance(agentName, employees) {
774
+ const roster = employees ?? loadEmployeesSync();
775
+ const emp = getEmployee(roster, agentName);
776
+ if (!emp) return false;
777
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
778
+ }
779
+ function addEmployee(employees, employee) {
780
+ const normalized = { ...employee, name: employee.name.toLowerCase() };
781
+ if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
782
+ throw new Error(`Employee '${normalized.name}' already exists`);
783
+ }
784
+ return [...employees, normalized];
785
+ }
786
+ function findExeBin() {
1070
787
  try {
1071
- process.kill(pid, 0);
1072
- return true;
788
+ return execSync3(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
1073
789
  } catch {
1074
- return false;
790
+ return null;
1075
791
  }
1076
792
  }
1077
- function acquireSpawnLock(sessionName) {
1078
- if (!existsSync9(SPAWN_LOCK_DIR)) {
1079
- mkdirSync4(SPAWN_LOCK_DIR, { recursive: true });
793
+ function registerBinSymlinks(name) {
794
+ const created = [];
795
+ const skipped = [];
796
+ const errors = [];
797
+ const exeBinPath = findExeBin();
798
+ if (!exeBinPath) {
799
+ errors.push("Could not find 'exe-os' in PATH");
800
+ return { created, skipped, errors };
1080
801
  }
1081
- const lockFile = spawnLockPath(sessionName);
1082
- if (existsSync9(lockFile)) {
802
+ const binDir = path5.dirname(exeBinPath);
803
+ let target;
804
+ try {
805
+ target = readlinkSync(exeBinPath);
806
+ } catch {
807
+ errors.push("Could not read 'exe' symlink");
808
+ return { created, skipped, errors };
809
+ }
810
+ for (const suffix of ["", "-opencode"]) {
811
+ const linkName = `${name}${suffix}`;
812
+ const linkPath = path5.join(binDir, linkName);
813
+ if (existsSync5(linkPath)) {
814
+ skipped.push(linkName);
815
+ continue;
816
+ }
1083
817
  try {
1084
- const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
1085
- const age = Date.now() - lock.timestamp;
1086
- if (isProcessAlive(lock.pid) && age < 6e4) {
1087
- return false;
1088
- }
1089
- } catch {
818
+ symlinkSync(target, linkPath);
819
+ created.push(linkName);
820
+ } catch (err) {
821
+ errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
1090
822
  }
1091
823
  }
1092
- writeFileSync4(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
1093
- return true;
824
+ return { created, skipped, errors };
1094
825
  }
1095
- function releaseSpawnLock(sessionName) {
826
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
827
+ var init_employees = __esm({
828
+ "src/lib/employees.ts"() {
829
+ "use strict";
830
+ init_config();
831
+ EMPLOYEES_PATH = path5.join(EXE_AI_DIR, "exe-employees.json");
832
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
833
+ }
834
+ });
835
+
836
+ // src/lib/license.ts
837
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
838
+ import { randomUUID } from "crypto";
839
+ import path6 from "path";
840
+ import { jwtVerify, importSPKI } from "jose";
841
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
842
+ var init_license = __esm({
843
+ "src/lib/license.ts"() {
844
+ "use strict";
845
+ init_config();
846
+ LICENSE_PATH = path6.join(EXE_AI_DIR, "license.key");
847
+ CACHE_PATH = path6.join(EXE_AI_DIR, "license-cache.json");
848
+ DEVICE_ID_PATH = path6.join(EXE_AI_DIR, "device-id");
849
+ PLAN_LIMITS = {
850
+ free: { devices: 1, employees: 1, memories: 5e3 },
851
+ pro: { devices: 2, employees: 5, memories: 1e5 },
852
+ team: { devices: 10, employees: 20, memories: 1e6 },
853
+ agency: { devices: 50, employees: 100, memories: 1e7 },
854
+ enterprise: { devices: -1, employees: -1, memories: -1 }
855
+ };
856
+ }
857
+ });
858
+
859
+ // src/lib/plan-limits.ts
860
+ import { readFileSync as readFileSync7, existsSync as existsSync7 } from "fs";
861
+ import path7 from "path";
862
+ function getLicenseSync() {
1096
863
  try {
1097
- unlinkSync2(spawnLockPath(sessionName));
864
+ if (!existsSync7(CACHE_PATH2)) return freeLicense();
865
+ const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
866
+ if (!raw.token || typeof raw.token !== "string") return freeLicense();
867
+ const parts = raw.token.split(".");
868
+ if (parts.length !== 3) return freeLicense();
869
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
870
+ const plan = payload.plan ?? "free";
871
+ const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
872
+ return {
873
+ valid: true,
874
+ plan,
875
+ email: payload.sub ?? "",
876
+ expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
877
+ deviceLimit: limits.devices,
878
+ employeeLimit: limits.employees,
879
+ memoryLimit: limits.memories
880
+ };
1098
881
  } catch {
882
+ return freeLicense();
1099
883
  }
1100
884
  }
1101
- function resolveBehaviorsExporterScript() {
885
+ function freeLicense() {
886
+ const limits = PLAN_LIMITS.free;
887
+ return {
888
+ valid: true,
889
+ plan: "free",
890
+ email: "",
891
+ expiresAt: null,
892
+ deviceLimit: limits.devices,
893
+ employeeLimit: limits.employees,
894
+ memoryLimit: limits.memories
895
+ };
896
+ }
897
+ function assertEmployeeLimitSync(rosterPath) {
898
+ const license = getLicenseSync();
899
+ if (license.employeeLimit < 0) return;
900
+ const filePath = rosterPath ?? EMPLOYEES_PATH;
901
+ let count = 0;
1102
902
  try {
1103
- const thisFile = fileURLToPath(import.meta.url);
1104
- const scriptPath = path9.join(
1105
- path9.dirname(thisFile),
1106
- "..",
1107
- "bin",
1108
- "exe-export-behaviors.js"
1109
- );
1110
- return existsSync9(scriptPath) ? scriptPath : null;
903
+ if (existsSync7(filePath)) {
904
+ const raw = readFileSync7(filePath, "utf8");
905
+ const employees = JSON.parse(raw);
906
+ count = Array.isArray(employees) ? employees.length : 0;
907
+ }
1111
908
  } catch {
1112
- return null;
909
+ throw new PlanLimitError(
910
+ `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
911
+ );
912
+ }
913
+ if (count >= license.employeeLimit) {
914
+ throw new PlanLimitError(
915
+ `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
916
+ );
1113
917
  }
1114
918
  }
1115
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
1116
- const script = resolveBehaviorsExporterScript();
1117
- if (!script) return null;
919
+ var PlanLimitError, CACHE_PATH2;
920
+ var init_plan_limits = __esm({
921
+ "src/lib/plan-limits.ts"() {
922
+ "use strict";
923
+ init_database();
924
+ init_employees();
925
+ init_license();
926
+ init_config();
927
+ PlanLimitError = class extends Error {
928
+ constructor(message) {
929
+ super(message);
930
+ this.name = "PlanLimitError";
931
+ }
932
+ };
933
+ CACHE_PATH2 = path7.join(EXE_AI_DIR, "license-cache.json");
934
+ }
935
+ });
936
+
937
+ // src/lib/session-kill-telemetry.ts
938
+ import crypto2 from "crypto";
939
+ async function recordSessionKill(input) {
1118
940
  try {
1119
- const output = execFileSync2(
1120
- process.execPath,
1121
- [script, agentId, projectName, sessionKey],
1122
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
1123
- ).trim();
1124
- return output.length > 0 ? output : null;
941
+ const client = getClient();
942
+ await client.execute({
943
+ sql: `INSERT INTO session_kills
944
+ (id, session_name, agent_id, killed_at, reason,
945
+ ticks_idle, estimated_tokens_saved)
946
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
947
+ args: [
948
+ crypto2.randomUUID(),
949
+ input.sessionName,
950
+ input.agentId,
951
+ (/* @__PURE__ */ new Date()).toISOString(),
952
+ input.reason,
953
+ input.ticksIdle ?? null,
954
+ input.estimatedTokensSaved ?? null
955
+ ]
956
+ });
1125
957
  } catch (err) {
1126
958
  process.stderr.write(
1127
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
959
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
1128
960
  `
1129
961
  );
1130
- return null;
1131
962
  }
1132
963
  }
1133
- function getMySession() {
1134
- return getTransport().getMySession();
1135
- }
1136
- function employeeSessionName(employee, exeSession, instance) {
1137
- const suffix = instance != null && instance > 0 ? String(instance) : "";
1138
- return `${employee}${suffix}-${exeSession}`;
1139
- }
1140
- function extractRootExe(name) {
1141
- const match = name.match(/(exe\d+)$/);
1142
- return match?.[1] ?? null;
1143
- }
1144
- function getParentExe(sessionKey) {
1145
- try {
1146
- const data = JSON.parse(readFileSync9(path9.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
1147
- return data.parentExe || null;
1148
- } catch {
1149
- return null;
964
+ var init_session_kill_telemetry = __esm({
965
+ "src/lib/session-kill-telemetry.ts"() {
966
+ "use strict";
967
+ init_database();
1150
968
  }
1151
- }
1152
- function resolveExeSession() {
1153
- const mySession = getMySession();
1154
- if (!mySession) return null;
1155
- try {
1156
- const key = getSessionKey();
1157
- const parentExe = getParentExe(key);
1158
- if (parentExe) {
1159
- return extractRootExe(parentExe) ?? parentExe;
969
+ });
970
+
971
+ // src/lib/capacity-monitor.ts
972
+ var capacity_monitor_exports = {};
973
+ __export(capacity_monitor_exports, {
974
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
975
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
976
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
977
+ confirmCapacityKill: () => confirmCapacityKill,
978
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
979
+ extractContextPercent: () => extractContextPercent,
980
+ isAtCapacity: () => isAtCapacity,
981
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
982
+ pollCapacityDead: () => pollCapacityDead
983
+ });
984
+ function resumeTaskTitle(agentId) {
985
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
986
+ }
987
+ function buildResumeContext(agentId, openTasks) {
988
+ const taskList = openTasks.map(
989
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
990
+ ).join("\n");
991
+ return [
992
+ "## Context",
993
+ "",
994
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
995
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
996
+ "",
997
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
998
+ "",
999
+ taskList,
1000
+ "",
1001
+ "Read each task file and chain through them. Build and commit after each one."
1002
+ ].join("\n");
1003
+ }
1004
+ function filterPaneContent(paneOutput) {
1005
+ return paneOutput.split("\n").filter((line) => {
1006
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
1007
+ for (const marker of CONTENT_LINE_MARKERS) {
1008
+ if (line.includes(marker)) return false;
1160
1009
  }
1161
- } catch {
1010
+ for (const re of SOURCE_CODE_MARKERS) {
1011
+ if (re.test(line)) return false;
1012
+ }
1013
+ return true;
1014
+ }).join("\n");
1015
+ }
1016
+ function extractContextPercent(paneOutput) {
1017
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
1018
+ if (!match) return null;
1019
+ const parsed = Number.parseInt(match[2], 10);
1020
+ return Number.isFinite(parsed) ? parsed : null;
1021
+ }
1022
+ function isAtCapacity(paneOutput) {
1023
+ const filtered = filterPaneContent(paneOutput);
1024
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
1025
+ }
1026
+ function confirmCapacityKill(agentId, now = Date.now()) {
1027
+ const pendingSince = _pendingCapacityKill.get(agentId);
1028
+ if (pendingSince === void 0) {
1029
+ _pendingCapacityKill.set(agentId, now);
1030
+ return false;
1162
1031
  }
1163
- return extractRootExe(mySession) ?? mySession;
1032
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
1033
+ _pendingCapacityKill.set(agentId, now);
1034
+ return false;
1035
+ }
1036
+ _pendingCapacityKill.delete(agentId);
1037
+ return true;
1164
1038
  }
1165
- function isEmployeeAlive(sessionName) {
1166
- return getTransport().isAlive(sessionName);
1039
+ function _resetPendingCapacityKills() {
1040
+ _pendingCapacityKill.clear();
1167
1041
  }
1168
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
1169
- const base = employeeSessionName(employeeName, exeSession);
1170
- if (!isAlive(base) && acquireSpawnLock(base)) return 0;
1171
- for (let i = 2; i <= maxInstances; i++) {
1172
- const candidate = employeeSessionName(employeeName, exeSession, i);
1173
- if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
1174
- }
1175
- return null;
1042
+ function _resetLastRelaunchCache() {
1043
+ _lastRelaunch.clear();
1176
1044
  }
1177
- function readDebounceState() {
1178
- try {
1179
- if (!existsSync9(DEBOUNCE_FILE)) return {};
1180
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
1181
- } catch {
1182
- return {};
1183
- }
1045
+ async function lastResumeCreatedAtMs(agentId) {
1046
+ const client = getClient();
1047
+ const result = await client.execute({
1048
+ sql: `SELECT MAX(created_at) AS last_created_at
1049
+ FROM tasks
1050
+ WHERE assigned_to = ? AND title LIKE ?`,
1051
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
1052
+ });
1053
+ const raw = result.rows[0]?.last_created_at;
1054
+ if (raw === null || raw === void 0) return null;
1055
+ const parsed = Date.parse(String(raw));
1056
+ return Number.isNaN(parsed) ? null : parsed;
1057
+ }
1058
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
1059
+ const cached = _lastRelaunch.get(agentId);
1060
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
1061
+ const persisted = await lastResumeCreatedAtMs(agentId);
1062
+ if (persisted === null) return false;
1063
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
1064
+ _lastRelaunch.set(agentId, persisted);
1065
+ return true;
1184
1066
  }
1185
- function writeDebounceState(state) {
1067
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
1068
+ const client = getClient();
1069
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1070
+ const context = buildResumeContext(agentId, openTasks);
1071
+ const existing = await client.execute({
1072
+ sql: `SELECT id FROM tasks
1073
+ WHERE assigned_to = ?
1074
+ AND title LIKE ?
1075
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
1076
+ ORDER BY created_at DESC
1077
+ LIMIT 1`,
1078
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
1079
+ });
1080
+ if (existing.rows.length > 0) {
1081
+ const taskId = String(existing.rows[0].id);
1082
+ await client.execute({
1083
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
1084
+ args: [context, now, taskId]
1085
+ });
1086
+ return { created: false, taskId };
1087
+ }
1088
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
1089
+ const task = await createTask2({
1090
+ title: resumeTaskTitle(agentId),
1091
+ assignedTo: agentId,
1092
+ assignedBy: "system",
1093
+ projectName: projectDir.split("/").pop() ?? "unknown",
1094
+ priority: "p0",
1095
+ context,
1096
+ baseDir: projectDir
1097
+ });
1098
+ return { created: true, taskId: task.id };
1099
+ }
1100
+ async function pollCapacityDead() {
1101
+ const transport = getTransport();
1102
+ const relaunched = [];
1103
+ const registered = listSessions().filter(
1104
+ (s) => s.agentId !== "exe"
1105
+ );
1106
+ if (registered.length === 0) return [];
1107
+ let liveSessions;
1186
1108
  try {
1187
- if (!existsSync9(SESSION_CACHE)) mkdirSync4(SESSION_CACHE, { recursive: true });
1188
- writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
1109
+ liveSessions = transport.listSessions();
1189
1110
  } catch {
1111
+ return [];
1190
1112
  }
1191
- }
1192
- function isDebounced(targetSession) {
1193
- const state = readDebounceState();
1194
- const lastSent = state[targetSession] ?? 0;
1113
+ for (const entry of registered) {
1114
+ const { windowName, agentId, projectDir } = entry;
1115
+ if (!liveSessions.includes(windowName)) continue;
1116
+ if (await isWithinRelaunchCooldown(agentId)) continue;
1117
+ let pane;
1118
+ try {
1119
+ pane = transport.capturePane(windowName, 15);
1120
+ } catch {
1121
+ continue;
1122
+ }
1123
+ if (!isAtCapacity(pane)) continue;
1124
+ const ctxPct = extractContextPercent(pane);
1125
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
1126
+ process.stderr.write(
1127
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
1128
+ `
1129
+ );
1130
+ continue;
1131
+ }
1132
+ if (!confirmCapacityKill(agentId)) {
1133
+ process.stderr.write(
1134
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
1135
+ `
1136
+ );
1137
+ continue;
1138
+ }
1139
+ const verify = await verifyPaneAtCapacity(windowName);
1140
+ if (!verify.atCapacity) {
1141
+ process.stderr.write(
1142
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
1143
+ `
1144
+ );
1145
+ void recordSessionKill({
1146
+ sessionName: windowName,
1147
+ agentId,
1148
+ reason: "capacity_false_positive_blocked"
1149
+ });
1150
+ continue;
1151
+ }
1152
+ process.stderr.write(
1153
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
1154
+ `
1155
+ );
1156
+ try {
1157
+ transport.kill(windowName);
1158
+ void recordSessionKill({
1159
+ sessionName: windowName,
1160
+ agentId,
1161
+ reason: "capacity"
1162
+ });
1163
+ const client = getClient();
1164
+ const openTasks = await client.execute({
1165
+ sql: `SELECT id, title, priority, task_file, status
1166
+ FROM tasks
1167
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
1168
+ ORDER BY
1169
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
1170
+ created_at ASC
1171
+ LIMIT 10`,
1172
+ args: [agentId]
1173
+ });
1174
+ if (openTasks.rows.length === 0) {
1175
+ process.stderr.write(
1176
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
1177
+ `
1178
+ );
1179
+ continue;
1180
+ }
1181
+ const { created } = await createOrRefreshResumeTask(
1182
+ agentId,
1183
+ projectDir,
1184
+ openTasks.rows
1185
+ );
1186
+ if (created) {
1187
+ await writeNotification({
1188
+ agentId: "system",
1189
+ agentRole: "daemon",
1190
+ event: "capacity_relaunch",
1191
+ project: projectDir.split("/").pop() ?? "unknown",
1192
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
1193
+ });
1194
+ }
1195
+ _lastRelaunch.set(agentId, Date.now());
1196
+ if (created) relaunched.push(agentId);
1197
+ } catch (err) {
1198
+ process.stderr.write(
1199
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
1200
+ `
1201
+ );
1202
+ }
1203
+ }
1204
+ return relaunched;
1205
+ }
1206
+ var CAPACITY_PATTERNS, CONTENT_LINE_PREFIX, CONTENT_LINE_MARKERS, SOURCE_CODE_MARKERS, RELAUNCH_COOLDOWN_MS, _lastRelaunch, RESUME_TITLE_PREFIX, RESUME_TITLE_LIKE_PATTERN, RESUME_ACTIVE_STATUSES, CONFIRMATION_WINDOW_MS, _pendingCapacityKill, CC_CONTEXT_BAR_RE, CTX_FLOOR_PERCENT;
1207
+ var init_capacity_monitor = __esm({
1208
+ "src/lib/capacity-monitor.ts"() {
1209
+ "use strict";
1210
+ init_session_registry();
1211
+ init_transport();
1212
+ init_notifications();
1213
+ init_database();
1214
+ init_session_kill_telemetry();
1215
+ init_tmux_routing();
1216
+ CAPACITY_PATTERNS = [
1217
+ /conversation is too long/i,
1218
+ /maximum context length/i,
1219
+ /context window.*(?:limit|exceed|full)/i,
1220
+ /reached.*(?:token|context).*limit/i
1221
+ ];
1222
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
1223
+ CONTENT_LINE_MARKERS = [
1224
+ "RESUME:",
1225
+ "intercom",
1226
+ "capacity-monitor",
1227
+ "CAPACITY_PATTERNS",
1228
+ "isAtCapacity",
1229
+ "CONTENT_LINE_MARKERS",
1230
+ "pollCapacityDead",
1231
+ "confirmCapacityKill",
1232
+ "session_kills",
1233
+ "capacity-monitor.test"
1234
+ ];
1235
+ SOURCE_CODE_MARKERS = [
1236
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
1237
+ /(?:maximum context length|conversation is too long).*["'`/]/i
1238
+ ];
1239
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
1240
+ _lastRelaunch = /* @__PURE__ */ new Map();
1241
+ RESUME_TITLE_PREFIX = "RESUME:";
1242
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
1243
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
1244
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
1245
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
1246
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
1247
+ CTX_FLOOR_PERCENT = 50;
1248
+ }
1249
+ });
1250
+
1251
+ // src/lib/tmux-routing.ts
1252
+ var tmux_routing_exports = {};
1253
+ __export(tmux_routing_exports, {
1254
+ acquireSpawnLock: () => acquireSpawnLock,
1255
+ employeeSessionName: () => employeeSessionName,
1256
+ ensureEmployee: () => ensureEmployee,
1257
+ extractRootExe: () => extractRootExe,
1258
+ findFreeInstance: () => findFreeInstance,
1259
+ getDispatchedBy: () => getDispatchedBy,
1260
+ getMySession: () => getMySession,
1261
+ getParentExe: () => getParentExe,
1262
+ getSessionState: () => getSessionState,
1263
+ isEmployeeAlive: () => isEmployeeAlive,
1264
+ isExeSession: () => isExeSession,
1265
+ isSessionBusy: () => isSessionBusy,
1266
+ notifyParentExe: () => notifyParentExe,
1267
+ parseParentExe: () => parseParentExe,
1268
+ registerParentExe: () => registerParentExe,
1269
+ releaseSpawnLock: () => releaseSpawnLock,
1270
+ resolveExeSession: () => resolveExeSession,
1271
+ sendIntercom: () => sendIntercom,
1272
+ spawnEmployee: () => spawnEmployee,
1273
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
1274
+ });
1275
+ import { execFileSync as execFileSync2, execSync as execSync4 } from "child_process";
1276
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync8, appendFileSync } from "fs";
1277
+ import path8 from "path";
1278
+ import os5 from "os";
1279
+ import { fileURLToPath } from "url";
1280
+ import { unlinkSync as unlinkSync2 } from "fs";
1281
+ function spawnLockPath(sessionName) {
1282
+ return path8.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
1283
+ }
1284
+ function isProcessAlive(pid) {
1285
+ try {
1286
+ process.kill(pid, 0);
1287
+ return true;
1288
+ } catch {
1289
+ return false;
1290
+ }
1291
+ }
1292
+ function acquireSpawnLock(sessionName) {
1293
+ if (!existsSync8(SPAWN_LOCK_DIR)) {
1294
+ mkdirSync4(SPAWN_LOCK_DIR, { recursive: true });
1295
+ }
1296
+ const lockFile = spawnLockPath(sessionName);
1297
+ if (existsSync8(lockFile)) {
1298
+ try {
1299
+ const lock = JSON.parse(readFileSync8(lockFile, "utf8"));
1300
+ const age = Date.now() - lock.timestamp;
1301
+ if (isProcessAlive(lock.pid) && age < 6e4) {
1302
+ return false;
1303
+ }
1304
+ } catch {
1305
+ }
1306
+ }
1307
+ writeFileSync4(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
1308
+ return true;
1309
+ }
1310
+ function releaseSpawnLock(sessionName) {
1311
+ try {
1312
+ unlinkSync2(spawnLockPath(sessionName));
1313
+ } catch {
1314
+ }
1315
+ }
1316
+ function resolveBehaviorsExporterScript() {
1317
+ try {
1318
+ const thisFile = fileURLToPath(import.meta.url);
1319
+ const scriptPath = path8.join(
1320
+ path8.dirname(thisFile),
1321
+ "..",
1322
+ "bin",
1323
+ "exe-export-behaviors.js"
1324
+ );
1325
+ return existsSync8(scriptPath) ? scriptPath : null;
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ }
1330
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
1331
+ const script = resolveBehaviorsExporterScript();
1332
+ if (!script) return null;
1333
+ try {
1334
+ const output = execFileSync2(
1335
+ process.execPath,
1336
+ [script, agentId, projectName, sessionKey],
1337
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
1338
+ ).trim();
1339
+ return output.length > 0 ? output : null;
1340
+ } catch (err) {
1341
+ process.stderr.write(
1342
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
1343
+ `
1344
+ );
1345
+ return null;
1346
+ }
1347
+ }
1348
+ function getMySession() {
1349
+ return getTransport().getMySession();
1350
+ }
1351
+ function employeeSessionName(employee, exeSession, instance) {
1352
+ if (!/^exe\d+$/.test(exeSession)) {
1353
+ const root = extractRootExe(exeSession);
1354
+ if (root) {
1355
+ process.stderr.write(
1356
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
1357
+ `
1358
+ );
1359
+ exeSession = root;
1360
+ } else {
1361
+ throw new Error(
1362
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
1363
+ );
1364
+ }
1365
+ }
1366
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
1367
+ const name = `${employee}${suffix}-${exeSession}`;
1368
+ if (!VALID_SESSION_NAME.test(name)) {
1369
+ throw new Error(
1370
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
1371
+ );
1372
+ }
1373
+ return name;
1374
+ }
1375
+ function parseParentExe(sessionName, agentId) {
1376
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1377
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
1378
+ const match = sessionName.match(regex);
1379
+ return match?.[1] ?? null;
1380
+ }
1381
+ function extractRootExe(name) {
1382
+ const match = name.match(/(exe\d+)$/);
1383
+ return match?.[1] ?? null;
1384
+ }
1385
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
1386
+ if (!existsSync8(SESSION_CACHE)) {
1387
+ mkdirSync4(SESSION_CACHE, { recursive: true });
1388
+ }
1389
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
1390
+ const filePath = path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
1391
+ writeFileSync4(filePath, JSON.stringify({
1392
+ parentExe: rootExe,
1393
+ dispatchedBy: dispatchedBy || rootExe,
1394
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1395
+ }));
1396
+ }
1397
+ function getParentExe(sessionKey) {
1398
+ try {
1399
+ const data = JSON.parse(readFileSync8(path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
1400
+ return data.parentExe || null;
1401
+ } catch {
1402
+ return null;
1403
+ }
1404
+ }
1405
+ function getDispatchedBy(sessionKey) {
1406
+ try {
1407
+ const data = JSON.parse(readFileSync8(
1408
+ path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
1409
+ "utf8"
1410
+ ));
1411
+ return data.dispatchedBy ?? data.parentExe ?? null;
1412
+ } catch {
1413
+ return null;
1414
+ }
1415
+ }
1416
+ function resolveExeSession() {
1417
+ const mySession = getMySession();
1418
+ if (!mySession) return null;
1419
+ try {
1420
+ const key = getSessionKey();
1421
+ const parentExe = getParentExe(key);
1422
+ if (parentExe) {
1423
+ return extractRootExe(parentExe) ?? parentExe;
1424
+ }
1425
+ } catch {
1426
+ }
1427
+ return extractRootExe(mySession) ?? mySession;
1428
+ }
1429
+ function isEmployeeAlive(sessionName) {
1430
+ return getTransport().isAlive(sessionName);
1431
+ }
1432
+ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
1433
+ const base = employeeSessionName(employeeName, exeSession);
1434
+ if (!isAlive(base) && acquireSpawnLock(base)) return 0;
1435
+ for (let i = 2; i <= maxInstances; i++) {
1436
+ const candidate = employeeSessionName(employeeName, exeSession, i);
1437
+ if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
1438
+ }
1439
+ return null;
1440
+ }
1441
+ async function verifyPaneAtCapacity(sessionName) {
1442
+ const transport = getTransport();
1443
+ if (!transport.isAlive(sessionName)) {
1444
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
1445
+ }
1446
+ let pane;
1447
+ try {
1448
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
1449
+ } catch (err) {
1450
+ return {
1451
+ atCapacity: false,
1452
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
1453
+ };
1454
+ }
1455
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
1456
+ if (!isAtCapacity2(pane)) {
1457
+ return {
1458
+ atCapacity: false,
1459
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
1460
+ };
1461
+ }
1462
+ return {
1463
+ atCapacity: true,
1464
+ reason: "capacity banner matched in recent pane output"
1465
+ };
1466
+ }
1467
+ function readDebounceState() {
1468
+ try {
1469
+ if (!existsSync8(DEBOUNCE_FILE)) return {};
1470
+ return JSON.parse(readFileSync8(DEBOUNCE_FILE, "utf8"));
1471
+ } catch {
1472
+ return {};
1473
+ }
1474
+ }
1475
+ function writeDebounceState(state) {
1476
+ try {
1477
+ if (!existsSync8(SESSION_CACHE)) mkdirSync4(SESSION_CACHE, { recursive: true });
1478
+ writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
1479
+ } catch {
1480
+ }
1481
+ }
1482
+ function isDebounced(targetSession) {
1483
+ const state = readDebounceState();
1484
+ const lastSent = state[targetSession] ?? 0;
1195
1485
  return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
1196
1486
  }
1197
1487
  function recordDebounce(targetSession) {
@@ -1230,6 +1520,10 @@ function getSessionState(sessionName) {
1230
1520
  return "offline";
1231
1521
  }
1232
1522
  }
1523
+ function isSessionBusy(sessionName) {
1524
+ const state = getSessionState(sessionName);
1525
+ return state === "thinking" || state === "tool";
1526
+ }
1233
1527
  function isExeSession(sessionName) {
1234
1528
  return /^exe\d*$/.test(sessionName);
1235
1529
  }
@@ -1275,297 +1569,912 @@ function sendIntercom(targetSession) {
1275
1569
  return "failed";
1276
1570
  }
1277
1571
  }
1278
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
1279
- if (employeeName === "exe") {
1280
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
1572
+ function notifyParentExe(sessionKey) {
1573
+ const target = getDispatchedBy(sessionKey);
1574
+ if (!target) {
1575
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
1576
+ `);
1577
+ return false;
1578
+ }
1579
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
1580
+ `);
1581
+ const result = sendIntercom(target);
1582
+ if (result === "failed") {
1583
+ const rootExe = resolveExeSession();
1584
+ if (rootExe && rootExe !== target) {
1585
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
1586
+ `);
1587
+ const fallback = sendIntercom(rootExe);
1588
+ return fallback !== "failed";
1589
+ }
1590
+ return false;
1591
+ }
1592
+ return true;
1593
+ }
1594
+ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
1595
+ if (employeeName === "exe") {
1596
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
1597
+ }
1598
+ try {
1599
+ assertEmployeeLimitSync();
1600
+ } catch (err) {
1601
+ if (err instanceof PlanLimitError) {
1602
+ return { status: "failed", sessionName: "", error: err.message };
1603
+ }
1604
+ }
1605
+ if (/-exe\d*$/.test(employeeName)) {
1606
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
1607
+ return {
1608
+ status: "failed",
1609
+ sessionName: "",
1610
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
1611
+ };
1612
+ }
1613
+ if (!/^exe\d+$/.test(exeSession)) {
1614
+ const root = extractRootExe(exeSession);
1615
+ if (root) {
1616
+ process.stderr.write(
1617
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
1618
+ `
1619
+ );
1620
+ exeSession = root;
1621
+ } else {
1622
+ return {
1623
+ status: "failed",
1624
+ sessionName: "",
1625
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
1626
+ };
1627
+ }
1628
+ }
1629
+ let effectiveInstance = opts?.instance;
1630
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
1631
+ const free = findFreeInstance(
1632
+ employeeName,
1633
+ exeSession,
1634
+ opts.maxAutoInstances ?? 10
1635
+ );
1636
+ if (free === null) {
1637
+ return {
1638
+ status: "failed",
1639
+ sessionName: employeeSessionName(employeeName, exeSession),
1640
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
1641
+ };
1642
+ }
1643
+ effectiveInstance = free === 0 ? void 0 : free;
1644
+ }
1645
+ const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
1646
+ if (isEmployeeAlive(sessionName)) {
1647
+ const result2 = sendIntercom(sessionName);
1648
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
1649
+ return { status: "intercom_sent", sessionName };
1650
+ }
1651
+ if (result2 === "delivered") {
1652
+ return { status: "intercom_unprocessed", sessionName };
1653
+ }
1654
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
1655
+ }
1656
+ const spawnOpts = { ...opts, instance: effectiveInstance };
1657
+ const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
1658
+ if (result.error) {
1659
+ return { status: "failed", sessionName, error: result.error };
1660
+ }
1661
+ return { status: "spawned", sessionName };
1662
+ }
1663
+ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
1664
+ const transport = getTransport();
1665
+ const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
1666
+ const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
1667
+ const logDir = path8.join(os5.homedir(), ".exe-os", "session-logs");
1668
+ const logFile = path8.join(logDir, `${instanceLabel}-${Date.now()}.log`);
1669
+ if (!existsSync8(logDir)) {
1670
+ mkdirSync4(logDir, { recursive: true });
1671
+ }
1672
+ transport.kill(sessionName);
1673
+ let cleanupSuffix = "";
1674
+ try {
1675
+ const thisFile = fileURLToPath(import.meta.url);
1676
+ const cleanupScript = path8.join(path8.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
1677
+ if (existsSync8(cleanupScript)) {
1678
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
1679
+ }
1680
+ } catch {
1681
+ }
1682
+ try {
1683
+ const claudeJsonPath = path8.join(os5.homedir(), ".claude.json");
1684
+ let claudeJson = {};
1685
+ try {
1686
+ claudeJson = JSON.parse(readFileSync8(claudeJsonPath, "utf8"));
1687
+ } catch {
1688
+ }
1689
+ if (!claudeJson.projects) claudeJson.projects = {};
1690
+ const projects = claudeJson.projects;
1691
+ const trustDir = opts?.cwd ?? projectDir;
1692
+ if (!projects[trustDir]) projects[trustDir] = {};
1693
+ projects[trustDir].hasTrustDialogAccepted = true;
1694
+ writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
1695
+ } catch {
1696
+ }
1697
+ try {
1698
+ const settingsDir = path8.join(os5.homedir(), ".claude", "projects");
1699
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
1700
+ const projSettingsDir = path8.join(settingsDir, normalizedKey);
1701
+ const settingsPath = path8.join(projSettingsDir, "settings.json");
1702
+ let settings = {};
1703
+ try {
1704
+ settings = JSON.parse(readFileSync8(settingsPath, "utf8"));
1705
+ } catch {
1706
+ }
1707
+ const perms = settings.permissions ?? {};
1708
+ const allow = perms.allow ?? [];
1709
+ const toolNames = [
1710
+ "recall_my_memory",
1711
+ "store_memory",
1712
+ "create_task",
1713
+ "update_task",
1714
+ "list_tasks",
1715
+ "get_task",
1716
+ "ask_team_memory",
1717
+ "store_behavior",
1718
+ "get_identity",
1719
+ "send_message"
1720
+ ];
1721
+ const requiredTools = expandDualPrefixTools(toolNames);
1722
+ let changed = false;
1723
+ for (const tool of requiredTools) {
1724
+ if (!allow.includes(tool)) {
1725
+ allow.push(tool);
1726
+ changed = true;
1727
+ }
1728
+ }
1729
+ if (changed) {
1730
+ perms.allow = allow;
1731
+ settings.permissions = perms;
1732
+ mkdirSync4(projSettingsDir, { recursive: true });
1733
+ writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
1734
+ }
1735
+ } catch {
1736
+ }
1737
+ const spawnCwd = opts?.cwd ?? projectDir;
1738
+ const useExeAgent = !!(opts?.model && opts?.provider);
1739
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
1740
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
1741
+ let identityFlag = "";
1742
+ let behaviorsFlag = "";
1743
+ let legacyFallbackWarned = false;
1744
+ if (!useExeAgent && !useBinSymlink) {
1745
+ const identityPath = path8.join(
1746
+ os5.homedir(),
1747
+ ".exe-os",
1748
+ "identity",
1749
+ `${employeeName}.md`
1750
+ );
1751
+ _resetCcAgentSupportCache();
1752
+ const hasAgentFlag = claudeSupportsAgentFlag();
1753
+ if (hasAgentFlag) {
1754
+ identityFlag = ` --agent ${employeeName}`;
1755
+ } else if (existsSync8(identityPath)) {
1756
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
1757
+ legacyFallbackWarned = true;
1758
+ }
1759
+ const behaviorsFile = exportBehaviorsSync(
1760
+ employeeName,
1761
+ path8.basename(spawnCwd),
1762
+ sessionName
1763
+ );
1764
+ if (behaviorsFile) {
1765
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
1766
+ }
1767
+ }
1768
+ if (legacyFallbackWarned) {
1769
+ process.stderr.write(
1770
+ `[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.
1771
+ `
1772
+ );
1773
+ }
1774
+ let sessionContextFlag = "";
1775
+ try {
1776
+ const ctxDir = path8.join(os5.homedir(), ".exe-os", "session-cache");
1777
+ mkdirSync4(ctxDir, { recursive: true });
1778
+ const ctxFile = path8.join(ctxDir, `session-context-${sessionName}.md`);
1779
+ const ctxContent = [
1780
+ `## Session Context`,
1781
+ `You are running in tmux session: ${sessionName}.`,
1782
+ `Your parent exe session is ${exeSession}.`,
1783
+ `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
1784
+ ].join("\n");
1785
+ writeFileSync4(ctxFile, ctxContent);
1786
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
1787
+ } catch {
1788
+ }
1789
+ let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
1790
+ if (ccProvider !== DEFAULT_PROVIDER) {
1791
+ const cfg = PROVIDER_TABLE[ccProvider];
1792
+ if (cfg?.apiKeyEnv) {
1793
+ const keyVal = process.env[cfg.apiKeyEnv];
1794
+ if (keyVal) {
1795
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
1796
+ }
1797
+ }
1798
+ }
1799
+ let spawnCommand;
1800
+ if (useExeAgent) {
1801
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
1802
+ } else if (useBinSymlink) {
1803
+ const binName = `${employeeName}-${ccProvider}`;
1804
+ process.stderr.write(
1805
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
1806
+ `
1807
+ );
1808
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
1809
+ } else {
1810
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
1811
+ }
1812
+ const spawnResult = transport.spawn(sessionName, {
1813
+ cwd: spawnCwd,
1814
+ command: spawnCommand
1815
+ });
1816
+ if (spawnResult.error) {
1817
+ releaseSpawnLock(sessionName);
1818
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
1819
+ }
1820
+ transport.pipeLog(sessionName, logFile);
1821
+ try {
1822
+ const mySession = getMySession();
1823
+ const dispatchInfo = path8.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
1824
+ writeFileSync4(dispatchInfo, JSON.stringify({
1825
+ dispatchedBy: mySession,
1826
+ rootExe: exeSession,
1827
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
1828
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1829
+ }));
1830
+ } catch {
1831
+ }
1832
+ let booted = false;
1833
+ for (let i = 0; i < 30; i++) {
1834
+ try {
1835
+ execSync4("sleep 0.5");
1836
+ } catch {
1837
+ }
1838
+ try {
1839
+ const pane = transport.capturePane(sessionName);
1840
+ if (useExeAgent) {
1841
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
1842
+ booted = true;
1843
+ break;
1844
+ }
1845
+ } else {
1846
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
1847
+ booted = true;
1848
+ break;
1849
+ }
1850
+ }
1851
+ } catch {
1852
+ }
1853
+ }
1854
+ if (!booted) {
1855
+ releaseSpawnLock(sessionName);
1856
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
1857
+ }
1858
+ if (!useExeAgent) {
1859
+ try {
1860
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
1861
+ } catch {
1862
+ }
1863
+ }
1864
+ registerSession({
1865
+ windowName: sessionName,
1866
+ agentId: employeeName,
1867
+ projectDir: spawnCwd,
1868
+ parentExe: exeSession,
1869
+ pid: 0,
1870
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1871
+ });
1872
+ releaseSpawnLock(sessionName);
1873
+ return { sessionName };
1874
+ }
1875
+ var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, VALID_SESSION_NAME, VERIFY_PANE_LINES, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
1876
+ var init_tmux_routing = __esm({
1877
+ "src/lib/tmux-routing.ts"() {
1878
+ "use strict";
1879
+ init_session_registry();
1880
+ init_session_key();
1881
+ init_transport();
1882
+ init_cc_agent_support();
1883
+ init_mcp_prefix();
1884
+ init_provider_table();
1885
+ init_intercom_queue();
1886
+ init_plan_limits();
1887
+ SPAWN_LOCK_DIR = path8.join(os5.homedir(), ".exe-os", "spawn-locks");
1888
+ SESSION_CACHE = path8.join(os5.homedir(), ".exe-os", "session-cache");
1889
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
1890
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
1891
+ VERIFY_PANE_LINES = 200;
1892
+ INTERCOM_DEBOUNCE_MS = 3e4;
1893
+ INTERCOM_LOG2 = path8.join(os5.homedir(), ".exe-os", "intercom.log");
1894
+ DEBOUNCE_FILE = path8.join(SESSION_CACHE, "intercom-debounce.json");
1895
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1896
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
1897
+ }
1898
+ });
1899
+
1900
+ // src/lib/tasks-crud.ts
1901
+ import crypto3 from "crypto";
1902
+ import path9 from "path";
1903
+ import { execSync as execSync5 } from "child_process";
1904
+ import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
1905
+ import { existsSync as existsSync9, readFileSync as readFileSync9 } from "fs";
1906
+ async function writeCheckpoint(input) {
1907
+ const client = getClient();
1908
+ const row = await resolveTask(client, input.taskId);
1909
+ const taskId = String(row.id);
1910
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1911
+ const blockedByIds = [];
1912
+ if (row.blocked_by) {
1913
+ blockedByIds.push(String(row.blocked_by));
1914
+ }
1915
+ const checkpoint = {
1916
+ step: input.step,
1917
+ context_summary: input.contextSummary,
1918
+ files_touched: input.filesTouched ?? [],
1919
+ blocked_by_ids: blockedByIds,
1920
+ last_checkpoint_at: now
1921
+ };
1922
+ const result = await client.execute({
1923
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
1924
+ args: [JSON.stringify(checkpoint), now, taskId]
1925
+ });
1926
+ if (result.rowsAffected === 0) {
1927
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
1928
+ }
1929
+ const countResult = await client.execute({
1930
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
1931
+ args: [taskId]
1932
+ });
1933
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
1934
+ return { checkpointCount };
1935
+ }
1936
+ function extractParentFromContext(contextBody) {
1937
+ if (!contextBody) return null;
1938
+ const match = contextBody.match(
1939
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1940
+ );
1941
+ return match ? match[1].toLowerCase() : null;
1942
+ }
1943
+ function slugify(title) {
1944
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1945
+ }
1946
+ async function resolveTask(client, identifier) {
1947
+ let result = await client.execute({
1948
+ sql: "SELECT * FROM tasks WHERE id = ?",
1949
+ args: [identifier]
1950
+ });
1951
+ if (result.rows.length === 1) return result.rows[0];
1952
+ result = await client.execute({
1953
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
1954
+ args: [`%${identifier}%`]
1955
+ });
1956
+ if (result.rows.length === 1) return result.rows[0];
1957
+ if (result.rows.length > 1) {
1958
+ const exact = result.rows.filter(
1959
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
1960
+ );
1961
+ if (exact.length === 1) return exact[0];
1962
+ const candidates = exact.length > 1 ? exact : result.rows;
1963
+ const active = candidates.filter(
1964
+ (r) => !["done", "cancelled"].includes(String(r.status))
1965
+ );
1966
+ if (active.length === 1) return active[0];
1967
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
1968
+ throw new Error(
1969
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1970
+ );
1971
+ }
1972
+ result = await client.execute({
1973
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
1974
+ args: [`%${identifier}%`]
1975
+ });
1976
+ if (result.rows.length === 1) return result.rows[0];
1977
+ if (result.rows.length > 1) {
1978
+ const active = result.rows.filter(
1979
+ (r) => !["done", "cancelled"].includes(String(r.status))
1980
+ );
1981
+ if (active.length === 1) return active[0];
1982
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
1983
+ throw new Error(
1984
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1985
+ );
1986
+ }
1987
+ throw new Error(`Task not found: ${identifier}`);
1988
+ }
1989
+ async function createTaskCore(input) {
1990
+ const client = getClient();
1991
+ const id = crypto3.randomUUID();
1992
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1993
+ const slug = slugify(input.title);
1994
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
1995
+ let blockedById = null;
1996
+ const initialStatus = input.blockedBy ? "blocked" : "open";
1997
+ if (input.blockedBy) {
1998
+ const blocker = await resolveTask(client, input.blockedBy);
1999
+ blockedById = String(blocker.id);
2000
+ }
2001
+ let parentTaskId = null;
2002
+ let parentRef = input.parentTaskId;
2003
+ if (!parentRef) {
2004
+ const extracted = extractParentFromContext(input.context);
2005
+ if (extracted) {
2006
+ parentRef = extracted;
2007
+ process.stderr.write(
2008
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
2009
+ );
2010
+ }
2011
+ }
2012
+ if (parentRef) {
2013
+ try {
2014
+ const parent = await resolveTask(client, parentRef);
2015
+ parentTaskId = String(parent.id);
2016
+ } catch (err) {
2017
+ if (!input.parentTaskId) {
2018
+ throw new Error(
2019
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
2020
+ );
2021
+ }
2022
+ throw err;
2023
+ }
2024
+ }
2025
+ let warning;
2026
+ const dupCheck = await client.execute({
2027
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
2028
+ args: [input.title, input.assignedTo]
2029
+ });
2030
+ if (dupCheck.rows.length > 0) {
2031
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
2032
+ }
2033
+ if (input.baseDir) {
2034
+ try {
2035
+ await mkdir3(path9.join(input.baseDir, "exe", "output"), { recursive: true });
2036
+ await mkdir3(path9.join(input.baseDir, "exe", "research"), { recursive: true });
2037
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
2038
+ await ensureGitignoreExe(input.baseDir);
2039
+ } catch {
2040
+ }
2041
+ }
2042
+ const complexity = input.complexity ?? "standard";
2043
+ let sessionScope = null;
2044
+ try {
2045
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
2046
+ sessionScope = resolveExeSession2();
2047
+ } catch {
2048
+ }
2049
+ await client.execute({
2050
+ sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, session_scope, created_at, updated_at)
2051
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2052
+ args: [
2053
+ id,
2054
+ input.title,
2055
+ input.assignedTo,
2056
+ input.assignedBy,
2057
+ input.projectName,
2058
+ input.priority,
2059
+ initialStatus,
2060
+ taskFile,
2061
+ blockedById,
2062
+ parentTaskId,
2063
+ input.reviewer ?? null,
2064
+ input.context,
2065
+ complexity,
2066
+ input.budgetTokens ?? null,
2067
+ input.budgetFallbackModel ?? null,
2068
+ 0,
2069
+ null,
2070
+ sessionScope,
2071
+ now,
2072
+ now
2073
+ ]
2074
+ });
2075
+ return {
2076
+ id,
2077
+ title: input.title,
2078
+ assignedTo: input.assignedTo,
2079
+ assignedBy: input.assignedBy,
2080
+ projectName: input.projectName,
2081
+ priority: input.priority,
2082
+ status: initialStatus,
2083
+ taskFile,
2084
+ createdAt: now,
2085
+ updatedAt: now,
2086
+ warning,
2087
+ budgetTokens: input.budgetTokens ?? null,
2088
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
2089
+ tokensUsed: 0,
2090
+ tokensWarnedAt: null
2091
+ };
2092
+ }
2093
+ async function listTasks(input) {
2094
+ const client = getClient();
2095
+ const conditions = [];
2096
+ const args = [];
2097
+ if (input.assignedTo) {
2098
+ conditions.push("assigned_to = ?");
2099
+ args.push(input.assignedTo);
2100
+ }
2101
+ if (input.status) {
2102
+ conditions.push("status = ?");
2103
+ args.push(input.status);
2104
+ } else {
2105
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
2106
+ }
2107
+ if (input.projectName) {
2108
+ conditions.push("project_name = ?");
2109
+ args.push(input.projectName);
2110
+ }
2111
+ if (input.priority) {
2112
+ conditions.push("priority = ?");
2113
+ args.push(input.priority);
1281
2114
  }
1282
2115
  try {
1283
- assertEmployeeLimitSync();
1284
- } catch (err) {
1285
- if (err instanceof PlanLimitError) {
1286
- return { status: "failed", sessionName: "", error: err.message };
2116
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
2117
+ const session = resolveExeSession2();
2118
+ if (session) {
2119
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
2120
+ args.push(session);
1287
2121
  }
2122
+ } catch {
1288
2123
  }
1289
- if (/-exe\d*$/.test(employeeName)) {
1290
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
1291
- return {
1292
- status: "failed",
1293
- sessionName: "",
1294
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
1295
- };
2124
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2125
+ const result = await client.execute({
2126
+ 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 LIMIT 1000`,
2127
+ args
2128
+ });
2129
+ return result.rows.map((r) => ({
2130
+ id: String(r.id),
2131
+ title: String(r.title),
2132
+ assignedTo: String(r.assigned_to),
2133
+ assignedBy: String(r.assigned_by),
2134
+ projectName: String(r.project_name),
2135
+ priority: String(r.priority),
2136
+ status: String(r.status),
2137
+ taskFile: String(r.task_file),
2138
+ createdAt: String(r.created_at),
2139
+ updatedAt: String(r.updated_at),
2140
+ checkpointCount: Number(r.checkpoint_count ?? 0),
2141
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
2142
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
2143
+ tokensUsed: Number(r.tokens_used ?? 0),
2144
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
2145
+ }));
2146
+ }
2147
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
2148
+ if (!taskContext) return null;
2149
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
2150
+ try {
2151
+ const since = new Date(taskCreatedAt).toISOString();
2152
+ const branch = execSync5(
2153
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
2154
+ { encoding: "utf8", timeout: 3e3 }
2155
+ ).trim();
2156
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
2157
+ const commitCount = execSync5(
2158
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
2159
+ { encoding: "utf8", timeout: 5e3 }
2160
+ ).trim();
2161
+ const count = parseInt(commitCount, 10);
2162
+ if (count === 0) {
2163
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
2164
+ }
2165
+ return null;
2166
+ } catch {
2167
+ return null;
1296
2168
  }
1297
- let effectiveInstance = opts?.instance;
1298
- if (effectiveInstance === void 0 && opts?.autoInstance) {
1299
- const free = findFreeInstance(
1300
- employeeName,
1301
- exeSession,
1302
- opts.maxAutoInstances ?? 10
2169
+ }
2170
+ async function updateTaskStatus(input) {
2171
+ const client = getClient();
2172
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2173
+ const row = await resolveTask(client, input.taskId);
2174
+ const taskId = String(row.id);
2175
+ const taskFile = String(row.task_file);
2176
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
2177
+ process.stderr.write(
2178
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
2179
+ `
1303
2180
  );
1304
- if (free === null) {
1305
- return {
1306
- status: "failed",
1307
- sessionName: employeeSessionName(employeeName, exeSession),
1308
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
1309
- };
2181
+ }
2182
+ if (input.status === "done") {
2183
+ const existingRow = await client.execute({
2184
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
2185
+ args: [taskId]
2186
+ });
2187
+ if (existingRow.rows.length > 0) {
2188
+ const ctx = existingRow.rows[0];
2189
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
2190
+ if (warning) {
2191
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
2192
+
2193
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
2194
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
2195
+ `);
2196
+ }
1310
2197
  }
1311
- effectiveInstance = free === 0 ? void 0 : free;
1312
2198
  }
1313
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
1314
- if (isEmployeeAlive(sessionName)) {
1315
- const result2 = sendIntercom(sessionName);
1316
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
1317
- return { status: "intercom_sent", sessionName };
2199
+ if (input.status === "in_progress") {
2200
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
2201
+ const claim = await client.execute({
2202
+ sql: `UPDATE tasks
2203
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
2204
+ WHERE id = ? AND status = 'open'`,
2205
+ args: [tmuxSession, now, taskId]
2206
+ });
2207
+ if (claim.rowsAffected === 0) {
2208
+ const current = await client.execute({
2209
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
2210
+ args: [taskId]
2211
+ });
2212
+ const cur = current.rows[0];
2213
+ const status = cur?.status ?? "unknown";
2214
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
2215
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
1318
2216
  }
1319
- if (result2 === "delivered") {
1320
- return { status: "intercom_unprocessed", sessionName };
2217
+ try {
2218
+ await writeCheckpoint({
2219
+ taskId,
2220
+ step: "claimed",
2221
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
2222
+ });
2223
+ } catch {
1321
2224
  }
1322
- return { status: "failed", sessionName, error: "intercom delivery failed" };
2225
+ return { row, taskFile, now, taskId };
1323
2226
  }
1324
- const spawnOpts = { ...opts, instance: effectiveInstance };
1325
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
1326
- if (result.error) {
1327
- return { status: "failed", sessionName, error: result.error };
1328
- }
1329
- return { status: "spawned", sessionName };
1330
- }
1331
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
1332
- const transport = getTransport();
1333
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
1334
- const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
1335
- const logDir = path9.join(os5.homedir(), ".exe-os", "session-logs");
1336
- const logFile = path9.join(logDir, `${instanceLabel}-${Date.now()}.log`);
1337
- if (!existsSync9(logDir)) {
1338
- mkdirSync4(logDir, { recursive: true });
2227
+ if (input.result) {
2228
+ await client.execute({
2229
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
2230
+ args: [input.status, input.result, now, taskId]
2231
+ });
2232
+ } else {
2233
+ await client.execute({
2234
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
2235
+ args: [input.status, now, taskId]
2236
+ });
1339
2237
  }
1340
- transport.kill(sessionName);
1341
- let cleanupSuffix = "";
1342
2238
  try {
1343
- const thisFile = fileURLToPath(import.meta.url);
1344
- const cleanupScript = path9.join(path9.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
1345
- if (existsSync9(cleanupScript)) {
1346
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
1347
- }
2239
+ await writeCheckpoint({
2240
+ taskId,
2241
+ step: `status_transition:${input.status}`,
2242
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
2243
+ });
1348
2244
  } catch {
1349
2245
  }
2246
+ return { row, taskFile, now, taskId };
2247
+ }
2248
+ async function deleteTaskCore(taskId, _baseDir) {
2249
+ const client = getClient();
2250
+ const row = await resolveTask(client, taskId);
2251
+ const id = String(row.id);
2252
+ const taskFile = String(row.task_file);
2253
+ const assignedTo = String(row.assigned_to);
2254
+ const assignedBy = String(row.assigned_by);
2255
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
2256
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
2257
+ return { taskFile, assignedTo, assignedBy, taskSlug };
2258
+ }
2259
+ async function ensureArchitectureDoc(baseDir, projectName) {
2260
+ const archPath = path9.join(baseDir, "exe", "ARCHITECTURE.md");
1350
2261
  try {
1351
- const claudeJsonPath = path9.join(os5.homedir(), ".claude.json");
1352
- let claudeJson = {};
1353
- try {
1354
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
1355
- } catch {
1356
- }
1357
- if (!claudeJson.projects) claudeJson.projects = {};
1358
- const projects = claudeJson.projects;
1359
- const trustDir = opts?.cwd ?? projectDir;
1360
- if (!projects[trustDir]) projects[trustDir] = {};
1361
- projects[trustDir].hasTrustDialogAccepted = true;
1362
- writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
2262
+ if (existsSync9(archPath)) return;
2263
+ const template = [
2264
+ `# ${projectName} \u2014 System Architecture`,
2265
+ "",
2266
+ "> Employees: read this before every task. Update it when you change system structure.",
2267
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2268
+ "",
2269
+ "## Overview",
2270
+ "",
2271
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
2272
+ "",
2273
+ "## Key Components",
2274
+ "",
2275
+ "<!-- List the major modules, services, or subsystems. -->",
2276
+ "",
2277
+ "## Data Flow",
2278
+ "",
2279
+ "<!-- How does data move through the system? What writes where? -->",
2280
+ "",
2281
+ "## Invariants",
2282
+ "",
2283
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
2284
+ "",
2285
+ "## Dependencies",
2286
+ "",
2287
+ "<!-- What depends on what? If I change X, what else is affected? -->",
2288
+ ""
2289
+ ].join("\n");
2290
+ await writeFile3(archPath, template, "utf-8");
1363
2291
  } catch {
1364
2292
  }
2293
+ }
2294
+ async function ensureGitignoreExe(baseDir) {
2295
+ const gitignorePath = path9.join(baseDir, ".gitignore");
1365
2296
  try {
1366
- const settingsDir = path9.join(os5.homedir(), ".claude", "projects");
1367
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
1368
- const projSettingsDir = path9.join(settingsDir, normalizedKey);
1369
- const settingsPath = path9.join(projSettingsDir, "settings.json");
1370
- let settings = {};
1371
- try {
1372
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
1373
- } catch {
1374
- }
1375
- const perms = settings.permissions ?? {};
1376
- const allow = perms.allow ?? [];
1377
- const toolNames = [
1378
- "recall_my_memory",
1379
- "store_memory",
1380
- "create_task",
1381
- "update_task",
1382
- "list_tasks",
1383
- "get_task",
1384
- "ask_team_memory",
1385
- "store_behavior",
1386
- "get_identity",
1387
- "send_message"
1388
- ];
1389
- const requiredTools = expandDualPrefixTools(toolNames);
1390
- let changed = false;
1391
- for (const tool of requiredTools) {
1392
- if (!allow.includes(tool)) {
1393
- allow.push(tool);
1394
- changed = true;
1395
- }
1396
- }
1397
- if (changed) {
1398
- perms.allow = allow;
1399
- settings.permissions = perms;
1400
- mkdirSync4(projSettingsDir, { recursive: true });
1401
- writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2297
+ if (existsSync9(gitignorePath)) {
2298
+ const content = readFileSync9(gitignorePath, "utf-8");
2299
+ if (/^\/?exe\/?$/m.test(content)) return;
2300
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
2301
+ } else {
2302
+ await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
1402
2303
  }
1403
2304
  } catch {
1404
2305
  }
1405
- const spawnCwd = opts?.cwd ?? projectDir;
1406
- const useExeAgent = !!(opts?.model && opts?.provider);
1407
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
1408
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
1409
- let identityFlag = "";
1410
- let behaviorsFlag = "";
1411
- let legacyFallbackWarned = false;
1412
- if (!useExeAgent && !useBinSymlink) {
1413
- const identityPath = path9.join(
1414
- os5.homedir(),
1415
- ".exe-os",
1416
- "identity",
1417
- `${employeeName}.md`
1418
- );
1419
- _resetCcAgentSupportCache();
1420
- const hasAgentFlag = claudeSupportsAgentFlag();
1421
- if (hasAgentFlag) {
1422
- identityFlag = ` --agent ${employeeName}`;
1423
- } else if (existsSync9(identityPath)) {
1424
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
1425
- legacyFallbackWarned = true;
1426
- }
1427
- const behaviorsFile = exportBehaviorsSync(
1428
- employeeName,
1429
- path9.basename(spawnCwd),
1430
- sessionName
1431
- );
1432
- if (behaviorsFile) {
1433
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
1434
- }
2306
+ }
2307
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
2308
+ var init_tasks_crud = __esm({
2309
+ "src/lib/tasks-crud.ts"() {
2310
+ "use strict";
2311
+ init_database();
2312
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
2313
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
1435
2314
  }
1436
- if (legacyFallbackWarned) {
2315
+ });
2316
+
2317
+ // src/lib/tasks-review.ts
2318
+ import path10 from "path";
2319
+ import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync3 } from "fs";
2320
+ async function countPendingReviews() {
2321
+ const client = getClient();
2322
+ const result = await client.execute({
2323
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
2324
+ args: []
2325
+ });
2326
+ return Number(result.rows[0]?.cnt) || 0;
2327
+ }
2328
+ async function countNewPendingReviewsSince(sinceIso) {
2329
+ const client = getClient();
2330
+ const result = await client.execute({
2331
+ sql: `SELECT COUNT(*) as cnt FROM tasks
2332
+ WHERE status = 'needs_review' AND updated_at > ?`,
2333
+ args: [sinceIso]
2334
+ });
2335
+ return Number(result.rows[0]?.cnt) || 0;
2336
+ }
2337
+ async function listPendingReviews(limit) {
2338
+ const client = getClient();
2339
+ const result = await client.execute({
2340
+ sql: `SELECT title, assigned_to, project_name FROM tasks
2341
+ WHERE status = 'needs_review'
2342
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
2343
+ args: [limit]
2344
+ });
2345
+ return result.rows;
2346
+ }
2347
+ async function cleanupOrphanedReviews() {
2348
+ const client = getClient();
2349
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2350
+ const r1 = await client.execute({
2351
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
2352
+ WHERE status = 'needs_review'
2353
+ AND assigned_by = 'system'
2354
+ AND title LIKE 'Review:%'
2355
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
2356
+ args: [now]
2357
+ });
2358
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
2359
+ const r2 = await client.execute({
2360
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
2361
+ WHERE status = 'needs_review'
2362
+ AND result IS NOT NULL
2363
+ AND updated_at < ?`,
2364
+ args: [now, staleThreshold]
2365
+ });
2366
+ const total = r1.rowsAffected + r2.rowsAffected;
2367
+ if (total > 0) {
1437
2368
  process.stderr.write(
1438
- `[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.
2369
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
1439
2370
  `
1440
2371
  );
1441
2372
  }
1442
- let sessionContextFlag = "";
1443
- try {
1444
- const ctxDir = path9.join(os5.homedir(), ".exe-os", "session-cache");
1445
- mkdirSync4(ctxDir, { recursive: true });
1446
- const ctxFile = path9.join(ctxDir, `session-context-${sessionName}.md`);
1447
- const ctxContent = [
1448
- `## Session Context`,
1449
- `You are running in tmux session: ${sessionName}.`,
1450
- `Your parent exe session is ${exeSession}.`,
1451
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
1452
- ].join("\n");
1453
- writeFileSync4(ctxFile, ctxContent);
1454
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
1455
- } catch {
2373
+ return total;
2374
+ }
2375
+ function getReviewChecklist(role, agent, taskSlug) {
2376
+ const roleLower = role.toLowerCase();
2377
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
2378
+ return {
2379
+ lens: "Code Quality (Engineer)",
2380
+ checklist: [
2381
+ "1. Do all tests pass? Any new tests needed?",
2382
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
2383
+ "3. Does it follow existing patterns and conventions in the codebase?",
2384
+ "4. Any regressions in the test suite?"
2385
+ ]
2386
+ };
1456
2387
  }
1457
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
1458
- if (ccProvider !== DEFAULT_PROVIDER) {
1459
- const cfg = PROVIDER_TABLE[ccProvider];
1460
- if (cfg?.apiKeyEnv) {
1461
- const keyVal = process.env[cfg.apiKeyEnv];
1462
- if (keyVal) {
1463
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
2388
+ if (roleLower === "cto" || roleLower.includes("architect")) {
2389
+ return {
2390
+ lens: "Architecture (CTO)",
2391
+ checklist: [
2392
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
2393
+ "2. Is it backward compatible? Any breaking changes?",
2394
+ "3. Does it introduce technical debt? Is that debt justified?",
2395
+ "4. Security implications? Any new attack surface?",
2396
+ "5. Does it scale? Performance considerations?",
2397
+ "6. Coordination: does this affect other employees' work or other projects?"
2398
+ ]
2399
+ };
2400
+ }
2401
+ if (roleLower === "coo" || roleLower.includes("operations")) {
2402
+ return {
2403
+ lens: "Strategic (COO)",
2404
+ checklist: [
2405
+ "1. Does this serve the project mission?",
2406
+ "2. Is this the right work at the right time?",
2407
+ "3. Does the architectural assessment make sense for the business?",
2408
+ "4. Any cross-project implications?"
2409
+ ]
2410
+ };
2411
+ }
2412
+ return {
2413
+ lens: "General",
2414
+ checklist: [
2415
+ "1. Read the original task's acceptance criteria",
2416
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
2417
+ "3. Verify code changes match requirements",
2418
+ "4. Check if tests were added/updated",
2419
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
2420
+ ]
2421
+ };
2422
+ }
2423
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
2424
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
2425
+ try {
2426
+ const client = getClient();
2427
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2428
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
2429
+ if (parentId) {
2430
+ const result = await client.execute({
2431
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
2432
+ args: [now, parentId]
2433
+ });
2434
+ if (result.rowsAffected > 0) {
2435
+ process.stderr.write(
2436
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
2437
+ `
2438
+ );
2439
+ }
2440
+ } else {
2441
+ const fileName = taskFile.split("/").pop() ?? "";
2442
+ const reviewPrefix = fileName.replace(".md", "");
2443
+ const parts = reviewPrefix.split("-");
2444
+ if (parts.length >= 3 && parts[0] === "review") {
2445
+ const agent = parts[1];
2446
+ const slug = parts.slice(2).join("-");
2447
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
2448
+ const result = await client.execute({
2449
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
2450
+ args: [now, originalTaskFile]
2451
+ });
2452
+ if (result.rowsAffected > 0) {
2453
+ process.stderr.write(
2454
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
2455
+ `
2456
+ );
2457
+ }
1464
2458
  }
1465
2459
  }
1466
- }
1467
- let spawnCommand;
1468
- if (useExeAgent) {
1469
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
1470
- } else if (useBinSymlink) {
1471
- const binName = `${employeeName}-${ccProvider}`;
2460
+ } catch (err) {
1472
2461
  process.stderr.write(
1473
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
2462
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
1474
2463
  `
1475
2464
  );
1476
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
1477
- } else {
1478
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
1479
- }
1480
- const spawnResult = transport.spawn(sessionName, {
1481
- cwd: spawnCwd,
1482
- command: spawnCommand
1483
- });
1484
- if (spawnResult.error) {
1485
- releaseSpawnLock(sessionName);
1486
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
1487
2465
  }
1488
- transport.pipeLog(sessionName, logFile);
1489
2466
  try {
1490
- const mySession = getMySession();
1491
- const dispatchInfo = path9.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
1492
- writeFileSync4(dispatchInfo, JSON.stringify({
1493
- dispatchedBy: mySession,
1494
- rootExe: exeSession,
1495
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
1496
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1497
- }));
1498
- } catch {
1499
- }
1500
- let booted = false;
1501
- for (let i = 0; i < 30; i++) {
1502
- try {
1503
- execSync5("sleep 0.5");
1504
- } catch {
1505
- }
1506
- try {
1507
- const pane = transport.capturePane(sessionName);
1508
- if (useExeAgent) {
1509
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
1510
- booted = true;
1511
- break;
1512
- }
1513
- } else {
1514
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
1515
- booted = true;
1516
- break;
2467
+ const cacheDir = path10.join(EXE_AI_DIR, "session-cache");
2468
+ if (existsSync10(cacheDir)) {
2469
+ for (const f of readdirSync2(cacheDir)) {
2470
+ if (f.startsWith("review-notified-")) {
2471
+ unlinkSync3(path10.join(cacheDir, f));
1517
2472
  }
1518
2473
  }
1519
- } catch {
1520
- }
1521
- }
1522
- if (!booted) {
1523
- releaseSpawnLock(sessionName);
1524
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
1525
- }
1526
- if (!useExeAgent) {
1527
- try {
1528
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
1529
- } catch {
1530
2474
  }
2475
+ } catch {
1531
2476
  }
1532
- registerSession({
1533
- windowName: sessionName,
1534
- agentId: employeeName,
1535
- projectDir: spawnCwd,
1536
- parentExe: exeSession,
1537
- pid: 0,
1538
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1539
- });
1540
- releaseSpawnLock(sessionName);
1541
- return { sessionName };
1542
2477
  }
1543
- var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
1544
- var init_tmux_routing = __esm({
1545
- "src/lib/tmux-routing.ts"() {
1546
- "use strict";
1547
- init_session_registry();
1548
- init_session_key();
1549
- init_transport();
1550
- init_cc_agent_support();
1551
- init_mcp_prefix();
1552
- init_provider_table();
1553
- init_intercom_queue();
1554
- init_plan_limits();
1555
- SPAWN_LOCK_DIR = path9.join(os5.homedir(), ".exe-os", "spawn-locks");
1556
- SESSION_CACHE = path9.join(os5.homedir(), ".exe-os", "session-cache");
1557
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
1558
- INTERCOM_DEBOUNCE_MS = 3e4;
1559
- INTERCOM_LOG2 = path9.join(os5.homedir(), ".exe-os", "intercom.log");
1560
- DEBOUNCE_FILE = path9.join(SESSION_CACHE, "intercom-debounce.json");
1561
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1562
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
1563
- }
1564
- });
1565
-
1566
- // src/lib/tasks-review.ts
1567
- import path10 from "path";
1568
- import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync3 } from "fs";
1569
2478
  var init_tasks_review = __esm({
1570
2479
  "src/lib/tasks-review.ts"() {
1571
2480
  "use strict";
@@ -1576,12 +2485,83 @@ var init_tasks_review = __esm({
1576
2485
  init_tasks_crud();
1577
2486
  init_tmux_routing();
1578
2487
  init_session_key();
2488
+ init_state_bus();
1579
2489
  }
1580
2490
  });
1581
2491
 
1582
2492
  // src/lib/tasks-chain.ts
1583
2493
  import path11 from "path";
1584
2494
  import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
2495
+ async function cascadeUnblock(taskId, baseDir, now) {
2496
+ const client = getClient();
2497
+ const unblocked = await client.execute({
2498
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
2499
+ WHERE blocked_by = ? AND status = 'blocked'`,
2500
+ args: [now, taskId]
2501
+ });
2502
+ if (baseDir && unblocked.rowsAffected > 0) {
2503
+ const unblockedRows = await client.execute({
2504
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
2505
+ args: [now]
2506
+ });
2507
+ for (const ur of unblockedRows.rows) {
2508
+ try {
2509
+ const ubFile = path11.join(baseDir, String(ur.task_file));
2510
+ let ubContent = await readFile3(ubFile, "utf-8");
2511
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
2512
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
2513
+ await writeFile4(ubFile, ubContent, "utf-8");
2514
+ } catch {
2515
+ }
2516
+ }
2517
+ }
2518
+ }
2519
+ async function findNextTask(assignedTo) {
2520
+ const client = getClient();
2521
+ const nextResult = await client.execute({
2522
+ sql: `SELECT title, task_file, priority FROM tasks
2523
+ WHERE assigned_to = ? AND status = 'open'
2524
+ ORDER BY priority ASC, created_at ASC
2525
+ LIMIT 1`,
2526
+ args: [assignedTo]
2527
+ });
2528
+ if (nextResult.rows.length === 1) {
2529
+ const nr = nextResult.rows[0];
2530
+ return {
2531
+ title: String(nr.title),
2532
+ priority: String(nr.priority),
2533
+ taskFile: String(nr.task_file)
2534
+ };
2535
+ }
2536
+ return void 0;
2537
+ }
2538
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
2539
+ const client = getClient();
2540
+ const remaining = await client.execute({
2541
+ sql: `SELECT COUNT(*) as cnt FROM tasks
2542
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
2543
+ args: [parentTaskId]
2544
+ });
2545
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
2546
+ if (cnt === 0) {
2547
+ const parentRow = await client.execute({
2548
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
2549
+ args: [parentTaskId]
2550
+ });
2551
+ if (parentRow.rows.length === 1) {
2552
+ const pr = parentRow.rows[0];
2553
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
2554
+ await writeNotification({
2555
+ agentId: String(pr.assigned_to),
2556
+ agentRole: "system",
2557
+ event: "subtasks_complete",
2558
+ project: parentProject,
2559
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
2560
+ taskFile: String(pr.task_file)
2561
+ });
2562
+ }
2563
+ }
2564
+ }
1585
2565
  var init_tasks_chain = __esm({
1586
2566
  "src/lib/tasks-chain.ts"() {
1587
2567
  "use strict";
@@ -1670,13 +2650,12 @@ function assertSessionScope(actionType, targetProject) {
1670
2650
  };
1671
2651
  }
1672
2652
  process.stderr.write(
1673
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
2653
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
1674
2654
  `
1675
2655
  );
1676
2656
  return {
1677
- allowed: true,
1678
- // v1: warn-only, don't block
1679
- reason: "cross_session_granted",
2657
+ allowed: false,
2658
+ reason: "cross_session_denied",
1680
2659
  currentProject,
1681
2660
  targetProject,
1682
2661
  targetSession: findSessionForProject(targetProject)?.windowName
@@ -1702,8 +2681,9 @@ async function dispatchTaskToEmployee(input) {
1702
2681
  try {
1703
2682
  const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
1704
2683
  const check = assertSessionScope2("dispatch_task", input.projectName);
1705
- if (check.reason === "cross_session_granted") {
2684
+ if (check.reason === "cross_session_denied") {
1706
2685
  crossProject = true;
2686
+ return { dispatched: "skipped", crossProject: true };
1707
2687
  }
1708
2688
  } catch {
1709
2689
  }
@@ -1735,6 +2715,19 @@ async function dispatchTaskToEmployee(input) {
1735
2715
  return { dispatched: "session_missing" };
1736
2716
  }
1737
2717
  }
2718
+ function notifyTaskDone() {
2719
+ try {
2720
+ const key = getSessionKey();
2721
+ if (key && !process.env.VITEST) notifyParentExe(key);
2722
+ } catch {
2723
+ }
2724
+ }
2725
+ async function markTaskNotificationsRead(taskFile) {
2726
+ try {
2727
+ await markAsReadByTaskFile(taskFile);
2728
+ } catch {
2729
+ }
2730
+ }
1738
2731
  var init_tasks_notify = __esm({
1739
2732
  "src/lib/tasks-notify.ts"() {
1740
2733
  "use strict";
@@ -1746,7 +2739,337 @@ var init_tasks_notify = __esm({
1746
2739
  }
1747
2740
  });
1748
2741
 
2742
+ // src/lib/behaviors.ts
2743
+ import crypto4 from "crypto";
2744
+ async function storeBehavior(opts) {
2745
+ const client = getClient();
2746
+ const id = crypto4.randomUUID();
2747
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2748
+ await client.execute({
2749
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
2750
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
2751
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
2752
+ });
2753
+ return id;
2754
+ }
2755
+ var init_behaviors = __esm({
2756
+ "src/lib/behaviors.ts"() {
2757
+ "use strict";
2758
+ init_database();
2759
+ }
2760
+ });
2761
+
2762
+ // src/lib/skill-learning.ts
2763
+ var skill_learning_exports = {};
2764
+ __export(skill_learning_exports, {
2765
+ captureAndLearn: () => captureAndLearn,
2766
+ captureTrajectory: () => captureTrajectory,
2767
+ editDistance: () => editDistance,
2768
+ extractSkill: () => extractSkill,
2769
+ extractTrajectory: () => extractTrajectory,
2770
+ findSimilarTrajectories: () => findSimilarTrajectories,
2771
+ hashSignature: () => hashSignature,
2772
+ storeTrajectory: () => storeTrajectory,
2773
+ sweepTrajectories: () => sweepTrajectories
2774
+ });
2775
+ import crypto5 from "crypto";
2776
+ async function extractTrajectory(taskId, agentId) {
2777
+ const client = getClient();
2778
+ const result = await client.execute({
2779
+ sql: `SELECT tool_name, raw_text
2780
+ FROM memories
2781
+ WHERE task_id = ? AND agent_id = ?
2782
+ ORDER BY timestamp ASC`,
2783
+ args: [taskId, agentId]
2784
+ });
2785
+ if (result.rows.length === 0) return [];
2786
+ const rawTools = result.rows.map((r) => {
2787
+ const toolName = String(r.tool_name);
2788
+ if (toolName === "Bash") {
2789
+ const text = String(r.raw_text);
2790
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
2791
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
2792
+ }
2793
+ return toolName;
2794
+ });
2795
+ const signature = [];
2796
+ for (const tool of rawTools) {
2797
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
2798
+ signature.push(tool);
2799
+ }
2800
+ }
2801
+ return signature;
2802
+ }
2803
+ function hashSignature(signature) {
2804
+ return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
2805
+ }
2806
+ async function storeTrajectory(opts) {
2807
+ const client = getClient();
2808
+ const id = crypto5.randomUUID();
2809
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2810
+ const signatureHash = hashSignature(opts.signature);
2811
+ await client.execute({
2812
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
2813
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2814
+ args: [
2815
+ id,
2816
+ opts.taskId,
2817
+ opts.agentId,
2818
+ opts.projectName,
2819
+ opts.taskTitle,
2820
+ JSON.stringify(opts.signature),
2821
+ signatureHash,
2822
+ opts.signature.length,
2823
+ now
2824
+ ]
2825
+ });
2826
+ return id;
2827
+ }
2828
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
2829
+ const client = getClient();
2830
+ const hash = hashSignature(signature);
2831
+ const result = await client.execute({
2832
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2833
+ FROM trajectories
2834
+ WHERE signature_hash = ?
2835
+ ORDER BY created_at DESC
2836
+ LIMIT 20`,
2837
+ args: [hash]
2838
+ });
2839
+ const mapRow = (r) => ({
2840
+ id: String(r.id),
2841
+ taskId: String(r.task_id),
2842
+ agentId: String(r.agent_id),
2843
+ projectName: String(r.project_name),
2844
+ taskTitle: String(r.task_title),
2845
+ signature: JSON.parse(String(r.signature)),
2846
+ signatureHash: String(r.signature_hash),
2847
+ toolCount: Number(r.tool_count),
2848
+ skillId: r.skill_id ? String(r.skill_id) : null,
2849
+ createdAt: String(r.created_at)
2850
+ });
2851
+ const matches = result.rows.map(mapRow);
2852
+ if (matches.length >= threshold) return matches;
2853
+ const nearResult = await client.execute({
2854
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2855
+ FROM trajectories
2856
+ WHERE tool_count BETWEEN ? AND ?
2857
+ AND signature_hash != ?
2858
+ ORDER BY created_at DESC
2859
+ LIMIT 50`,
2860
+ args: [
2861
+ Math.max(1, signature.length - 3),
2862
+ signature.length + 3,
2863
+ hash
2864
+ ]
2865
+ });
2866
+ for (const r of nearResult.rows) {
2867
+ const candidateSig = JSON.parse(String(r.signature));
2868
+ if (editDistance(signature, candidateSig) <= 2) {
2869
+ matches.push(mapRow(r));
2870
+ }
2871
+ }
2872
+ return matches;
2873
+ }
2874
+ async function captureTrajectory(opts) {
2875
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
2876
+ if (signature.length < 3) {
2877
+ return { trajectoryId: "", similarCount: 0, similar: [] };
2878
+ }
2879
+ const trajectoryId = await storeTrajectory({
2880
+ taskId: opts.taskId,
2881
+ agentId: opts.agentId,
2882
+ projectName: opts.projectName,
2883
+ taskTitle: opts.taskTitle,
2884
+ signature
2885
+ });
2886
+ const similar = await findSimilarTrajectories(
2887
+ signature,
2888
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
2889
+ );
2890
+ return { trajectoryId, similarCount: similar.length, similar };
2891
+ }
2892
+ function buildExtractionPrompt(trajectories) {
2893
+ const items = trajectories.map((t, i) => {
2894
+ const sig = t.signature.join(" \u2192 ");
2895
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
2896
+ Signature: ${sig}`;
2897
+ }).join("\n\n");
2898
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
2899
+
2900
+ ${items}
2901
+
2902
+ Extract the reusable procedure. Format your response EXACTLY like this:
2903
+
2904
+ SKILL: {name \u2014 short, descriptive}
2905
+ TRIGGER: {when to use this \u2014 one sentence}
2906
+ STEPS:
2907
+ 1. ...
2908
+ 2. ...
2909
+ PITFALLS: {common mistakes to avoid}
2910
+
2911
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
2912
+ }
2913
+ async function extractSkill(trajectories, model) {
2914
+ if (trajectories.length === 0) return null;
2915
+ const config = await loadConfig();
2916
+ const skillModel = model ?? config.skillModel;
2917
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
2918
+ const client = new Anthropic();
2919
+ const prompt = buildExtractionPrompt(trajectories);
2920
+ const response = await client.messages.create({
2921
+ model: skillModel,
2922
+ max_tokens: 500,
2923
+ messages: [{ role: "user", content: prompt }]
2924
+ });
2925
+ const textBlock = response.content.find((b) => b.type === "text");
2926
+ const skillText = textBlock?.text;
2927
+ if (!skillText) return null;
2928
+ const agentId = trajectories[0].agentId;
2929
+ const projectName = trajectories[0].projectName;
2930
+ const skillId = await storeBehavior({
2931
+ agentId,
2932
+ content: skillText,
2933
+ domain: "skill",
2934
+ projectName
2935
+ });
2936
+ const dbClient = getClient();
2937
+ for (const t of trajectories) {
2938
+ await dbClient.execute({
2939
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
2940
+ args: [skillId, t.id]
2941
+ });
2942
+ }
2943
+ process.stderr.write(
2944
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
2945
+ `
2946
+ );
2947
+ return skillId;
2948
+ }
2949
+ async function captureAndLearn(opts) {
2950
+ try {
2951
+ const config = await loadConfig();
2952
+ if (!config.skillLearning) return;
2953
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
2954
+ ...opts,
2955
+ skillThreshold: config.skillThreshold
2956
+ });
2957
+ if (!trajectoryId) return;
2958
+ if (similarCount >= config.skillThreshold) {
2959
+ const unprocessed = similar.filter((t) => !t.skillId);
2960
+ if (unprocessed.length >= config.skillThreshold) {
2961
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
2962
+ process.stderr.write(
2963
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
2964
+ `
2965
+ );
2966
+ });
2967
+ }
2968
+ }
2969
+ } catch (err) {
2970
+ process.stderr.write(
2971
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
2972
+ `
2973
+ );
2974
+ }
2975
+ }
2976
+ async function sweepTrajectories(threshold, model) {
2977
+ const config = await loadConfig();
2978
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
2979
+ const t = threshold ?? config.skillThreshold;
2980
+ const client = getClient();
2981
+ const result = await client.execute({
2982
+ sql: `SELECT signature_hash, COUNT(*) as cnt
2983
+ FROM trajectories
2984
+ WHERE skill_id IS NULL
2985
+ GROUP BY signature_hash
2986
+ HAVING cnt >= ?
2987
+ ORDER BY cnt DESC
2988
+ LIMIT 10`,
2989
+ args: [t]
2990
+ });
2991
+ let clustersProcessed = 0;
2992
+ let skillsExtracted = 0;
2993
+ for (const row of result.rows) {
2994
+ const hash = String(row.signature_hash);
2995
+ const trajResult = await client.execute({
2996
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
2997
+ FROM trajectories
2998
+ WHERE signature_hash = ? AND skill_id IS NULL
2999
+ ORDER BY created_at DESC
3000
+ LIMIT 10`,
3001
+ args: [hash]
3002
+ });
3003
+ const trajectories = trajResult.rows.map((r) => ({
3004
+ id: String(r.id),
3005
+ taskId: String(r.task_id),
3006
+ agentId: String(r.agent_id),
3007
+ projectName: String(r.project_name),
3008
+ taskTitle: String(r.task_title),
3009
+ signature: JSON.parse(String(r.signature)),
3010
+ signatureHash: String(r.signature_hash),
3011
+ toolCount: Number(r.tool_count),
3012
+ skillId: null,
3013
+ createdAt: String(r.created_at)
3014
+ }));
3015
+ if (trajectories.length >= t) {
3016
+ clustersProcessed++;
3017
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
3018
+ if (skillId) skillsExtracted++;
3019
+ }
3020
+ }
3021
+ return { clustersProcessed, skillsExtracted };
3022
+ }
3023
+ function editDistance(a, b) {
3024
+ const m = a.length;
3025
+ const n = b.length;
3026
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
3027
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
3028
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
3029
+ for (let i = 1; i <= m; i++) {
3030
+ for (let j = 1; j <= n; j++) {
3031
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
3032
+ dp[i][j] = Math.min(
3033
+ dp[i - 1][j] + 1,
3034
+ dp[i][j - 1] + 1,
3035
+ dp[i - 1][j - 1] + cost
3036
+ );
3037
+ }
3038
+ }
3039
+ return dp[m][n];
3040
+ }
3041
+ var DEFAULT_SKILL_THRESHOLD;
3042
+ var init_skill_learning = __esm({
3043
+ "src/lib/skill-learning.ts"() {
3044
+ "use strict";
3045
+ init_database();
3046
+ init_behaviors();
3047
+ init_config();
3048
+ DEFAULT_SKILL_THRESHOLD = 3;
3049
+ }
3050
+ });
3051
+
1749
3052
  // src/lib/tasks.ts
3053
+ var tasks_exports = {};
3054
+ __export(tasks_exports, {
3055
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
3056
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
3057
+ countPendingReviews: () => countPendingReviews,
3058
+ createTask: () => createTask,
3059
+ createTaskCore: () => createTaskCore,
3060
+ deleteTask: () => deleteTask,
3061
+ deleteTaskCore: () => deleteTaskCore,
3062
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
3063
+ ensureGitignoreExe: () => ensureGitignoreExe,
3064
+ getReviewChecklist: () => getReviewChecklist,
3065
+ listPendingReviews: () => listPendingReviews,
3066
+ listTasks: () => listTasks,
3067
+ resolveTask: () => resolveTask,
3068
+ slugify: () => slugify,
3069
+ updateTask: () => updateTask,
3070
+ updateTaskStatus: () => updateTaskStatus,
3071
+ writeCheckpoint: () => writeCheckpoint
3072
+ });
1750
3073
  import path13 from "path";
1751
3074
  import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, unlinkSync as unlinkSync4 } from "fs";
1752
3075
  async function createTask(input) {
@@ -1763,12 +3086,141 @@ async function createTask(input) {
1763
3086
  }
1764
3087
  return result;
1765
3088
  }
3089
+ async function updateTask(input) {
3090
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
3091
+ try {
3092
+ const agent = String(row.assigned_to);
3093
+ const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
3094
+ const cachePath = path13.join(cacheDir, `current-task-${agent}.json`);
3095
+ if (input.status === "in_progress") {
3096
+ mkdirSync5(cacheDir, { recursive: true });
3097
+ writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
3098
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
3099
+ try {
3100
+ unlinkSync4(cachePath);
3101
+ } catch {
3102
+ }
3103
+ }
3104
+ } catch {
3105
+ }
3106
+ if (input.status === "done") {
3107
+ await cleanupReviewFile(row, taskFile, input.baseDir);
3108
+ }
3109
+ if (input.status === "done" || input.status === "cancelled") {
3110
+ try {
3111
+ const client = getClient();
3112
+ const taskTitle = String(row.title);
3113
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
3114
+ await client.execute({
3115
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3116
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
3117
+ args: [now, `%left '${escaped}' as in\\_progress%`]
3118
+ });
3119
+ } catch {
3120
+ }
3121
+ try {
3122
+ const client = getClient();
3123
+ const cascaded = await client.execute({
3124
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3125
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
3126
+ args: [now, taskId]
3127
+ });
3128
+ if (cascaded.rowsAffected > 0) {
3129
+ process.stderr.write(
3130
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
3131
+ `
3132
+ );
3133
+ }
3134
+ } catch {
3135
+ }
3136
+ }
3137
+ const isTerminal = input.status === "done" || input.status === "needs_review";
3138
+ if (isTerminal) {
3139
+ const isExe = String(row.assigned_to) === "exe";
3140
+ if (!isExe) {
3141
+ notifyTaskDone();
3142
+ }
3143
+ await markTaskNotificationsRead(taskFile);
3144
+ if (input.status === "done") {
3145
+ try {
3146
+ await cascadeUnblock(taskId, input.baseDir, now);
3147
+ } catch {
3148
+ }
3149
+ orgBus.emit({
3150
+ type: "task_completed",
3151
+ taskId,
3152
+ employee: String(row.assigned_to),
3153
+ result: input.result ?? "",
3154
+ timestamp: now
3155
+ });
3156
+ if (row.parent_task_id) {
3157
+ try {
3158
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
3159
+ } catch {
3160
+ }
3161
+ }
3162
+ }
3163
+ }
3164
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
3165
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
3166
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
3167
+ taskId,
3168
+ agentId: String(row.assigned_to),
3169
+ projectName: String(row.project_name),
3170
+ taskTitle: String(row.title)
3171
+ })
3172
+ ).catch((err) => {
3173
+ process.stderr.write(
3174
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
3175
+ `
3176
+ );
3177
+ });
3178
+ }
3179
+ let nextTask;
3180
+ if (isTerminal && String(row.assigned_to) !== "exe") {
3181
+ try {
3182
+ nextTask = await findNextTask(String(row.assigned_to));
3183
+ } catch {
3184
+ }
3185
+ }
3186
+ return {
3187
+ id: String(row.id),
3188
+ title: String(row.title),
3189
+ assignedTo: String(row.assigned_to),
3190
+ assignedBy: String(row.assigned_by),
3191
+ projectName: String(row.project_name),
3192
+ priority: String(row.priority),
3193
+ status: input.status,
3194
+ taskFile,
3195
+ createdAt: String(row.created_at),
3196
+ updatedAt: now,
3197
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
3198
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
3199
+ tokensUsed: Number(row.tokens_used ?? 0),
3200
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
3201
+ nextTask
3202
+ };
3203
+ }
3204
+ async function deleteTask(taskId, baseDir) {
3205
+ const client = getClient();
3206
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
3207
+ const reviewer = assignedBy || "exe";
3208
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
3209
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
3210
+ await client.execute({
3211
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
3212
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
3213
+ });
3214
+ await markAsReadByTaskFile(taskFile);
3215
+ await markAsReadByTaskFile(reviewFile);
3216
+ }
1766
3217
  var init_tasks = __esm({
1767
3218
  "src/lib/tasks.ts"() {
1768
3219
  "use strict";
1769
3220
  init_database();
1770
3221
  init_config();
1771
3222
  init_notifications();
3223
+ init_state_bus();
1772
3224
  init_tasks_crud();
1773
3225
  init_tasks_review();
1774
3226
  init_tasks_crud();