@askexenow/exe-os 0.8.40 → 0.8.42
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.
- package/dist/bin/backfill-conversations.js +805 -642
- package/dist/bin/backfill-responses.js +804 -641
- package/dist/bin/backfill-vectors.js +791 -634
- package/dist/bin/cleanup-stale-review-tasks.js +788 -631
- package/dist/bin/cli.js +1376 -659
- package/dist/bin/exe-agent.js +20 -1
- package/dist/bin/exe-assign.js +1503 -1343
- package/dist/bin/exe-boot.js +2549 -1784
- package/dist/bin/exe-call.js +39 -1
- package/dist/bin/exe-cloud.js +12 -2
- package/dist/bin/exe-dispatch.js +39 -2
- package/dist/bin/exe-doctor.js +791 -634
- package/dist/bin/exe-export-behaviors.js +792 -637
- package/dist/bin/exe-forget.js +145 -0
- package/dist/bin/exe-gateway.js +2501 -1846
- package/dist/bin/exe-heartbeat.js +147 -1
- package/dist/bin/exe-kill.js +795 -640
- package/dist/bin/exe-launch-agent.js +2168 -2008
- package/dist/bin/exe-link.js +44 -12
- package/dist/bin/exe-new-employee.js +6 -2
- package/dist/bin/exe-pending-messages.js +146 -1
- package/dist/bin/exe-pending-notifications.js +788 -631
- package/dist/bin/exe-pending-reviews.js +176 -1
- package/dist/bin/exe-rename.js +23 -0
- package/dist/bin/exe-review.js +490 -327
- package/dist/bin/exe-search.js +157 -4
- package/dist/bin/exe-session-cleanup.js +2487 -403
- package/dist/bin/exe-settings.js +2 -1
- package/dist/bin/exe-status.js +474 -317
- package/dist/bin/exe-team.js +474 -317
- package/dist/bin/git-sweep.js +2691 -151
- package/dist/bin/graph-backfill.js +794 -637
- package/dist/bin/graph-export.js +798 -641
- package/dist/bin/scan-tasks.js +2951 -44
- package/dist/bin/setup.js +50 -26
- package/dist/bin/shard-migrate.js +792 -637
- package/dist/bin/wiki-sync.js +794 -637
- package/dist/gateway/index.js +2542 -1887
- package/dist/hooks/bug-report-worker.js +2118 -576
- package/dist/hooks/commit-complete.js +2690 -150
- package/dist/hooks/error-recall.js +157 -4
- package/dist/hooks/ingest-worker.js +1455 -803
- package/dist/hooks/instructions-loaded.js +151 -0
- package/dist/hooks/notification.js +153 -2
- package/dist/hooks/post-compact.js +164 -0
- package/dist/hooks/pre-compact.js +3073 -101
- package/dist/hooks/pre-tool-use.js +151 -0
- package/dist/hooks/prompt-ingest-worker.js +1670 -1509
- package/dist/hooks/prompt-submit.js +2650 -1074
- package/dist/hooks/response-ingest-worker.js +154 -6
- package/dist/hooks/session-end.js +153 -2
- package/dist/hooks/session-start.js +157 -4
- package/dist/hooks/stop.js +151 -0
- package/dist/hooks/subagent-stop.js +155 -2
- package/dist/hooks/summary-worker.js +190 -21
- package/dist/index.js +326 -102
- package/dist/lib/cloud-sync.js +31 -10
- package/dist/lib/config.js +2 -0
- package/dist/lib/consolidation.js +69 -2
- package/dist/lib/database.js +19 -0
- package/dist/lib/device-registry.js +19 -0
- package/dist/lib/embedder.js +3 -1
- package/dist/lib/employee-templates.js +20 -1
- package/dist/lib/exe-daemon.js +285 -18
- package/dist/lib/hybrid-search.js +157 -4
- package/dist/lib/messaging.js +39 -2
- package/dist/lib/schedules.js +792 -637
- package/dist/lib/store.js +796 -636
- package/dist/lib/tasks.js +1485 -918
- package/dist/lib/tmux-routing.js +194 -10
- package/dist/mcp/server.js +1643 -924
- package/dist/mcp/tools/create-task.js +2283 -829
- package/dist/mcp/tools/list-tasks.js +2788 -159
- package/dist/mcp/tools/send-message.js +39 -2
- package/dist/mcp/tools/update-task.js +79 -0
- package/dist/runtime/index.js +280 -68
- package/dist/tui/App.js +1485 -645
- package/package.json +3 -2
|
@@ -30,6 +30,7 @@ var config_exports = {};
|
|
|
30
30
|
__export(config_exports, {
|
|
31
31
|
CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
|
|
32
32
|
CONFIG_PATH: () => CONFIG_PATH,
|
|
33
|
+
COO_AGENT_NAME: () => COO_AGENT_NAME,
|
|
33
34
|
CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
|
|
34
35
|
DB_PATH: () => DB_PATH,
|
|
35
36
|
EXE_AI_DIR: () => EXE_AI_DIR,
|
|
@@ -185,7 +186,7 @@ async function loadConfigFrom(configPath) {
|
|
|
185
186
|
return { ...DEFAULT_CONFIG };
|
|
186
187
|
}
|
|
187
188
|
}
|
|
188
|
-
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
189
|
+
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, COO_AGENT_NAME, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
189
190
|
var init_config = __esm({
|
|
190
191
|
"src/lib/config.ts"() {
|
|
191
192
|
"use strict";
|
|
@@ -193,6 +194,7 @@ var init_config = __esm({
|
|
|
193
194
|
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
194
195
|
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
195
196
|
CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
|
|
197
|
+
COO_AGENT_NAME = "exe";
|
|
196
198
|
LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
|
|
197
199
|
CURRENT_CONFIG_VERSION = 1;
|
|
198
200
|
DEFAULT_CONFIG = {
|
|
@@ -573,6 +575,13 @@ async function ensureSchema() {
|
|
|
573
575
|
});
|
|
574
576
|
} catch {
|
|
575
577
|
}
|
|
578
|
+
try {
|
|
579
|
+
await client.execute({
|
|
580
|
+
sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
|
|
581
|
+
args: []
|
|
582
|
+
});
|
|
583
|
+
} catch {
|
|
584
|
+
}
|
|
576
585
|
try {
|
|
577
586
|
await client.execute({
|
|
578
587
|
sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
|
|
@@ -1019,6 +1028,18 @@ async function ensureSchema() {
|
|
|
1019
1028
|
CREATE INDEX IF NOT EXISTS idx_session_kills_agent
|
|
1020
1029
|
ON session_kills(agent_id);
|
|
1021
1030
|
`);
|
|
1031
|
+
await client.execute(`
|
|
1032
|
+
CREATE TABLE IF NOT EXISTS global_procedures (
|
|
1033
|
+
id TEXT PRIMARY KEY,
|
|
1034
|
+
title TEXT NOT NULL,
|
|
1035
|
+
content TEXT NOT NULL,
|
|
1036
|
+
priority TEXT NOT NULL DEFAULT 'p0',
|
|
1037
|
+
domain TEXT,
|
|
1038
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1039
|
+
created_at TEXT NOT NULL,
|
|
1040
|
+
updated_at TEXT NOT NULL
|
|
1041
|
+
)
|
|
1042
|
+
`);
|
|
1022
1043
|
await client.executeMultiple(`
|
|
1023
1044
|
CREATE TABLE IF NOT EXISTS conversations (
|
|
1024
1045
|
id TEXT PRIMARY KEY,
|
|
@@ -1226,6 +1247,61 @@ var init_keychain = __esm({
|
|
|
1226
1247
|
}
|
|
1227
1248
|
});
|
|
1228
1249
|
|
|
1250
|
+
// src/lib/state-bus.ts
|
|
1251
|
+
var StateBus, orgBus;
|
|
1252
|
+
var init_state_bus = __esm({
|
|
1253
|
+
"src/lib/state-bus.ts"() {
|
|
1254
|
+
"use strict";
|
|
1255
|
+
StateBus = class {
|
|
1256
|
+
handlers = /* @__PURE__ */ new Map();
|
|
1257
|
+
globalHandlers = /* @__PURE__ */ new Set();
|
|
1258
|
+
/** Emit an event to all subscribers */
|
|
1259
|
+
emit(event) {
|
|
1260
|
+
const typeHandlers = this.handlers.get(event.type);
|
|
1261
|
+
if (typeHandlers) {
|
|
1262
|
+
for (const handler of typeHandlers) {
|
|
1263
|
+
try {
|
|
1264
|
+
handler(event);
|
|
1265
|
+
} catch {
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
for (const handler of this.globalHandlers) {
|
|
1270
|
+
try {
|
|
1271
|
+
handler(event);
|
|
1272
|
+
} catch {
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
/** Subscribe to a specific event type */
|
|
1277
|
+
on(type, handler) {
|
|
1278
|
+
if (!this.handlers.has(type)) {
|
|
1279
|
+
this.handlers.set(type, /* @__PURE__ */ new Set());
|
|
1280
|
+
}
|
|
1281
|
+
this.handlers.get(type).add(handler);
|
|
1282
|
+
}
|
|
1283
|
+
/** Subscribe to ALL events */
|
|
1284
|
+
onAny(handler) {
|
|
1285
|
+
this.globalHandlers.add(handler);
|
|
1286
|
+
}
|
|
1287
|
+
/** Unsubscribe from a specific event type */
|
|
1288
|
+
off(type, handler) {
|
|
1289
|
+
this.handlers.get(type)?.delete(handler);
|
|
1290
|
+
}
|
|
1291
|
+
/** Unsubscribe from ALL events */
|
|
1292
|
+
offAny(handler) {
|
|
1293
|
+
this.globalHandlers.delete(handler);
|
|
1294
|
+
}
|
|
1295
|
+
/** Remove all listeners */
|
|
1296
|
+
clear() {
|
|
1297
|
+
this.handlers.clear();
|
|
1298
|
+
this.globalHandlers.clear();
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
orgBus = new StateBus();
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
|
|
1229
1305
|
// src/lib/shard-manager.ts
|
|
1230
1306
|
var shard_manager_exports = {};
|
|
1231
1307
|
__export(shard_manager_exports, {
|
|
@@ -1467,6 +1543,71 @@ var init_shard_manager = __esm({
|
|
|
1467
1543
|
}
|
|
1468
1544
|
});
|
|
1469
1545
|
|
|
1546
|
+
// src/lib/global-procedures.ts
|
|
1547
|
+
var global_procedures_exports = {};
|
|
1548
|
+
__export(global_procedures_exports, {
|
|
1549
|
+
deactivateGlobalProcedure: () => deactivateGlobalProcedure,
|
|
1550
|
+
getGlobalProceduresBlock: () => getGlobalProceduresBlock,
|
|
1551
|
+
loadGlobalProcedures: () => loadGlobalProcedures,
|
|
1552
|
+
storeGlobalProcedure: () => storeGlobalProcedure
|
|
1553
|
+
});
|
|
1554
|
+
import { randomUUID } from "crypto";
|
|
1555
|
+
async function loadGlobalProcedures() {
|
|
1556
|
+
const client = getClient();
|
|
1557
|
+
const result = await client.execute({
|
|
1558
|
+
sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
|
|
1559
|
+
args: []
|
|
1560
|
+
});
|
|
1561
|
+
const procedures = result.rows;
|
|
1562
|
+
if (procedures.length > 0) {
|
|
1563
|
+
_cache = procedures.map((p) => `### ${p.title}
|
|
1564
|
+
${p.content}`).join("\n\n");
|
|
1565
|
+
} else {
|
|
1566
|
+
_cache = "";
|
|
1567
|
+
}
|
|
1568
|
+
_cacheLoaded = true;
|
|
1569
|
+
return procedures;
|
|
1570
|
+
}
|
|
1571
|
+
function getGlobalProceduresBlock() {
|
|
1572
|
+
if (!_cacheLoaded) return "";
|
|
1573
|
+
if (!_cache) return "";
|
|
1574
|
+
return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
|
|
1575
|
+
|
|
1576
|
+
${_cache}
|
|
1577
|
+
`;
|
|
1578
|
+
}
|
|
1579
|
+
async function storeGlobalProcedure(input2) {
|
|
1580
|
+
const id = randomUUID();
|
|
1581
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1582
|
+
const client = getClient();
|
|
1583
|
+
await client.execute({
|
|
1584
|
+
sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
|
|
1585
|
+
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
1586
|
+
args: [id, input2.title, input2.content, input2.priority ?? "p0", input2.domain ?? null, now, now]
|
|
1587
|
+
});
|
|
1588
|
+
await loadGlobalProcedures();
|
|
1589
|
+
return id;
|
|
1590
|
+
}
|
|
1591
|
+
async function deactivateGlobalProcedure(id) {
|
|
1592
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1593
|
+
const client = getClient();
|
|
1594
|
+
const result = await client.execute({
|
|
1595
|
+
sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
|
|
1596
|
+
args: [now, id]
|
|
1597
|
+
});
|
|
1598
|
+
await loadGlobalProcedures();
|
|
1599
|
+
return result.rowsAffected > 0;
|
|
1600
|
+
}
|
|
1601
|
+
var _cache, _cacheLoaded;
|
|
1602
|
+
var init_global_procedures = __esm({
|
|
1603
|
+
"src/lib/global-procedures.ts"() {
|
|
1604
|
+
"use strict";
|
|
1605
|
+
init_database();
|
|
1606
|
+
_cache = "";
|
|
1607
|
+
_cacheLoaded = false;
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
|
|
1470
1611
|
// src/lib/store.ts
|
|
1471
1612
|
var store_exports = {};
|
|
1472
1613
|
__export(store_exports, {
|
|
@@ -1546,6 +1687,11 @@ async function initStore(options) {
|
|
|
1546
1687
|
"version-query"
|
|
1547
1688
|
);
|
|
1548
1689
|
_nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
1690
|
+
try {
|
|
1691
|
+
const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
|
|
1692
|
+
await loadGlobalProcedures2();
|
|
1693
|
+
} catch {
|
|
1694
|
+
}
|
|
1549
1695
|
}
|
|
1550
1696
|
function classifyTier(record) {
|
|
1551
1697
|
if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
|
|
@@ -1587,6 +1733,12 @@ async function writeMemory(record) {
|
|
|
1587
1733
|
supersedes_id: record.supersedes_id ?? null
|
|
1588
1734
|
};
|
|
1589
1735
|
_pendingRecords.push(dbRow);
|
|
1736
|
+
orgBus.emit({
|
|
1737
|
+
type: "memory_stored",
|
|
1738
|
+
agentId: record.agent_id,
|
|
1739
|
+
project: record.project_name,
|
|
1740
|
+
timestamp: record.timestamp
|
|
1741
|
+
});
|
|
1590
1742
|
const MAX_PENDING = 1e3;
|
|
1591
1743
|
if (_pendingRecords.length > MAX_PENDING) {
|
|
1592
1744
|
const dropped = _pendingRecords.length - MAX_PENDING;
|
|
@@ -1932,6 +2084,7 @@ var init_store = __esm({
|
|
|
1932
2084
|
init_database();
|
|
1933
2085
|
init_keychain();
|
|
1934
2086
|
init_config();
|
|
2087
|
+
init_state_bus();
|
|
1935
2088
|
INIT_MAX_RETRIES = 3;
|
|
1936
2089
|
INIT_RETRY_DELAY_MS = 1e3;
|
|
1937
2090
|
_pendingRecords = [];
|
|
@@ -2035,7 +2188,7 @@ var init_self_query_router = __esm({
|
|
|
2035
2188
|
// src/lib/exe-daemon-client.ts
|
|
2036
2189
|
import net from "net";
|
|
2037
2190
|
import { spawn } from "child_process";
|
|
2038
|
-
import { randomUUID } from "crypto";
|
|
2191
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2039
2192
|
import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
|
|
2040
2193
|
import path4 from "path";
|
|
2041
2194
|
import { fileURLToPath } from "url";
|
|
@@ -2227,7 +2380,7 @@ function sendRequest(texts, priority) {
|
|
|
2227
2380
|
resolve({ error: "Not connected" });
|
|
2228
2381
|
return;
|
|
2229
2382
|
}
|
|
2230
|
-
const id =
|
|
2383
|
+
const id = randomUUID2();
|
|
2231
2384
|
const timer = setTimeout(() => {
|
|
2232
2385
|
_pending.delete(id);
|
|
2233
2386
|
resolve({ error: "Request timeout" });
|
|
@@ -2245,7 +2398,7 @@ function sendRequest(texts, priority) {
|
|
|
2245
2398
|
async function pingDaemon() {
|
|
2246
2399
|
if (!_socket || !_connected) return null;
|
|
2247
2400
|
return new Promise((resolve) => {
|
|
2248
|
-
const id =
|
|
2401
|
+
const id = randomUUID2();
|
|
2249
2402
|
const timer = setTimeout(() => {
|
|
2250
2403
|
_pending.delete(id);
|
|
2251
2404
|
resolve(null);
|
|
@@ -2411,8 +2564,8 @@ async function embedDirect(text) {
|
|
|
2411
2564
|
const llamaCpp = await import("node-llama-cpp");
|
|
2412
2565
|
const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
2413
2566
|
const { existsSync: existsSync17 } = await import("fs");
|
|
2414
|
-
const
|
|
2415
|
-
const modelPath =
|
|
2567
|
+
const path21 = await import("path");
|
|
2568
|
+
const modelPath = path21.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
|
|
2416
2569
|
if (!existsSync17(modelPath)) {
|
|
2417
2570
|
throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
|
|
2418
2571
|
}
|
|
@@ -3126,7 +3279,7 @@ function queueIntercom(targetSession, reason) {
|
|
|
3126
3279
|
}
|
|
3127
3280
|
writeQueue(queue);
|
|
3128
3281
|
}
|
|
3129
|
-
function drainQueue(
|
|
3282
|
+
function drainQueue(isSessionBusy2, sendKeys) {
|
|
3130
3283
|
const queue = readQueue();
|
|
3131
3284
|
if (queue.length === 0) return { drained: 0, failed: 0 };
|
|
3132
3285
|
const remaining = [];
|
|
@@ -3140,7 +3293,7 @@ function drainQueue(isSessionBusy, sendKeys) {
|
|
|
3140
3293
|
continue;
|
|
3141
3294
|
}
|
|
3142
3295
|
try {
|
|
3143
|
-
if (!
|
|
3296
|
+
if (!isSessionBusy2(item.targetSession)) {
|
|
3144
3297
|
const success = sendKeys(item.targetSession);
|
|
3145
3298
|
if (success) {
|
|
3146
3299
|
logQueue(`DRAINED \u2192 ${item.targetSession} (after ${item.attempts} retries)`);
|
|
@@ -3212,21 +3365,36 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
|
3212
3365
|
return [];
|
|
3213
3366
|
}
|
|
3214
3367
|
}
|
|
3368
|
+
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
3369
|
+
if (!existsSync9(employeesPath)) return [];
|
|
3370
|
+
try {
|
|
3371
|
+
return JSON.parse(readFileSync7(employeesPath, "utf-8"));
|
|
3372
|
+
} catch {
|
|
3373
|
+
return [];
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3215
3376
|
function getEmployee(employees, name) {
|
|
3216
3377
|
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
3217
3378
|
}
|
|
3218
|
-
|
|
3379
|
+
function isMultiInstance(agentName, employees) {
|
|
3380
|
+
const roster = employees ?? loadEmployeesSync();
|
|
3381
|
+
const emp = getEmployee(roster, agentName);
|
|
3382
|
+
if (!emp) return false;
|
|
3383
|
+
return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
|
|
3384
|
+
}
|
|
3385
|
+
var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
|
|
3219
3386
|
var init_employees = __esm({
|
|
3220
3387
|
"src/lib/employees.ts"() {
|
|
3221
3388
|
"use strict";
|
|
3222
3389
|
init_config();
|
|
3223
3390
|
EMPLOYEES_PATH = path11.join(EXE_AI_DIR, "exe-employees.json");
|
|
3391
|
+
MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
|
|
3224
3392
|
}
|
|
3225
3393
|
});
|
|
3226
3394
|
|
|
3227
3395
|
// src/lib/license.ts
|
|
3228
3396
|
import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
|
|
3229
|
-
import { randomUUID as
|
|
3397
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
3230
3398
|
import path12 from "path";
|
|
3231
3399
|
import { jwtVerify, importSPKI } from "jose";
|
|
3232
3400
|
var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
|
|
@@ -3325,1258 +3493,2666 @@ var init_plan_limits = __esm({
|
|
|
3325
3493
|
}
|
|
3326
3494
|
});
|
|
3327
3495
|
|
|
3328
|
-
// src/lib/
|
|
3329
|
-
import
|
|
3330
|
-
import { readFileSync as readFileSync10, writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, existsSync as existsSync12, appendFileSync } from "fs";
|
|
3496
|
+
// src/lib/notifications.ts
|
|
3497
|
+
import crypto3 from "crypto";
|
|
3331
3498
|
import path14 from "path";
|
|
3332
3499
|
import os5 from "os";
|
|
3333
|
-
import {
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3500
|
+
import {
|
|
3501
|
+
readFileSync as readFileSync10,
|
|
3502
|
+
readdirSync as readdirSync4,
|
|
3503
|
+
unlinkSync as unlinkSync3,
|
|
3504
|
+
existsSync as existsSync12,
|
|
3505
|
+
rmdirSync
|
|
3506
|
+
} from "fs";
|
|
3507
|
+
async function writeNotification(notification) {
|
|
3339
3508
|
try {
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3509
|
+
const client = getClient();
|
|
3510
|
+
const id = crypto3.randomUUID();
|
|
3511
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3512
|
+
await client.execute({
|
|
3513
|
+
sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
|
|
3514
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
|
|
3515
|
+
args: [
|
|
3516
|
+
id,
|
|
3517
|
+
notification.agentId,
|
|
3518
|
+
notification.agentRole,
|
|
3519
|
+
notification.event,
|
|
3520
|
+
notification.project,
|
|
3521
|
+
notification.summary,
|
|
3522
|
+
notification.taskFile ?? null,
|
|
3523
|
+
now
|
|
3524
|
+
]
|
|
3525
|
+
});
|
|
3526
|
+
} catch (err) {
|
|
3527
|
+
process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
|
|
3528
|
+
`);
|
|
3360
3529
|
}
|
|
3361
|
-
writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
|
|
3362
|
-
return true;
|
|
3363
3530
|
}
|
|
3364
|
-
function
|
|
3531
|
+
async function markAsReadByTaskFile(taskFile) {
|
|
3365
3532
|
try {
|
|
3366
|
-
|
|
3533
|
+
const client = getClient();
|
|
3534
|
+
await client.execute({
|
|
3535
|
+
sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
|
|
3536
|
+
args: [taskFile]
|
|
3537
|
+
});
|
|
3367
3538
|
} catch {
|
|
3368
3539
|
}
|
|
3369
3540
|
}
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
path14.dirname(thisFile),
|
|
3375
|
-
"..",
|
|
3376
|
-
"bin",
|
|
3377
|
-
"exe-export-behaviors.js"
|
|
3378
|
-
);
|
|
3379
|
-
return existsSync12(scriptPath) ? scriptPath : null;
|
|
3380
|
-
} catch {
|
|
3381
|
-
return null;
|
|
3541
|
+
var init_notifications = __esm({
|
|
3542
|
+
"src/lib/notifications.ts"() {
|
|
3543
|
+
"use strict";
|
|
3544
|
+
init_database();
|
|
3382
3545
|
}
|
|
3383
|
-
}
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3546
|
+
});
|
|
3547
|
+
|
|
3548
|
+
// src/lib/session-kill-telemetry.ts
|
|
3549
|
+
import crypto4 from "crypto";
|
|
3550
|
+
async function recordSessionKill(input2) {
|
|
3387
3551
|
try {
|
|
3388
|
-
const
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3552
|
+
const client = getClient();
|
|
3553
|
+
await client.execute({
|
|
3554
|
+
sql: `INSERT INTO session_kills
|
|
3555
|
+
(id, session_name, agent_id, killed_at, reason,
|
|
3556
|
+
ticks_idle, estimated_tokens_saved)
|
|
3557
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
3558
|
+
args: [
|
|
3559
|
+
crypto4.randomUUID(),
|
|
3560
|
+
input2.sessionName,
|
|
3561
|
+
input2.agentId,
|
|
3562
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
3563
|
+
input2.reason,
|
|
3564
|
+
input2.ticksIdle ?? null,
|
|
3565
|
+
input2.estimatedTokensSaved ?? null
|
|
3566
|
+
]
|
|
3567
|
+
});
|
|
3394
3568
|
} catch (err) {
|
|
3395
3569
|
process.stderr.write(
|
|
3396
|
-
`[
|
|
3570
|
+
`[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
|
|
3397
3571
|
`
|
|
3398
3572
|
);
|
|
3399
|
-
return null;
|
|
3400
3573
|
}
|
|
3401
3574
|
}
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
const suffix = instance != null && instance > 0 ? String(instance) : "";
|
|
3407
|
-
return `${employee}${suffix}-${exeSession}`;
|
|
3408
|
-
}
|
|
3409
|
-
function extractRootExe(name) {
|
|
3410
|
-
const match = name.match(/(exe\d+)$/);
|
|
3411
|
-
return match?.[1] ?? null;
|
|
3412
|
-
}
|
|
3413
|
-
function getParentExe(sessionKey) {
|
|
3414
|
-
try {
|
|
3415
|
-
const data = JSON.parse(readFileSync10(path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
3416
|
-
return data.parentExe || null;
|
|
3417
|
-
} catch {
|
|
3418
|
-
return null;
|
|
3575
|
+
var init_session_kill_telemetry = __esm({
|
|
3576
|
+
"src/lib/session-kill-telemetry.ts"() {
|
|
3577
|
+
"use strict";
|
|
3578
|
+
init_database();
|
|
3419
3579
|
}
|
|
3420
|
-
}
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
3429
|
-
|
|
3430
|
-
|
|
3580
|
+
});
|
|
3581
|
+
|
|
3582
|
+
// src/lib/tasks-crud.ts
|
|
3583
|
+
import crypto5 from "crypto";
|
|
3584
|
+
import path15 from "path";
|
|
3585
|
+
import { execSync as execSync7 } from "child_process";
|
|
3586
|
+
import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
|
|
3587
|
+
import { existsSync as existsSync13, readFileSync as readFileSync11 } from "fs";
|
|
3588
|
+
async function writeCheckpoint(input2) {
|
|
3589
|
+
const client = getClient();
|
|
3590
|
+
const row = await resolveTask(client, input2.taskId);
|
|
3591
|
+
const taskId = String(row.id);
|
|
3592
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3593
|
+
const blockedByIds = [];
|
|
3594
|
+
if (row.blocked_by) {
|
|
3595
|
+
blockedByIds.push(String(row.blocked_by));
|
|
3596
|
+
}
|
|
3597
|
+
const checkpoint = {
|
|
3598
|
+
step: input2.step,
|
|
3599
|
+
context_summary: input2.contextSummary,
|
|
3600
|
+
files_touched: input2.filesTouched ?? [],
|
|
3601
|
+
blocked_by_ids: blockedByIds,
|
|
3602
|
+
last_checkpoint_at: now
|
|
3603
|
+
};
|
|
3604
|
+
const result = await client.execute({
|
|
3605
|
+
sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
|
|
3606
|
+
args: [JSON.stringify(checkpoint), now, taskId]
|
|
3607
|
+
});
|
|
3608
|
+
if (result.rowsAffected === 0) {
|
|
3609
|
+
throw new Error(`Checkpoint write failed: task ${taskId} not found`);
|
|
3431
3610
|
}
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3611
|
+
const countResult = await client.execute({
|
|
3612
|
+
sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
|
|
3613
|
+
args: [taskId]
|
|
3614
|
+
});
|
|
3615
|
+
const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
|
|
3616
|
+
return { checkpointCount };
|
|
3436
3617
|
}
|
|
3437
|
-
function
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
}
|
|
3444
|
-
return null;
|
|
3618
|
+
function extractParentFromContext(contextBody) {
|
|
3619
|
+
if (!contextBody) return null;
|
|
3620
|
+
const match = contextBody.match(
|
|
3621
|
+
/Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
|
|
3622
|
+
);
|
|
3623
|
+
return match ? match[1].toLowerCase() : null;
|
|
3445
3624
|
}
|
|
3446
|
-
function
|
|
3447
|
-
|
|
3448
|
-
if (!existsSync12(DEBOUNCE_FILE)) return {};
|
|
3449
|
-
return JSON.parse(readFileSync10(DEBOUNCE_FILE, "utf8"));
|
|
3450
|
-
} catch {
|
|
3451
|
-
return {};
|
|
3452
|
-
}
|
|
3625
|
+
function slugify(title) {
|
|
3626
|
+
return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
3453
3627
|
}
|
|
3454
|
-
function
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
}
|
|
3628
|
+
async function resolveTask(client, identifier) {
|
|
3629
|
+
let result = await client.execute({
|
|
3630
|
+
sql: "SELECT * FROM tasks WHERE id = ?",
|
|
3631
|
+
args: [identifier]
|
|
3632
|
+
});
|
|
3633
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
3634
|
+
result = await client.execute({
|
|
3635
|
+
sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
|
|
3636
|
+
args: [`%${identifier}%`]
|
|
3637
|
+
});
|
|
3638
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
3639
|
+
if (result.rows.length > 1) {
|
|
3640
|
+
const exact = result.rows.filter(
|
|
3641
|
+
(r) => String(r.task_file).endsWith(`/${identifier}.md`)
|
|
3642
|
+
);
|
|
3643
|
+
if (exact.length === 1) return exact[0];
|
|
3644
|
+
const candidates = exact.length > 1 ? exact : result.rows;
|
|
3645
|
+
const active = candidates.filter(
|
|
3646
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
3647
|
+
);
|
|
3648
|
+
if (active.length === 1) return active[0];
|
|
3649
|
+
const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
3650
|
+
throw new Error(
|
|
3651
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
3652
|
+
);
|
|
3459
3653
|
}
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3654
|
+
result = await client.execute({
|
|
3655
|
+
sql: "SELECT * FROM tasks WHERE title LIKE ?",
|
|
3656
|
+
args: [`%${identifier}%`]
|
|
3657
|
+
});
|
|
3658
|
+
if (result.rows.length === 1) return result.rows[0];
|
|
3659
|
+
if (result.rows.length > 1) {
|
|
3660
|
+
const active = result.rows.filter(
|
|
3661
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
3662
|
+
);
|
|
3663
|
+
if (active.length === 1) return active[0];
|
|
3664
|
+
const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
3665
|
+
throw new Error(
|
|
3666
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
3667
|
+
);
|
|
3472
3668
|
}
|
|
3473
|
-
|
|
3669
|
+
throw new Error(`Task not found: ${identifier}`);
|
|
3474
3670
|
}
|
|
3475
|
-
function
|
|
3476
|
-
const
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3671
|
+
async function createTaskCore(input2) {
|
|
3672
|
+
const client = getClient();
|
|
3673
|
+
const id = crypto5.randomUUID();
|
|
3674
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3675
|
+
const slug = slugify(input2.title);
|
|
3676
|
+
const taskFile = input2.taskFile ?? `exe/${input2.assignedTo}/${slug}.md`;
|
|
3677
|
+
let blockedById = null;
|
|
3678
|
+
const initialStatus = input2.blockedBy ? "blocked" : "open";
|
|
3679
|
+
if (input2.blockedBy) {
|
|
3680
|
+
const blocker = await resolveTask(client, input2.blockedBy);
|
|
3681
|
+
blockedById = String(blocker.id);
|
|
3483
3682
|
}
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3683
|
+
let parentTaskId = null;
|
|
3684
|
+
let parentRef = input2.parentTaskId;
|
|
3685
|
+
if (!parentRef) {
|
|
3686
|
+
const extracted = extractParentFromContext(input2.context);
|
|
3687
|
+
if (extracted) {
|
|
3688
|
+
parentRef = extracted;
|
|
3689
|
+
process.stderr.write(
|
|
3690
|
+
"[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
|
|
3691
|
+
);
|
|
3692
|
+
}
|
|
3693
|
+
}
|
|
3694
|
+
if (parentRef) {
|
|
3695
|
+
try {
|
|
3696
|
+
const parent = await resolveTask(client, parentRef);
|
|
3697
|
+
parentTaskId = String(parent.id);
|
|
3698
|
+
} catch (err) {
|
|
3699
|
+
if (!input2.parentTaskId) {
|
|
3700
|
+
throw new Error(
|
|
3701
|
+
`create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
|
|
3702
|
+
);
|
|
3493
3703
|
}
|
|
3704
|
+
throw err;
|
|
3494
3705
|
}
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3706
|
+
}
|
|
3707
|
+
let warning;
|
|
3708
|
+
const dupCheck = await client.execute({
|
|
3709
|
+
sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
|
|
3710
|
+
args: [input2.title, input2.assignedTo]
|
|
3711
|
+
});
|
|
3712
|
+
if (dupCheck.rows.length > 0) {
|
|
3713
|
+
warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
|
|
3714
|
+
}
|
|
3715
|
+
if (input2.baseDir) {
|
|
3716
|
+
try {
|
|
3717
|
+
await mkdir4(path15.join(input2.baseDir, "exe", "output"), { recursive: true });
|
|
3718
|
+
await mkdir4(path15.join(input2.baseDir, "exe", "research"), { recursive: true });
|
|
3719
|
+
await ensureArchitectureDoc(input2.baseDir, input2.projectName);
|
|
3720
|
+
await ensureGitignoreExe(input2.baseDir);
|
|
3721
|
+
} catch {
|
|
3722
|
+
}
|
|
3723
|
+
}
|
|
3724
|
+
const complexity = input2.complexity ?? "standard";
|
|
3725
|
+
let sessionScope = null;
|
|
3726
|
+
try {
|
|
3727
|
+
const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
|
|
3728
|
+
sessionScope = resolveExeSession2();
|
|
3498
3729
|
} catch {
|
|
3499
|
-
return "offline";
|
|
3500
3730
|
}
|
|
3731
|
+
await client.execute({
|
|
3732
|
+
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)
|
|
3733
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
3734
|
+
args: [
|
|
3735
|
+
id,
|
|
3736
|
+
input2.title,
|
|
3737
|
+
input2.assignedTo,
|
|
3738
|
+
input2.assignedBy,
|
|
3739
|
+
input2.projectName,
|
|
3740
|
+
input2.priority,
|
|
3741
|
+
initialStatus,
|
|
3742
|
+
taskFile,
|
|
3743
|
+
blockedById,
|
|
3744
|
+
parentTaskId,
|
|
3745
|
+
input2.reviewer ?? null,
|
|
3746
|
+
input2.context,
|
|
3747
|
+
complexity,
|
|
3748
|
+
input2.budgetTokens ?? null,
|
|
3749
|
+
input2.budgetFallbackModel ?? null,
|
|
3750
|
+
0,
|
|
3751
|
+
null,
|
|
3752
|
+
sessionScope,
|
|
3753
|
+
now,
|
|
3754
|
+
now
|
|
3755
|
+
]
|
|
3756
|
+
});
|
|
3757
|
+
return {
|
|
3758
|
+
id,
|
|
3759
|
+
title: input2.title,
|
|
3760
|
+
assignedTo: input2.assignedTo,
|
|
3761
|
+
assignedBy: input2.assignedBy,
|
|
3762
|
+
projectName: input2.projectName,
|
|
3763
|
+
priority: input2.priority,
|
|
3764
|
+
status: initialStatus,
|
|
3765
|
+
taskFile,
|
|
3766
|
+
createdAt: now,
|
|
3767
|
+
updatedAt: now,
|
|
3768
|
+
warning,
|
|
3769
|
+
budgetTokens: input2.budgetTokens ?? null,
|
|
3770
|
+
budgetFallbackModel: input2.budgetFallbackModel ?? null,
|
|
3771
|
+
tokensUsed: 0,
|
|
3772
|
+
tokensWarnedAt: null
|
|
3773
|
+
};
|
|
3501
3774
|
}
|
|
3502
|
-
function
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
return "skipped_exe";
|
|
3775
|
+
async function listTasks(input2) {
|
|
3776
|
+
const client = getClient();
|
|
3777
|
+
const conditions = [];
|
|
3778
|
+
const args = [];
|
|
3779
|
+
if (input2.assignedTo) {
|
|
3780
|
+
conditions.push("assigned_to = ?");
|
|
3781
|
+
args.push(input2.assignedTo);
|
|
3510
3782
|
}
|
|
3511
|
-
if (
|
|
3512
|
-
|
|
3513
|
-
|
|
3783
|
+
if (input2.status) {
|
|
3784
|
+
conditions.push("status = ?");
|
|
3785
|
+
args.push(input2.status);
|
|
3786
|
+
} else {
|
|
3787
|
+
conditions.push("status IN ('open', 'in_progress', 'blocked')");
|
|
3788
|
+
}
|
|
3789
|
+
if (input2.projectName) {
|
|
3790
|
+
conditions.push("project_name = ?");
|
|
3791
|
+
args.push(input2.projectName);
|
|
3792
|
+
}
|
|
3793
|
+
if (input2.priority) {
|
|
3794
|
+
conditions.push("priority = ?");
|
|
3795
|
+
args.push(input2.priority);
|
|
3514
3796
|
}
|
|
3515
3797
|
try {
|
|
3516
|
-
const
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
const sessionState = getSessionState(targetSession);
|
|
3522
|
-
if (sessionState === "no_claude") {
|
|
3523
|
-
queueIntercom(targetSession, "claude not running in session");
|
|
3524
|
-
recordDebounce(targetSession);
|
|
3525
|
-
logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
|
|
3526
|
-
return "queued";
|
|
3527
|
-
}
|
|
3528
|
-
if (sessionState === "thinking" || sessionState === "tool") {
|
|
3529
|
-
queueIntercom(targetSession, "session busy at send time");
|
|
3530
|
-
recordDebounce(targetSession);
|
|
3531
|
-
logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
|
|
3532
|
-
return "queued";
|
|
3533
|
-
}
|
|
3534
|
-
if (transport.isPaneInCopyMode(targetSession)) {
|
|
3535
|
-
logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
|
|
3536
|
-
transport.sendKeys(targetSession, "q");
|
|
3798
|
+
const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
|
|
3799
|
+
const session = resolveExeSession2();
|
|
3800
|
+
if (session) {
|
|
3801
|
+
conditions.push("(session_scope IS NULL OR session_scope = ?)");
|
|
3802
|
+
args.push(session);
|
|
3537
3803
|
}
|
|
3538
|
-
transport.sendKeys(targetSession, "/exe-intercom");
|
|
3539
|
-
recordDebounce(targetSession);
|
|
3540
|
-
logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
|
|
3541
|
-
return "delivered";
|
|
3542
3804
|
} catch {
|
|
3543
|
-
logIntercom(`FAIL \u2192 ${targetSession}`);
|
|
3544
|
-
return "failed";
|
|
3545
3805
|
}
|
|
3806
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
3807
|
+
const result = await client.execute({
|
|
3808
|
+
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`,
|
|
3809
|
+
args
|
|
3810
|
+
});
|
|
3811
|
+
return result.rows.map((r) => ({
|
|
3812
|
+
id: String(r.id),
|
|
3813
|
+
title: String(r.title),
|
|
3814
|
+
assignedTo: String(r.assigned_to),
|
|
3815
|
+
assignedBy: String(r.assigned_by),
|
|
3816
|
+
projectName: String(r.project_name),
|
|
3817
|
+
priority: String(r.priority),
|
|
3818
|
+
status: String(r.status),
|
|
3819
|
+
taskFile: String(r.task_file),
|
|
3820
|
+
createdAt: String(r.created_at),
|
|
3821
|
+
updatedAt: String(r.updated_at),
|
|
3822
|
+
checkpointCount: Number(r.checkpoint_count ?? 0),
|
|
3823
|
+
budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
|
|
3824
|
+
budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
|
|
3825
|
+
tokensUsed: Number(r.tokens_used ?? 0),
|
|
3826
|
+
tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
|
|
3827
|
+
}));
|
|
3546
3828
|
}
|
|
3547
|
-
function
|
|
3548
|
-
if (
|
|
3549
|
-
|
|
3550
|
-
}
|
|
3829
|
+
function checkStaleCompletion(taskContext, taskCreatedAt) {
|
|
3830
|
+
if (!taskContext) return null;
|
|
3831
|
+
if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
|
|
3551
3832
|
try {
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3833
|
+
const since = new Date(taskCreatedAt).toISOString();
|
|
3834
|
+
const branch = execSync7(
|
|
3835
|
+
"git rev-parse --abbrev-ref HEAD 2>/dev/null",
|
|
3836
|
+
{ encoding: "utf8", timeout: 3e3 }
|
|
3837
|
+
).trim();
|
|
3838
|
+
const branchArg = branch && branch !== "HEAD" ? branch : "";
|
|
3839
|
+
const commitCount = execSync7(
|
|
3840
|
+
`git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
|
|
3841
|
+
{ encoding: "utf8", timeout: 5e3 }
|
|
3842
|
+
).trim();
|
|
3843
|
+
const count = parseInt(commitCount, 10);
|
|
3844
|
+
if (count === 0) {
|
|
3845
|
+
return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
|
|
3556
3846
|
}
|
|
3847
|
+
return null;
|
|
3848
|
+
} catch {
|
|
3849
|
+
return null;
|
|
3557
3850
|
}
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
employeeName,
|
|
3570
|
-
exeSession,
|
|
3571
|
-
opts.maxAutoInstances ?? 10
|
|
3851
|
+
}
|
|
3852
|
+
async function updateTaskStatus(input2) {
|
|
3853
|
+
const client = getClient();
|
|
3854
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3855
|
+
const row = await resolveTask(client, input2.taskId);
|
|
3856
|
+
const taskId = String(row.id);
|
|
3857
|
+
const taskFile = String(row.task_file);
|
|
3858
|
+
if (input2.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
|
|
3859
|
+
process.stderr.write(
|
|
3860
|
+
`[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
|
|
3861
|
+
`
|
|
3572
3862
|
);
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3863
|
+
}
|
|
3864
|
+
if (input2.status === "done") {
|
|
3865
|
+
const existingRow = await client.execute({
|
|
3866
|
+
sql: "SELECT context, created_at FROM tasks WHERE id = ?",
|
|
3867
|
+
args: [taskId]
|
|
3868
|
+
});
|
|
3869
|
+
if (existingRow.rows.length > 0) {
|
|
3870
|
+
const ctx = existingRow.rows[0];
|
|
3871
|
+
const warning = checkStaleCompletion(ctx.context, ctx.created_at);
|
|
3872
|
+
if (warning) {
|
|
3873
|
+
input2.result = input2.result ? `\u26A0\uFE0F ${warning}
|
|
3874
|
+
|
|
3875
|
+
${input2.result}` : `\u26A0\uFE0F ${warning}`;
|
|
3876
|
+
process.stderr.write(`[tasks] ${warning} (task: ${taskId})
|
|
3877
|
+
`);
|
|
3878
|
+
}
|
|
3579
3879
|
}
|
|
3580
|
-
effectiveInstance = free === 0 ? void 0 : free;
|
|
3581
3880
|
}
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
const
|
|
3585
|
-
|
|
3586
|
-
|
|
3881
|
+
if (input2.status === "in_progress") {
|
|
3882
|
+
const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
|
|
3883
|
+
const claim = await client.execute({
|
|
3884
|
+
sql: `UPDATE tasks
|
|
3885
|
+
SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
|
|
3886
|
+
WHERE id = ? AND status = 'open'`,
|
|
3887
|
+
args: [tmuxSession, now, taskId]
|
|
3888
|
+
});
|
|
3889
|
+
if (claim.rowsAffected === 0) {
|
|
3890
|
+
const current = await client.execute({
|
|
3891
|
+
sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
|
|
3892
|
+
args: [taskId]
|
|
3893
|
+
});
|
|
3894
|
+
const cur = current.rows[0];
|
|
3895
|
+
const status = cur?.status ?? "unknown";
|
|
3896
|
+
const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
|
|
3897
|
+
throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
|
|
3587
3898
|
}
|
|
3588
|
-
|
|
3589
|
-
|
|
3899
|
+
try {
|
|
3900
|
+
await writeCheckpoint({
|
|
3901
|
+
taskId,
|
|
3902
|
+
step: "claimed",
|
|
3903
|
+
contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
|
|
3904
|
+
});
|
|
3905
|
+
} catch {
|
|
3590
3906
|
}
|
|
3591
|
-
return {
|
|
3592
|
-
}
|
|
3593
|
-
const spawnOpts = { ...opts, instance: effectiveInstance };
|
|
3594
|
-
const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
|
|
3595
|
-
if (result.error) {
|
|
3596
|
-
return { status: "failed", sessionName, error: result.error };
|
|
3907
|
+
return { row, taskFile, now, taskId };
|
|
3597
3908
|
}
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
3607
|
-
|
|
3909
|
+
if (input2.result) {
|
|
3910
|
+
await client.execute({
|
|
3911
|
+
sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
|
|
3912
|
+
args: [input2.status, input2.result, now, taskId]
|
|
3913
|
+
});
|
|
3914
|
+
} else {
|
|
3915
|
+
await client.execute({
|
|
3916
|
+
sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
|
|
3917
|
+
args: [input2.status, now, taskId]
|
|
3918
|
+
});
|
|
3608
3919
|
}
|
|
3609
|
-
transport.kill(sessionName);
|
|
3610
|
-
let cleanupSuffix = "";
|
|
3611
3920
|
try {
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
}
|
|
3921
|
+
await writeCheckpoint({
|
|
3922
|
+
taskId,
|
|
3923
|
+
step: `status_transition:${input2.status}`,
|
|
3924
|
+
contextSummary: input2.result ? `Transitioned to ${input2.status}. Result: ${input2.result.slice(0, 500)}` : `Transitioned to ${input2.status}.`
|
|
3925
|
+
});
|
|
3617
3926
|
} catch {
|
|
3618
3927
|
}
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
|
|
3928
|
+
return { row, taskFile, now, taskId };
|
|
3929
|
+
}
|
|
3930
|
+
async function deleteTaskCore(taskId, _baseDir) {
|
|
3931
|
+
const client = getClient();
|
|
3932
|
+
const row = await resolveTask(client, taskId);
|
|
3933
|
+
const id = String(row.id);
|
|
3934
|
+
const taskFile = String(row.task_file);
|
|
3935
|
+
const assignedTo = String(row.assigned_to);
|
|
3936
|
+
const assignedBy = String(row.assigned_by);
|
|
3937
|
+
await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
|
|
3938
|
+
const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
|
|
3939
|
+
return { taskFile, assignedTo, assignedBy, taskSlug };
|
|
3940
|
+
}
|
|
3941
|
+
async function ensureArchitectureDoc(baseDir, projectName) {
|
|
3942
|
+
const archPath = path15.join(baseDir, "exe", "ARCHITECTURE.md");
|
|
3943
|
+
try {
|
|
3944
|
+
if (existsSync13(archPath)) return;
|
|
3945
|
+
const template = [
|
|
3946
|
+
`# ${projectName} \u2014 System Architecture`,
|
|
3947
|
+
"",
|
|
3948
|
+
"> Employees: read this before every task. Update it when you change system structure.",
|
|
3949
|
+
`> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
3950
|
+
"",
|
|
3951
|
+
"## Overview",
|
|
3952
|
+
"",
|
|
3953
|
+
"<!-- Describe what this system does, its main components, and how they connect. -->",
|
|
3954
|
+
"",
|
|
3955
|
+
"## Key Components",
|
|
3956
|
+
"",
|
|
3957
|
+
"<!-- List the major modules, services, or subsystems. -->",
|
|
3958
|
+
"",
|
|
3959
|
+
"## Data Flow",
|
|
3960
|
+
"",
|
|
3961
|
+
"<!-- How does data move through the system? What writes where? -->",
|
|
3962
|
+
"",
|
|
3963
|
+
"## Invariants",
|
|
3964
|
+
"",
|
|
3965
|
+
"<!-- Rules that must never be violated. What breaks if these are wrong? -->",
|
|
3966
|
+
"",
|
|
3967
|
+
"## Dependencies",
|
|
3968
|
+
"",
|
|
3969
|
+
"<!-- What depends on what? If I change X, what else is affected? -->",
|
|
3970
|
+
""
|
|
3971
|
+
].join("\n");
|
|
3972
|
+
await writeFile4(archPath, template, "utf-8");
|
|
3632
3973
|
} catch {
|
|
3633
3974
|
}
|
|
3975
|
+
}
|
|
3976
|
+
async function ensureGitignoreExe(baseDir) {
|
|
3977
|
+
const gitignorePath = path15.join(baseDir, ".gitignore");
|
|
3634
3978
|
try {
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
settings = JSON.parse(readFileSync10(settingsPath, "utf8"));
|
|
3642
|
-
} catch {
|
|
3643
|
-
}
|
|
3644
|
-
const perms = settings.permissions ?? {};
|
|
3645
|
-
const allow = perms.allow ?? [];
|
|
3646
|
-
const toolNames = [
|
|
3647
|
-
"recall_my_memory",
|
|
3648
|
-
"store_memory",
|
|
3649
|
-
"create_task",
|
|
3650
|
-
"update_task",
|
|
3651
|
-
"list_tasks",
|
|
3652
|
-
"get_task",
|
|
3653
|
-
"ask_team_memory",
|
|
3654
|
-
"store_behavior",
|
|
3655
|
-
"get_identity",
|
|
3656
|
-
"send_message"
|
|
3657
|
-
];
|
|
3658
|
-
const requiredTools = expandDualPrefixTools(toolNames);
|
|
3659
|
-
let changed = false;
|
|
3660
|
-
for (const tool of requiredTools) {
|
|
3661
|
-
if (!allow.includes(tool)) {
|
|
3662
|
-
allow.push(tool);
|
|
3663
|
-
changed = true;
|
|
3664
|
-
}
|
|
3665
|
-
}
|
|
3666
|
-
if (changed) {
|
|
3667
|
-
perms.allow = allow;
|
|
3668
|
-
settings.permissions = perms;
|
|
3669
|
-
mkdirSync6(projSettingsDir, { recursive: true });
|
|
3670
|
-
writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
3979
|
+
if (existsSync13(gitignorePath)) {
|
|
3980
|
+
const content = readFileSync11(gitignorePath, "utf-8");
|
|
3981
|
+
if (/^\/?exe\/?$/m.test(content)) return;
|
|
3982
|
+
await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
|
|
3983
|
+
} else {
|
|
3984
|
+
await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
|
|
3671
3985
|
}
|
|
3672
3986
|
} catch {
|
|
3673
3987
|
}
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
const identityPath = path14.join(
|
|
3683
|
-
os5.homedir(),
|
|
3684
|
-
".exe-os",
|
|
3685
|
-
"identity",
|
|
3686
|
-
`${employeeName}.md`
|
|
3687
|
-
);
|
|
3688
|
-
_resetCcAgentSupportCache();
|
|
3689
|
-
const hasAgentFlag = claudeSupportsAgentFlag();
|
|
3690
|
-
if (hasAgentFlag) {
|
|
3691
|
-
identityFlag = ` --agent ${employeeName}`;
|
|
3692
|
-
} else if (existsSync12(identityPath)) {
|
|
3693
|
-
identityFlag = ` --append-system-prompt-file ${identityPath}`;
|
|
3694
|
-
legacyFallbackWarned = true;
|
|
3695
|
-
}
|
|
3696
|
-
const behaviorsFile = exportBehaviorsSync(
|
|
3697
|
-
employeeName,
|
|
3698
|
-
path14.basename(spawnCwd),
|
|
3699
|
-
sessionName
|
|
3700
|
-
);
|
|
3701
|
-
if (behaviorsFile) {
|
|
3702
|
-
behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
|
|
3703
|
-
}
|
|
3988
|
+
}
|
|
3989
|
+
var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
|
|
3990
|
+
var init_tasks_crud = __esm({
|
|
3991
|
+
"src/lib/tasks-crud.ts"() {
|
|
3992
|
+
"use strict";
|
|
3993
|
+
init_database();
|
|
3994
|
+
DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
|
|
3995
|
+
TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
|
|
3704
3996
|
}
|
|
3705
|
-
|
|
3997
|
+
});
|
|
3998
|
+
|
|
3999
|
+
// src/lib/tasks-review.ts
|
|
4000
|
+
var tasks_review_exports = {};
|
|
4001
|
+
__export(tasks_review_exports, {
|
|
4002
|
+
cleanupOrphanedReviews: () => cleanupOrphanedReviews,
|
|
4003
|
+
cleanupReviewFile: () => cleanupReviewFile,
|
|
4004
|
+
countNewPendingReviewsSince: () => countNewPendingReviewsSince,
|
|
4005
|
+
countPendingReviews: () => countPendingReviews,
|
|
4006
|
+
createReviewForCompletedTask: () => createReviewForCompletedTask,
|
|
4007
|
+
getReviewChecklist: () => getReviewChecklist,
|
|
4008
|
+
listPendingReviews: () => listPendingReviews
|
|
4009
|
+
});
|
|
4010
|
+
import path16 from "path";
|
|
4011
|
+
import { existsSync as existsSync14, readdirSync as readdirSync5, unlinkSync as unlinkSync4 } from "fs";
|
|
4012
|
+
async function countPendingReviews() {
|
|
4013
|
+
const client = getClient();
|
|
4014
|
+
const result = await client.execute({
|
|
4015
|
+
sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
|
|
4016
|
+
args: []
|
|
4017
|
+
});
|
|
4018
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
4019
|
+
}
|
|
4020
|
+
async function countNewPendingReviewsSince(sinceIso) {
|
|
4021
|
+
const client = getClient();
|
|
4022
|
+
const result = await client.execute({
|
|
4023
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
4024
|
+
WHERE status = 'needs_review' AND updated_at > ?`,
|
|
4025
|
+
args: [sinceIso]
|
|
4026
|
+
});
|
|
4027
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
4028
|
+
}
|
|
4029
|
+
async function listPendingReviews(limit) {
|
|
4030
|
+
const client = getClient();
|
|
4031
|
+
const result = await client.execute({
|
|
4032
|
+
sql: `SELECT title, assigned_to, project_name FROM tasks
|
|
4033
|
+
WHERE status = 'needs_review'
|
|
4034
|
+
ORDER BY priority ASC, created_at DESC LIMIT ?`,
|
|
4035
|
+
args: [limit]
|
|
4036
|
+
});
|
|
4037
|
+
return result.rows;
|
|
4038
|
+
}
|
|
4039
|
+
async function cleanupOrphanedReviews() {
|
|
4040
|
+
const client = getClient();
|
|
4041
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4042
|
+
const r1 = await client.execute({
|
|
4043
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
4044
|
+
WHERE status = 'needs_review'
|
|
4045
|
+
AND assigned_by = 'system'
|
|
4046
|
+
AND title LIKE 'Review:%'
|
|
4047
|
+
AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
|
|
4048
|
+
args: [now]
|
|
4049
|
+
});
|
|
4050
|
+
const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
|
|
4051
|
+
const r2 = await client.execute({
|
|
4052
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
4053
|
+
WHERE status = 'needs_review'
|
|
4054
|
+
AND result IS NOT NULL
|
|
4055
|
+
AND updated_at < ?`,
|
|
4056
|
+
args: [now, staleThreshold]
|
|
4057
|
+
});
|
|
4058
|
+
const total = r1.rowsAffected + r2.rowsAffected;
|
|
4059
|
+
if (total > 0) {
|
|
3706
4060
|
process.stderr.write(
|
|
3707
|
-
`[
|
|
4061
|
+
`[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
|
|
3708
4062
|
`
|
|
3709
4063
|
);
|
|
3710
4064
|
}
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
}
|
|
3726
|
-
let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
|
|
3727
|
-
if (ccProvider !== DEFAULT_PROVIDER) {
|
|
3728
|
-
const cfg = PROVIDER_TABLE[ccProvider];
|
|
3729
|
-
if (cfg?.apiKeyEnv) {
|
|
3730
|
-
const keyVal = process.env[cfg.apiKeyEnv];
|
|
3731
|
-
if (keyVal) {
|
|
3732
|
-
envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
|
|
3733
|
-
}
|
|
3734
|
-
}
|
|
4065
|
+
return total;
|
|
4066
|
+
}
|
|
4067
|
+
function getReviewChecklist(role, agent, taskSlug) {
|
|
4068
|
+
const roleLower = role.toLowerCase();
|
|
4069
|
+
if (roleLower.includes("engineer") || roleLower === "principal engineer") {
|
|
4070
|
+
return {
|
|
4071
|
+
lens: "Code Quality (Engineer)",
|
|
4072
|
+
checklist: [
|
|
4073
|
+
"1. Do all tests pass? Any new tests needed?",
|
|
4074
|
+
"2. Is the code clean \u2014 no dead code, no TODOs left?",
|
|
4075
|
+
"3. Does it follow existing patterns and conventions in the codebase?",
|
|
4076
|
+
"4. Any regressions in the test suite?"
|
|
4077
|
+
]
|
|
4078
|
+
};
|
|
3735
4079
|
}
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
4080
|
+
if (roleLower === "cto" || roleLower.includes("architect")) {
|
|
4081
|
+
return {
|
|
4082
|
+
lens: "Architecture (CTO)",
|
|
4083
|
+
checklist: [
|
|
4084
|
+
"1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
|
|
4085
|
+
"2. Is it backward compatible? Any breaking changes?",
|
|
4086
|
+
"3. Does it introduce technical debt? Is that debt justified?",
|
|
4087
|
+
"4. Security implications? Any new attack surface?",
|
|
4088
|
+
"5. Does it scale? Performance considerations?",
|
|
4089
|
+
"6. Coordination: does this affect other employees' work or other projects?"
|
|
4090
|
+
]
|
|
4091
|
+
};
|
|
3748
4092
|
}
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
4093
|
+
if (roleLower === "coo" || roleLower.includes("operations")) {
|
|
4094
|
+
return {
|
|
4095
|
+
lens: "Strategic (COO)",
|
|
4096
|
+
checklist: [
|
|
4097
|
+
"1. Does this serve the project mission?",
|
|
4098
|
+
"2. Is this the right work at the right time?",
|
|
4099
|
+
"3. Does the architectural assessment make sense for the business?",
|
|
4100
|
+
"4. Any cross-project implications?"
|
|
4101
|
+
]
|
|
4102
|
+
};
|
|
3756
4103
|
}
|
|
3757
|
-
|
|
4104
|
+
return {
|
|
4105
|
+
lens: "General",
|
|
4106
|
+
checklist: [
|
|
4107
|
+
"1. Read the original task's acceptance criteria",
|
|
4108
|
+
`2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
|
|
4109
|
+
"3. Verify code changes match requirements",
|
|
4110
|
+
"4. Check if tests were added/updated",
|
|
4111
|
+
`5. Look for output files in exe/output/${agent}-${taskSlug}*`
|
|
4112
|
+
]
|
|
4113
|
+
};
|
|
4114
|
+
}
|
|
4115
|
+
async function createReviewForCompletedTask(row, result, _baseDir, now) {
|
|
4116
|
+
const taskFile = String(row.task_file);
|
|
4117
|
+
if (String(row.assigned_to) === "exe") return;
|
|
4118
|
+
if (String(row.title).startsWith("Review:")) return;
|
|
4119
|
+
const fileName = taskFile.split("/").pop() ?? "";
|
|
4120
|
+
if (fileName.startsWith("review-") && String(row.assigned_by) === "system") return;
|
|
4121
|
+
if (fileName.startsWith("review-") && String(row.assigned_to) === "system") return;
|
|
4122
|
+
const client = getClient();
|
|
4123
|
+
const agent = String(row.assigned_to);
|
|
4124
|
+
const reviewer = String(row.reviewer || row.assigned_by) || "exe";
|
|
4125
|
+
let reviewerRole = "unknown";
|
|
3758
4126
|
try {
|
|
3759
|
-
const
|
|
3760
|
-
const
|
|
3761
|
-
|
|
3762
|
-
dispatchedBy: mySession,
|
|
3763
|
-
rootExe: exeSession,
|
|
3764
|
-
provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
|
|
3765
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3766
|
-
}));
|
|
4127
|
+
const employees = await loadEmployees();
|
|
4128
|
+
const emp = getEmployee(employees, reviewer);
|
|
4129
|
+
if (emp) reviewerRole = emp.role;
|
|
3767
4130
|
} catch {
|
|
3768
4131
|
}
|
|
3769
|
-
|
|
3770
|
-
|
|
4132
|
+
const taskTitle = String(row.title);
|
|
4133
|
+
const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "unknown";
|
|
4134
|
+
const { lens, checklist } = getReviewChecklist(reviewerRole, agent, taskSlug);
|
|
4135
|
+
const reviewSlug = `review-${agent}-${taskSlug}`;
|
|
4136
|
+
const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
|
|
4137
|
+
await client.execute({
|
|
4138
|
+
sql: "DELETE FROM tasks WHERE task_file = ?",
|
|
4139
|
+
args: [reviewFile]
|
|
4140
|
+
});
|
|
4141
|
+
process.stderr.write(
|
|
4142
|
+
`[review] Creating review for "${taskTitle}" \u2192 assigned to ${reviewer} (${reviewerRole})
|
|
4143
|
+
`
|
|
4144
|
+
);
|
|
4145
|
+
const reviewContext = [
|
|
4146
|
+
`${agent} marked this task as done:`,
|
|
4147
|
+
`- Original task: ${taskFile}`,
|
|
4148
|
+
`- Result: ${result ?? "No result summary provided"}`,
|
|
4149
|
+
"",
|
|
4150
|
+
`## Review lens: ${lens}`,
|
|
4151
|
+
`You are reviewing as **${reviewer}** (${reviewerRole}).`,
|
|
4152
|
+
"",
|
|
4153
|
+
"## Review checklist",
|
|
4154
|
+
...checklist,
|
|
4155
|
+
"",
|
|
4156
|
+
"## Verdict",
|
|
4157
|
+
"After review, update this task:",
|
|
4158
|
+
"- **Approved:** mark this review task as done",
|
|
4159
|
+
"- **Needs work:** re-open the original task with notes, mark this review as done"
|
|
4160
|
+
].join("\n");
|
|
4161
|
+
const originalTaskId = String(row.id);
|
|
4162
|
+
const reviewTask = await createTaskCore({
|
|
4163
|
+
title: `Review: ${agent} completed "${taskTitle}"`,
|
|
4164
|
+
assignedTo: reviewer,
|
|
4165
|
+
assignedBy: "system",
|
|
4166
|
+
projectName: String(row.project_name),
|
|
4167
|
+
priority: "p1",
|
|
4168
|
+
context: reviewContext,
|
|
4169
|
+
taskFile: reviewFile,
|
|
4170
|
+
parentTaskId: originalTaskId,
|
|
4171
|
+
skipDispatch: true
|
|
4172
|
+
});
|
|
4173
|
+
const reviewId = reviewTask.id;
|
|
4174
|
+
orgBus.emit({
|
|
4175
|
+
type: "review_created",
|
|
4176
|
+
reviewId,
|
|
4177
|
+
employee: agent,
|
|
4178
|
+
reviewer,
|
|
4179
|
+
timestamp: now
|
|
4180
|
+
});
|
|
4181
|
+
await writeNotification({
|
|
4182
|
+
agentId: agent,
|
|
4183
|
+
agentRole: String(row.assigned_to),
|
|
4184
|
+
event: "task_complete",
|
|
4185
|
+
project: String(row.project_name),
|
|
4186
|
+
summary: `completed "${taskTitle}" \u2014 review task created`,
|
|
4187
|
+
taskFile: reviewFile
|
|
4188
|
+
});
|
|
4189
|
+
const originalPriority = String(row.priority).toLowerCase();
|
|
4190
|
+
const autoApprove = originalPriority === "p2" && result?.toLowerCase().includes("tests pass");
|
|
4191
|
+
if (!autoApprove) {
|
|
3771
4192
|
try {
|
|
3772
|
-
|
|
4193
|
+
const key = getSessionKey();
|
|
4194
|
+
const exeSession = getParentExe(key);
|
|
4195
|
+
if (exeSession) {
|
|
4196
|
+
sendIntercom(exeSession);
|
|
4197
|
+
}
|
|
3773
4198
|
} catch {
|
|
3774
4199
|
}
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
4200
|
+
}
|
|
4201
|
+
if (autoApprove) {
|
|
4202
|
+
process.stderr.write(
|
|
4203
|
+
`[review] Auto-approving review for "${taskTitle}" (P2 + tests pass)
|
|
4204
|
+
`
|
|
4205
|
+
);
|
|
4206
|
+
await client.execute({
|
|
4207
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?",
|
|
4208
|
+
args: [now, reviewId]
|
|
4209
|
+
});
|
|
4210
|
+
}
|
|
4211
|
+
}
|
|
4212
|
+
async function cleanupReviewFile(row, taskFile, _baseDir) {
|
|
4213
|
+
if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
|
|
4214
|
+
try {
|
|
4215
|
+
const client = getClient();
|
|
4216
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4217
|
+
const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
|
|
4218
|
+
if (parentId) {
|
|
4219
|
+
const result = await client.execute({
|
|
4220
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
|
|
4221
|
+
args: [now, parentId]
|
|
4222
|
+
});
|
|
4223
|
+
if (result.rowsAffected > 0) {
|
|
4224
|
+
process.stderr.write(
|
|
4225
|
+
`[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
|
|
4226
|
+
`
|
|
4227
|
+
);
|
|
4228
|
+
}
|
|
4229
|
+
} else {
|
|
4230
|
+
const fileName = taskFile.split("/").pop() ?? "";
|
|
4231
|
+
const reviewPrefix = fileName.replace(".md", "");
|
|
4232
|
+
const parts = reviewPrefix.split("-");
|
|
4233
|
+
if (parts.length >= 3 && parts[0] === "review") {
|
|
4234
|
+
const agent = parts[1];
|
|
4235
|
+
const slug = parts.slice(2).join("-");
|
|
4236
|
+
const originalTaskFile = `exe/${agent}/${slug}.md`;
|
|
4237
|
+
const result = await client.execute({
|
|
4238
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
|
|
4239
|
+
args: [now, originalTaskFile]
|
|
4240
|
+
});
|
|
4241
|
+
if (result.rowsAffected > 0) {
|
|
4242
|
+
process.stderr.write(
|
|
4243
|
+
`[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
|
|
4244
|
+
`
|
|
4245
|
+
);
|
|
3786
4246
|
}
|
|
3787
4247
|
}
|
|
3788
|
-
} catch {
|
|
3789
4248
|
}
|
|
4249
|
+
} catch (err) {
|
|
4250
|
+
process.stderr.write(
|
|
4251
|
+
`[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
|
|
4252
|
+
`
|
|
4253
|
+
);
|
|
3790
4254
|
}
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
4255
|
+
try {
|
|
4256
|
+
const cacheDir = path16.join(EXE_AI_DIR, "session-cache");
|
|
4257
|
+
if (existsSync14(cacheDir)) {
|
|
4258
|
+
for (const f of readdirSync5(cacheDir)) {
|
|
4259
|
+
if (f.startsWith("review-notified-")) {
|
|
4260
|
+
unlinkSync4(path16.join(cacheDir, f));
|
|
4261
|
+
}
|
|
4262
|
+
}
|
|
3799
4263
|
}
|
|
4264
|
+
} catch {
|
|
3800
4265
|
}
|
|
3801
|
-
registerSession({
|
|
3802
|
-
windowName: sessionName,
|
|
3803
|
-
agentId: employeeName,
|
|
3804
|
-
projectDir: spawnCwd,
|
|
3805
|
-
parentExe: exeSession,
|
|
3806
|
-
pid: 0,
|
|
3807
|
-
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3808
|
-
});
|
|
3809
|
-
releaseSpawnLock2(sessionName);
|
|
3810
|
-
return { sessionName };
|
|
3811
4266
|
}
|
|
3812
|
-
var
|
|
3813
|
-
|
|
3814
|
-
"src/lib/tmux-routing.ts"() {
|
|
4267
|
+
var init_tasks_review = __esm({
|
|
4268
|
+
"src/lib/tasks-review.ts"() {
|
|
3815
4269
|
"use strict";
|
|
3816
|
-
|
|
4270
|
+
init_database();
|
|
4271
|
+
init_config();
|
|
4272
|
+
init_employees();
|
|
4273
|
+
init_notifications();
|
|
4274
|
+
init_tasks_crud();
|
|
4275
|
+
init_tmux_routing();
|
|
3817
4276
|
init_session_key();
|
|
3818
|
-
|
|
3819
|
-
init_cc_agent_support();
|
|
3820
|
-
init_mcp_prefix();
|
|
3821
|
-
init_provider_table();
|
|
3822
|
-
init_intercom_queue();
|
|
3823
|
-
init_plan_limits();
|
|
3824
|
-
SPAWN_LOCK_DIR = path14.join(os5.homedir(), ".exe-os", "spawn-locks");
|
|
3825
|
-
SESSION_CACHE = path14.join(os5.homedir(), ".exe-os", "session-cache");
|
|
3826
|
-
BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
|
|
3827
|
-
INTERCOM_DEBOUNCE_MS = 3e4;
|
|
3828
|
-
INTERCOM_LOG2 = path14.join(os5.homedir(), ".exe-os", "intercom.log");
|
|
3829
|
-
DEBOUNCE_FILE = path14.join(SESSION_CACHE, "intercom-debounce.json");
|
|
3830
|
-
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
3831
|
-
BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
|
|
4277
|
+
init_state_bus();
|
|
3832
4278
|
}
|
|
3833
4279
|
});
|
|
3834
4280
|
|
|
3835
|
-
// src/lib/
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
getFailedMessages: () => getFailedMessages,
|
|
3840
|
-
getMessageStatus: () => getMessageStatus,
|
|
3841
|
-
getPendingMessages: () => getPendingMessages,
|
|
3842
|
-
getReadMessages: () => getReadMessages,
|
|
3843
|
-
getUnacknowledgedMessages: () => getUnacknowledgedMessages,
|
|
3844
|
-
markAcknowledged: () => markAcknowledged,
|
|
3845
|
-
markFailed: () => markFailed,
|
|
3846
|
-
markProcessed: () => markProcessed,
|
|
3847
|
-
markRead: () => markRead,
|
|
3848
|
-
retryPendingMessages: () => retryPendingMessages,
|
|
3849
|
-
sendMessage: () => sendMessage,
|
|
3850
|
-
setWsClientSend: () => setWsClientSend
|
|
3851
|
-
});
|
|
3852
|
-
import crypto3 from "crypto";
|
|
3853
|
-
function generateUlid() {
|
|
3854
|
-
const timestamp = Date.now().toString(36).padStart(10, "0");
|
|
3855
|
-
const random = crypto3.randomBytes(10).toString("hex").slice(0, 16);
|
|
3856
|
-
return (timestamp + random).toUpperCase();
|
|
3857
|
-
}
|
|
3858
|
-
function rowToMessage(row) {
|
|
3859
|
-
return {
|
|
3860
|
-
id: row.id,
|
|
3861
|
-
fromAgent: row.from_agent,
|
|
3862
|
-
fromDevice: row.from_device,
|
|
3863
|
-
targetAgent: row.target_agent,
|
|
3864
|
-
targetProject: row.target_project ?? null,
|
|
3865
|
-
targetDevice: row.target_device,
|
|
3866
|
-
content: row.content,
|
|
3867
|
-
priority: row.priority ?? "normal",
|
|
3868
|
-
status: row.status ?? "pending",
|
|
3869
|
-
serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
|
|
3870
|
-
retryCount: Number(row.retry_count ?? 0),
|
|
3871
|
-
createdAt: row.created_at,
|
|
3872
|
-
deliveredAt: row.delivered_at ?? null,
|
|
3873
|
-
processedAt: row.processed_at ?? null,
|
|
3874
|
-
failedAt: row.failed_at ?? null,
|
|
3875
|
-
failureReason: row.failure_reason ?? null
|
|
3876
|
-
};
|
|
3877
|
-
}
|
|
3878
|
-
async function sendMessage(input2) {
|
|
4281
|
+
// src/lib/tasks-chain.ts
|
|
4282
|
+
import path17 from "path";
|
|
4283
|
+
import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
|
|
4284
|
+
async function cascadeUnblock(taskId, baseDir, now) {
|
|
3879
4285
|
const client = getClient();
|
|
3880
|
-
const
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
|
|
3885
|
-
VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
|
|
3886
|
-
args: [
|
|
3887
|
-
id,
|
|
3888
|
-
input2.fromAgent,
|
|
3889
|
-
input2.targetAgent,
|
|
3890
|
-
input2.targetProject ?? null,
|
|
3891
|
-
targetDevice,
|
|
3892
|
-
input2.content,
|
|
3893
|
-
input2.priority ?? "normal",
|
|
3894
|
-
now
|
|
3895
|
-
]
|
|
4286
|
+
const unblocked = await client.execute({
|
|
4287
|
+
sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
|
|
4288
|
+
WHERE blocked_by = ? AND status = 'blocked'`,
|
|
4289
|
+
args: [now, taskId]
|
|
3896
4290
|
});
|
|
3897
|
-
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
4291
|
+
if (baseDir && unblocked.rowsAffected > 0) {
|
|
4292
|
+
const unblockedRows = await client.execute({
|
|
4293
|
+
sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
|
|
4294
|
+
args: [now]
|
|
4295
|
+
});
|
|
4296
|
+
for (const ur of unblockedRows.rows) {
|
|
4297
|
+
try {
|
|
4298
|
+
const ubFile = path17.join(baseDir, String(ur.task_file));
|
|
4299
|
+
let ubContent = await readFile4(ubFile, "utf-8");
|
|
4300
|
+
ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
|
|
4301
|
+
ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
|
|
4302
|
+
await writeFile5(ubFile, ubContent, "utf-8");
|
|
4303
|
+
} catch {
|
|
4304
|
+
}
|
|
3902
4305
|
}
|
|
3903
|
-
} catch {
|
|
3904
4306
|
}
|
|
3905
|
-
const result = await client.execute({
|
|
3906
|
-
sql: "SELECT * FROM messages WHERE id = ?",
|
|
3907
|
-
args: [id]
|
|
3908
|
-
});
|
|
3909
|
-
return rowToMessage(result.rows[0]);
|
|
3910
4307
|
}
|
|
3911
|
-
function
|
|
3912
|
-
_wsClientSend = fn;
|
|
3913
|
-
}
|
|
3914
|
-
async function deliverCrossMachineMessage(messageId, targetDevice) {
|
|
4308
|
+
async function findNextTask(assignedTo) {
|
|
3915
4309
|
const client = getClient();
|
|
3916
|
-
const
|
|
3917
|
-
sql:
|
|
3918
|
-
|
|
4310
|
+
const nextResult = await client.execute({
|
|
4311
|
+
sql: `SELECT title, task_file, priority FROM tasks
|
|
4312
|
+
WHERE assigned_to = ? AND status = 'open'
|
|
4313
|
+
ORDER BY priority ASC, created_at ASC
|
|
4314
|
+
LIMIT 1`,
|
|
4315
|
+
args: [assignedTo]
|
|
3919
4316
|
});
|
|
3920
|
-
if (
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
4317
|
+
if (nextResult.rows.length === 1) {
|
|
4318
|
+
const nr = nextResult.rows[0];
|
|
4319
|
+
return {
|
|
4320
|
+
title: String(nr.title),
|
|
4321
|
+
priority: String(nr.priority),
|
|
4322
|
+
taskFile: String(nr.task_file)
|
|
4323
|
+
};
|
|
3925
4324
|
}
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
4325
|
+
return void 0;
|
|
4326
|
+
}
|
|
4327
|
+
async function checkSubtaskCompletion(parentTaskId, projectName) {
|
|
4328
|
+
const client = getClient();
|
|
4329
|
+
const remaining = await client.execute({
|
|
4330
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
4331
|
+
WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
|
|
4332
|
+
args: [parentTaskId]
|
|
3934
4333
|
});
|
|
3935
|
-
const
|
|
3936
|
-
if (
|
|
3937
|
-
await client.execute({
|
|
3938
|
-
sql:
|
|
3939
|
-
args: [
|
|
4334
|
+
const cnt = Number(remaining.rows[0]?.cnt ?? 1);
|
|
4335
|
+
if (cnt === 0) {
|
|
4336
|
+
const parentRow = await client.execute({
|
|
4337
|
+
sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
|
|
4338
|
+
args: [parentTaskId]
|
|
3940
4339
|
});
|
|
3941
|
-
|
|
4340
|
+
if (parentRow.rows.length === 1) {
|
|
4341
|
+
const pr = parentRow.rows[0];
|
|
4342
|
+
const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
|
|
4343
|
+
await writeNotification({
|
|
4344
|
+
agentId: String(pr.assigned_to),
|
|
4345
|
+
agentRole: "system",
|
|
4346
|
+
event: "subtasks_complete",
|
|
4347
|
+
project: parentProject,
|
|
4348
|
+
summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
|
|
4349
|
+
taskFile: String(pr.task_file)
|
|
4350
|
+
});
|
|
4351
|
+
}
|
|
3942
4352
|
}
|
|
3943
|
-
return false;
|
|
3944
4353
|
}
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
3949
|
-
|
|
3950
|
-
}
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
|
|
4354
|
+
var init_tasks_chain = __esm({
|
|
4355
|
+
"src/lib/tasks-chain.ts"() {
|
|
4356
|
+
"use strict";
|
|
4357
|
+
init_database();
|
|
4358
|
+
init_notifications();
|
|
4359
|
+
}
|
|
4360
|
+
});
|
|
4361
|
+
|
|
4362
|
+
// src/lib/session-scope.ts
|
|
4363
|
+
var session_scope_exports = {};
|
|
4364
|
+
__export(session_scope_exports, {
|
|
4365
|
+
assertSessionScope: () => assertSessionScope,
|
|
4366
|
+
findSessionForProject: () => findSessionForProject,
|
|
4367
|
+
getSessionProject: () => getSessionProject
|
|
4368
|
+
});
|
|
4369
|
+
function getSessionProject(sessionName) {
|
|
4370
|
+
const sessions = listSessions();
|
|
4371
|
+
const entry = sessions.find((s) => s.windowName === sessionName);
|
|
4372
|
+
if (!entry) return null;
|
|
4373
|
+
const parts = entry.projectDir.split("/").filter(Boolean);
|
|
4374
|
+
return parts[parts.length - 1] ?? null;
|
|
4375
|
+
}
|
|
4376
|
+
function findSessionForProject(projectName) {
|
|
4377
|
+
const sessions = listSessions();
|
|
4378
|
+
for (const s of sessions) {
|
|
4379
|
+
const proj = s.projectDir.split("/").filter(Boolean).pop();
|
|
4380
|
+
if (proj === projectName && s.agentId === "exe") return s;
|
|
4381
|
+
}
|
|
4382
|
+
return null;
|
|
4383
|
+
}
|
|
4384
|
+
function assertSessionScope(actionType, targetProject) {
|
|
3956
4385
|
try {
|
|
4386
|
+
const currentProject = getProjectName();
|
|
3957
4387
|
const exeSession = resolveExeSession();
|
|
3958
4388
|
if (!exeSession) {
|
|
3959
|
-
|
|
4389
|
+
return { allowed: true, reason: "no_session" };
|
|
3960
4390
|
}
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
4391
|
+
if (currentProject === targetProject) {
|
|
4392
|
+
return {
|
|
4393
|
+
allowed: true,
|
|
4394
|
+
reason: "same_session",
|
|
4395
|
+
currentProject,
|
|
4396
|
+
targetProject
|
|
4397
|
+
};
|
|
3964
4398
|
}
|
|
3965
|
-
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
|
|
3969
|
-
return
|
|
4399
|
+
process.stderr.write(
|
|
4400
|
+
`[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
|
|
4401
|
+
`
|
|
4402
|
+
);
|
|
4403
|
+
return {
|
|
4404
|
+
allowed: false,
|
|
4405
|
+
reason: "cross_session_denied",
|
|
4406
|
+
currentProject,
|
|
4407
|
+
targetProject,
|
|
4408
|
+
targetSession: findSessionForProject(targetProject)?.windowName
|
|
4409
|
+
};
|
|
3970
4410
|
} catch {
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
|
|
4411
|
+
return { allowed: true, reason: "no_session" };
|
|
4412
|
+
}
|
|
4413
|
+
}
|
|
4414
|
+
var init_session_scope = __esm({
|
|
4415
|
+
"src/lib/session-scope.ts"() {
|
|
4416
|
+
"use strict";
|
|
4417
|
+
init_session_registry();
|
|
4418
|
+
init_project_name();
|
|
4419
|
+
init_tmux_routing();
|
|
4420
|
+
}
|
|
4421
|
+
});
|
|
4422
|
+
|
|
4423
|
+
// src/lib/tasks-notify.ts
|
|
4424
|
+
async function dispatchTaskToEmployee(input2) {
|
|
4425
|
+
if (input2.assignedTo === "exe") return { dispatched: "skipped" };
|
|
4426
|
+
let crossProject = false;
|
|
4427
|
+
if (input2.projectName) {
|
|
4428
|
+
try {
|
|
4429
|
+
const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
|
|
4430
|
+
const check = assertSessionScope2("dispatch_task", input2.projectName);
|
|
4431
|
+
if (check.reason === "cross_session_denied") {
|
|
4432
|
+
crossProject = true;
|
|
4433
|
+
return { dispatched: "skipped", crossProject: true };
|
|
4434
|
+
}
|
|
4435
|
+
} catch {
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
4438
|
+
try {
|
|
4439
|
+
const transport = getTransport();
|
|
4440
|
+
const exeSession = resolveExeSession();
|
|
4441
|
+
if (!exeSession) return { dispatched: "session_missing" };
|
|
4442
|
+
const sessionName = employeeSessionName(input2.assignedTo, exeSession);
|
|
4443
|
+
if (transport.isAlive(sessionName)) {
|
|
4444
|
+
const result = sendIntercom(sessionName);
|
|
4445
|
+
const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
|
|
4446
|
+
return { dispatched, session: sessionName, crossProject };
|
|
3974
4447
|
} else {
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
|
|
4448
|
+
const projectDir = input2.projectDir ?? process.cwd();
|
|
4449
|
+
const result = ensureEmployee(input2.assignedTo, exeSession, projectDir, {
|
|
4450
|
+
autoInstance: isMultiInstance(input2.assignedTo)
|
|
3978
4451
|
});
|
|
4452
|
+
if (result.status === "failed") {
|
|
4453
|
+
process.stderr.write(
|
|
4454
|
+
`[dispatch] Failed to spawn ${input2.assignedTo}: ${result.error}
|
|
4455
|
+
`
|
|
4456
|
+
);
|
|
4457
|
+
return { dispatched: "session_missing" };
|
|
4458
|
+
}
|
|
4459
|
+
return { dispatched: "spawned", session: result.sessionName, crossProject };
|
|
3979
4460
|
}
|
|
3980
|
-
|
|
4461
|
+
} catch {
|
|
4462
|
+
return { dispatched: "session_missing" };
|
|
3981
4463
|
}
|
|
3982
4464
|
}
|
|
3983
|
-
|
|
3984
|
-
|
|
3985
|
-
|
|
3986
|
-
|
|
3987
|
-
|
|
3988
|
-
|
|
3989
|
-
args: [targetAgent]
|
|
3990
|
-
});
|
|
3991
|
-
return result.rows.map((row) => rowToMessage(row));
|
|
4465
|
+
function notifyTaskDone() {
|
|
4466
|
+
try {
|
|
4467
|
+
const key = getSessionKey();
|
|
4468
|
+
if (key && !process.env.VITEST) notifyParentExe(key);
|
|
4469
|
+
} catch {
|
|
4470
|
+
}
|
|
3992
4471
|
}
|
|
3993
|
-
async function
|
|
4472
|
+
async function markTaskNotificationsRead(taskFile) {
|
|
4473
|
+
try {
|
|
4474
|
+
await markAsReadByTaskFile(taskFile);
|
|
4475
|
+
} catch {
|
|
4476
|
+
}
|
|
4477
|
+
}
|
|
4478
|
+
var init_tasks_notify = __esm({
|
|
4479
|
+
"src/lib/tasks-notify.ts"() {
|
|
4480
|
+
"use strict";
|
|
4481
|
+
init_tmux_routing();
|
|
4482
|
+
init_session_key();
|
|
4483
|
+
init_notifications();
|
|
4484
|
+
init_transport();
|
|
4485
|
+
init_employees();
|
|
4486
|
+
}
|
|
4487
|
+
});
|
|
4488
|
+
|
|
4489
|
+
// src/lib/behaviors.ts
|
|
4490
|
+
import crypto6 from "crypto";
|
|
4491
|
+
async function storeBehavior(opts) {
|
|
3994
4492
|
const client = getClient();
|
|
4493
|
+
const id = crypto6.randomUUID();
|
|
4494
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3995
4495
|
await client.execute({
|
|
3996
|
-
sql:
|
|
3997
|
-
|
|
4496
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
|
|
4497
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
4498
|
+
args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
|
|
3998
4499
|
});
|
|
4500
|
+
return id;
|
|
3999
4501
|
}
|
|
4000
|
-
|
|
4502
|
+
var init_behaviors = __esm({
|
|
4503
|
+
"src/lib/behaviors.ts"() {
|
|
4504
|
+
"use strict";
|
|
4505
|
+
init_database();
|
|
4506
|
+
}
|
|
4507
|
+
});
|
|
4508
|
+
|
|
4509
|
+
// src/lib/skill-learning.ts
|
|
4510
|
+
var skill_learning_exports = {};
|
|
4511
|
+
__export(skill_learning_exports, {
|
|
4512
|
+
captureAndLearn: () => captureAndLearn,
|
|
4513
|
+
captureTrajectory: () => captureTrajectory,
|
|
4514
|
+
editDistance: () => editDistance,
|
|
4515
|
+
extractSkill: () => extractSkill,
|
|
4516
|
+
extractTrajectory: () => extractTrajectory,
|
|
4517
|
+
findSimilarTrajectories: () => findSimilarTrajectories,
|
|
4518
|
+
hashSignature: () => hashSignature,
|
|
4519
|
+
storeTrajectory: () => storeTrajectory,
|
|
4520
|
+
sweepTrajectories: () => sweepTrajectories
|
|
4521
|
+
});
|
|
4522
|
+
import crypto7 from "crypto";
|
|
4523
|
+
async function extractTrajectory(taskId, agentId) {
|
|
4001
4524
|
const client = getClient();
|
|
4002
|
-
await client.execute({
|
|
4003
|
-
sql:
|
|
4004
|
-
|
|
4525
|
+
const result = await client.execute({
|
|
4526
|
+
sql: `SELECT tool_name, raw_text
|
|
4527
|
+
FROM memories
|
|
4528
|
+
WHERE task_id = ? AND agent_id = ?
|
|
4529
|
+
ORDER BY timestamp ASC`,
|
|
4530
|
+
args: [taskId, agentId]
|
|
4531
|
+
});
|
|
4532
|
+
if (result.rows.length === 0) return [];
|
|
4533
|
+
const rawTools = result.rows.map((r) => {
|
|
4534
|
+
const toolName = String(r.tool_name);
|
|
4535
|
+
if (toolName === "Bash") {
|
|
4536
|
+
const text = String(r.raw_text);
|
|
4537
|
+
const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
|
|
4538
|
+
return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
|
|
4539
|
+
}
|
|
4540
|
+
return toolName;
|
|
4005
4541
|
});
|
|
4542
|
+
const signature = [];
|
|
4543
|
+
for (const tool of rawTools) {
|
|
4544
|
+
if (signature.length === 0 || signature[signature.length - 1] !== tool) {
|
|
4545
|
+
signature.push(tool);
|
|
4546
|
+
}
|
|
4547
|
+
}
|
|
4548
|
+
return signature;
|
|
4006
4549
|
}
|
|
4007
|
-
|
|
4550
|
+
function hashSignature(signature) {
|
|
4551
|
+
return crypto7.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
|
|
4552
|
+
}
|
|
4553
|
+
async function storeTrajectory(opts) {
|
|
4008
4554
|
const client = getClient();
|
|
4555
|
+
const id = crypto7.randomUUID();
|
|
4556
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4557
|
+
const signatureHash = hashSignature(opts.signature);
|
|
4009
4558
|
await client.execute({
|
|
4010
|
-
sql:
|
|
4011
|
-
|
|
4559
|
+
sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
|
|
4560
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
4561
|
+
args: [
|
|
4562
|
+
id,
|
|
4563
|
+
opts.taskId,
|
|
4564
|
+
opts.agentId,
|
|
4565
|
+
opts.projectName,
|
|
4566
|
+
opts.taskTitle,
|
|
4567
|
+
JSON.stringify(opts.signature),
|
|
4568
|
+
signatureHash,
|
|
4569
|
+
opts.signature.length,
|
|
4570
|
+
now
|
|
4571
|
+
]
|
|
4012
4572
|
});
|
|
4573
|
+
return id;
|
|
4013
4574
|
}
|
|
4014
|
-
async function
|
|
4575
|
+
async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
|
|
4015
4576
|
const client = getClient();
|
|
4577
|
+
const hash = hashSignature(signature);
|
|
4016
4578
|
const result = await client.execute({
|
|
4017
|
-
sql:
|
|
4018
|
-
|
|
4579
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
4580
|
+
FROM trajectories
|
|
4581
|
+
WHERE signature_hash = ?
|
|
4582
|
+
ORDER BY created_at DESC
|
|
4583
|
+
LIMIT 20`,
|
|
4584
|
+
args: [hash]
|
|
4019
4585
|
});
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4586
|
+
const mapRow = (r) => ({
|
|
4587
|
+
id: String(r.id),
|
|
4588
|
+
taskId: String(r.task_id),
|
|
4589
|
+
agentId: String(r.agent_id),
|
|
4590
|
+
projectName: String(r.project_name),
|
|
4591
|
+
taskTitle: String(r.task_title),
|
|
4592
|
+
signature: JSON.parse(String(r.signature)),
|
|
4593
|
+
signatureHash: String(r.signature_hash),
|
|
4594
|
+
toolCount: Number(r.tool_count),
|
|
4595
|
+
skillId: r.skill_id ? String(r.skill_id) : null,
|
|
4596
|
+
createdAt: String(r.created_at)
|
|
4029
4597
|
});
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
4598
|
+
const matches = result.rows.map(mapRow);
|
|
4599
|
+
if (matches.length >= threshold) return matches;
|
|
4600
|
+
const nearResult = await client.execute({
|
|
4601
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
4602
|
+
FROM trajectories
|
|
4603
|
+
WHERE tool_count BETWEEN ? AND ?
|
|
4604
|
+
AND signature_hash != ?
|
|
4605
|
+
ORDER BY created_at DESC
|
|
4606
|
+
LIMIT 50`,
|
|
4607
|
+
args: [
|
|
4608
|
+
Math.max(1, signature.length - 3),
|
|
4609
|
+
signature.length + 3,
|
|
4610
|
+
hash
|
|
4611
|
+
]
|
|
4037
4612
|
});
|
|
4038
|
-
|
|
4613
|
+
for (const r of nearResult.rows) {
|
|
4614
|
+
const candidateSig = JSON.parse(String(r.signature));
|
|
4615
|
+
if (editDistance(signature, candidateSig) <= 2) {
|
|
4616
|
+
matches.push(mapRow(r));
|
|
4617
|
+
}
|
|
4618
|
+
}
|
|
4619
|
+
return matches;
|
|
4039
4620
|
}
|
|
4040
|
-
async function
|
|
4041
|
-
const
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4621
|
+
async function captureTrajectory(opts) {
|
|
4622
|
+
const signature = await extractTrajectory(opts.taskId, opts.agentId);
|
|
4623
|
+
if (signature.length < 3) {
|
|
4624
|
+
return { trajectoryId: "", similarCount: 0, similar: [] };
|
|
4625
|
+
}
|
|
4626
|
+
const trajectoryId = await storeTrajectory({
|
|
4627
|
+
taskId: opts.taskId,
|
|
4628
|
+
agentId: opts.agentId,
|
|
4629
|
+
projectName: opts.projectName,
|
|
4630
|
+
taskTitle: opts.taskTitle,
|
|
4631
|
+
signature
|
|
4045
4632
|
});
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
4051
|
-
|
|
4633
|
+
const similar = await findSimilarTrajectories(
|
|
4634
|
+
signature,
|
|
4635
|
+
opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
|
|
4636
|
+
);
|
|
4637
|
+
return { trajectoryId, similarCount: similar.length, similar };
|
|
4638
|
+
}
|
|
4639
|
+
function buildExtractionPrompt(trajectories) {
|
|
4640
|
+
const items = trajectories.map((t, i) => {
|
|
4641
|
+
const sig = t.signature.join(" \u2192 ");
|
|
4642
|
+
return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
|
|
4643
|
+
Signature: ${sig}`;
|
|
4644
|
+
}).join("\n\n");
|
|
4645
|
+
return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
|
|
4646
|
+
|
|
4647
|
+
${items}
|
|
4648
|
+
|
|
4649
|
+
Extract the reusable procedure. Format your response EXACTLY like this:
|
|
4650
|
+
|
|
4651
|
+
SKILL: {name \u2014 short, descriptive}
|
|
4652
|
+
TRIGGER: {when to use this \u2014 one sentence}
|
|
4653
|
+
STEPS:
|
|
4654
|
+
1. ...
|
|
4655
|
+
2. ...
|
|
4656
|
+
PITFALLS: {common mistakes to avoid}
|
|
4657
|
+
|
|
4658
|
+
Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
|
|
4659
|
+
}
|
|
4660
|
+
async function extractSkill(trajectories, model) {
|
|
4661
|
+
if (trajectories.length === 0) return null;
|
|
4662
|
+
const config = await loadConfig();
|
|
4663
|
+
const skillModel = model ?? config.skillModel;
|
|
4664
|
+
const Anthropic = (await import("@anthropic-ai/sdk")).default;
|
|
4665
|
+
const client = new Anthropic();
|
|
4666
|
+
const prompt = buildExtractionPrompt(trajectories);
|
|
4667
|
+
const response = await client.messages.create({
|
|
4668
|
+
model: skillModel,
|
|
4669
|
+
max_tokens: 500,
|
|
4670
|
+
messages: [{ role: "user", content: prompt }]
|
|
4052
4671
|
});
|
|
4053
|
-
|
|
4672
|
+
const textBlock = response.content.find((b) => b.type === "text");
|
|
4673
|
+
const skillText = textBlock?.text;
|
|
4674
|
+
if (!skillText) return null;
|
|
4675
|
+
const agentId = trajectories[0].agentId;
|
|
4676
|
+
const projectName = trajectories[0].projectName;
|
|
4677
|
+
const skillId = await storeBehavior({
|
|
4678
|
+
agentId,
|
|
4679
|
+
content: skillText,
|
|
4680
|
+
domain: "skill",
|
|
4681
|
+
projectName
|
|
4682
|
+
});
|
|
4683
|
+
const dbClient = getClient();
|
|
4684
|
+
for (const t of trajectories) {
|
|
4685
|
+
await dbClient.execute({
|
|
4686
|
+
sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
|
|
4687
|
+
args: [skillId, t.id]
|
|
4688
|
+
});
|
|
4689
|
+
}
|
|
4690
|
+
process.stderr.write(
|
|
4691
|
+
`[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
|
|
4692
|
+
`
|
|
4693
|
+
);
|
|
4694
|
+
return skillId;
|
|
4054
4695
|
}
|
|
4055
|
-
async function
|
|
4696
|
+
async function captureAndLearn(opts) {
|
|
4697
|
+
try {
|
|
4698
|
+
const config = await loadConfig();
|
|
4699
|
+
if (!config.skillLearning) return;
|
|
4700
|
+
const { trajectoryId, similarCount, similar } = await captureTrajectory({
|
|
4701
|
+
...opts,
|
|
4702
|
+
skillThreshold: config.skillThreshold
|
|
4703
|
+
});
|
|
4704
|
+
if (!trajectoryId) return;
|
|
4705
|
+
if (similarCount >= config.skillThreshold) {
|
|
4706
|
+
const unprocessed = similar.filter((t) => !t.skillId);
|
|
4707
|
+
if (unprocessed.length >= config.skillThreshold) {
|
|
4708
|
+
extractSkill(unprocessed, config.skillModel).catch((err) => {
|
|
4709
|
+
process.stderr.write(
|
|
4710
|
+
`[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
|
|
4711
|
+
`
|
|
4712
|
+
);
|
|
4713
|
+
});
|
|
4714
|
+
}
|
|
4715
|
+
}
|
|
4716
|
+
} catch (err) {
|
|
4717
|
+
process.stderr.write(
|
|
4718
|
+
`[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
|
|
4719
|
+
`
|
|
4720
|
+
);
|
|
4721
|
+
}
|
|
4722
|
+
}
|
|
4723
|
+
async function sweepTrajectories(threshold, model) {
|
|
4724
|
+
const config = await loadConfig();
|
|
4725
|
+
if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
|
|
4726
|
+
const t = threshold ?? config.skillThreshold;
|
|
4056
4727
|
const client = getClient();
|
|
4057
4728
|
const result = await client.execute({
|
|
4058
|
-
sql: `SELECT *
|
|
4059
|
-
|
|
4060
|
-
|
|
4061
|
-
|
|
4729
|
+
sql: `SELECT signature_hash, COUNT(*) as cnt
|
|
4730
|
+
FROM trajectories
|
|
4731
|
+
WHERE skill_id IS NULL
|
|
4732
|
+
GROUP BY signature_hash
|
|
4733
|
+
HAVING cnt >= ?
|
|
4734
|
+
ORDER BY cnt DESC
|
|
4735
|
+
LIMIT 10`,
|
|
4736
|
+
args: [t]
|
|
4062
4737
|
});
|
|
4063
|
-
let
|
|
4738
|
+
let clustersProcessed = 0;
|
|
4739
|
+
let skillsExtracted = 0;
|
|
4064
4740
|
for (const row of result.rows) {
|
|
4065
|
-
const
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
|
|
4741
|
+
const hash = String(row.signature_hash);
|
|
4742
|
+
const trajResult = await client.execute({
|
|
4743
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
|
|
4744
|
+
FROM trajectories
|
|
4745
|
+
WHERE signature_hash = ? AND skill_id IS NULL
|
|
4746
|
+
ORDER BY created_at DESC
|
|
4747
|
+
LIMIT 10`,
|
|
4748
|
+
args: [hash]
|
|
4749
|
+
});
|
|
4750
|
+
const trajectories = trajResult.rows.map((r) => ({
|
|
4751
|
+
id: String(r.id),
|
|
4752
|
+
taskId: String(r.task_id),
|
|
4753
|
+
agentId: String(r.agent_id),
|
|
4754
|
+
projectName: String(r.project_name),
|
|
4755
|
+
taskTitle: String(r.task_title),
|
|
4756
|
+
signature: JSON.parse(String(r.signature)),
|
|
4757
|
+
signatureHash: String(r.signature_hash),
|
|
4758
|
+
toolCount: Number(r.tool_count),
|
|
4759
|
+
skillId: null,
|
|
4760
|
+
createdAt: String(r.created_at)
|
|
4761
|
+
}));
|
|
4762
|
+
if (trajectories.length >= t) {
|
|
4763
|
+
clustersProcessed++;
|
|
4764
|
+
const skillId = await extractSkill(trajectories, model ?? config.skillModel);
|
|
4765
|
+
if (skillId) skillsExtracted++;
|
|
4070
4766
|
}
|
|
4071
4767
|
}
|
|
4072
|
-
return
|
|
4768
|
+
return { clustersProcessed, skillsExtracted };
|
|
4769
|
+
}
|
|
4770
|
+
function editDistance(a, b) {
|
|
4771
|
+
const m = a.length;
|
|
4772
|
+
const n = b.length;
|
|
4773
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
4774
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
4775
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
4776
|
+
for (let i = 1; i <= m; i++) {
|
|
4777
|
+
for (let j = 1; j <= n; j++) {
|
|
4778
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
4779
|
+
dp[i][j] = Math.min(
|
|
4780
|
+
dp[i - 1][j] + 1,
|
|
4781
|
+
dp[i][j - 1] + 1,
|
|
4782
|
+
dp[i - 1][j - 1] + cost
|
|
4783
|
+
);
|
|
4784
|
+
}
|
|
4785
|
+
}
|
|
4786
|
+
return dp[m][n];
|
|
4073
4787
|
}
|
|
4074
|
-
var
|
|
4075
|
-
var
|
|
4076
|
-
"src/lib/
|
|
4788
|
+
var DEFAULT_SKILL_THRESHOLD;
|
|
4789
|
+
var init_skill_learning = __esm({
|
|
4790
|
+
"src/lib/skill-learning.ts"() {
|
|
4077
4791
|
"use strict";
|
|
4078
4792
|
init_database();
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4793
|
+
init_behaviors();
|
|
4794
|
+
init_config();
|
|
4795
|
+
DEFAULT_SKILL_THRESHOLD = 3;
|
|
4082
4796
|
}
|
|
4083
4797
|
});
|
|
4084
4798
|
|
|
4085
|
-
// src/lib/
|
|
4086
|
-
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
|
|
4799
|
+
// src/lib/tasks.ts
|
|
4800
|
+
var tasks_exports = {};
|
|
4801
|
+
__export(tasks_exports, {
|
|
4802
|
+
cleanupOrphanedReviews: () => cleanupOrphanedReviews,
|
|
4803
|
+
countNewPendingReviewsSince: () => countNewPendingReviewsSince,
|
|
4804
|
+
countPendingReviews: () => countPendingReviews,
|
|
4805
|
+
createTask: () => createTask,
|
|
4806
|
+
createTaskCore: () => createTaskCore,
|
|
4807
|
+
deleteTask: () => deleteTask,
|
|
4808
|
+
deleteTaskCore: () => deleteTaskCore,
|
|
4809
|
+
ensureArchitectureDoc: () => ensureArchitectureDoc,
|
|
4810
|
+
ensureGitignoreExe: () => ensureGitignoreExe,
|
|
4811
|
+
getReviewChecklist: () => getReviewChecklist,
|
|
4812
|
+
listPendingReviews: () => listPendingReviews,
|
|
4813
|
+
listTasks: () => listTasks,
|
|
4814
|
+
resolveTask: () => resolveTask,
|
|
4815
|
+
slugify: () => slugify,
|
|
4816
|
+
updateTask: () => updateTask,
|
|
4817
|
+
updateTaskStatus: () => updateTaskStatus,
|
|
4818
|
+
writeCheckpoint: () => writeCheckpoint
|
|
4819
|
+
});
|
|
4820
|
+
import path18 from "path";
|
|
4821
|
+
import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, unlinkSync as unlinkSync5 } from "fs";
|
|
4822
|
+
async function createTask(input2) {
|
|
4823
|
+
const result = await createTaskCore(input2);
|
|
4824
|
+
if (!input2.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
|
|
4825
|
+
dispatchTaskToEmployee({
|
|
4826
|
+
assignedTo: input2.assignedTo,
|
|
4827
|
+
title: input2.title,
|
|
4828
|
+
priority: input2.priority,
|
|
4829
|
+
taskFile: result.taskFile,
|
|
4830
|
+
initialStatus: result.status,
|
|
4831
|
+
projectName: input2.projectName
|
|
4832
|
+
});
|
|
4833
|
+
}
|
|
4834
|
+
return result;
|
|
4835
|
+
}
|
|
4836
|
+
async function updateTask(input2) {
|
|
4837
|
+
const { row, taskFile, now, taskId } = await updateTaskStatus(input2);
|
|
4097
4838
|
try {
|
|
4098
|
-
const
|
|
4099
|
-
const
|
|
4100
|
-
const
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4839
|
+
const agent = String(row.assigned_to);
|
|
4840
|
+
const cacheDir = path18.join(EXE_AI_DIR, "session-cache");
|
|
4841
|
+
const cachePath = path18.join(cacheDir, `current-task-${agent}.json`);
|
|
4842
|
+
if (input2.status === "in_progress") {
|
|
4843
|
+
mkdirSync6(cacheDir, { recursive: true });
|
|
4844
|
+
writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
|
|
4845
|
+
} else if (input2.status === "done" || input2.status === "blocked" || input2.status === "cancelled") {
|
|
4846
|
+
try {
|
|
4847
|
+
unlinkSync5(cachePath);
|
|
4848
|
+
} catch {
|
|
4849
|
+
}
|
|
4850
|
+
}
|
|
4851
|
+
} catch {
|
|
4852
|
+
}
|
|
4853
|
+
if (input2.status === "done") {
|
|
4854
|
+
await cleanupReviewFile(row, taskFile, input2.baseDir);
|
|
4855
|
+
}
|
|
4856
|
+
if (input2.status === "done" || input2.status === "cancelled") {
|
|
4857
|
+
try {
|
|
4858
|
+
const client = getClient();
|
|
4859
|
+
const taskTitle = String(row.title);
|
|
4860
|
+
const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
4861
|
+
await client.execute({
|
|
4862
|
+
sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
|
|
4863
|
+
WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
|
|
4864
|
+
args: [now, `%left '${escaped}' as in\\_progress%`]
|
|
4865
|
+
});
|
|
4866
|
+
} catch {
|
|
4867
|
+
}
|
|
4868
|
+
try {
|
|
4869
|
+
const client = getClient();
|
|
4870
|
+
const cascaded = await client.execute({
|
|
4871
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
4872
|
+
WHERE parent_task_id = ? AND status = 'needs_review'`,
|
|
4873
|
+
args: [now, taskId]
|
|
4874
|
+
});
|
|
4875
|
+
if (cascaded.rowsAffected > 0) {
|
|
4876
|
+
process.stderr.write(
|
|
4877
|
+
`[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
|
|
4878
|
+
`
|
|
4879
|
+
);
|
|
4880
|
+
}
|
|
4881
|
+
} catch {
|
|
4882
|
+
}
|
|
4883
|
+
}
|
|
4884
|
+
const isTerminal = input2.status === "done" || input2.status === "needs_review";
|
|
4885
|
+
if (isTerminal) {
|
|
4886
|
+
const isExe = String(row.assigned_to) === "exe";
|
|
4887
|
+
if (!isExe) {
|
|
4888
|
+
notifyTaskDone();
|
|
4889
|
+
}
|
|
4890
|
+
await markTaskNotificationsRead(taskFile);
|
|
4891
|
+
if (input2.status === "done") {
|
|
4892
|
+
try {
|
|
4893
|
+
await cascadeUnblock(taskId, input2.baseDir, now);
|
|
4894
|
+
} catch {
|
|
4895
|
+
}
|
|
4896
|
+
orgBus.emit({
|
|
4897
|
+
type: "task_completed",
|
|
4898
|
+
taskId,
|
|
4899
|
+
employee: String(row.assigned_to),
|
|
4900
|
+
result: input2.result ?? "",
|
|
4901
|
+
timestamp: now
|
|
4902
|
+
});
|
|
4903
|
+
if (row.parent_task_id) {
|
|
4904
|
+
try {
|
|
4905
|
+
await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
|
|
4906
|
+
} catch {
|
|
4907
|
+
}
|
|
4908
|
+
}
|
|
4909
|
+
}
|
|
4910
|
+
}
|
|
4911
|
+
if (input2.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
|
|
4912
|
+
Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
|
|
4913
|
+
({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
|
|
4914
|
+
taskId,
|
|
4915
|
+
agentId: String(row.assigned_to),
|
|
4916
|
+
projectName: String(row.project_name),
|
|
4917
|
+
taskTitle: String(row.title)
|
|
4918
|
+
})
|
|
4919
|
+
).catch((err) => {
|
|
4920
|
+
process.stderr.write(
|
|
4921
|
+
`[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
|
|
4922
|
+
`
|
|
4923
|
+
);
|
|
4114
4924
|
});
|
|
4115
|
-
} catch (err) {
|
|
4116
|
-
process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
|
|
4117
|
-
`);
|
|
4118
4925
|
}
|
|
4926
|
+
let nextTask;
|
|
4927
|
+
if (isTerminal && String(row.assigned_to) !== "exe") {
|
|
4928
|
+
try {
|
|
4929
|
+
nextTask = await findNextTask(String(row.assigned_to));
|
|
4930
|
+
} catch {
|
|
4931
|
+
}
|
|
4932
|
+
}
|
|
4933
|
+
return {
|
|
4934
|
+
id: String(row.id),
|
|
4935
|
+
title: String(row.title),
|
|
4936
|
+
assignedTo: String(row.assigned_to),
|
|
4937
|
+
assignedBy: String(row.assigned_by),
|
|
4938
|
+
projectName: String(row.project_name),
|
|
4939
|
+
priority: String(row.priority),
|
|
4940
|
+
status: input2.status,
|
|
4941
|
+
taskFile,
|
|
4942
|
+
createdAt: String(row.created_at),
|
|
4943
|
+
updatedAt: now,
|
|
4944
|
+
budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
|
|
4945
|
+
budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
|
|
4946
|
+
tokensUsed: Number(row.tokens_used ?? 0),
|
|
4947
|
+
tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
|
|
4948
|
+
nextTask
|
|
4949
|
+
};
|
|
4119
4950
|
}
|
|
4120
|
-
|
|
4121
|
-
|
|
4951
|
+
async function deleteTask(taskId, baseDir) {
|
|
4952
|
+
const client = getClient();
|
|
4953
|
+
const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
|
|
4954
|
+
const reviewer = assignedBy || "exe";
|
|
4955
|
+
const reviewSlug = `review-${assignedTo}-${taskSlug}`;
|
|
4956
|
+
const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
|
|
4957
|
+
await client.execute({
|
|
4958
|
+
sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
|
|
4959
|
+
args: [reviewFile, `exe/exe/${reviewSlug}.md`]
|
|
4960
|
+
});
|
|
4961
|
+
await markAsReadByTaskFile(taskFile);
|
|
4962
|
+
await markAsReadByTaskFile(reviewFile);
|
|
4963
|
+
}
|
|
4964
|
+
var init_tasks = __esm({
|
|
4965
|
+
"src/lib/tasks.ts"() {
|
|
4122
4966
|
"use strict";
|
|
4123
4967
|
init_database();
|
|
4968
|
+
init_config();
|
|
4969
|
+
init_notifications();
|
|
4970
|
+
init_state_bus();
|
|
4971
|
+
init_tasks_crud();
|
|
4972
|
+
init_tasks_review();
|
|
4973
|
+
init_tasks_crud();
|
|
4974
|
+
init_tasks_chain();
|
|
4975
|
+
init_tasks_review();
|
|
4976
|
+
init_tasks_notify();
|
|
4124
4977
|
}
|
|
4125
4978
|
});
|
|
4126
4979
|
|
|
4127
|
-
// src/lib/
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
)
|
|
4138
|
-
|
|
4980
|
+
// src/lib/capacity-monitor.ts
|
|
4981
|
+
var capacity_monitor_exports = {};
|
|
4982
|
+
__export(capacity_monitor_exports, {
|
|
4983
|
+
CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
|
|
4984
|
+
_resetLastRelaunchCache: () => _resetLastRelaunchCache,
|
|
4985
|
+
_resetPendingCapacityKills: () => _resetPendingCapacityKills,
|
|
4986
|
+
confirmCapacityKill: () => confirmCapacityKill,
|
|
4987
|
+
createOrRefreshResumeTask: () => createOrRefreshResumeTask,
|
|
4988
|
+
extractContextPercent: () => extractContextPercent,
|
|
4989
|
+
isAtCapacity: () => isAtCapacity,
|
|
4990
|
+
isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
|
|
4991
|
+
pollCapacityDead: () => pollCapacityDead
|
|
4992
|
+
});
|
|
4993
|
+
function resumeTaskTitle(agentId) {
|
|
4994
|
+
return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
|
|
4995
|
+
}
|
|
4996
|
+
function buildResumeContext(agentId, openTasks) {
|
|
4997
|
+
const taskList = openTasks.map(
|
|
4998
|
+
(r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
|
|
4999
|
+
).join("\n");
|
|
5000
|
+
return [
|
|
5001
|
+
"## Context",
|
|
5002
|
+
"",
|
|
5003
|
+
`${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
|
|
5004
|
+
"Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
|
|
5005
|
+
"",
|
|
5006
|
+
`You have ${openTasks.length} open task(s). Work through them in priority order:`,
|
|
5007
|
+
"",
|
|
5008
|
+
taskList,
|
|
5009
|
+
"",
|
|
5010
|
+
"Read each task file and chain through them. Build and commit after each one."
|
|
5011
|
+
].join("\n");
|
|
4139
5012
|
}
|
|
4140
|
-
function
|
|
4141
|
-
return
|
|
5013
|
+
function filterPaneContent(paneOutput) {
|
|
5014
|
+
return paneOutput.split("\n").filter((line) => {
|
|
5015
|
+
if (CONTENT_LINE_PREFIX.test(line)) return false;
|
|
5016
|
+
for (const marker of CONTENT_LINE_MARKERS) {
|
|
5017
|
+
if (line.includes(marker)) return false;
|
|
5018
|
+
}
|
|
5019
|
+
for (const re of SOURCE_CODE_MARKERS) {
|
|
5020
|
+
if (re.test(line)) return false;
|
|
5021
|
+
}
|
|
5022
|
+
return true;
|
|
5023
|
+
}).join("\n");
|
|
5024
|
+
}
|
|
5025
|
+
function extractContextPercent(paneOutput) {
|
|
5026
|
+
const match = paneOutput.match(CC_CONTEXT_BAR_RE);
|
|
5027
|
+
if (!match) return null;
|
|
5028
|
+
const parsed = Number.parseInt(match[2], 10);
|
|
5029
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
5030
|
+
}
|
|
5031
|
+
function isAtCapacity(paneOutput) {
|
|
5032
|
+
const filtered = filterPaneContent(paneOutput);
|
|
5033
|
+
return CAPACITY_PATTERNS.some((p) => p.test(filtered));
|
|
5034
|
+
}
|
|
5035
|
+
function confirmCapacityKill(agentId, now = Date.now()) {
|
|
5036
|
+
const pendingSince = _pendingCapacityKill.get(agentId);
|
|
5037
|
+
if (pendingSince === void 0) {
|
|
5038
|
+
_pendingCapacityKill.set(agentId, now);
|
|
5039
|
+
return false;
|
|
5040
|
+
}
|
|
5041
|
+
if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
|
|
5042
|
+
_pendingCapacityKill.set(agentId, now);
|
|
5043
|
+
return false;
|
|
5044
|
+
}
|
|
5045
|
+
_pendingCapacityKill.delete(agentId);
|
|
5046
|
+
return true;
|
|
4142
5047
|
}
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
|
|
4146
|
-
|
|
5048
|
+
function _resetPendingCapacityKills() {
|
|
5049
|
+
_pendingCapacityKill.clear();
|
|
5050
|
+
}
|
|
5051
|
+
function _resetLastRelaunchCache() {
|
|
5052
|
+
_lastRelaunch.clear();
|
|
5053
|
+
}
|
|
5054
|
+
async function lastResumeCreatedAtMs(agentId) {
|
|
5055
|
+
const client = getClient();
|
|
5056
|
+
const result = await client.execute({
|
|
5057
|
+
sql: `SELECT MAX(created_at) AS last_created_at
|
|
5058
|
+
FROM tasks
|
|
5059
|
+
WHERE assigned_to = ? AND title LIKE ?`,
|
|
5060
|
+
args: [agentId, `${RESUME_TITLE_PREFIX} %`]
|
|
4147
5061
|
});
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
|
|
5062
|
+
const raw = result.rows[0]?.last_created_at;
|
|
5063
|
+
if (raw === null || raw === void 0) return null;
|
|
5064
|
+
const parsed = Date.parse(String(raw));
|
|
5065
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
5066
|
+
}
|
|
5067
|
+
async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
|
|
5068
|
+
const cached = _lastRelaunch.get(agentId);
|
|
5069
|
+
if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
|
|
5070
|
+
const persisted = await lastResumeCreatedAtMs(agentId);
|
|
5071
|
+
if (persisted === null) return false;
|
|
5072
|
+
if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
|
|
5073
|
+
_lastRelaunch.set(agentId, persisted);
|
|
5074
|
+
return true;
|
|
5075
|
+
}
|
|
5076
|
+
async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
|
|
5077
|
+
const client = getClient();
|
|
5078
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
5079
|
+
const context = buildResumeContext(agentId, openTasks);
|
|
5080
|
+
const existing = await client.execute({
|
|
5081
|
+
sql: `SELECT id FROM tasks
|
|
5082
|
+
WHERE assigned_to = ?
|
|
5083
|
+
AND title LIKE ?
|
|
5084
|
+
AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
|
|
5085
|
+
ORDER BY created_at DESC
|
|
5086
|
+
LIMIT 1`,
|
|
5087
|
+
args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
|
|
4152
5088
|
});
|
|
4153
|
-
if (
|
|
4154
|
-
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
const active = candidates.filter(
|
|
4161
|
-
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
4162
|
-
);
|
|
4163
|
-
if (active.length === 1) return active[0];
|
|
4164
|
-
const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
4165
|
-
throw new Error(
|
|
4166
|
-
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
4167
|
-
);
|
|
5089
|
+
if (existing.rows.length > 0) {
|
|
5090
|
+
const taskId = String(existing.rows[0].id);
|
|
5091
|
+
await client.execute({
|
|
5092
|
+
sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
|
|
5093
|
+
args: [context, now, taskId]
|
|
5094
|
+
});
|
|
5095
|
+
return { created: false, taskId };
|
|
4168
5096
|
}
|
|
4169
|
-
|
|
4170
|
-
|
|
4171
|
-
|
|
5097
|
+
const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
|
|
5098
|
+
const task = await createTask2({
|
|
5099
|
+
title: resumeTaskTitle(agentId),
|
|
5100
|
+
assignedTo: agentId,
|
|
5101
|
+
assignedBy: "system",
|
|
5102
|
+
projectName: projectDir.split("/").pop() ?? "unknown",
|
|
5103
|
+
priority: "p0",
|
|
5104
|
+
context,
|
|
5105
|
+
baseDir: projectDir
|
|
4172
5106
|
});
|
|
4173
|
-
|
|
4174
|
-
|
|
4175
|
-
|
|
4176
|
-
|
|
5107
|
+
return { created: true, taskId: task.id };
|
|
5108
|
+
}
|
|
5109
|
+
async function pollCapacityDead() {
|
|
5110
|
+
const transport = getTransport();
|
|
5111
|
+
const relaunched = [];
|
|
5112
|
+
const registered = listSessions().filter(
|
|
5113
|
+
(s) => s.agentId !== "exe"
|
|
5114
|
+
);
|
|
5115
|
+
if (registered.length === 0) return [];
|
|
5116
|
+
let liveSessions;
|
|
5117
|
+
try {
|
|
5118
|
+
liveSessions = transport.listSessions();
|
|
5119
|
+
} catch {
|
|
5120
|
+
return [];
|
|
5121
|
+
}
|
|
5122
|
+
for (const entry of registered) {
|
|
5123
|
+
const { windowName, agentId, projectDir } = entry;
|
|
5124
|
+
if (!liveSessions.includes(windowName)) continue;
|
|
5125
|
+
if (await isWithinRelaunchCooldown(agentId)) continue;
|
|
5126
|
+
let pane;
|
|
5127
|
+
try {
|
|
5128
|
+
pane = transport.capturePane(windowName, 15);
|
|
5129
|
+
} catch {
|
|
5130
|
+
continue;
|
|
5131
|
+
}
|
|
5132
|
+
if (!isAtCapacity(pane)) continue;
|
|
5133
|
+
const ctxPct = extractContextPercent(pane);
|
|
5134
|
+
if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
|
|
5135
|
+
process.stderr.write(
|
|
5136
|
+
`[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
|
|
5137
|
+
`
|
|
5138
|
+
);
|
|
5139
|
+
continue;
|
|
5140
|
+
}
|
|
5141
|
+
if (!confirmCapacityKill(agentId)) {
|
|
5142
|
+
process.stderr.write(
|
|
5143
|
+
`[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
|
|
5144
|
+
`
|
|
5145
|
+
);
|
|
5146
|
+
continue;
|
|
5147
|
+
}
|
|
5148
|
+
const verify = await verifyPaneAtCapacity(windowName);
|
|
5149
|
+
if (!verify.atCapacity) {
|
|
5150
|
+
process.stderr.write(
|
|
5151
|
+
`[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
|
|
5152
|
+
`
|
|
5153
|
+
);
|
|
5154
|
+
void recordSessionKill({
|
|
5155
|
+
sessionName: windowName,
|
|
5156
|
+
agentId,
|
|
5157
|
+
reason: "capacity_false_positive_blocked"
|
|
5158
|
+
});
|
|
5159
|
+
continue;
|
|
5160
|
+
}
|
|
5161
|
+
process.stderr.write(
|
|
5162
|
+
`[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
|
|
5163
|
+
`
|
|
4177
5164
|
);
|
|
4178
|
-
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
|
|
5165
|
+
try {
|
|
5166
|
+
transport.kill(windowName);
|
|
5167
|
+
void recordSessionKill({
|
|
5168
|
+
sessionName: windowName,
|
|
5169
|
+
agentId,
|
|
5170
|
+
reason: "capacity"
|
|
5171
|
+
});
|
|
5172
|
+
const client = getClient();
|
|
5173
|
+
const openTasks = await client.execute({
|
|
5174
|
+
sql: `SELECT id, title, priority, task_file, status
|
|
5175
|
+
FROM tasks
|
|
5176
|
+
WHERE assigned_to = ? AND status IN ('open', 'in_progress')
|
|
5177
|
+
ORDER BY
|
|
5178
|
+
CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
|
|
5179
|
+
created_at ASC
|
|
5180
|
+
LIMIT 10`,
|
|
5181
|
+
args: [agentId]
|
|
5182
|
+
});
|
|
5183
|
+
if (openTasks.rows.length === 0) {
|
|
5184
|
+
process.stderr.write(
|
|
5185
|
+
`[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
|
|
5186
|
+
`
|
|
5187
|
+
);
|
|
5188
|
+
continue;
|
|
5189
|
+
}
|
|
5190
|
+
const { created } = await createOrRefreshResumeTask(
|
|
5191
|
+
agentId,
|
|
5192
|
+
projectDir,
|
|
5193
|
+
openTasks.rows
|
|
5194
|
+
);
|
|
5195
|
+
if (created) {
|
|
5196
|
+
await writeNotification({
|
|
5197
|
+
agentId: "system",
|
|
5198
|
+
agentRole: "daemon",
|
|
5199
|
+
event: "capacity_relaunch",
|
|
5200
|
+
project: projectDir.split("/").pop() ?? "unknown",
|
|
5201
|
+
summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
|
|
5202
|
+
});
|
|
5203
|
+
}
|
|
5204
|
+
_lastRelaunch.set(agentId, Date.now());
|
|
5205
|
+
if (created) relaunched.push(agentId);
|
|
5206
|
+
} catch (err) {
|
|
5207
|
+
process.stderr.write(
|
|
5208
|
+
`[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
|
|
5209
|
+
`
|
|
5210
|
+
);
|
|
5211
|
+
}
|
|
5212
|
+
}
|
|
5213
|
+
return relaunched;
|
|
5214
|
+
}
|
|
5215
|
+
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;
|
|
5216
|
+
var init_capacity_monitor = __esm({
|
|
5217
|
+
"src/lib/capacity-monitor.ts"() {
|
|
5218
|
+
"use strict";
|
|
5219
|
+
init_session_registry();
|
|
5220
|
+
init_transport();
|
|
5221
|
+
init_notifications();
|
|
5222
|
+
init_database();
|
|
5223
|
+
init_session_kill_telemetry();
|
|
5224
|
+
init_tmux_routing();
|
|
5225
|
+
CAPACITY_PATTERNS = [
|
|
5226
|
+
/conversation is too long/i,
|
|
5227
|
+
/maximum context length/i,
|
|
5228
|
+
/context window.*(?:limit|exceed|full)/i,
|
|
5229
|
+
/reached.*(?:token|context).*limit/i
|
|
5230
|
+
];
|
|
5231
|
+
CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
|
|
5232
|
+
CONTENT_LINE_MARKERS = [
|
|
5233
|
+
"RESUME:",
|
|
5234
|
+
"intercom",
|
|
5235
|
+
"capacity-monitor",
|
|
5236
|
+
"CAPACITY_PATTERNS",
|
|
5237
|
+
"isAtCapacity",
|
|
5238
|
+
"CONTENT_LINE_MARKERS",
|
|
5239
|
+
"pollCapacityDead",
|
|
5240
|
+
"confirmCapacityKill",
|
|
5241
|
+
"session_kills",
|
|
5242
|
+
"capacity-monitor.test"
|
|
5243
|
+
];
|
|
5244
|
+
SOURCE_CODE_MARKERS = [
|
|
5245
|
+
/["'`/].*(?:maximum context length|conversation is too long)/i,
|
|
5246
|
+
/(?:maximum context length|conversation is too long).*["'`/]/i
|
|
5247
|
+
];
|
|
5248
|
+
RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
|
|
5249
|
+
_lastRelaunch = /* @__PURE__ */ new Map();
|
|
5250
|
+
RESUME_TITLE_PREFIX = "RESUME:";
|
|
5251
|
+
RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
|
|
5252
|
+
RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
|
|
5253
|
+
CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
|
|
5254
|
+
_pendingCapacityKill = /* @__PURE__ */ new Map();
|
|
5255
|
+
CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
|
|
5256
|
+
CTX_FLOOR_PERCENT = 50;
|
|
5257
|
+
}
|
|
5258
|
+
});
|
|
5259
|
+
|
|
5260
|
+
// src/lib/tmux-routing.ts
|
|
5261
|
+
var tmux_routing_exports = {};
|
|
5262
|
+
__export(tmux_routing_exports, {
|
|
5263
|
+
acquireSpawnLock: () => acquireSpawnLock2,
|
|
5264
|
+
employeeSessionName: () => employeeSessionName,
|
|
5265
|
+
ensureEmployee: () => ensureEmployee,
|
|
5266
|
+
extractRootExe: () => extractRootExe,
|
|
5267
|
+
findFreeInstance: () => findFreeInstance,
|
|
5268
|
+
getDispatchedBy: () => getDispatchedBy,
|
|
5269
|
+
getMySession: () => getMySession,
|
|
5270
|
+
getParentExe: () => getParentExe,
|
|
5271
|
+
getSessionState: () => getSessionState,
|
|
5272
|
+
isEmployeeAlive: () => isEmployeeAlive,
|
|
5273
|
+
isExeSession: () => isExeSession,
|
|
5274
|
+
isSessionBusy: () => isSessionBusy,
|
|
5275
|
+
notifyParentExe: () => notifyParentExe,
|
|
5276
|
+
parseParentExe: () => parseParentExe,
|
|
5277
|
+
registerParentExe: () => registerParentExe,
|
|
5278
|
+
releaseSpawnLock: () => releaseSpawnLock2,
|
|
5279
|
+
resolveExeSession: () => resolveExeSession,
|
|
5280
|
+
sendIntercom: () => sendIntercom,
|
|
5281
|
+
spawnEmployee: () => spawnEmployee,
|
|
5282
|
+
verifyPaneAtCapacity: () => verifyPaneAtCapacity
|
|
5283
|
+
});
|
|
5284
|
+
import { execFileSync as execFileSync2, execSync as execSync8 } from "child_process";
|
|
5285
|
+
import { readFileSync as readFileSync12, writeFileSync as writeFileSync6, mkdirSync as mkdirSync7, existsSync as existsSync15, appendFileSync } from "fs";
|
|
5286
|
+
import path19 from "path";
|
|
5287
|
+
import os6 from "os";
|
|
5288
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
5289
|
+
import { unlinkSync as unlinkSync6 } from "fs";
|
|
5290
|
+
function spawnLockPath(sessionName) {
|
|
5291
|
+
return path19.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
|
|
5292
|
+
}
|
|
5293
|
+
function isProcessAlive(pid) {
|
|
5294
|
+
try {
|
|
5295
|
+
process.kill(pid, 0);
|
|
5296
|
+
return true;
|
|
5297
|
+
} catch {
|
|
5298
|
+
return false;
|
|
5299
|
+
}
|
|
5300
|
+
}
|
|
5301
|
+
function acquireSpawnLock2(sessionName) {
|
|
5302
|
+
if (!existsSync15(SPAWN_LOCK_DIR)) {
|
|
5303
|
+
mkdirSync7(SPAWN_LOCK_DIR, { recursive: true });
|
|
5304
|
+
}
|
|
5305
|
+
const lockFile = spawnLockPath(sessionName);
|
|
5306
|
+
if (existsSync15(lockFile)) {
|
|
5307
|
+
try {
|
|
5308
|
+
const lock = JSON.parse(readFileSync12(lockFile, "utf8"));
|
|
5309
|
+
const age = Date.now() - lock.timestamp;
|
|
5310
|
+
if (isProcessAlive(lock.pid) && age < 6e4) {
|
|
5311
|
+
return false;
|
|
5312
|
+
}
|
|
5313
|
+
} catch {
|
|
5314
|
+
}
|
|
5315
|
+
}
|
|
5316
|
+
writeFileSync6(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
|
|
5317
|
+
return true;
|
|
5318
|
+
}
|
|
5319
|
+
function releaseSpawnLock2(sessionName) {
|
|
5320
|
+
try {
|
|
5321
|
+
unlinkSync6(spawnLockPath(sessionName));
|
|
5322
|
+
} catch {
|
|
5323
|
+
}
|
|
5324
|
+
}
|
|
5325
|
+
function resolveBehaviorsExporterScript() {
|
|
5326
|
+
try {
|
|
5327
|
+
const thisFile = fileURLToPath2(import.meta.url);
|
|
5328
|
+
const scriptPath = path19.join(
|
|
5329
|
+
path19.dirname(thisFile),
|
|
5330
|
+
"..",
|
|
5331
|
+
"bin",
|
|
5332
|
+
"exe-export-behaviors.js"
|
|
4182
5333
|
);
|
|
5334
|
+
return existsSync15(scriptPath) ? scriptPath : null;
|
|
5335
|
+
} catch {
|
|
5336
|
+
return null;
|
|
4183
5337
|
}
|
|
4184
|
-
throw new Error(`Task not found: ${identifier}`);
|
|
4185
5338
|
}
|
|
4186
|
-
|
|
5339
|
+
function exportBehaviorsSync(agentId, projectName, sessionKey) {
|
|
5340
|
+
const script = resolveBehaviorsExporterScript();
|
|
5341
|
+
if (!script) return null;
|
|
5342
|
+
try {
|
|
5343
|
+
const output = execFileSync2(
|
|
5344
|
+
process.execPath,
|
|
5345
|
+
[script, agentId, projectName, sessionKey],
|
|
5346
|
+
{ encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
|
|
5347
|
+
).trim();
|
|
5348
|
+
return output.length > 0 ? output : null;
|
|
5349
|
+
} catch (err) {
|
|
5350
|
+
process.stderr.write(
|
|
5351
|
+
`[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
|
|
5352
|
+
`
|
|
5353
|
+
);
|
|
5354
|
+
return null;
|
|
5355
|
+
}
|
|
5356
|
+
}
|
|
5357
|
+
function getMySession() {
|
|
5358
|
+
return getTransport().getMySession();
|
|
5359
|
+
}
|
|
5360
|
+
function employeeSessionName(employee, exeSession, instance) {
|
|
5361
|
+
if (!/^exe\d+$/.test(exeSession)) {
|
|
5362
|
+
const root = extractRootExe(exeSession);
|
|
5363
|
+
if (root) {
|
|
5364
|
+
process.stderr.write(
|
|
5365
|
+
`[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
|
|
5366
|
+
`
|
|
5367
|
+
);
|
|
5368
|
+
exeSession = root;
|
|
5369
|
+
} else {
|
|
5370
|
+
throw new Error(
|
|
5371
|
+
`Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
|
|
5372
|
+
);
|
|
5373
|
+
}
|
|
5374
|
+
}
|
|
5375
|
+
const suffix = instance != null && instance > 0 ? String(instance) : "";
|
|
5376
|
+
const name = `${employee}${suffix}-${exeSession}`;
|
|
5377
|
+
if (!VALID_SESSION_NAME.test(name)) {
|
|
5378
|
+
throw new Error(
|
|
5379
|
+
`Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
|
|
5380
|
+
);
|
|
5381
|
+
}
|
|
5382
|
+
return name;
|
|
5383
|
+
}
|
|
5384
|
+
function parseParentExe(sessionName, agentId) {
|
|
5385
|
+
const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5386
|
+
const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
|
|
5387
|
+
const match = sessionName.match(regex);
|
|
5388
|
+
return match?.[1] ?? null;
|
|
5389
|
+
}
|
|
5390
|
+
function extractRootExe(name) {
|
|
5391
|
+
const match = name.match(/(exe\d+)$/);
|
|
5392
|
+
return match?.[1] ?? null;
|
|
5393
|
+
}
|
|
5394
|
+
function registerParentExe(sessionKey, parentExe, dispatchedBy) {
|
|
5395
|
+
if (!existsSync15(SESSION_CACHE)) {
|
|
5396
|
+
mkdirSync7(SESSION_CACHE, { recursive: true });
|
|
5397
|
+
}
|
|
5398
|
+
const rootExe = extractRootExe(parentExe) ?? parentExe;
|
|
5399
|
+
const filePath = path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
|
|
5400
|
+
writeFileSync6(filePath, JSON.stringify({
|
|
5401
|
+
parentExe: rootExe,
|
|
5402
|
+
dispatchedBy: dispatchedBy || rootExe,
|
|
5403
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5404
|
+
}));
|
|
5405
|
+
}
|
|
5406
|
+
function getParentExe(sessionKey) {
|
|
5407
|
+
try {
|
|
5408
|
+
const data = JSON.parse(readFileSync12(path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
5409
|
+
return data.parentExe || null;
|
|
5410
|
+
} catch {
|
|
5411
|
+
return null;
|
|
5412
|
+
}
|
|
5413
|
+
}
|
|
5414
|
+
function getDispatchedBy(sessionKey) {
|
|
5415
|
+
try {
|
|
5416
|
+
const data = JSON.parse(readFileSync12(
|
|
5417
|
+
path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
|
|
5418
|
+
"utf8"
|
|
5419
|
+
));
|
|
5420
|
+
return data.dispatchedBy ?? data.parentExe ?? null;
|
|
5421
|
+
} catch {
|
|
5422
|
+
return null;
|
|
5423
|
+
}
|
|
5424
|
+
}
|
|
5425
|
+
function resolveExeSession() {
|
|
5426
|
+
const mySession = getMySession();
|
|
5427
|
+
if (!mySession) return null;
|
|
5428
|
+
try {
|
|
5429
|
+
const key = getSessionKey();
|
|
5430
|
+
const parentExe = getParentExe(key);
|
|
5431
|
+
if (parentExe) {
|
|
5432
|
+
return extractRootExe(parentExe) ?? parentExe;
|
|
5433
|
+
}
|
|
5434
|
+
} catch {
|
|
5435
|
+
}
|
|
5436
|
+
return extractRootExe(mySession) ?? mySession;
|
|
5437
|
+
}
|
|
5438
|
+
function isEmployeeAlive(sessionName) {
|
|
5439
|
+
return getTransport().isAlive(sessionName);
|
|
5440
|
+
}
|
|
5441
|
+
function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
|
|
5442
|
+
const base = employeeSessionName(employeeName, exeSession);
|
|
5443
|
+
if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
|
|
5444
|
+
for (let i = 2; i <= maxInstances; i++) {
|
|
5445
|
+
const candidate = employeeSessionName(employeeName, exeSession, i);
|
|
5446
|
+
if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
|
|
5447
|
+
}
|
|
5448
|
+
return null;
|
|
5449
|
+
}
|
|
5450
|
+
async function verifyPaneAtCapacity(sessionName) {
|
|
5451
|
+
const transport = getTransport();
|
|
5452
|
+
if (!transport.isAlive(sessionName)) {
|
|
5453
|
+
return { atCapacity: false, reason: `session ${sessionName} is not alive` };
|
|
5454
|
+
}
|
|
5455
|
+
let pane;
|
|
5456
|
+
try {
|
|
5457
|
+
pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
|
|
5458
|
+
} catch (err) {
|
|
5459
|
+
return {
|
|
5460
|
+
atCapacity: false,
|
|
5461
|
+
reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
|
|
5462
|
+
};
|
|
5463
|
+
}
|
|
5464
|
+
const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
|
|
5465
|
+
if (!isAtCapacity2(pane)) {
|
|
5466
|
+
return {
|
|
5467
|
+
atCapacity: false,
|
|
5468
|
+
reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
|
|
5469
|
+
};
|
|
5470
|
+
}
|
|
5471
|
+
return {
|
|
5472
|
+
atCapacity: true,
|
|
5473
|
+
reason: "capacity banner matched in recent pane output"
|
|
5474
|
+
};
|
|
5475
|
+
}
|
|
5476
|
+
function readDebounceState() {
|
|
5477
|
+
try {
|
|
5478
|
+
if (!existsSync15(DEBOUNCE_FILE)) return {};
|
|
5479
|
+
return JSON.parse(readFileSync12(DEBOUNCE_FILE, "utf8"));
|
|
5480
|
+
} catch {
|
|
5481
|
+
return {};
|
|
5482
|
+
}
|
|
5483
|
+
}
|
|
5484
|
+
function writeDebounceState(state) {
|
|
5485
|
+
try {
|
|
5486
|
+
if (!existsSync15(SESSION_CACHE)) mkdirSync7(SESSION_CACHE, { recursive: true });
|
|
5487
|
+
writeFileSync6(DEBOUNCE_FILE, JSON.stringify(state));
|
|
5488
|
+
} catch {
|
|
5489
|
+
}
|
|
5490
|
+
}
|
|
5491
|
+
function isDebounced(targetSession) {
|
|
5492
|
+
const state = readDebounceState();
|
|
5493
|
+
const lastSent = state[targetSession] ?? 0;
|
|
5494
|
+
return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
|
|
5495
|
+
}
|
|
5496
|
+
function recordDebounce(targetSession) {
|
|
5497
|
+
const state = readDebounceState();
|
|
5498
|
+
state[targetSession] = Date.now();
|
|
5499
|
+
const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
|
|
5500
|
+
for (const key of Object.keys(state)) {
|
|
5501
|
+
if ((state[key] ?? 0) < cutoff) delete state[key];
|
|
5502
|
+
}
|
|
5503
|
+
writeDebounceState(state);
|
|
5504
|
+
}
|
|
5505
|
+
function logIntercom(msg) {
|
|
5506
|
+
const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
|
|
5507
|
+
`;
|
|
5508
|
+
process.stderr.write(`[intercom] ${msg}
|
|
5509
|
+
`);
|
|
5510
|
+
try {
|
|
5511
|
+
appendFileSync(INTERCOM_LOG2, line);
|
|
5512
|
+
} catch {
|
|
5513
|
+
}
|
|
5514
|
+
}
|
|
5515
|
+
function getSessionState(sessionName) {
|
|
5516
|
+
const transport = getTransport();
|
|
5517
|
+
if (!transport.isAlive(sessionName)) return "offline";
|
|
5518
|
+
try {
|
|
5519
|
+
const pane = transport.capturePane(sessionName, 5);
|
|
5520
|
+
if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
|
|
5521
|
+
if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
|
|
5522
|
+
return "no_claude";
|
|
5523
|
+
}
|
|
5524
|
+
}
|
|
5525
|
+
if (/Running…/.test(pane)) return "tool";
|
|
5526
|
+
if (BUSY_PATTERN.test(pane)) return "thinking";
|
|
5527
|
+
return "idle";
|
|
5528
|
+
} catch {
|
|
5529
|
+
return "offline";
|
|
5530
|
+
}
|
|
5531
|
+
}
|
|
5532
|
+
function isSessionBusy(sessionName) {
|
|
5533
|
+
const state = getSessionState(sessionName);
|
|
5534
|
+
return state === "thinking" || state === "tool";
|
|
5535
|
+
}
|
|
5536
|
+
function isExeSession(sessionName) {
|
|
5537
|
+
return /^exe\d*$/.test(sessionName);
|
|
5538
|
+
}
|
|
5539
|
+
function sendIntercom(targetSession) {
|
|
5540
|
+
const transport = getTransport();
|
|
5541
|
+
if (isExeSession(targetSession)) {
|
|
5542
|
+
logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
|
|
5543
|
+
return "skipped_exe";
|
|
5544
|
+
}
|
|
5545
|
+
if (isDebounced(targetSession)) {
|
|
5546
|
+
logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
|
|
5547
|
+
return "debounced";
|
|
5548
|
+
}
|
|
5549
|
+
try {
|
|
5550
|
+
const sessions = transport.listSessions();
|
|
5551
|
+
if (!sessions.includes(targetSession)) {
|
|
5552
|
+
logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
|
|
5553
|
+
return "failed";
|
|
5554
|
+
}
|
|
5555
|
+
const sessionState = getSessionState(targetSession);
|
|
5556
|
+
if (sessionState === "no_claude") {
|
|
5557
|
+
queueIntercom(targetSession, "claude not running in session");
|
|
5558
|
+
recordDebounce(targetSession);
|
|
5559
|
+
logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
|
|
5560
|
+
return "queued";
|
|
5561
|
+
}
|
|
5562
|
+
if (sessionState === "thinking" || sessionState === "tool") {
|
|
5563
|
+
queueIntercom(targetSession, "session busy at send time");
|
|
5564
|
+
recordDebounce(targetSession);
|
|
5565
|
+
logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
|
|
5566
|
+
return "queued";
|
|
5567
|
+
}
|
|
5568
|
+
if (transport.isPaneInCopyMode(targetSession)) {
|
|
5569
|
+
logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
|
|
5570
|
+
transport.sendKeys(targetSession, "q");
|
|
5571
|
+
}
|
|
5572
|
+
transport.sendKeys(targetSession, "/exe-intercom");
|
|
5573
|
+
recordDebounce(targetSession);
|
|
5574
|
+
logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
|
|
5575
|
+
return "delivered";
|
|
5576
|
+
} catch {
|
|
5577
|
+
logIntercom(`FAIL \u2192 ${targetSession}`);
|
|
5578
|
+
return "failed";
|
|
5579
|
+
}
|
|
5580
|
+
}
|
|
5581
|
+
function notifyParentExe(sessionKey) {
|
|
5582
|
+
const target = getDispatchedBy(sessionKey);
|
|
5583
|
+
if (!target) {
|
|
5584
|
+
process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
|
|
5585
|
+
`);
|
|
5586
|
+
return false;
|
|
5587
|
+
}
|
|
5588
|
+
process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
|
|
5589
|
+
`);
|
|
5590
|
+
const result = sendIntercom(target);
|
|
5591
|
+
if (result === "failed") {
|
|
5592
|
+
const rootExe = resolveExeSession();
|
|
5593
|
+
if (rootExe && rootExe !== target) {
|
|
5594
|
+
process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
|
|
5595
|
+
`);
|
|
5596
|
+
const fallback = sendIntercom(rootExe);
|
|
5597
|
+
return fallback !== "failed";
|
|
5598
|
+
}
|
|
5599
|
+
return false;
|
|
5600
|
+
}
|
|
5601
|
+
return true;
|
|
5602
|
+
}
|
|
5603
|
+
function ensureEmployee(employeeName, exeSession, projectDir, opts) {
|
|
5604
|
+
if (employeeName === "exe") {
|
|
5605
|
+
return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
|
|
5606
|
+
}
|
|
5607
|
+
try {
|
|
5608
|
+
assertEmployeeLimitSync();
|
|
5609
|
+
} catch (err) {
|
|
5610
|
+
if (err instanceof PlanLimitError) {
|
|
5611
|
+
return { status: "failed", sessionName: "", error: err.message };
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
if (/-exe\d*$/.test(employeeName)) {
|
|
5615
|
+
const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
|
|
5616
|
+
return {
|
|
5617
|
+
status: "failed",
|
|
5618
|
+
sessionName: "",
|
|
5619
|
+
error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
|
|
5620
|
+
};
|
|
5621
|
+
}
|
|
5622
|
+
if (!/^exe\d+$/.test(exeSession)) {
|
|
5623
|
+
const root = extractRootExe(exeSession);
|
|
5624
|
+
if (root) {
|
|
5625
|
+
process.stderr.write(
|
|
5626
|
+
`[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
|
|
5627
|
+
`
|
|
5628
|
+
);
|
|
5629
|
+
exeSession = root;
|
|
5630
|
+
} else {
|
|
5631
|
+
return {
|
|
5632
|
+
status: "failed",
|
|
5633
|
+
sessionName: "",
|
|
5634
|
+
error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
|
|
5635
|
+
};
|
|
5636
|
+
}
|
|
5637
|
+
}
|
|
5638
|
+
let effectiveInstance = opts?.instance;
|
|
5639
|
+
if (effectiveInstance === void 0 && opts?.autoInstance) {
|
|
5640
|
+
const free = findFreeInstance(
|
|
5641
|
+
employeeName,
|
|
5642
|
+
exeSession,
|
|
5643
|
+
opts.maxAutoInstances ?? 10
|
|
5644
|
+
);
|
|
5645
|
+
if (free === null) {
|
|
5646
|
+
return {
|
|
5647
|
+
status: "failed",
|
|
5648
|
+
sessionName: employeeSessionName(employeeName, exeSession),
|
|
5649
|
+
error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
|
|
5650
|
+
};
|
|
5651
|
+
}
|
|
5652
|
+
effectiveInstance = free === 0 ? void 0 : free;
|
|
5653
|
+
}
|
|
5654
|
+
const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
|
|
5655
|
+
if (isEmployeeAlive(sessionName)) {
|
|
5656
|
+
const result2 = sendIntercom(sessionName);
|
|
5657
|
+
if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
|
|
5658
|
+
return { status: "intercom_sent", sessionName };
|
|
5659
|
+
}
|
|
5660
|
+
if (result2 === "delivered") {
|
|
5661
|
+
return { status: "intercom_unprocessed", sessionName };
|
|
5662
|
+
}
|
|
5663
|
+
return { status: "failed", sessionName, error: "intercom delivery failed" };
|
|
5664
|
+
}
|
|
5665
|
+
const spawnOpts = { ...opts, instance: effectiveInstance };
|
|
5666
|
+
const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
|
|
5667
|
+
if (result.error) {
|
|
5668
|
+
return { status: "failed", sessionName, error: result.error };
|
|
5669
|
+
}
|
|
5670
|
+
return { status: "spawned", sessionName };
|
|
5671
|
+
}
|
|
5672
|
+
function spawnEmployee(employeeName, exeSession, projectDir, opts) {
|
|
5673
|
+
const transport = getTransport();
|
|
5674
|
+
const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
|
|
5675
|
+
const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
|
|
5676
|
+
const logDir = path19.join(os6.homedir(), ".exe-os", "session-logs");
|
|
5677
|
+
const logFile = path19.join(logDir, `${instanceLabel}-${Date.now()}.log`);
|
|
5678
|
+
if (!existsSync15(logDir)) {
|
|
5679
|
+
mkdirSync7(logDir, { recursive: true });
|
|
5680
|
+
}
|
|
5681
|
+
transport.kill(sessionName);
|
|
5682
|
+
let cleanupSuffix = "";
|
|
5683
|
+
try {
|
|
5684
|
+
const thisFile = fileURLToPath2(import.meta.url);
|
|
5685
|
+
const cleanupScript = path19.join(path19.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
|
|
5686
|
+
if (existsSync15(cleanupScript)) {
|
|
5687
|
+
cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
|
|
5688
|
+
}
|
|
5689
|
+
} catch {
|
|
5690
|
+
}
|
|
5691
|
+
try {
|
|
5692
|
+
const claudeJsonPath = path19.join(os6.homedir(), ".claude.json");
|
|
5693
|
+
let claudeJson = {};
|
|
5694
|
+
try {
|
|
5695
|
+
claudeJson = JSON.parse(readFileSync12(claudeJsonPath, "utf8"));
|
|
5696
|
+
} catch {
|
|
5697
|
+
}
|
|
5698
|
+
if (!claudeJson.projects) claudeJson.projects = {};
|
|
5699
|
+
const projects = claudeJson.projects;
|
|
5700
|
+
const trustDir = opts?.cwd ?? projectDir;
|
|
5701
|
+
if (!projects[trustDir]) projects[trustDir] = {};
|
|
5702
|
+
projects[trustDir].hasTrustDialogAccepted = true;
|
|
5703
|
+
writeFileSync6(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
|
|
5704
|
+
} catch {
|
|
5705
|
+
}
|
|
5706
|
+
try {
|
|
5707
|
+
const settingsDir = path19.join(os6.homedir(), ".claude", "projects");
|
|
5708
|
+
const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
|
|
5709
|
+
const projSettingsDir = path19.join(settingsDir, normalizedKey);
|
|
5710
|
+
const settingsPath = path19.join(projSettingsDir, "settings.json");
|
|
5711
|
+
let settings = {};
|
|
5712
|
+
try {
|
|
5713
|
+
settings = JSON.parse(readFileSync12(settingsPath, "utf8"));
|
|
5714
|
+
} catch {
|
|
5715
|
+
}
|
|
5716
|
+
const perms = settings.permissions ?? {};
|
|
5717
|
+
const allow = perms.allow ?? [];
|
|
5718
|
+
const toolNames = [
|
|
5719
|
+
"recall_my_memory",
|
|
5720
|
+
"store_memory",
|
|
5721
|
+
"create_task",
|
|
5722
|
+
"update_task",
|
|
5723
|
+
"list_tasks",
|
|
5724
|
+
"get_task",
|
|
5725
|
+
"ask_team_memory",
|
|
5726
|
+
"store_behavior",
|
|
5727
|
+
"get_identity",
|
|
5728
|
+
"send_message"
|
|
5729
|
+
];
|
|
5730
|
+
const requiredTools = expandDualPrefixTools(toolNames);
|
|
5731
|
+
let changed = false;
|
|
5732
|
+
for (const tool of requiredTools) {
|
|
5733
|
+
if (!allow.includes(tool)) {
|
|
5734
|
+
allow.push(tool);
|
|
5735
|
+
changed = true;
|
|
5736
|
+
}
|
|
5737
|
+
}
|
|
5738
|
+
if (changed) {
|
|
5739
|
+
perms.allow = allow;
|
|
5740
|
+
settings.permissions = perms;
|
|
5741
|
+
mkdirSync7(projSettingsDir, { recursive: true });
|
|
5742
|
+
writeFileSync6(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
5743
|
+
}
|
|
5744
|
+
} catch {
|
|
5745
|
+
}
|
|
5746
|
+
const spawnCwd = opts?.cwd ?? projectDir;
|
|
5747
|
+
const useExeAgent = !!(opts?.model && opts?.provider);
|
|
5748
|
+
const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
|
|
5749
|
+
const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
|
|
5750
|
+
let identityFlag = "";
|
|
5751
|
+
let behaviorsFlag = "";
|
|
5752
|
+
let legacyFallbackWarned = false;
|
|
5753
|
+
if (!useExeAgent && !useBinSymlink) {
|
|
5754
|
+
const identityPath = path19.join(
|
|
5755
|
+
os6.homedir(),
|
|
5756
|
+
".exe-os",
|
|
5757
|
+
"identity",
|
|
5758
|
+
`${employeeName}.md`
|
|
5759
|
+
);
|
|
5760
|
+
_resetCcAgentSupportCache();
|
|
5761
|
+
const hasAgentFlag = claudeSupportsAgentFlag();
|
|
5762
|
+
if (hasAgentFlag) {
|
|
5763
|
+
identityFlag = ` --agent ${employeeName}`;
|
|
5764
|
+
} else if (existsSync15(identityPath)) {
|
|
5765
|
+
identityFlag = ` --append-system-prompt-file ${identityPath}`;
|
|
5766
|
+
legacyFallbackWarned = true;
|
|
5767
|
+
}
|
|
5768
|
+
const behaviorsFile = exportBehaviorsSync(
|
|
5769
|
+
employeeName,
|
|
5770
|
+
path19.basename(spawnCwd),
|
|
5771
|
+
sessionName
|
|
5772
|
+
);
|
|
5773
|
+
if (behaviorsFile) {
|
|
5774
|
+
behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
|
|
5775
|
+
}
|
|
5776
|
+
}
|
|
5777
|
+
if (legacyFallbackWarned) {
|
|
5778
|
+
process.stderr.write(
|
|
5779
|
+
`[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.
|
|
5780
|
+
`
|
|
5781
|
+
);
|
|
5782
|
+
}
|
|
5783
|
+
let sessionContextFlag = "";
|
|
5784
|
+
try {
|
|
5785
|
+
const ctxDir = path19.join(os6.homedir(), ".exe-os", "session-cache");
|
|
5786
|
+
mkdirSync7(ctxDir, { recursive: true });
|
|
5787
|
+
const ctxFile = path19.join(ctxDir, `session-context-${sessionName}.md`);
|
|
5788
|
+
const ctxContent = [
|
|
5789
|
+
`## Session Context`,
|
|
5790
|
+
`You are running in tmux session: ${sessionName}.`,
|
|
5791
|
+
`Your parent exe session is ${exeSession}.`,
|
|
5792
|
+
`Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
|
|
5793
|
+
].join("\n");
|
|
5794
|
+
writeFileSync6(ctxFile, ctxContent);
|
|
5795
|
+
sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
|
|
5796
|
+
} catch {
|
|
5797
|
+
}
|
|
5798
|
+
let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
|
|
5799
|
+
if (ccProvider !== DEFAULT_PROVIDER) {
|
|
5800
|
+
const cfg = PROVIDER_TABLE[ccProvider];
|
|
5801
|
+
if (cfg?.apiKeyEnv) {
|
|
5802
|
+
const keyVal = process.env[cfg.apiKeyEnv];
|
|
5803
|
+
if (keyVal) {
|
|
5804
|
+
envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
|
|
5805
|
+
}
|
|
5806
|
+
}
|
|
5807
|
+
}
|
|
5808
|
+
let spawnCommand;
|
|
5809
|
+
if (useExeAgent) {
|
|
5810
|
+
spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
|
|
5811
|
+
} else if (useBinSymlink) {
|
|
5812
|
+
const binName = `${employeeName}-${ccProvider}`;
|
|
5813
|
+
process.stderr.write(
|
|
5814
|
+
`[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
|
|
5815
|
+
`
|
|
5816
|
+
);
|
|
5817
|
+
spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
|
|
5818
|
+
} else {
|
|
5819
|
+
spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
|
|
5820
|
+
}
|
|
5821
|
+
const spawnResult = transport.spawn(sessionName, {
|
|
5822
|
+
cwd: spawnCwd,
|
|
5823
|
+
command: spawnCommand
|
|
5824
|
+
});
|
|
5825
|
+
if (spawnResult.error) {
|
|
5826
|
+
releaseSpawnLock2(sessionName);
|
|
5827
|
+
return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
|
|
5828
|
+
}
|
|
5829
|
+
transport.pipeLog(sessionName, logFile);
|
|
5830
|
+
try {
|
|
5831
|
+
const mySession = getMySession();
|
|
5832
|
+
const dispatchInfo = path19.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
|
|
5833
|
+
writeFileSync6(dispatchInfo, JSON.stringify({
|
|
5834
|
+
dispatchedBy: mySession,
|
|
5835
|
+
rootExe: exeSession,
|
|
5836
|
+
provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
|
|
5837
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5838
|
+
}));
|
|
5839
|
+
} catch {
|
|
5840
|
+
}
|
|
5841
|
+
let booted = false;
|
|
5842
|
+
for (let i = 0; i < 30; i++) {
|
|
5843
|
+
try {
|
|
5844
|
+
execSync8("sleep 0.5");
|
|
5845
|
+
} catch {
|
|
5846
|
+
}
|
|
5847
|
+
try {
|
|
5848
|
+
const pane = transport.capturePane(sessionName);
|
|
5849
|
+
if (useExeAgent) {
|
|
5850
|
+
if (pane.includes("[exe-agent]") || pane.includes("online")) {
|
|
5851
|
+
booted = true;
|
|
5852
|
+
break;
|
|
5853
|
+
}
|
|
5854
|
+
} else {
|
|
5855
|
+
if (pane.includes("Claude Code") || pane.includes("\u276F")) {
|
|
5856
|
+
booted = true;
|
|
5857
|
+
break;
|
|
5858
|
+
}
|
|
5859
|
+
}
|
|
5860
|
+
} catch {
|
|
5861
|
+
}
|
|
5862
|
+
}
|
|
5863
|
+
if (!booted) {
|
|
5864
|
+
releaseSpawnLock2(sessionName);
|
|
5865
|
+
return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
|
|
5866
|
+
}
|
|
5867
|
+
if (!useExeAgent) {
|
|
5868
|
+
try {
|
|
5869
|
+
transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
|
|
5870
|
+
} catch {
|
|
5871
|
+
}
|
|
5872
|
+
}
|
|
5873
|
+
registerSession({
|
|
5874
|
+
windowName: sessionName,
|
|
5875
|
+
agentId: employeeName,
|
|
5876
|
+
projectDir: spawnCwd,
|
|
5877
|
+
parentExe: exeSession,
|
|
5878
|
+
pid: 0,
|
|
5879
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5880
|
+
});
|
|
5881
|
+
releaseSpawnLock2(sessionName);
|
|
5882
|
+
return { sessionName };
|
|
5883
|
+
}
|
|
5884
|
+
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;
|
|
5885
|
+
var init_tmux_routing = __esm({
|
|
5886
|
+
"src/lib/tmux-routing.ts"() {
|
|
5887
|
+
"use strict";
|
|
5888
|
+
init_session_registry();
|
|
5889
|
+
init_session_key();
|
|
5890
|
+
init_transport();
|
|
5891
|
+
init_cc_agent_support();
|
|
5892
|
+
init_mcp_prefix();
|
|
5893
|
+
init_provider_table();
|
|
5894
|
+
init_intercom_queue();
|
|
5895
|
+
init_plan_limits();
|
|
5896
|
+
SPAWN_LOCK_DIR = path19.join(os6.homedir(), ".exe-os", "spawn-locks");
|
|
5897
|
+
SESSION_CACHE = path19.join(os6.homedir(), ".exe-os", "session-cache");
|
|
5898
|
+
BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
|
|
5899
|
+
VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
|
|
5900
|
+
VERIFY_PANE_LINES = 200;
|
|
5901
|
+
INTERCOM_DEBOUNCE_MS = 3e4;
|
|
5902
|
+
INTERCOM_LOG2 = path19.join(os6.homedir(), ".exe-os", "intercom.log");
|
|
5903
|
+
DEBOUNCE_FILE = path19.join(SESSION_CACHE, "intercom-debounce.json");
|
|
5904
|
+
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
5905
|
+
BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
|
|
5906
|
+
}
|
|
5907
|
+
});
|
|
5908
|
+
|
|
5909
|
+
// src/lib/messaging.ts
|
|
5910
|
+
var messaging_exports = {};
|
|
5911
|
+
__export(messaging_exports, {
|
|
5912
|
+
deliverLocalMessage: () => deliverLocalMessage,
|
|
5913
|
+
getFailedMessages: () => getFailedMessages,
|
|
5914
|
+
getMessageStatus: () => getMessageStatus,
|
|
5915
|
+
getPendingMessages: () => getPendingMessages,
|
|
5916
|
+
getReadMessages: () => getReadMessages,
|
|
5917
|
+
getUnacknowledgedMessages: () => getUnacknowledgedMessages,
|
|
5918
|
+
markAcknowledged: () => markAcknowledged,
|
|
5919
|
+
markFailed: () => markFailed,
|
|
5920
|
+
markProcessed: () => markProcessed,
|
|
5921
|
+
markRead: () => markRead,
|
|
5922
|
+
retryPendingMessages: () => retryPendingMessages,
|
|
5923
|
+
sendMessage: () => sendMessage,
|
|
5924
|
+
setWsClientSend: () => setWsClientSend
|
|
5925
|
+
});
|
|
5926
|
+
import crypto8 from "crypto";
|
|
5927
|
+
function generateUlid() {
|
|
5928
|
+
const timestamp = Date.now().toString(36).padStart(10, "0");
|
|
5929
|
+
const random = crypto8.randomBytes(10).toString("hex").slice(0, 16);
|
|
5930
|
+
return (timestamp + random).toUpperCase();
|
|
5931
|
+
}
|
|
5932
|
+
function rowToMessage(row) {
|
|
5933
|
+
return {
|
|
5934
|
+
id: row.id,
|
|
5935
|
+
fromAgent: row.from_agent,
|
|
5936
|
+
fromDevice: row.from_device,
|
|
5937
|
+
targetAgent: row.target_agent,
|
|
5938
|
+
targetProject: row.target_project ?? null,
|
|
5939
|
+
targetDevice: row.target_device,
|
|
5940
|
+
content: row.content,
|
|
5941
|
+
priority: row.priority ?? "normal",
|
|
5942
|
+
status: row.status ?? "pending",
|
|
5943
|
+
serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
|
|
5944
|
+
retryCount: Number(row.retry_count ?? 0),
|
|
5945
|
+
createdAt: row.created_at,
|
|
5946
|
+
deliveredAt: row.delivered_at ?? null,
|
|
5947
|
+
processedAt: row.processed_at ?? null,
|
|
5948
|
+
failedAt: row.failed_at ?? null,
|
|
5949
|
+
failureReason: row.failure_reason ?? null
|
|
5950
|
+
};
|
|
5951
|
+
}
|
|
5952
|
+
async function sendMessage(input2) {
|
|
4187
5953
|
const client = getClient();
|
|
4188
|
-
const id =
|
|
5954
|
+
const id = generateUlid();
|
|
4189
5955
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4190
|
-
const
|
|
4191
|
-
const taskFile = input2.taskFile ?? `exe/${input2.assignedTo}/${slug}.md`;
|
|
4192
|
-
let blockedById = null;
|
|
4193
|
-
const initialStatus = input2.blockedBy ? "blocked" : "open";
|
|
4194
|
-
if (input2.blockedBy) {
|
|
4195
|
-
const blocker = await resolveTask(client, input2.blockedBy);
|
|
4196
|
-
blockedById = String(blocker.id);
|
|
4197
|
-
}
|
|
4198
|
-
let parentTaskId = null;
|
|
4199
|
-
let parentRef = input2.parentTaskId;
|
|
4200
|
-
if (!parentRef) {
|
|
4201
|
-
const extracted = extractParentFromContext(input2.context);
|
|
4202
|
-
if (extracted) {
|
|
4203
|
-
parentRef = extracted;
|
|
4204
|
-
process.stderr.write(
|
|
4205
|
-
"[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
|
|
4206
|
-
);
|
|
4207
|
-
}
|
|
4208
|
-
}
|
|
4209
|
-
if (parentRef) {
|
|
4210
|
-
try {
|
|
4211
|
-
const parent = await resolveTask(client, parentRef);
|
|
4212
|
-
parentTaskId = String(parent.id);
|
|
4213
|
-
} catch (err) {
|
|
4214
|
-
if (!input2.parentTaskId) {
|
|
4215
|
-
throw new Error(
|
|
4216
|
-
`create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
|
|
4217
|
-
);
|
|
4218
|
-
}
|
|
4219
|
-
throw err;
|
|
4220
|
-
}
|
|
4221
|
-
}
|
|
4222
|
-
let warning;
|
|
4223
|
-
const dupCheck = await client.execute({
|
|
4224
|
-
sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
|
|
4225
|
-
args: [input2.title, input2.assignedTo]
|
|
4226
|
-
});
|
|
4227
|
-
if (dupCheck.rows.length > 0) {
|
|
4228
|
-
warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
|
|
4229
|
-
}
|
|
4230
|
-
if (input2.baseDir) {
|
|
4231
|
-
try {
|
|
4232
|
-
await mkdir4(path16.join(input2.baseDir, "exe", "output"), { recursive: true });
|
|
4233
|
-
await mkdir4(path16.join(input2.baseDir, "exe", "research"), { recursive: true });
|
|
4234
|
-
await ensureArchitectureDoc(input2.baseDir, input2.projectName);
|
|
4235
|
-
await ensureGitignoreExe(input2.baseDir);
|
|
4236
|
-
} catch {
|
|
4237
|
-
}
|
|
4238
|
-
}
|
|
4239
|
-
const complexity = input2.complexity ?? "standard";
|
|
5956
|
+
const targetDevice = input2.targetDevice ?? "local";
|
|
4240
5957
|
await client.execute({
|
|
4241
|
-
sql: `INSERT INTO
|
|
4242
|
-
VALUES (?, ?,
|
|
5958
|
+
sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
|
|
5959
|
+
VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
|
|
4243
5960
|
args: [
|
|
4244
5961
|
id,
|
|
4245
|
-
input2.
|
|
4246
|
-
input2.
|
|
4247
|
-
input2.
|
|
4248
|
-
|
|
4249
|
-
input2.
|
|
4250
|
-
|
|
4251
|
-
taskFile,
|
|
4252
|
-
blockedById,
|
|
4253
|
-
parentTaskId,
|
|
4254
|
-
input2.reviewer ?? null,
|
|
4255
|
-
input2.context,
|
|
4256
|
-
complexity,
|
|
4257
|
-
input2.budgetTokens ?? null,
|
|
4258
|
-
input2.budgetFallbackModel ?? null,
|
|
4259
|
-
0,
|
|
4260
|
-
null,
|
|
4261
|
-
now,
|
|
5962
|
+
input2.fromAgent,
|
|
5963
|
+
input2.targetAgent,
|
|
5964
|
+
input2.targetProject ?? null,
|
|
5965
|
+
targetDevice,
|
|
5966
|
+
input2.content,
|
|
5967
|
+
input2.priority ?? "normal",
|
|
4262
5968
|
now
|
|
4263
5969
|
]
|
|
4264
5970
|
});
|
|
4265
|
-
return {
|
|
4266
|
-
id,
|
|
4267
|
-
title: input2.title,
|
|
4268
|
-
assignedTo: input2.assignedTo,
|
|
4269
|
-
assignedBy: input2.assignedBy,
|
|
4270
|
-
projectName: input2.projectName,
|
|
4271
|
-
priority: input2.priority,
|
|
4272
|
-
status: initialStatus,
|
|
4273
|
-
taskFile,
|
|
4274
|
-
createdAt: now,
|
|
4275
|
-
updatedAt: now,
|
|
4276
|
-
warning,
|
|
4277
|
-
budgetTokens: input2.budgetTokens ?? null,
|
|
4278
|
-
budgetFallbackModel: input2.budgetFallbackModel ?? null,
|
|
4279
|
-
tokensUsed: 0,
|
|
4280
|
-
tokensWarnedAt: null
|
|
4281
|
-
};
|
|
4282
|
-
}
|
|
4283
|
-
async function ensureArchitectureDoc(baseDir, projectName) {
|
|
4284
|
-
const archPath = path16.join(baseDir, "exe", "ARCHITECTURE.md");
|
|
4285
5971
|
try {
|
|
4286
|
-
if (
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
`> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
4292
|
-
"",
|
|
4293
|
-
"## Overview",
|
|
4294
|
-
"",
|
|
4295
|
-
"<!-- Describe what this system does, its main components, and how they connect. -->",
|
|
4296
|
-
"",
|
|
4297
|
-
"## Key Components",
|
|
4298
|
-
"",
|
|
4299
|
-
"<!-- List the major modules, services, or subsystems. -->",
|
|
4300
|
-
"",
|
|
4301
|
-
"## Data Flow",
|
|
4302
|
-
"",
|
|
4303
|
-
"<!-- How does data move through the system? What writes where? -->",
|
|
4304
|
-
"",
|
|
4305
|
-
"## Invariants",
|
|
4306
|
-
"",
|
|
4307
|
-
"<!-- Rules that must never be violated. What breaks if these are wrong? -->",
|
|
4308
|
-
"",
|
|
4309
|
-
"## Dependencies",
|
|
4310
|
-
"",
|
|
4311
|
-
"<!-- What depends on what? If I change X, what else is affected? -->",
|
|
4312
|
-
""
|
|
4313
|
-
].join("\n");
|
|
4314
|
-
await writeFile4(archPath, template, "utf-8");
|
|
5972
|
+
if (targetDevice !== "local") {
|
|
5973
|
+
await deliverCrossMachineMessage(id, targetDevice);
|
|
5974
|
+
} else {
|
|
5975
|
+
await deliverLocalMessage(id);
|
|
5976
|
+
}
|
|
4315
5977
|
} catch {
|
|
4316
5978
|
}
|
|
5979
|
+
const result = await client.execute({
|
|
5980
|
+
sql: "SELECT * FROM messages WHERE id = ?",
|
|
5981
|
+
args: [id]
|
|
5982
|
+
});
|
|
5983
|
+
return rowToMessage(result.rows[0]);
|
|
4317
5984
|
}
|
|
4318
|
-
|
|
4319
|
-
|
|
5985
|
+
function setWsClientSend(fn) {
|
|
5986
|
+
_wsClientSend = fn;
|
|
5987
|
+
}
|
|
5988
|
+
async function deliverCrossMachineMessage(messageId, targetDevice) {
|
|
5989
|
+
const client = getClient();
|
|
5990
|
+
const result = await client.execute({
|
|
5991
|
+
sql: "SELECT * FROM messages WHERE id = ?",
|
|
5992
|
+
args: [messageId]
|
|
5993
|
+
});
|
|
5994
|
+
if (result.rows.length === 0) return false;
|
|
5995
|
+
const msg = rowToMessage(result.rows[0]);
|
|
5996
|
+
if (msg.status !== "pending") return false;
|
|
5997
|
+
if (!_wsClientSend) {
|
|
5998
|
+
return false;
|
|
5999
|
+
}
|
|
6000
|
+
const payload = JSON.stringify({
|
|
6001
|
+
id: msg.id,
|
|
6002
|
+
fromAgent: msg.fromAgent,
|
|
6003
|
+
targetAgent: msg.targetAgent,
|
|
6004
|
+
targetProject: msg.targetProject,
|
|
6005
|
+
content: msg.content,
|
|
6006
|
+
priority: msg.priority,
|
|
6007
|
+
createdAt: msg.createdAt
|
|
6008
|
+
});
|
|
6009
|
+
const sent = _wsClientSend(targetDevice, payload);
|
|
6010
|
+
if (sent) {
|
|
6011
|
+
await client.execute({
|
|
6012
|
+
sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
|
|
6013
|
+
args: [messageId]
|
|
6014
|
+
});
|
|
6015
|
+
return true;
|
|
6016
|
+
}
|
|
6017
|
+
return false;
|
|
6018
|
+
}
|
|
6019
|
+
async function deliverLocalMessage(messageId) {
|
|
6020
|
+
const client = getClient();
|
|
6021
|
+
const result = await client.execute({
|
|
6022
|
+
sql: "SELECT * FROM messages WHERE id = ?",
|
|
6023
|
+
args: [messageId]
|
|
6024
|
+
});
|
|
6025
|
+
if (result.rows.length === 0) return false;
|
|
6026
|
+
const msg = rowToMessage(result.rows[0]);
|
|
6027
|
+
if (msg.status !== "pending") return false;
|
|
6028
|
+
const targetAgent = msg.targetAgent;
|
|
6029
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4320
6030
|
try {
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
6031
|
+
const exeSession = resolveExeSession();
|
|
6032
|
+
if (!exeSession) {
|
|
6033
|
+
throw new Error("No exe session found");
|
|
6034
|
+
}
|
|
6035
|
+
const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
|
|
6036
|
+
if (ensureResult.status === "failed") {
|
|
6037
|
+
throw new Error(ensureResult.error ?? "ensureEmployee failed");
|
|
4327
6038
|
}
|
|
6039
|
+
await client.execute({
|
|
6040
|
+
sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
|
|
6041
|
+
args: [now, messageId]
|
|
6042
|
+
});
|
|
6043
|
+
return true;
|
|
4328
6044
|
} catch {
|
|
6045
|
+
const newRetryCount = msg.retryCount + 1;
|
|
6046
|
+
if (newRetryCount >= MAX_RETRIES3) {
|
|
6047
|
+
await markFailed(messageId, "session unavailable after 10 retries");
|
|
6048
|
+
} else {
|
|
6049
|
+
await client.execute({
|
|
6050
|
+
sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
|
|
6051
|
+
args: [newRetryCount, messageId]
|
|
6052
|
+
});
|
|
6053
|
+
}
|
|
6054
|
+
return false;
|
|
4329
6055
|
}
|
|
4330
6056
|
}
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
}
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
6057
|
+
async function getPendingMessages(targetAgent) {
|
|
6058
|
+
const client = getClient();
|
|
6059
|
+
const result = await client.execute({
|
|
6060
|
+
sql: `SELECT * FROM messages
|
|
6061
|
+
WHERE target_agent = ? AND status IN ('pending', 'delivered')
|
|
6062
|
+
ORDER BY id`,
|
|
6063
|
+
args: [targetAgent]
|
|
6064
|
+
});
|
|
6065
|
+
return result.rows.map((row) => rowToMessage(row));
|
|
6066
|
+
}
|
|
6067
|
+
async function markRead(messageId) {
|
|
6068
|
+
const client = getClient();
|
|
6069
|
+
await client.execute({
|
|
6070
|
+
sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
|
|
6071
|
+
args: [messageId]
|
|
6072
|
+
});
|
|
6073
|
+
}
|
|
6074
|
+
async function markAcknowledged(messageId) {
|
|
6075
|
+
const client = getClient();
|
|
6076
|
+
await client.execute({
|
|
6077
|
+
sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
|
|
6078
|
+
args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
|
|
6079
|
+
});
|
|
6080
|
+
}
|
|
6081
|
+
async function markProcessed(messageId) {
|
|
4351
6082
|
const client = getClient();
|
|
4352
|
-
|
|
4353
|
-
sql: "
|
|
4354
|
-
args: []
|
|
6083
|
+
await client.execute({
|
|
6084
|
+
sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
|
|
6085
|
+
args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
|
|
4355
6086
|
});
|
|
4356
|
-
return Number(result.rows[0]?.cnt) || 0;
|
|
4357
6087
|
}
|
|
4358
|
-
async function
|
|
6088
|
+
async function getMessageStatus(messageId) {
|
|
4359
6089
|
const client = getClient();
|
|
4360
6090
|
const result = await client.execute({
|
|
4361
|
-
sql:
|
|
4362
|
-
|
|
4363
|
-
args: [sinceIso]
|
|
6091
|
+
sql: "SELECT status FROM messages WHERE id = ?",
|
|
6092
|
+
args: [messageId]
|
|
4364
6093
|
});
|
|
4365
|
-
return
|
|
6094
|
+
return result.rows[0]?.status ?? null;
|
|
4366
6095
|
}
|
|
4367
|
-
async function
|
|
6096
|
+
async function getUnacknowledgedMessages(targetAgent) {
|
|
4368
6097
|
const client = getClient();
|
|
4369
6098
|
const result = await client.execute({
|
|
4370
|
-
sql: `SELECT
|
|
4371
|
-
WHERE
|
|
4372
|
-
ORDER BY
|
|
4373
|
-
args: [
|
|
6099
|
+
sql: `SELECT * FROM messages
|
|
6100
|
+
WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
|
|
6101
|
+
ORDER BY id`,
|
|
6102
|
+
args: [targetAgent]
|
|
4374
6103
|
});
|
|
4375
|
-
return result.rows;
|
|
6104
|
+
return result.rows.map((row) => rowToMessage(row));
|
|
4376
6105
|
}
|
|
4377
|
-
function
|
|
4378
|
-
const
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
"2. Is the code clean \u2014 no dead code, no TODOs left?",
|
|
4385
|
-
"3. Does it follow existing patterns and conventions in the codebase?",
|
|
4386
|
-
"4. Any regressions in the test suite?"
|
|
4387
|
-
]
|
|
4388
|
-
};
|
|
4389
|
-
}
|
|
4390
|
-
if (roleLower === "cto" || roleLower.includes("architect")) {
|
|
4391
|
-
return {
|
|
4392
|
-
lens: "Architecture (CTO)",
|
|
4393
|
-
checklist: [
|
|
4394
|
-
"1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
|
|
4395
|
-
"2. Is it backward compatible? Any breaking changes?",
|
|
4396
|
-
"3. Does it introduce technical debt? Is that debt justified?",
|
|
4397
|
-
"4. Security implications? Any new attack surface?",
|
|
4398
|
-
"5. Does it scale? Performance considerations?",
|
|
4399
|
-
"6. Coordination: does this affect other employees' work or other projects?"
|
|
4400
|
-
]
|
|
4401
|
-
};
|
|
4402
|
-
}
|
|
4403
|
-
if (roleLower === "coo" || roleLower.includes("operations")) {
|
|
4404
|
-
return {
|
|
4405
|
-
lens: "Strategic (COO)",
|
|
4406
|
-
checklist: [
|
|
4407
|
-
"1. Does this serve the project mission?",
|
|
4408
|
-
"2. Is this the right work at the right time?",
|
|
4409
|
-
"3. Does the architectural assessment make sense for the business?",
|
|
4410
|
-
"4. Any cross-project implications?"
|
|
4411
|
-
]
|
|
4412
|
-
};
|
|
4413
|
-
}
|
|
4414
|
-
return {
|
|
4415
|
-
lens: "General",
|
|
4416
|
-
checklist: [
|
|
4417
|
-
"1. Read the original task's acceptance criteria",
|
|
4418
|
-
`2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
|
|
4419
|
-
"3. Verify code changes match requirements",
|
|
4420
|
-
"4. Check if tests were added/updated",
|
|
4421
|
-
`5. Look for output files in exe/output/${agent}-${taskSlug}*`
|
|
4422
|
-
]
|
|
4423
|
-
};
|
|
6106
|
+
async function getReadMessages(targetAgent) {
|
|
6107
|
+
const client = getClient();
|
|
6108
|
+
const result = await client.execute({
|
|
6109
|
+
sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
|
|
6110
|
+
args: [targetAgent]
|
|
6111
|
+
});
|
|
6112
|
+
return result.rows.map((row) => rowToMessage(row));
|
|
4424
6113
|
}
|
|
4425
|
-
async function
|
|
4426
|
-
const taskFile = String(row.task_file);
|
|
4427
|
-
if (String(row.assigned_to) === "exe") return;
|
|
4428
|
-
if (String(row.title).startsWith("Review:")) return;
|
|
4429
|
-
const fileName = taskFile.split("/").pop() ?? "";
|
|
4430
|
-
if (fileName.startsWith("review-") && String(row.assigned_by) === "system") return;
|
|
4431
|
-
if (fileName.startsWith("review-") && String(row.assigned_to) === "system") return;
|
|
6114
|
+
async function markFailed(messageId, reason) {
|
|
4432
6115
|
const client = getClient();
|
|
4433
|
-
const agent = String(row.assigned_to);
|
|
4434
|
-
const reviewer = String(row.reviewer || row.assigned_by) || "exe";
|
|
4435
|
-
let reviewerRole = "unknown";
|
|
4436
|
-
try {
|
|
4437
|
-
const employees = await loadEmployees();
|
|
4438
|
-
const emp = getEmployee(employees, reviewer);
|
|
4439
|
-
if (emp) reviewerRole = emp.role;
|
|
4440
|
-
} catch {
|
|
4441
|
-
}
|
|
4442
|
-
const taskTitle = String(row.title);
|
|
4443
|
-
const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "unknown";
|
|
4444
|
-
const { lens, checklist } = getReviewChecklist(reviewerRole, agent, taskSlug);
|
|
4445
|
-
const reviewSlug = `review-${agent}-${taskSlug}`;
|
|
4446
|
-
const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
|
|
4447
6116
|
await client.execute({
|
|
4448
|
-
sql: "
|
|
4449
|
-
args: [
|
|
6117
|
+
sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
|
|
6118
|
+
args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
|
|
4450
6119
|
});
|
|
4451
|
-
|
|
4452
|
-
|
|
4453
|
-
|
|
4454
|
-
|
|
4455
|
-
|
|
4456
|
-
|
|
4457
|
-
`- Original task: ${taskFile}`,
|
|
4458
|
-
`- Result: ${result ?? "No result summary provided"}`,
|
|
4459
|
-
"",
|
|
4460
|
-
`## Review lens: ${lens}`,
|
|
4461
|
-
`You are reviewing as **${reviewer}** (${reviewerRole}).`,
|
|
4462
|
-
"",
|
|
4463
|
-
"## Review checklist",
|
|
4464
|
-
...checklist,
|
|
4465
|
-
"",
|
|
4466
|
-
"## Verdict",
|
|
4467
|
-
"After review, update this task:",
|
|
4468
|
-
"- **Approved:** mark this review task as done",
|
|
4469
|
-
"- **Needs work:** re-open the original task with notes, mark this review as done"
|
|
4470
|
-
].join("\n");
|
|
4471
|
-
const originalTaskId = String(row.id);
|
|
4472
|
-
const reviewTask = await createTaskCore({
|
|
4473
|
-
title: `Review: ${agent} completed "${taskTitle}"`,
|
|
4474
|
-
assignedTo: reviewer,
|
|
4475
|
-
assignedBy: "system",
|
|
4476
|
-
projectName: String(row.project_name),
|
|
4477
|
-
priority: "p1",
|
|
4478
|
-
context: reviewContext,
|
|
4479
|
-
taskFile: reviewFile,
|
|
4480
|
-
parentTaskId: originalTaskId,
|
|
4481
|
-
skipDispatch: true
|
|
6120
|
+
}
|
|
6121
|
+
async function getFailedMessages() {
|
|
6122
|
+
const client = getClient();
|
|
6123
|
+
const result = await client.execute({
|
|
6124
|
+
sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
|
|
6125
|
+
args: []
|
|
4482
6126
|
});
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
4490
|
-
|
|
6127
|
+
return result.rows.map((row) => rowToMessage(row));
|
|
6128
|
+
}
|
|
6129
|
+
async function retryPendingMessages() {
|
|
6130
|
+
const client = getClient();
|
|
6131
|
+
const result = await client.execute({
|
|
6132
|
+
sql: `SELECT * FROM messages
|
|
6133
|
+
WHERE status = 'pending' AND retry_count < ?
|
|
6134
|
+
ORDER BY id`,
|
|
6135
|
+
args: [MAX_RETRIES3]
|
|
4491
6136
|
});
|
|
4492
|
-
|
|
4493
|
-
const
|
|
4494
|
-
|
|
6137
|
+
let delivered = 0;
|
|
6138
|
+
for (const row of result.rows) {
|
|
6139
|
+
const msg = rowToMessage(row);
|
|
4495
6140
|
try {
|
|
4496
|
-
const
|
|
4497
|
-
|
|
4498
|
-
if (exeSession) {
|
|
4499
|
-
sendIntercom(exeSession);
|
|
4500
|
-
}
|
|
6141
|
+
const success = await deliverLocalMessage(msg.id);
|
|
6142
|
+
if (success) delivered++;
|
|
4501
6143
|
} catch {
|
|
4502
6144
|
}
|
|
4503
6145
|
}
|
|
4504
|
-
|
|
4505
|
-
process.stderr.write(
|
|
4506
|
-
`[review] Auto-approving review for "${taskTitle}" (P2 + tests pass)
|
|
4507
|
-
`
|
|
4508
|
-
);
|
|
4509
|
-
await client.execute({
|
|
4510
|
-
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?",
|
|
4511
|
-
args: [now, reviewId]
|
|
4512
|
-
});
|
|
4513
|
-
}
|
|
4514
|
-
}
|
|
4515
|
-
async function cleanupReviewFile(row, taskFile, _baseDir) {
|
|
4516
|
-
if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
|
|
4517
|
-
try {
|
|
4518
|
-
const client = getClient();
|
|
4519
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4520
|
-
const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
|
|
4521
|
-
if (parentId) {
|
|
4522
|
-
const result = await client.execute({
|
|
4523
|
-
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
|
|
4524
|
-
args: [now, parentId]
|
|
4525
|
-
});
|
|
4526
|
-
if (result.rowsAffected > 0) {
|
|
4527
|
-
process.stderr.write(
|
|
4528
|
-
`[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
|
|
4529
|
-
`
|
|
4530
|
-
);
|
|
4531
|
-
}
|
|
4532
|
-
} else {
|
|
4533
|
-
const fileName = taskFile.split("/").pop() ?? "";
|
|
4534
|
-
const reviewPrefix = fileName.replace(".md", "");
|
|
4535
|
-
const parts = reviewPrefix.split("-");
|
|
4536
|
-
if (parts.length >= 3 && parts[0] === "review") {
|
|
4537
|
-
const agent = parts[1];
|
|
4538
|
-
const slug = parts.slice(2).join("-");
|
|
4539
|
-
const originalTaskFile = `exe/${agent}/${slug}.md`;
|
|
4540
|
-
const result = await client.execute({
|
|
4541
|
-
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
|
|
4542
|
-
args: [now, originalTaskFile]
|
|
4543
|
-
});
|
|
4544
|
-
if (result.rowsAffected > 0) {
|
|
4545
|
-
process.stderr.write(
|
|
4546
|
-
`[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
|
|
4547
|
-
`
|
|
4548
|
-
);
|
|
4549
|
-
}
|
|
4550
|
-
}
|
|
4551
|
-
}
|
|
4552
|
-
} catch (err) {
|
|
4553
|
-
process.stderr.write(
|
|
4554
|
-
`[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
|
|
4555
|
-
`
|
|
4556
|
-
);
|
|
4557
|
-
}
|
|
4558
|
-
try {
|
|
4559
|
-
const cacheDir = path17.join(EXE_AI_DIR, "session-cache");
|
|
4560
|
-
if (existsSync15(cacheDir)) {
|
|
4561
|
-
for (const f of readdirSync5(cacheDir)) {
|
|
4562
|
-
if (f.startsWith("review-notified-")) {
|
|
4563
|
-
unlinkSync5(path17.join(cacheDir, f));
|
|
4564
|
-
}
|
|
4565
|
-
}
|
|
4566
|
-
}
|
|
4567
|
-
} catch {
|
|
4568
|
-
}
|
|
6146
|
+
return delivered;
|
|
4569
6147
|
}
|
|
4570
|
-
var
|
|
4571
|
-
|
|
6148
|
+
var MAX_RETRIES3, _wsClientSend;
|
|
6149
|
+
var init_messaging = __esm({
|
|
6150
|
+
"src/lib/messaging.ts"() {
|
|
4572
6151
|
"use strict";
|
|
4573
6152
|
init_database();
|
|
4574
|
-
init_config();
|
|
4575
|
-
init_employees();
|
|
4576
|
-
init_notifications();
|
|
4577
|
-
init_tasks_crud();
|
|
4578
6153
|
init_tmux_routing();
|
|
4579
|
-
|
|
6154
|
+
MAX_RETRIES3 = 10;
|
|
6155
|
+
_wsClientSend = null;
|
|
4580
6156
|
}
|
|
4581
6157
|
});
|
|
4582
6158
|
|
|
@@ -4585,8 +6161,8 @@ init_config();
|
|
|
4585
6161
|
init_config();
|
|
4586
6162
|
init_store();
|
|
4587
6163
|
import { spawn as spawn2 } from "child_process";
|
|
4588
|
-
import { readFileSync as readFileSync13, writeFileSync as
|
|
4589
|
-
import
|
|
6164
|
+
import { readFileSync as readFileSync13, writeFileSync as writeFileSync7, mkdirSync as mkdirSync8, existsSync as existsSync16, openSync as openSync2, closeSync as closeSync2 } from "fs";
|
|
6165
|
+
import path20 from "path";
|
|
4590
6166
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
4591
6167
|
|
|
4592
6168
|
// src/lib/hybrid-search.ts
|
|
@@ -5017,7 +6593,7 @@ if (!process.env.AGENT_ID) {
|
|
|
5017
6593
|
if (!loadConfigSync().autoRetrieval) {
|
|
5018
6594
|
process.exit(0);
|
|
5019
6595
|
}
|
|
5020
|
-
var WORKER_LOG_PATH =
|
|
6596
|
+
var WORKER_LOG_PATH = path20.join(EXE_AI_DIR, "workers.log");
|
|
5021
6597
|
function openWorkerLog() {
|
|
5022
6598
|
try {
|
|
5023
6599
|
return openSync2(WORKER_LOG_PATH, "a");
|
|
@@ -5025,10 +6601,10 @@ function openWorkerLog() {
|
|
|
5025
6601
|
return "ignore";
|
|
5026
6602
|
}
|
|
5027
6603
|
}
|
|
5028
|
-
var CACHE_DIR2 =
|
|
6604
|
+
var CACHE_DIR2 = path20.join(EXE_AI_DIR, "session-cache");
|
|
5029
6605
|
function loadInjectedIds(sessionId) {
|
|
5030
6606
|
try {
|
|
5031
|
-
const raw = readFileSync13(
|
|
6607
|
+
const raw = readFileSync13(path20.join(CACHE_DIR2, `${sessionId}.json`), "utf8");
|
|
5032
6608
|
return new Set(JSON.parse(raw));
|
|
5033
6609
|
} catch {
|
|
5034
6610
|
return /* @__PURE__ */ new Set();
|
|
@@ -5036,9 +6612,9 @@ function loadInjectedIds(sessionId) {
|
|
|
5036
6612
|
}
|
|
5037
6613
|
function saveInjectedIds(sessionId, ids) {
|
|
5038
6614
|
try {
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
|
|
6615
|
+
mkdirSync8(CACHE_DIR2, { recursive: true });
|
|
6616
|
+
writeFileSync7(
|
|
6617
|
+
path20.join(CACHE_DIR2, `${sessionId}.json`),
|
|
5042
6618
|
JSON.stringify([...ids])
|
|
5043
6619
|
);
|
|
5044
6620
|
} catch {
|
|
@@ -5117,11 +6693,11 @@ ${fresh.map(
|
|
|
5117
6693
|
}
|
|
5118
6694
|
}
|
|
5119
6695
|
let reviewContext = "";
|
|
5120
|
-
if (agent.agentId ===
|
|
6696
|
+
if (agent.agentId === COO_AGENT_NAME || agent.agentId === "default") {
|
|
5121
6697
|
try {
|
|
5122
6698
|
const { countPendingReviews: countPendingReviews2, countNewPendingReviewsSince: countNewPendingReviewsSince2 } = await Promise.resolve().then(() => (init_tasks_review(), tasks_review_exports));
|
|
5123
6699
|
const sessionKey = getSessionKey();
|
|
5124
|
-
const lastCheckPath =
|
|
6700
|
+
const lastCheckPath = path20.join(CACHE_DIR2, `review-lastcheck-${sessionKey}.json`);
|
|
5125
6701
|
let lastCheckedAt = "";
|
|
5126
6702
|
try {
|
|
5127
6703
|
lastCheckedAt = readFileSync13(lastCheckPath, "utf8").trim();
|
|
@@ -5182,8 +6758,8 @@ IMPORTANT: After completing your current task, you MUST address the pending revi
|
|
|
5182
6758
|
function spawnPromptWorker(prompt, sessionId, agent) {
|
|
5183
6759
|
if (!loadConfigSync().autoIngestion) return;
|
|
5184
6760
|
try {
|
|
5185
|
-
const workerPath =
|
|
5186
|
-
|
|
6761
|
+
const workerPath = path20.resolve(
|
|
6762
|
+
path20.dirname(fileURLToPath3(import.meta.url)),
|
|
5187
6763
|
"prompt-ingest-worker.js"
|
|
5188
6764
|
);
|
|
5189
6765
|
if (!existsSync16(workerPath)) {
|