@askexenow/exe-os 0.8.57 → 0.8.59
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/cli.js +57 -5
- package/dist/bin/customer-readiness.js +127 -0
- package/dist/bin/exe-boot.js +102 -93
- package/dist/bin/exe-dispatch.js +3735 -242
- package/dist/bin/exe-gateway.js +15 -8
- package/dist/bin/exe-heartbeat.js +34 -49
- package/dist/bin/exe-link.js +91 -88
- package/dist/bin/exe-pending-reviews.js +15 -31
- package/dist/bin/exe-session-cleanup.js +847 -2940
- package/dist/bin/git-sweep.js +11 -5
- package/dist/bin/scan-tasks.js +11 -5
- package/dist/gateway/index.js +15 -8
- package/dist/hooks/bug-report-worker.js +11 -5
- package/dist/hooks/commit-complete.js +11 -5
- package/dist/hooks/ingest-worker.js +11 -5
- package/dist/hooks/pre-compact.js +11 -5
- package/dist/hooks/prompt-submit.js +522 -2613
- package/dist/hooks/summary-worker.js +91 -88
- package/dist/index.js +36 -8
- package/dist/lib/cloud-sync.js +91 -88
- package/dist/lib/exe-daemon.js +43 -50
- package/dist/lib/messaging.js +23 -519
- package/dist/lib/tasks.js +11 -5
- package/dist/lib/tmux-routing.js +11 -5
- package/dist/mcp/server.js +16 -9
- package/dist/mcp/tools/create-task.js +11 -5
- package/dist/mcp/tools/list-tasks.js +0 -1
- package/dist/mcp/tools/send-message.js +29 -525
- package/dist/mcp/tools/update-task.js +0 -1
- package/dist/runtime/index.js +32 -5
- package/dist/tui/App.js +57 -5
- package/package.json +2 -2
package/dist/bin/exe-dispatch.js
CHANGED
|
@@ -319,242 +319,3083 @@ var init_intercom_queue = __esm({
|
|
|
319
319
|
});
|
|
320
320
|
|
|
321
321
|
// src/lib/db-retry.ts
|
|
322
|
+
function isBusyError(err) {
|
|
323
|
+
if (err instanceof Error) {
|
|
324
|
+
const msg = err.message.toLowerCase();
|
|
325
|
+
return msg.includes("sqlite_busy") || msg.includes("database is locked");
|
|
326
|
+
}
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
function delay(ms) {
|
|
330
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
331
|
+
}
|
|
332
|
+
async function retryOnBusy(fn, label) {
|
|
333
|
+
let lastError;
|
|
334
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
335
|
+
try {
|
|
336
|
+
return await fn();
|
|
337
|
+
} catch (err) {
|
|
338
|
+
lastError = err;
|
|
339
|
+
if (!isBusyError(err) || attempt === MAX_RETRIES) {
|
|
340
|
+
throw err;
|
|
341
|
+
}
|
|
342
|
+
const backoff = BASE_DELAY_MS * Math.pow(2, attempt);
|
|
343
|
+
const jitter = Math.floor(Math.random() * MAX_JITTER_MS);
|
|
344
|
+
process.stderr.write(
|
|
345
|
+
`[exe-os] SQLITE_BUSY ${label} retry ${attempt + 1}/${MAX_RETRIES} \u2014 waiting ${backoff + jitter}ms
|
|
346
|
+
`
|
|
347
|
+
);
|
|
348
|
+
await delay(backoff + jitter);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
throw lastError;
|
|
352
|
+
}
|
|
353
|
+
function wrapWithRetry(client) {
|
|
354
|
+
return new Proxy(client, {
|
|
355
|
+
get(target, prop, receiver) {
|
|
356
|
+
if (prop === "execute") {
|
|
357
|
+
return (sql) => retryOnBusy(() => target.execute(sql), "execute");
|
|
358
|
+
}
|
|
359
|
+
if (prop === "batch") {
|
|
360
|
+
return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
|
|
361
|
+
}
|
|
362
|
+
return Reflect.get(target, prop, receiver);
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
|
|
322
367
|
var init_db_retry = __esm({
|
|
323
368
|
"src/lib/db-retry.ts"() {
|
|
324
369
|
"use strict";
|
|
370
|
+
MAX_RETRIES = 3;
|
|
371
|
+
BASE_DELAY_MS = 200;
|
|
372
|
+
MAX_JITTER_MS = 300;
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// src/lib/database.ts
|
|
377
|
+
import { createClient } from "@libsql/client";
|
|
378
|
+
async function initDatabase(config) {
|
|
379
|
+
if (_client) {
|
|
380
|
+
_client.close();
|
|
381
|
+
_client = null;
|
|
382
|
+
_resilientClient = null;
|
|
383
|
+
}
|
|
384
|
+
const opts = {
|
|
385
|
+
url: `file:${config.dbPath}`
|
|
386
|
+
};
|
|
387
|
+
if (config.encryptionKey) {
|
|
388
|
+
opts.encryptionKey = config.encryptionKey;
|
|
389
|
+
}
|
|
390
|
+
_client = createClient(opts);
|
|
391
|
+
_resilientClient = wrapWithRetry(_client);
|
|
392
|
+
}
|
|
393
|
+
function getClient() {
|
|
394
|
+
if (!_resilientClient) {
|
|
395
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
396
|
+
}
|
|
397
|
+
return _resilientClient;
|
|
398
|
+
}
|
|
399
|
+
function getRawClient() {
|
|
400
|
+
if (!_client) {
|
|
401
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
402
|
+
}
|
|
403
|
+
return _client;
|
|
404
|
+
}
|
|
405
|
+
async function ensureSchema() {
|
|
406
|
+
const client = getRawClient();
|
|
407
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
408
|
+
await client.execute("PRAGMA busy_timeout = 30000");
|
|
409
|
+
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
410
|
+
try {
|
|
411
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
412
|
+
} catch {
|
|
413
|
+
}
|
|
414
|
+
await client.executeMultiple(`
|
|
415
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
416
|
+
id TEXT PRIMARY KEY,
|
|
417
|
+
agent_id TEXT NOT NULL,
|
|
418
|
+
agent_role TEXT NOT NULL,
|
|
419
|
+
session_id TEXT NOT NULL,
|
|
420
|
+
timestamp TEXT NOT NULL,
|
|
421
|
+
tool_name TEXT NOT NULL,
|
|
422
|
+
project_name TEXT NOT NULL,
|
|
423
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
424
|
+
raw_text TEXT NOT NULL,
|
|
425
|
+
vector F32_BLOB(1024),
|
|
426
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
427
|
+
);
|
|
428
|
+
|
|
429
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent
|
|
430
|
+
ON memories(agent_id);
|
|
431
|
+
|
|
432
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp
|
|
433
|
+
ON memories(timestamp);
|
|
434
|
+
|
|
435
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
436
|
+
ON memories(session_id);
|
|
437
|
+
|
|
438
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
439
|
+
ON memories(project_name);
|
|
440
|
+
|
|
441
|
+
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
442
|
+
ON memories(tool_name);
|
|
443
|
+
|
|
444
|
+
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
445
|
+
ON memories(version);
|
|
446
|
+
|
|
447
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
448
|
+
ON memories(agent_id, project_name);
|
|
449
|
+
`);
|
|
450
|
+
await client.executeMultiple(`
|
|
451
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
452
|
+
raw_text,
|
|
453
|
+
content='memories',
|
|
454
|
+
content_rowid='rowid'
|
|
455
|
+
);
|
|
456
|
+
|
|
457
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
458
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
459
|
+
END;
|
|
460
|
+
|
|
461
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
462
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
463
|
+
END;
|
|
464
|
+
|
|
465
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
466
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
467
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
468
|
+
END;
|
|
469
|
+
`);
|
|
470
|
+
await client.executeMultiple(`
|
|
471
|
+
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
472
|
+
key TEXT PRIMARY KEY,
|
|
473
|
+
value TEXT NOT NULL
|
|
474
|
+
);
|
|
475
|
+
`);
|
|
476
|
+
await client.executeMultiple(`
|
|
477
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
478
|
+
id TEXT PRIMARY KEY,
|
|
479
|
+
title TEXT NOT NULL,
|
|
480
|
+
assigned_to TEXT NOT NULL,
|
|
481
|
+
assigned_by TEXT NOT NULL,
|
|
482
|
+
project_name TEXT NOT NULL,
|
|
483
|
+
priority TEXT NOT NULL DEFAULT 'p1',
|
|
484
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
485
|
+
task_file TEXT,
|
|
486
|
+
created_at TEXT NOT NULL,
|
|
487
|
+
updated_at TEXT NOT NULL
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
491
|
+
ON tasks(assigned_to, status);
|
|
492
|
+
`);
|
|
493
|
+
await client.executeMultiple(`
|
|
494
|
+
CREATE TABLE IF NOT EXISTS behaviors (
|
|
495
|
+
id TEXT PRIMARY KEY,
|
|
496
|
+
agent_id TEXT NOT NULL,
|
|
497
|
+
project_name TEXT,
|
|
498
|
+
domain TEXT,
|
|
499
|
+
content TEXT NOT NULL,
|
|
500
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
501
|
+
created_at TEXT NOT NULL,
|
|
502
|
+
updated_at TEXT NOT NULL
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
506
|
+
ON behaviors(agent_id, active);
|
|
507
|
+
`);
|
|
508
|
+
try {
|
|
509
|
+
const existing = await client.execute({
|
|
510
|
+
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
|
|
511
|
+
args: []
|
|
512
|
+
});
|
|
513
|
+
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
514
|
+
await client.executeMultiple(`
|
|
515
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
516
|
+
VALUES
|
|
517
|
+
(hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
518
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
519
|
+
VALUES
|
|
520
|
+
(hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
521
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
522
|
+
VALUES
|
|
523
|
+
(hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
524
|
+
`);
|
|
525
|
+
}
|
|
526
|
+
} catch {
|
|
527
|
+
}
|
|
528
|
+
try {
|
|
529
|
+
await client.execute({
|
|
530
|
+
sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
|
|
531
|
+
args: []
|
|
532
|
+
});
|
|
533
|
+
} catch {
|
|
534
|
+
}
|
|
535
|
+
try {
|
|
536
|
+
await client.execute({
|
|
537
|
+
sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
|
|
538
|
+
args: []
|
|
539
|
+
});
|
|
540
|
+
} catch {
|
|
541
|
+
}
|
|
542
|
+
try {
|
|
543
|
+
await client.execute({
|
|
544
|
+
sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
|
|
545
|
+
args: []
|
|
546
|
+
});
|
|
547
|
+
} catch {
|
|
548
|
+
}
|
|
549
|
+
try {
|
|
550
|
+
await client.execute({
|
|
551
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
|
|
552
|
+
ON tasks(parent_task_id)
|
|
553
|
+
WHERE parent_task_id IS NOT NULL`,
|
|
554
|
+
args: []
|
|
555
|
+
});
|
|
556
|
+
} catch {
|
|
557
|
+
}
|
|
558
|
+
try {
|
|
559
|
+
await client.execute({
|
|
560
|
+
sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
|
|
561
|
+
args: []
|
|
562
|
+
});
|
|
563
|
+
} catch {
|
|
564
|
+
}
|
|
565
|
+
try {
|
|
566
|
+
await client.execute({
|
|
567
|
+
sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
|
|
568
|
+
args: []
|
|
569
|
+
});
|
|
570
|
+
} catch {
|
|
571
|
+
}
|
|
572
|
+
try {
|
|
573
|
+
await client.execute({
|
|
574
|
+
sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
|
|
575
|
+
args: []
|
|
576
|
+
});
|
|
577
|
+
} catch {
|
|
578
|
+
}
|
|
579
|
+
try {
|
|
580
|
+
await client.execute({
|
|
581
|
+
sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
|
|
582
|
+
args: []
|
|
583
|
+
});
|
|
584
|
+
} catch {
|
|
585
|
+
}
|
|
586
|
+
try {
|
|
587
|
+
await client.execute({
|
|
588
|
+
sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
|
|
589
|
+
args: []
|
|
590
|
+
});
|
|
591
|
+
} catch {
|
|
592
|
+
}
|
|
593
|
+
try {
|
|
594
|
+
await client.execute({
|
|
595
|
+
sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
|
|
596
|
+
args: []
|
|
597
|
+
});
|
|
598
|
+
} catch {
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
await client.execute({
|
|
602
|
+
sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
|
|
603
|
+
args: []
|
|
604
|
+
});
|
|
605
|
+
} catch {
|
|
606
|
+
}
|
|
607
|
+
try {
|
|
608
|
+
await client.execute({
|
|
609
|
+
sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
|
|
610
|
+
args: []
|
|
611
|
+
});
|
|
612
|
+
} catch {
|
|
613
|
+
}
|
|
614
|
+
try {
|
|
615
|
+
await client.execute({
|
|
616
|
+
sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
|
|
617
|
+
args: []
|
|
618
|
+
});
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
try {
|
|
622
|
+
await client.execute({
|
|
623
|
+
sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
|
|
624
|
+
args: []
|
|
625
|
+
});
|
|
626
|
+
} catch {
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
await client.execute({
|
|
630
|
+
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
631
|
+
args: []
|
|
632
|
+
});
|
|
633
|
+
} catch {
|
|
634
|
+
}
|
|
635
|
+
try {
|
|
636
|
+
await client.execute({
|
|
637
|
+
sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
|
|
638
|
+
args: []
|
|
639
|
+
});
|
|
640
|
+
} catch {
|
|
641
|
+
}
|
|
642
|
+
try {
|
|
643
|
+
await client.execute({
|
|
644
|
+
sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
|
|
645
|
+
args: []
|
|
646
|
+
});
|
|
647
|
+
} catch {
|
|
648
|
+
}
|
|
649
|
+
await client.executeMultiple(`
|
|
650
|
+
CREATE TABLE IF NOT EXISTS consolidations (
|
|
651
|
+
id TEXT PRIMARY KEY,
|
|
652
|
+
consolidated_memory_id TEXT NOT NULL,
|
|
653
|
+
source_memory_id TEXT NOT NULL,
|
|
654
|
+
created_at TEXT NOT NULL
|
|
655
|
+
);
|
|
656
|
+
|
|
657
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_source
|
|
658
|
+
ON consolidations(source_memory_id);
|
|
659
|
+
|
|
660
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
|
|
661
|
+
ON consolidations(consolidated_memory_id);
|
|
662
|
+
`);
|
|
663
|
+
await client.executeMultiple(`
|
|
664
|
+
CREATE TABLE IF NOT EXISTS reminders (
|
|
665
|
+
id TEXT PRIMARY KEY,
|
|
666
|
+
text TEXT NOT NULL,
|
|
667
|
+
created_at TEXT NOT NULL,
|
|
668
|
+
due_date TEXT,
|
|
669
|
+
completed_at TEXT
|
|
670
|
+
);
|
|
671
|
+
`);
|
|
672
|
+
await client.executeMultiple(`
|
|
673
|
+
CREATE TABLE IF NOT EXISTS notifications (
|
|
674
|
+
id TEXT PRIMARY KEY,
|
|
675
|
+
agent_id TEXT NOT NULL,
|
|
676
|
+
agent_role TEXT NOT NULL,
|
|
677
|
+
event TEXT NOT NULL,
|
|
678
|
+
project TEXT NOT NULL,
|
|
679
|
+
summary TEXT NOT NULL,
|
|
680
|
+
task_file TEXT,
|
|
681
|
+
read INTEGER NOT NULL DEFAULT 0,
|
|
682
|
+
created_at TEXT NOT NULL
|
|
683
|
+
);
|
|
684
|
+
|
|
685
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_read
|
|
686
|
+
ON notifications(read);
|
|
687
|
+
|
|
688
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
689
|
+
ON notifications(agent_id);
|
|
690
|
+
|
|
691
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
692
|
+
ON notifications(task_file);
|
|
693
|
+
`);
|
|
694
|
+
await client.executeMultiple(`
|
|
695
|
+
CREATE TABLE IF NOT EXISTS schedules (
|
|
696
|
+
id TEXT PRIMARY KEY,
|
|
697
|
+
cron TEXT NOT NULL,
|
|
698
|
+
description TEXT NOT NULL,
|
|
699
|
+
job_type TEXT NOT NULL DEFAULT 'report',
|
|
700
|
+
prompt TEXT,
|
|
701
|
+
assigned_to TEXT,
|
|
702
|
+
project_name TEXT,
|
|
703
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
704
|
+
use_crontab INTEGER NOT NULL DEFAULT 0,
|
|
705
|
+
created_at TEXT NOT NULL
|
|
706
|
+
);
|
|
707
|
+
`);
|
|
708
|
+
await client.executeMultiple(`
|
|
709
|
+
CREATE TABLE IF NOT EXISTS device_registry (
|
|
710
|
+
device_id TEXT PRIMARY KEY,
|
|
711
|
+
friendly_name TEXT NOT NULL,
|
|
712
|
+
hostname TEXT NOT NULL,
|
|
713
|
+
projects TEXT NOT NULL DEFAULT '[]',
|
|
714
|
+
agents TEXT NOT NULL DEFAULT '[]',
|
|
715
|
+
connected INTEGER DEFAULT 0,
|
|
716
|
+
last_seen TEXT NOT NULL
|
|
717
|
+
);
|
|
718
|
+
`);
|
|
719
|
+
await client.executeMultiple(`
|
|
720
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
721
|
+
id TEXT PRIMARY KEY,
|
|
722
|
+
from_agent TEXT NOT NULL,
|
|
723
|
+
from_device TEXT NOT NULL DEFAULT 'local',
|
|
724
|
+
target_agent TEXT NOT NULL,
|
|
725
|
+
target_project TEXT,
|
|
726
|
+
target_device TEXT NOT NULL DEFAULT 'local',
|
|
727
|
+
content TEXT NOT NULL,
|
|
728
|
+
priority TEXT DEFAULT 'normal',
|
|
729
|
+
status TEXT DEFAULT 'pending',
|
|
730
|
+
server_seq INTEGER,
|
|
731
|
+
retry_count INTEGER DEFAULT 0,
|
|
732
|
+
created_at TEXT NOT NULL,
|
|
733
|
+
delivered_at TEXT,
|
|
734
|
+
processed_at TEXT,
|
|
735
|
+
failed_at TEXT,
|
|
736
|
+
failure_reason TEXT
|
|
737
|
+
);
|
|
738
|
+
|
|
739
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
740
|
+
ON messages(target_agent, status);
|
|
741
|
+
|
|
742
|
+
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
743
|
+
ON messages(target_agent, from_agent, server_seq);
|
|
744
|
+
`);
|
|
745
|
+
try {
|
|
746
|
+
await client.execute({
|
|
747
|
+
sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
748
|
+
args: []
|
|
749
|
+
});
|
|
750
|
+
await client.execute({
|
|
751
|
+
sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
752
|
+
args: []
|
|
753
|
+
});
|
|
754
|
+
await client.execute({
|
|
755
|
+
sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
756
|
+
args: []
|
|
757
|
+
});
|
|
758
|
+
await client.execute({
|
|
759
|
+
sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
760
|
+
args: []
|
|
761
|
+
});
|
|
762
|
+
} catch {
|
|
763
|
+
}
|
|
764
|
+
await client.executeMultiple(`
|
|
765
|
+
CREATE TABLE IF NOT EXISTS trajectories (
|
|
766
|
+
id TEXT PRIMARY KEY,
|
|
767
|
+
task_id TEXT NOT NULL,
|
|
768
|
+
agent_id TEXT NOT NULL,
|
|
769
|
+
project_name TEXT NOT NULL,
|
|
770
|
+
task_title TEXT NOT NULL,
|
|
771
|
+
signature TEXT NOT NULL,
|
|
772
|
+
signature_hash TEXT NOT NULL,
|
|
773
|
+
tool_count INTEGER NOT NULL,
|
|
774
|
+
skill_id TEXT,
|
|
775
|
+
created_at TEXT NOT NULL
|
|
776
|
+
);
|
|
777
|
+
|
|
778
|
+
CREATE INDEX IF NOT EXISTS idx_trajectories_hash
|
|
779
|
+
ON trajectories(signature_hash);
|
|
780
|
+
|
|
781
|
+
CREATE INDEX IF NOT EXISTS idx_trajectories_agent
|
|
782
|
+
ON trajectories(agent_id);
|
|
783
|
+
`);
|
|
784
|
+
try {
|
|
785
|
+
await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
|
|
786
|
+
} catch {
|
|
787
|
+
}
|
|
788
|
+
await client.executeMultiple(`
|
|
789
|
+
CREATE TABLE IF NOT EXISTS consolidations (
|
|
790
|
+
id TEXT PRIMARY KEY,
|
|
791
|
+
consolidated_memory_id TEXT NOT NULL,
|
|
792
|
+
source_memory_id TEXT NOT NULL,
|
|
793
|
+
created_at TEXT NOT NULL
|
|
794
|
+
);
|
|
795
|
+
|
|
796
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_source
|
|
797
|
+
ON consolidations(source_memory_id);
|
|
798
|
+
`);
|
|
799
|
+
await client.executeMultiple(`
|
|
800
|
+
CREATE TABLE IF NOT EXISTS audit_trail (
|
|
801
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
802
|
+
timestamp TEXT NOT NULL,
|
|
803
|
+
session_id TEXT NOT NULL,
|
|
804
|
+
agent_id TEXT NOT NULL,
|
|
805
|
+
tool TEXT NOT NULL,
|
|
806
|
+
input TEXT,
|
|
807
|
+
decision TEXT NOT NULL,
|
|
808
|
+
reason TEXT,
|
|
809
|
+
is_customer_facing INTEGER NOT NULL DEFAULT 0
|
|
810
|
+
);
|
|
811
|
+
|
|
812
|
+
CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
|
|
813
|
+
ON audit_trail(agent_id, timestamp);
|
|
814
|
+
|
|
815
|
+
CREATE INDEX IF NOT EXISTS idx_audit_trail_session
|
|
816
|
+
ON audit_trail(session_id);
|
|
817
|
+
`);
|
|
818
|
+
try {
|
|
819
|
+
await client.execute({
|
|
820
|
+
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
821
|
+
args: []
|
|
822
|
+
});
|
|
823
|
+
} catch {
|
|
824
|
+
}
|
|
825
|
+
try {
|
|
826
|
+
await client.execute({
|
|
827
|
+
sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
|
|
828
|
+
args: []
|
|
829
|
+
});
|
|
830
|
+
} catch {
|
|
831
|
+
}
|
|
832
|
+
try {
|
|
833
|
+
await client.execute({
|
|
834
|
+
sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
|
|
835
|
+
args: []
|
|
836
|
+
});
|
|
837
|
+
} catch {
|
|
838
|
+
}
|
|
839
|
+
try {
|
|
840
|
+
await client.execute({
|
|
841
|
+
sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
|
|
842
|
+
args: []
|
|
843
|
+
});
|
|
844
|
+
} catch {
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
await client.execute({
|
|
848
|
+
sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
|
|
849
|
+
args: []
|
|
850
|
+
});
|
|
851
|
+
} catch {
|
|
852
|
+
}
|
|
853
|
+
try {
|
|
854
|
+
await client.execute({
|
|
855
|
+
sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
|
|
856
|
+
args: []
|
|
857
|
+
});
|
|
858
|
+
} catch {
|
|
859
|
+
}
|
|
860
|
+
try {
|
|
861
|
+
await client.execute({
|
|
862
|
+
sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
|
|
863
|
+
args: []
|
|
864
|
+
});
|
|
865
|
+
} catch {
|
|
866
|
+
}
|
|
867
|
+
try {
|
|
868
|
+
await client.execute({
|
|
869
|
+
sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
|
|
870
|
+
args: []
|
|
871
|
+
});
|
|
872
|
+
} catch {
|
|
873
|
+
}
|
|
874
|
+
for (const col of [
|
|
875
|
+
"ALTER TABLE memories ADD COLUMN content_hash TEXT",
|
|
876
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
|
|
877
|
+
]) {
|
|
878
|
+
try {
|
|
879
|
+
await client.execute(col);
|
|
880
|
+
} catch {
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
await client.executeMultiple(`
|
|
884
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
885
|
+
id TEXT PRIMARY KEY,
|
|
886
|
+
name TEXT NOT NULL,
|
|
887
|
+
type TEXT NOT NULL,
|
|
888
|
+
first_seen TEXT NOT NULL,
|
|
889
|
+
last_seen TEXT NOT NULL,
|
|
890
|
+
properties TEXT DEFAULT '{}',
|
|
891
|
+
UNIQUE(name, type)
|
|
892
|
+
);
|
|
893
|
+
|
|
894
|
+
CREATE TABLE IF NOT EXISTS relationships (
|
|
895
|
+
id TEXT PRIMARY KEY,
|
|
896
|
+
source_entity_id TEXT NOT NULL,
|
|
897
|
+
target_entity_id TEXT NOT NULL,
|
|
898
|
+
type TEXT NOT NULL,
|
|
899
|
+
weight REAL DEFAULT 1.0,
|
|
900
|
+
timestamp TEXT NOT NULL,
|
|
901
|
+
properties TEXT DEFAULT '{}',
|
|
902
|
+
UNIQUE(source_entity_id, target_entity_id, type)
|
|
903
|
+
);
|
|
904
|
+
|
|
905
|
+
CREATE TABLE IF NOT EXISTS entity_memories (
|
|
906
|
+
entity_id TEXT NOT NULL,
|
|
907
|
+
memory_id TEXT NOT NULL,
|
|
908
|
+
PRIMARY KEY (entity_id, memory_id)
|
|
909
|
+
);
|
|
910
|
+
|
|
911
|
+
CREATE TABLE IF NOT EXISTS relationship_memories (
|
|
912
|
+
relationship_id TEXT NOT NULL,
|
|
913
|
+
memory_id TEXT NOT NULL,
|
|
914
|
+
PRIMARY KEY (relationship_id, memory_id)
|
|
915
|
+
);
|
|
916
|
+
|
|
917
|
+
CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
|
|
918
|
+
CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
|
|
919
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
|
|
920
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
|
|
921
|
+
|
|
922
|
+
CREATE TABLE IF NOT EXISTS hyperedges (
|
|
923
|
+
id TEXT PRIMARY KEY,
|
|
924
|
+
label TEXT NOT NULL,
|
|
925
|
+
relation TEXT NOT NULL,
|
|
926
|
+
confidence REAL DEFAULT 1.0,
|
|
927
|
+
timestamp TEXT NOT NULL
|
|
928
|
+
);
|
|
929
|
+
|
|
930
|
+
CREATE TABLE IF NOT EXISTS hyperedge_nodes (
|
|
931
|
+
hyperedge_id TEXT NOT NULL,
|
|
932
|
+
entity_id TEXT NOT NULL,
|
|
933
|
+
PRIMARY KEY (hyperedge_id, entity_id)
|
|
934
|
+
);
|
|
935
|
+
`);
|
|
936
|
+
await client.executeMultiple(`
|
|
937
|
+
CREATE TABLE IF NOT EXISTS entity_aliases (
|
|
938
|
+
alias TEXT NOT NULL PRIMARY KEY,
|
|
939
|
+
canonical_entity_id TEXT NOT NULL
|
|
940
|
+
);
|
|
941
|
+
CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
|
|
942
|
+
`);
|
|
943
|
+
for (const col of [
|
|
944
|
+
"ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
|
|
945
|
+
"ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
|
|
946
|
+
]) {
|
|
947
|
+
try {
|
|
948
|
+
await client.execute(col);
|
|
949
|
+
} catch {
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
try {
|
|
953
|
+
await client.execute(
|
|
954
|
+
`CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
|
|
955
|
+
);
|
|
956
|
+
} catch {
|
|
957
|
+
}
|
|
958
|
+
await client.executeMultiple(`
|
|
959
|
+
CREATE TABLE IF NOT EXISTS identity (
|
|
960
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
961
|
+
agent_id TEXT NOT NULL UNIQUE,
|
|
962
|
+
content_hash TEXT NOT NULL,
|
|
963
|
+
updated_at TEXT NOT NULL,
|
|
964
|
+
updated_by TEXT NOT NULL
|
|
965
|
+
);
|
|
966
|
+
|
|
967
|
+
CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
|
|
968
|
+
`);
|
|
969
|
+
await client.executeMultiple(`
|
|
970
|
+
CREATE TABLE IF NOT EXISTS chat_history (
|
|
971
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
972
|
+
session_id TEXT NOT NULL,
|
|
973
|
+
role TEXT NOT NULL,
|
|
974
|
+
content TEXT NOT NULL,
|
|
975
|
+
tool_name TEXT,
|
|
976
|
+
tool_id TEXT,
|
|
977
|
+
is_error INTEGER NOT NULL DEFAULT 0,
|
|
978
|
+
timestamp INTEGER NOT NULL
|
|
979
|
+
);
|
|
980
|
+
|
|
981
|
+
CREATE INDEX IF NOT EXISTS idx_chat_history_session
|
|
982
|
+
ON chat_history(session_id, id);
|
|
983
|
+
`);
|
|
984
|
+
await client.executeMultiple(`
|
|
985
|
+
CREATE TABLE IF NOT EXISTS workspaces (
|
|
986
|
+
id TEXT PRIMARY KEY,
|
|
987
|
+
slug TEXT NOT NULL UNIQUE,
|
|
988
|
+
name TEXT NOT NULL,
|
|
989
|
+
owner_agent_id TEXT,
|
|
990
|
+
created_at TEXT NOT NULL,
|
|
991
|
+
metadata TEXT
|
|
992
|
+
);
|
|
993
|
+
|
|
994
|
+
CREATE INDEX IF NOT EXISTS idx_workspaces_slug
|
|
995
|
+
ON workspaces(slug);
|
|
996
|
+
`);
|
|
997
|
+
await client.executeMultiple(`
|
|
998
|
+
CREATE TABLE IF NOT EXISTS documents (
|
|
999
|
+
id TEXT PRIMARY KEY,
|
|
1000
|
+
workspace_id TEXT NOT NULL,
|
|
1001
|
+
filename TEXT NOT NULL,
|
|
1002
|
+
mime TEXT,
|
|
1003
|
+
source_type TEXT,
|
|
1004
|
+
user_id TEXT,
|
|
1005
|
+
uploaded_at TEXT NOT NULL,
|
|
1006
|
+
metadata TEXT,
|
|
1007
|
+
FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
|
|
1008
|
+
);
|
|
1009
|
+
|
|
1010
|
+
CREATE INDEX IF NOT EXISTS idx_documents_workspace
|
|
1011
|
+
ON documents(workspace_id);
|
|
1012
|
+
|
|
1013
|
+
CREATE INDEX IF NOT EXISTS idx_documents_user
|
|
1014
|
+
ON documents(user_id);
|
|
1015
|
+
`);
|
|
1016
|
+
for (const column of [
|
|
1017
|
+
"workspace_id TEXT",
|
|
1018
|
+
"document_id TEXT",
|
|
1019
|
+
"user_id TEXT",
|
|
1020
|
+
"char_offset INTEGER",
|
|
1021
|
+
"page_number INTEGER"
|
|
1022
|
+
]) {
|
|
1023
|
+
try {
|
|
1024
|
+
await client.execute({
|
|
1025
|
+
sql: `ALTER TABLE memories ADD COLUMN ${column}`,
|
|
1026
|
+
args: []
|
|
1027
|
+
});
|
|
1028
|
+
} catch {
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
for (const col of [
|
|
1032
|
+
"ALTER TABLE memories ADD COLUMN source_path TEXT",
|
|
1033
|
+
"ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
|
|
1034
|
+
]) {
|
|
1035
|
+
try {
|
|
1036
|
+
await client.execute(col);
|
|
1037
|
+
} catch {
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
await client.executeMultiple(`
|
|
1041
|
+
CREATE INDEX IF NOT EXISTS idx_memories_workspace
|
|
1042
|
+
ON memories(workspace_id);
|
|
1043
|
+
|
|
1044
|
+
CREATE INDEX IF NOT EXISTS idx_memories_document
|
|
1045
|
+
ON memories(document_id);
|
|
1046
|
+
|
|
1047
|
+
CREATE INDEX IF NOT EXISTS idx_memories_user
|
|
1048
|
+
ON memories(user_id);
|
|
1049
|
+
`);
|
|
1050
|
+
await client.executeMultiple(`
|
|
1051
|
+
CREATE TABLE IF NOT EXISTS session_kills (
|
|
1052
|
+
id TEXT PRIMARY KEY,
|
|
1053
|
+
session_name TEXT NOT NULL,
|
|
1054
|
+
agent_id TEXT NOT NULL,
|
|
1055
|
+
killed_at TIMESTAMP NOT NULL,
|
|
1056
|
+
reason TEXT NOT NULL,
|
|
1057
|
+
ticks_idle INTEGER,
|
|
1058
|
+
estimated_tokens_saved INTEGER
|
|
1059
|
+
);
|
|
1060
|
+
|
|
1061
|
+
CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
|
|
1062
|
+
ON session_kills(killed_at);
|
|
1063
|
+
|
|
1064
|
+
CREATE INDEX IF NOT EXISTS idx_session_kills_agent
|
|
1065
|
+
ON session_kills(agent_id);
|
|
1066
|
+
`);
|
|
1067
|
+
await client.execute(`
|
|
1068
|
+
CREATE TABLE IF NOT EXISTS global_procedures (
|
|
1069
|
+
id TEXT PRIMARY KEY,
|
|
1070
|
+
title TEXT NOT NULL,
|
|
1071
|
+
content TEXT NOT NULL,
|
|
1072
|
+
priority TEXT NOT NULL DEFAULT 'p0',
|
|
1073
|
+
domain TEXT,
|
|
1074
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1075
|
+
created_at TEXT NOT NULL,
|
|
1076
|
+
updated_at TEXT NOT NULL
|
|
1077
|
+
)
|
|
1078
|
+
`);
|
|
1079
|
+
await client.executeMultiple(`
|
|
1080
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
1081
|
+
id TEXT PRIMARY KEY,
|
|
1082
|
+
platform TEXT NOT NULL,
|
|
1083
|
+
external_id TEXT,
|
|
1084
|
+
sender_id TEXT NOT NULL,
|
|
1085
|
+
sender_name TEXT,
|
|
1086
|
+
sender_phone TEXT,
|
|
1087
|
+
sender_email TEXT,
|
|
1088
|
+
recipient_id TEXT,
|
|
1089
|
+
channel_id TEXT NOT NULL,
|
|
1090
|
+
thread_id TEXT,
|
|
1091
|
+
reply_to_id TEXT,
|
|
1092
|
+
content_text TEXT,
|
|
1093
|
+
content_media TEXT,
|
|
1094
|
+
content_metadata TEXT,
|
|
1095
|
+
agent_response TEXT,
|
|
1096
|
+
agent_name TEXT,
|
|
1097
|
+
timestamp TEXT NOT NULL,
|
|
1098
|
+
ingested_at TEXT NOT NULL
|
|
1099
|
+
);
|
|
1100
|
+
|
|
1101
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_platform
|
|
1102
|
+
ON conversations(platform);
|
|
1103
|
+
|
|
1104
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_sender
|
|
1105
|
+
ON conversations(sender_id);
|
|
1106
|
+
|
|
1107
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
|
|
1108
|
+
ON conversations(timestamp);
|
|
1109
|
+
|
|
1110
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_thread
|
|
1111
|
+
ON conversations(thread_id);
|
|
1112
|
+
|
|
1113
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_channel
|
|
1114
|
+
ON conversations(channel_id);
|
|
1115
|
+
`);
|
|
1116
|
+
try {
|
|
1117
|
+
await client.execute({
|
|
1118
|
+
sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
|
|
1119
|
+
args: []
|
|
1120
|
+
});
|
|
1121
|
+
} catch {
|
|
1122
|
+
}
|
|
1123
|
+
try {
|
|
1124
|
+
await client.execute({
|
|
1125
|
+
sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
|
|
1126
|
+
args: []
|
|
1127
|
+
});
|
|
1128
|
+
} catch {
|
|
1129
|
+
}
|
|
1130
|
+
try {
|
|
1131
|
+
await client.execute({
|
|
1132
|
+
sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
|
|
1133
|
+
args: []
|
|
1134
|
+
});
|
|
1135
|
+
} catch {
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
await client.execute({
|
|
1139
|
+
sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
|
|
1140
|
+
args: []
|
|
1141
|
+
});
|
|
1142
|
+
} catch {
|
|
1143
|
+
}
|
|
1144
|
+
await client.executeMultiple(`
|
|
1145
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
|
|
1146
|
+
content_text,
|
|
1147
|
+
sender_name,
|
|
1148
|
+
agent_response,
|
|
1149
|
+
content='conversations',
|
|
1150
|
+
content_rowid='rowid'
|
|
1151
|
+
);
|
|
1152
|
+
|
|
1153
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
|
|
1154
|
+
INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
|
|
1155
|
+
VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
|
|
1156
|
+
END;
|
|
1157
|
+
|
|
1158
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
|
|
1159
|
+
INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
|
|
1160
|
+
VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
|
|
1161
|
+
END;
|
|
1162
|
+
|
|
1163
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
|
|
1164
|
+
INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
|
|
1165
|
+
VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
|
|
1166
|
+
INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
|
|
1167
|
+
VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
|
|
1168
|
+
END;
|
|
1169
|
+
`);
|
|
1170
|
+
try {
|
|
1171
|
+
await client.execute({
|
|
1172
|
+
sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
|
|
1173
|
+
args: []
|
|
1174
|
+
});
|
|
1175
|
+
} catch {
|
|
1176
|
+
}
|
|
1177
|
+
try {
|
|
1178
|
+
await client.execute(
|
|
1179
|
+
`CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
|
|
1180
|
+
);
|
|
1181
|
+
} catch {
|
|
1182
|
+
}
|
|
1183
|
+
try {
|
|
1184
|
+
await client.execute({
|
|
1185
|
+
sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
|
|
1186
|
+
args: []
|
|
1187
|
+
});
|
|
1188
|
+
await client.execute({
|
|
1189
|
+
sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
|
|
1190
|
+
args: []
|
|
1191
|
+
});
|
|
1192
|
+
} catch {
|
|
1193
|
+
}
|
|
1194
|
+
try {
|
|
1195
|
+
await client.execute({
|
|
1196
|
+
sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
|
|
1197
|
+
args: []
|
|
1198
|
+
});
|
|
1199
|
+
} catch {
|
|
1200
|
+
}
|
|
1201
|
+
try {
|
|
1202
|
+
await client.execute(
|
|
1203
|
+
`CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
|
|
1204
|
+
);
|
|
1205
|
+
} catch {
|
|
1206
|
+
}
|
|
1207
|
+
for (const col of [
|
|
1208
|
+
"ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
|
|
1209
|
+
"ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
|
|
1210
|
+
]) {
|
|
1211
|
+
try {
|
|
1212
|
+
await client.execute(col);
|
|
1213
|
+
} catch {
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
var _client, _resilientClient, initTurso;
|
|
1218
|
+
var init_database = __esm({
|
|
1219
|
+
"src/lib/database.ts"() {
|
|
1220
|
+
"use strict";
|
|
1221
|
+
init_db_retry();
|
|
1222
|
+
_client = null;
|
|
1223
|
+
_resilientClient = null;
|
|
1224
|
+
initTurso = initDatabase;
|
|
1225
|
+
}
|
|
1226
|
+
});
|
|
1227
|
+
|
|
1228
|
+
// src/lib/config.ts
|
|
1229
|
+
import { readFile, writeFile, mkdir, chmod } from "fs/promises";
|
|
1230
|
+
import { readFileSync as readFileSync3, existsSync as existsSync3, renameSync as renameSync2 } from "fs";
|
|
1231
|
+
import path3 from "path";
|
|
1232
|
+
import os3 from "os";
|
|
1233
|
+
function resolveDataDir() {
|
|
1234
|
+
if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
|
|
1235
|
+
if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
|
|
1236
|
+
const newDir = path3.join(os3.homedir(), ".exe-os");
|
|
1237
|
+
const legacyDir = path3.join(os3.homedir(), ".exe-mem");
|
|
1238
|
+
if (!existsSync3(newDir) && existsSync3(legacyDir)) {
|
|
1239
|
+
try {
|
|
1240
|
+
renameSync2(legacyDir, newDir);
|
|
1241
|
+
process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
|
|
1242
|
+
`);
|
|
1243
|
+
} catch {
|
|
1244
|
+
return legacyDir;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return newDir;
|
|
1248
|
+
}
|
|
1249
|
+
function migrateLegacyConfig(raw) {
|
|
1250
|
+
if ("r2" in raw) {
|
|
1251
|
+
process.stderr.write(
|
|
1252
|
+
"[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
|
|
1253
|
+
);
|
|
1254
|
+
delete raw.r2;
|
|
1255
|
+
}
|
|
1256
|
+
if ("syncIntervalMs" in raw) {
|
|
1257
|
+
delete raw.syncIntervalMs;
|
|
1258
|
+
}
|
|
1259
|
+
return raw;
|
|
1260
|
+
}
|
|
1261
|
+
function migrateConfig(raw) {
|
|
1262
|
+
const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
|
|
1263
|
+
let currentVersion = fromVersion;
|
|
1264
|
+
let migrated = false;
|
|
1265
|
+
if (currentVersion > CURRENT_CONFIG_VERSION) {
|
|
1266
|
+
return { config: raw, migrated: false, fromVersion };
|
|
1267
|
+
}
|
|
1268
|
+
for (const migration of CONFIG_MIGRATIONS) {
|
|
1269
|
+
if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
|
|
1270
|
+
raw = migration.migrate(raw);
|
|
1271
|
+
currentVersion = migration.to;
|
|
1272
|
+
migrated = true;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
return { config: raw, migrated, fromVersion };
|
|
1276
|
+
}
|
|
1277
|
+
function normalizeScalingRoadmap(raw) {
|
|
1278
|
+
const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
|
|
1279
|
+
const userRoadmap = raw.scalingRoadmap ?? {};
|
|
1280
|
+
const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
|
|
1281
|
+
if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
|
|
1282
|
+
userAuto.enabled = raw.rerankerEnabled;
|
|
1283
|
+
}
|
|
1284
|
+
raw.scalingRoadmap = {
|
|
1285
|
+
...userRoadmap,
|
|
1286
|
+
rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
function normalizeSessionLifecycle(raw) {
|
|
1290
|
+
const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
|
|
1291
|
+
const userSL = raw.sessionLifecycle ?? {};
|
|
1292
|
+
raw.sessionLifecycle = { ...defaultSL, ...userSL };
|
|
1293
|
+
}
|
|
1294
|
+
function normalizeAutoUpdate(raw) {
|
|
1295
|
+
const defaultAU = DEFAULT_CONFIG.autoUpdate;
|
|
1296
|
+
const userAU = raw.autoUpdate ?? {};
|
|
1297
|
+
raw.autoUpdate = { ...defaultAU, ...userAU };
|
|
1298
|
+
}
|
|
1299
|
+
async function loadConfig() {
|
|
1300
|
+
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
1301
|
+
await mkdir(dir, { recursive: true });
|
|
1302
|
+
const configPath = path3.join(dir, "config.json");
|
|
1303
|
+
if (!existsSync3(configPath)) {
|
|
1304
|
+
return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
|
|
1305
|
+
}
|
|
1306
|
+
const raw = await readFile(configPath, "utf-8");
|
|
1307
|
+
try {
|
|
1308
|
+
let parsed = JSON.parse(raw);
|
|
1309
|
+
parsed = migrateLegacyConfig(parsed);
|
|
1310
|
+
const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
|
|
1311
|
+
if (migrated) {
|
|
1312
|
+
process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
|
|
1313
|
+
`);
|
|
1314
|
+
try {
|
|
1315
|
+
await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
|
|
1316
|
+
} catch {
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
normalizeScalingRoadmap(migratedCfg);
|
|
1320
|
+
normalizeSessionLifecycle(migratedCfg);
|
|
1321
|
+
normalizeAutoUpdate(migratedCfg);
|
|
1322
|
+
const config = { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db"), ...migratedCfg };
|
|
1323
|
+
if (config.dbPath.startsWith("~")) {
|
|
1324
|
+
config.dbPath = config.dbPath.replace(/^~/, os3.homedir());
|
|
1325
|
+
}
|
|
1326
|
+
return config;
|
|
1327
|
+
} catch {
|
|
1328
|
+
return { ...DEFAULT_CONFIG, dbPath: path3.join(dir, "memories.db") };
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
1332
|
+
var init_config = __esm({
|
|
1333
|
+
"src/lib/config.ts"() {
|
|
1334
|
+
"use strict";
|
|
1335
|
+
EXE_AI_DIR = resolveDataDir();
|
|
1336
|
+
DB_PATH = path3.join(EXE_AI_DIR, "memories.db");
|
|
1337
|
+
MODELS_DIR = path3.join(EXE_AI_DIR, "models");
|
|
1338
|
+
CONFIG_PATH = path3.join(EXE_AI_DIR, "config.json");
|
|
1339
|
+
LEGACY_LANCE_PATH = path3.join(EXE_AI_DIR, "local.lance");
|
|
1340
|
+
CURRENT_CONFIG_VERSION = 1;
|
|
1341
|
+
DEFAULT_CONFIG = {
|
|
1342
|
+
config_version: CURRENT_CONFIG_VERSION,
|
|
1343
|
+
dbPath: DB_PATH,
|
|
1344
|
+
modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
|
|
1345
|
+
embeddingDim: 1024,
|
|
1346
|
+
batchSize: 20,
|
|
1347
|
+
flushIntervalMs: 1e4,
|
|
1348
|
+
autoIngestion: true,
|
|
1349
|
+
autoRetrieval: true,
|
|
1350
|
+
searchMode: "hybrid",
|
|
1351
|
+
hookSearchMode: "hybrid",
|
|
1352
|
+
fileGrepEnabled: true,
|
|
1353
|
+
splashEffect: true,
|
|
1354
|
+
consolidationEnabled: true,
|
|
1355
|
+
consolidationIntervalMs: 6 * 60 * 60 * 1e3,
|
|
1356
|
+
consolidationModel: "claude-haiku-4-5-20251001",
|
|
1357
|
+
consolidationMaxCallsPerRun: 20,
|
|
1358
|
+
selfQueryRouter: true,
|
|
1359
|
+
selfQueryModel: "claude-haiku-4-5-20251001",
|
|
1360
|
+
rerankerEnabled: true,
|
|
1361
|
+
scalingRoadmap: {
|
|
1362
|
+
rerankerAutoTrigger: {
|
|
1363
|
+
enabled: true,
|
|
1364
|
+
broadQueryMinCardinality: 5e4,
|
|
1365
|
+
fetchTopK: 150,
|
|
1366
|
+
returnTopK: 5
|
|
1367
|
+
}
|
|
1368
|
+
},
|
|
1369
|
+
graphRagEnabled: true,
|
|
1370
|
+
wikiEnabled: false,
|
|
1371
|
+
wikiUrl: "",
|
|
1372
|
+
wikiApiKey: "",
|
|
1373
|
+
wikiSyncIntervalMs: 30 * 60 * 1e3,
|
|
1374
|
+
wikiWorkspaceMapping: {
|
|
1375
|
+
exe: "Executive",
|
|
1376
|
+
yoshi: "Engineering",
|
|
1377
|
+
mari: "Marketing",
|
|
1378
|
+
tom: "Engineering",
|
|
1379
|
+
sasha: "Production"
|
|
1380
|
+
},
|
|
1381
|
+
wikiAutoUpdate: true,
|
|
1382
|
+
wikiAutoUpdateThreshold: 0.5,
|
|
1383
|
+
wikiAutoUpdateCreateNew: true,
|
|
1384
|
+
skillLearning: true,
|
|
1385
|
+
skillThreshold: 3,
|
|
1386
|
+
skillModel: "claude-haiku-4-5-20251001",
|
|
1387
|
+
exeHeartbeat: {
|
|
1388
|
+
enabled: true,
|
|
1389
|
+
intervalSeconds: 60,
|
|
1390
|
+
staleInProgressThresholdHours: 2
|
|
1391
|
+
},
|
|
1392
|
+
sessionLifecycle: {
|
|
1393
|
+
idleKillEnabled: true,
|
|
1394
|
+
idleKillTicksRequired: 3,
|
|
1395
|
+
idleKillIntercomAckWindowMs: 1e4,
|
|
1396
|
+
maxAutoInstances: 10
|
|
1397
|
+
},
|
|
1398
|
+
autoUpdate: {
|
|
1399
|
+
checkOnBoot: true,
|
|
1400
|
+
autoInstall: false,
|
|
1401
|
+
checkIntervalMs: 24 * 60 * 60 * 1e3
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
CONFIG_MIGRATIONS = [
|
|
1405
|
+
{
|
|
1406
|
+
from: 0,
|
|
1407
|
+
to: 1,
|
|
1408
|
+
migrate: (cfg) => {
|
|
1409
|
+
cfg.config_version = 1;
|
|
1410
|
+
return cfg;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
];
|
|
1414
|
+
}
|
|
1415
|
+
});
|
|
1416
|
+
|
|
1417
|
+
// src/lib/employees.ts
|
|
1418
|
+
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
|
|
1419
|
+
import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
|
|
1420
|
+
import { execSync as execSync3 } from "child_process";
|
|
1421
|
+
import path4 from "path";
|
|
1422
|
+
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
1423
|
+
if (!existsSync4(employeesPath)) return [];
|
|
1424
|
+
try {
|
|
1425
|
+
return JSON.parse(readFileSync4(employeesPath, "utf-8"));
|
|
1426
|
+
} catch {
|
|
1427
|
+
return [];
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
function getEmployee(employees, name) {
|
|
1431
|
+
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
1432
|
+
}
|
|
1433
|
+
function isMultiInstance(agentName, employees) {
|
|
1434
|
+
const roster = employees ?? loadEmployeesSync();
|
|
1435
|
+
const emp = getEmployee(roster, agentName);
|
|
1436
|
+
if (!emp) return false;
|
|
1437
|
+
return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
|
|
1438
|
+
}
|
|
1439
|
+
var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
|
|
1440
|
+
var init_employees = __esm({
|
|
1441
|
+
"src/lib/employees.ts"() {
|
|
1442
|
+
"use strict";
|
|
1443
|
+
init_config();
|
|
1444
|
+
EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
|
|
1445
|
+
MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
|
|
1446
|
+
}
|
|
1447
|
+
});
|
|
1448
|
+
|
|
1449
|
+
// src/lib/license.ts
|
|
1450
|
+
import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, existsSync as existsSync5, mkdirSync as mkdirSync3 } from "fs";
|
|
1451
|
+
import { randomUUID } from "crypto";
|
|
1452
|
+
import path5 from "path";
|
|
1453
|
+
import { jwtVerify, importSPKI } from "jose";
|
|
1454
|
+
var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
|
|
1455
|
+
var init_license = __esm({
|
|
1456
|
+
"src/lib/license.ts"() {
|
|
1457
|
+
"use strict";
|
|
1458
|
+
init_config();
|
|
1459
|
+
LICENSE_PATH = path5.join(EXE_AI_DIR, "license.key");
|
|
1460
|
+
CACHE_PATH = path5.join(EXE_AI_DIR, "license-cache.json");
|
|
1461
|
+
DEVICE_ID_PATH = path5.join(EXE_AI_DIR, "device-id");
|
|
1462
|
+
PLAN_LIMITS = {
|
|
1463
|
+
free: { devices: 1, employees: 1, memories: 5e3 },
|
|
1464
|
+
pro: { devices: 2, employees: 5, memories: 1e5 },
|
|
1465
|
+
team: { devices: 10, employees: 20, memories: 1e6 },
|
|
1466
|
+
agency: { devices: 50, employees: 100, memories: 1e7 },
|
|
1467
|
+
enterprise: { devices: -1, employees: -1, memories: -1 }
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1471
|
+
|
|
1472
|
+
// src/lib/plan-limits.ts
|
|
1473
|
+
import { readFileSync as readFileSync6, existsSync as existsSync6 } from "fs";
|
|
1474
|
+
import path6 from "path";
|
|
1475
|
+
function getLicenseSync() {
|
|
1476
|
+
try {
|
|
1477
|
+
if (!existsSync6(CACHE_PATH2)) return freeLicense();
|
|
1478
|
+
const raw = JSON.parse(readFileSync6(CACHE_PATH2, "utf8"));
|
|
1479
|
+
if (!raw.token || typeof raw.token !== "string") return freeLicense();
|
|
1480
|
+
const parts = raw.token.split(".");
|
|
1481
|
+
if (parts.length !== 3) return freeLicense();
|
|
1482
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
|
|
1483
|
+
const plan = payload.plan ?? "free";
|
|
1484
|
+
const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
|
|
1485
|
+
return {
|
|
1486
|
+
valid: true,
|
|
1487
|
+
plan,
|
|
1488
|
+
email: payload.sub ?? "",
|
|
1489
|
+
expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
|
|
1490
|
+
deviceLimit: limits.devices,
|
|
1491
|
+
employeeLimit: limits.employees,
|
|
1492
|
+
memoryLimit: limits.memories
|
|
1493
|
+
};
|
|
1494
|
+
} catch {
|
|
1495
|
+
return freeLicense();
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
function freeLicense() {
|
|
1499
|
+
const limits = PLAN_LIMITS.free;
|
|
1500
|
+
return {
|
|
1501
|
+
valid: true,
|
|
1502
|
+
plan: "free",
|
|
1503
|
+
email: "",
|
|
1504
|
+
expiresAt: null,
|
|
1505
|
+
deviceLimit: limits.devices,
|
|
1506
|
+
employeeLimit: limits.employees,
|
|
1507
|
+
memoryLimit: limits.memories
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
function assertEmployeeLimitSync(rosterPath) {
|
|
1511
|
+
const license = getLicenseSync();
|
|
1512
|
+
if (license.employeeLimit < 0) return;
|
|
1513
|
+
const filePath = rosterPath ?? EMPLOYEES_PATH;
|
|
1514
|
+
let count = 0;
|
|
1515
|
+
try {
|
|
1516
|
+
if (existsSync6(filePath)) {
|
|
1517
|
+
const raw = readFileSync6(filePath, "utf8");
|
|
1518
|
+
const employees = JSON.parse(raw);
|
|
1519
|
+
count = Array.isArray(employees) ? employees.length : 0;
|
|
1520
|
+
}
|
|
1521
|
+
} catch {
|
|
1522
|
+
throw new PlanLimitError(
|
|
1523
|
+
`Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
if (count >= license.employeeLimit) {
|
|
1527
|
+
throw new PlanLimitError(
|
|
1528
|
+
`Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
|
|
1529
|
+
);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
var PlanLimitError, CACHE_PATH2;
|
|
1533
|
+
var init_plan_limits = __esm({
|
|
1534
|
+
"src/lib/plan-limits.ts"() {
|
|
1535
|
+
"use strict";
|
|
1536
|
+
init_database();
|
|
1537
|
+
init_employees();
|
|
1538
|
+
init_license();
|
|
1539
|
+
init_config();
|
|
1540
|
+
PlanLimitError = class extends Error {
|
|
1541
|
+
constructor(message) {
|
|
1542
|
+
super(message);
|
|
1543
|
+
this.name = "PlanLimitError";
|
|
1544
|
+
}
|
|
1545
|
+
};
|
|
1546
|
+
CACHE_PATH2 = path6.join(EXE_AI_DIR, "license-cache.json");
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
|
|
1550
|
+
// src/lib/notifications.ts
|
|
1551
|
+
import crypto from "crypto";
|
|
1552
|
+
import path7 from "path";
|
|
1553
|
+
import os4 from "os";
|
|
1554
|
+
import {
|
|
1555
|
+
readFileSync as readFileSync7,
|
|
1556
|
+
readdirSync,
|
|
1557
|
+
unlinkSync,
|
|
1558
|
+
existsSync as existsSync7,
|
|
1559
|
+
rmdirSync
|
|
1560
|
+
} from "fs";
|
|
1561
|
+
async function writeNotification(notification) {
|
|
1562
|
+
try {
|
|
1563
|
+
const client = getClient();
|
|
1564
|
+
const id = crypto.randomUUID();
|
|
1565
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1566
|
+
await client.execute({
|
|
1567
|
+
sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
|
|
1568
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
|
|
1569
|
+
args: [
|
|
1570
|
+
id,
|
|
1571
|
+
notification.agentId,
|
|
1572
|
+
notification.agentRole,
|
|
1573
|
+
notification.event,
|
|
1574
|
+
notification.project,
|
|
1575
|
+
notification.summary,
|
|
1576
|
+
notification.taskFile ?? null,
|
|
1577
|
+
now
|
|
1578
|
+
]
|
|
1579
|
+
});
|
|
1580
|
+
} catch (err) {
|
|
1581
|
+
process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
|
|
1582
|
+
`);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
async function markAsReadByTaskFile(taskFile) {
|
|
1586
|
+
try {
|
|
1587
|
+
const client = getClient();
|
|
1588
|
+
await client.execute({
|
|
1589
|
+
sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
|
|
1590
|
+
args: [taskFile]
|
|
1591
|
+
});
|
|
1592
|
+
} catch {
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
var init_notifications = __esm({
|
|
1596
|
+
"src/lib/notifications.ts"() {
|
|
1597
|
+
"use strict";
|
|
1598
|
+
init_database();
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
|
|
1602
|
+
// src/lib/session-kill-telemetry.ts
|
|
1603
|
+
import crypto2 from "crypto";
|
|
1604
|
+
async function recordSessionKill(input) {
|
|
1605
|
+
try {
|
|
1606
|
+
const client = getClient();
|
|
1607
|
+
await client.execute({
|
|
1608
|
+
sql: `INSERT INTO session_kills
|
|
1609
|
+
(id, session_name, agent_id, killed_at, reason,
|
|
1610
|
+
ticks_idle, estimated_tokens_saved)
|
|
1611
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
1612
|
+
args: [
|
|
1613
|
+
crypto2.randomUUID(),
|
|
1614
|
+
input.sessionName,
|
|
1615
|
+
input.agentId,
|
|
1616
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
1617
|
+
input.reason,
|
|
1618
|
+
input.ticksIdle ?? null,
|
|
1619
|
+
input.estimatedTokensSaved ?? null
|
|
1620
|
+
]
|
|
1621
|
+
});
|
|
1622
|
+
} catch (err) {
|
|
1623
|
+
process.stderr.write(
|
|
1624
|
+
`[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
|
|
1625
|
+
`
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
var init_session_kill_telemetry = __esm({
|
|
1630
|
+
"src/lib/session-kill-telemetry.ts"() {
|
|
1631
|
+
"use strict";
|
|
1632
|
+
init_database();
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
|
|
1636
|
+
// src/lib/task-scope.ts
|
|
1637
|
+
function getCurrentSessionScope() {
|
|
1638
|
+
try {
|
|
1639
|
+
return resolveExeSession();
|
|
1640
|
+
} catch {
|
|
1641
|
+
return null;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
function sessionScopeFilter(sessionScope, tableAlias) {
|
|
1645
|
+
const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
|
|
1646
|
+
if (!scope) return { sql: "", args: [] };
|
|
1647
|
+
const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
|
|
1648
|
+
return {
|
|
1649
|
+
sql: ` AND (${col} IS NULL OR ${col} = ?)`,
|
|
1650
|
+
args: [scope]
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
var init_task_scope = __esm({
|
|
1654
|
+
"src/lib/task-scope.ts"() {
|
|
1655
|
+
"use strict";
|
|
1656
|
+
init_tmux_routing();
|
|
1657
|
+
}
|
|
1658
|
+
});
|
|
1659
|
+
|
|
1660
|
+
// src/lib/state-bus.ts
|
|
1661
|
+
var StateBus, orgBus;
|
|
1662
|
+
var init_state_bus = __esm({
|
|
1663
|
+
"src/lib/state-bus.ts"() {
|
|
1664
|
+
"use strict";
|
|
1665
|
+
StateBus = class {
|
|
1666
|
+
handlers = /* @__PURE__ */ new Map();
|
|
1667
|
+
globalHandlers = /* @__PURE__ */ new Set();
|
|
1668
|
+
/** Emit an event to all subscribers */
|
|
1669
|
+
emit(event) {
|
|
1670
|
+
const typeHandlers = this.handlers.get(event.type);
|
|
1671
|
+
if (typeHandlers) {
|
|
1672
|
+
for (const handler of typeHandlers) {
|
|
1673
|
+
try {
|
|
1674
|
+
handler(event);
|
|
1675
|
+
} catch {
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
for (const handler of this.globalHandlers) {
|
|
1680
|
+
try {
|
|
1681
|
+
handler(event);
|
|
1682
|
+
} catch {
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
/** Subscribe to a specific event type */
|
|
1687
|
+
on(type, handler) {
|
|
1688
|
+
if (!this.handlers.has(type)) {
|
|
1689
|
+
this.handlers.set(type, /* @__PURE__ */ new Set());
|
|
1690
|
+
}
|
|
1691
|
+
this.handlers.get(type).add(handler);
|
|
1692
|
+
}
|
|
1693
|
+
/** Subscribe to ALL events */
|
|
1694
|
+
onAny(handler) {
|
|
1695
|
+
this.globalHandlers.add(handler);
|
|
1696
|
+
}
|
|
1697
|
+
/** Unsubscribe from a specific event type */
|
|
1698
|
+
off(type, handler) {
|
|
1699
|
+
this.handlers.get(type)?.delete(handler);
|
|
1700
|
+
}
|
|
1701
|
+
/** Unsubscribe from ALL events */
|
|
1702
|
+
offAny(handler) {
|
|
1703
|
+
this.globalHandlers.delete(handler);
|
|
1704
|
+
}
|
|
1705
|
+
/** Remove all listeners */
|
|
1706
|
+
clear() {
|
|
1707
|
+
this.handlers.clear();
|
|
1708
|
+
this.globalHandlers.clear();
|
|
1709
|
+
}
|
|
1710
|
+
};
|
|
1711
|
+
orgBus = new StateBus();
|
|
1712
|
+
}
|
|
1713
|
+
});
|
|
1714
|
+
|
|
1715
|
+
// src/lib/tasks-crud.ts
|
|
1716
|
+
import crypto3 from "crypto";
|
|
1717
|
+
import path8 from "path";
|
|
1718
|
+
import { execSync as execSync4 } from "child_process";
|
|
1719
|
+
import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
|
|
1720
|
+
import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
1721
|
+
async function writeCheckpoint(input) {
|
|
1722
|
+
const client = getClient();
|
|
1723
|
+
const row = await resolveTask(client, input.taskId);
|
|
1724
|
+
const taskId = String(row.id);
|
|
1725
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1726
|
+
const blockedByIds = [];
|
|
1727
|
+
if (row.blocked_by) {
|
|
1728
|
+
blockedByIds.push(String(row.blocked_by));
|
|
1729
|
+
}
|
|
1730
|
+
const checkpoint = {
|
|
1731
|
+
step: input.step,
|
|
1732
|
+
context_summary: input.contextSummary,
|
|
1733
|
+
files_touched: input.filesTouched ?? [],
|
|
1734
|
+
blocked_by_ids: blockedByIds,
|
|
1735
|
+
last_checkpoint_at: now
|
|
1736
|
+
};
|
|
1737
|
+
const result2 = await client.execute({
|
|
1738
|
+
sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
|
|
1739
|
+
args: [JSON.stringify(checkpoint), now, taskId]
|
|
1740
|
+
});
|
|
1741
|
+
if (result2.rowsAffected === 0) {
|
|
1742
|
+
throw new Error(`Checkpoint write failed: task ${taskId} not found`);
|
|
1743
|
+
}
|
|
1744
|
+
const countResult = await client.execute({
|
|
1745
|
+
sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
|
|
1746
|
+
args: [taskId]
|
|
1747
|
+
});
|
|
1748
|
+
const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
|
|
1749
|
+
return { checkpointCount };
|
|
1750
|
+
}
|
|
1751
|
+
function extractParentFromContext(contextBody) {
|
|
1752
|
+
if (!contextBody) return null;
|
|
1753
|
+
const match = contextBody.match(
|
|
1754
|
+
/Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
|
|
1755
|
+
);
|
|
1756
|
+
return match ? match[1].toLowerCase() : null;
|
|
1757
|
+
}
|
|
1758
|
+
function slugify(title) {
|
|
1759
|
+
return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
1760
|
+
}
|
|
1761
|
+
async function resolveTask(client, identifier, scopeSession) {
|
|
1762
|
+
const scope = sessionScopeFilter(scopeSession);
|
|
1763
|
+
let result2 = await client.execute({
|
|
1764
|
+
sql: `SELECT * FROM tasks WHERE id = ?${scope.sql}`,
|
|
1765
|
+
args: [identifier, ...scope.args]
|
|
1766
|
+
});
|
|
1767
|
+
if (result2.rows.length === 1) return result2.rows[0];
|
|
1768
|
+
result2 = await client.execute({
|
|
1769
|
+
sql: `SELECT * FROM tasks WHERE task_file LIKE ?${scope.sql}`,
|
|
1770
|
+
args: [`%${identifier}%`, ...scope.args]
|
|
1771
|
+
});
|
|
1772
|
+
if (result2.rows.length === 1) return result2.rows[0];
|
|
1773
|
+
if (result2.rows.length > 1) {
|
|
1774
|
+
const exact = result2.rows.filter(
|
|
1775
|
+
(r) => String(r.task_file).endsWith(`/${identifier}.md`)
|
|
1776
|
+
);
|
|
1777
|
+
if (exact.length === 1) return exact[0];
|
|
1778
|
+
const candidates = exact.length > 1 ? exact : result2.rows;
|
|
1779
|
+
const active = candidates.filter(
|
|
1780
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
1781
|
+
);
|
|
1782
|
+
if (active.length === 1) return active[0];
|
|
1783
|
+
const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
1784
|
+
throw new Error(
|
|
1785
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
1786
|
+
);
|
|
1787
|
+
}
|
|
1788
|
+
result2 = await client.execute({
|
|
1789
|
+
sql: `SELECT * FROM tasks WHERE title LIKE ?${scope.sql}`,
|
|
1790
|
+
args: [`%${identifier}%`, ...scope.args]
|
|
1791
|
+
});
|
|
1792
|
+
if (result2.rows.length === 1) return result2.rows[0];
|
|
1793
|
+
if (result2.rows.length > 1) {
|
|
1794
|
+
const active = result2.rows.filter(
|
|
1795
|
+
(r) => !["done", "cancelled"].includes(String(r.status))
|
|
1796
|
+
);
|
|
1797
|
+
if (active.length === 1) return active[0];
|
|
1798
|
+
const matches = (active.length > 1 ? active : result2.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
|
|
1799
|
+
throw new Error(
|
|
1800
|
+
`Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
|
|
1801
|
+
);
|
|
1802
|
+
}
|
|
1803
|
+
throw new Error(`Task not found: ${identifier}`);
|
|
1804
|
+
}
|
|
1805
|
+
async function createTaskCore(input) {
|
|
1806
|
+
const client = getClient();
|
|
1807
|
+
const id = crypto3.randomUUID();
|
|
1808
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1809
|
+
const slug = slugify(input.title);
|
|
1810
|
+
const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
|
|
1811
|
+
let blockedById = null;
|
|
1812
|
+
const initialStatus = input.blockedBy ? "blocked" : "open";
|
|
1813
|
+
if (input.blockedBy) {
|
|
1814
|
+
const blocker = await resolveTask(client, input.blockedBy);
|
|
1815
|
+
blockedById = String(blocker.id);
|
|
1816
|
+
}
|
|
1817
|
+
let parentTaskId = null;
|
|
1818
|
+
let parentRef = input.parentTaskId;
|
|
1819
|
+
if (!parentRef) {
|
|
1820
|
+
const extracted = extractParentFromContext(input.context);
|
|
1821
|
+
if (extracted) {
|
|
1822
|
+
parentRef = extracted;
|
|
1823
|
+
process.stderr.write(
|
|
1824
|
+
"[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (parentRef) {
|
|
1829
|
+
try {
|
|
1830
|
+
const parent = await resolveTask(client, parentRef);
|
|
1831
|
+
parentTaskId = String(parent.id);
|
|
1832
|
+
} catch (err) {
|
|
1833
|
+
if (!input.parentTaskId) {
|
|
1834
|
+
throw new Error(
|
|
1835
|
+
`create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
|
|
1836
|
+
);
|
|
1837
|
+
}
|
|
1838
|
+
throw err;
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
let warning;
|
|
1842
|
+
const dupScope = sessionScopeFilter();
|
|
1843
|
+
const dupCheck = await client.execute({
|
|
1844
|
+
sql: `SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')${dupScope.sql}`,
|
|
1845
|
+
args: [input.title, input.assignedTo, ...dupScope.args]
|
|
1846
|
+
});
|
|
1847
|
+
if (dupCheck.rows.length > 0) {
|
|
1848
|
+
warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
|
|
1849
|
+
}
|
|
1850
|
+
if (input.baseDir) {
|
|
1851
|
+
try {
|
|
1852
|
+
await mkdir3(path8.join(input.baseDir, "exe", "output"), { recursive: true });
|
|
1853
|
+
await mkdir3(path8.join(input.baseDir, "exe", "research"), { recursive: true });
|
|
1854
|
+
await ensureArchitectureDoc(input.baseDir, input.projectName);
|
|
1855
|
+
await ensureGitignoreExe(input.baseDir);
|
|
1856
|
+
} catch {
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const complexity = input.complexity ?? "standard";
|
|
1860
|
+
let sessionScope = null;
|
|
1861
|
+
try {
|
|
1862
|
+
const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
|
|
1863
|
+
sessionScope = resolveExeSession2();
|
|
1864
|
+
} catch {
|
|
1865
|
+
}
|
|
1866
|
+
await client.execute({
|
|
1867
|
+
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)
|
|
1868
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1869
|
+
args: [
|
|
1870
|
+
id,
|
|
1871
|
+
input.title,
|
|
1872
|
+
input.assignedTo,
|
|
1873
|
+
input.assignedBy,
|
|
1874
|
+
input.projectName,
|
|
1875
|
+
input.priority,
|
|
1876
|
+
initialStatus,
|
|
1877
|
+
taskFile,
|
|
1878
|
+
blockedById,
|
|
1879
|
+
parentTaskId,
|
|
1880
|
+
input.reviewer ?? null,
|
|
1881
|
+
input.context,
|
|
1882
|
+
complexity,
|
|
1883
|
+
input.budgetTokens ?? null,
|
|
1884
|
+
input.budgetFallbackModel ?? null,
|
|
1885
|
+
0,
|
|
1886
|
+
null,
|
|
1887
|
+
sessionScope,
|
|
1888
|
+
now,
|
|
1889
|
+
now
|
|
1890
|
+
]
|
|
1891
|
+
});
|
|
1892
|
+
return {
|
|
1893
|
+
id,
|
|
1894
|
+
title: input.title,
|
|
1895
|
+
assignedTo: input.assignedTo,
|
|
1896
|
+
assignedBy: input.assignedBy,
|
|
1897
|
+
projectName: input.projectName,
|
|
1898
|
+
priority: input.priority,
|
|
1899
|
+
status: initialStatus,
|
|
1900
|
+
taskFile,
|
|
1901
|
+
createdAt: now,
|
|
1902
|
+
updatedAt: now,
|
|
1903
|
+
warning,
|
|
1904
|
+
budgetTokens: input.budgetTokens ?? null,
|
|
1905
|
+
budgetFallbackModel: input.budgetFallbackModel ?? null,
|
|
1906
|
+
tokensUsed: 0,
|
|
1907
|
+
tokensWarnedAt: null
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
async function listTasks(input) {
|
|
1911
|
+
const client = getClient();
|
|
1912
|
+
const conditions = [];
|
|
1913
|
+
const args = [];
|
|
1914
|
+
if (input.assignedTo) {
|
|
1915
|
+
conditions.push("assigned_to = ?");
|
|
1916
|
+
args.push(input.assignedTo);
|
|
1917
|
+
}
|
|
1918
|
+
if (input.status) {
|
|
1919
|
+
conditions.push("status = ?");
|
|
1920
|
+
args.push(input.status);
|
|
1921
|
+
} else {
|
|
1922
|
+
conditions.push("status IN ('open', 'in_progress', 'blocked')");
|
|
1923
|
+
}
|
|
1924
|
+
if (input.projectName) {
|
|
1925
|
+
conditions.push("project_name = ?");
|
|
1926
|
+
args.push(input.projectName);
|
|
1927
|
+
}
|
|
1928
|
+
if (input.priority) {
|
|
1929
|
+
conditions.push("priority = ?");
|
|
1930
|
+
args.push(input.priority);
|
|
1931
|
+
}
|
|
1932
|
+
const scope = sessionScopeFilter();
|
|
1933
|
+
if (scope.sql) {
|
|
1934
|
+
conditions.push("(session_scope IS NULL OR session_scope = ?)");
|
|
1935
|
+
args.push(...scope.args);
|
|
1936
|
+
}
|
|
1937
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1938
|
+
const result2 = await client.execute({
|
|
1939
|
+
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`,
|
|
1940
|
+
args
|
|
1941
|
+
});
|
|
1942
|
+
return result2.rows.map((r) => ({
|
|
1943
|
+
id: String(r.id),
|
|
1944
|
+
title: String(r.title),
|
|
1945
|
+
assignedTo: String(r.assigned_to),
|
|
1946
|
+
assignedBy: String(r.assigned_by),
|
|
1947
|
+
projectName: String(r.project_name),
|
|
1948
|
+
priority: String(r.priority),
|
|
1949
|
+
status: String(r.status),
|
|
1950
|
+
taskFile: String(r.task_file),
|
|
1951
|
+
createdAt: String(r.created_at),
|
|
1952
|
+
updatedAt: String(r.updated_at),
|
|
1953
|
+
checkpointCount: Number(r.checkpoint_count ?? 0),
|
|
1954
|
+
budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
|
|
1955
|
+
budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
|
|
1956
|
+
tokensUsed: Number(r.tokens_used ?? 0),
|
|
1957
|
+
tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
|
|
1958
|
+
}));
|
|
1959
|
+
}
|
|
1960
|
+
function checkStaleCompletion(taskContext, taskCreatedAt) {
|
|
1961
|
+
if (!taskContext) return null;
|
|
1962
|
+
if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
|
|
1963
|
+
try {
|
|
1964
|
+
const since = new Date(taskCreatedAt).toISOString();
|
|
1965
|
+
const branch = execSync4(
|
|
1966
|
+
"git rev-parse --abbrev-ref HEAD 2>/dev/null",
|
|
1967
|
+
{ encoding: "utf8", timeout: 3e3 }
|
|
1968
|
+
).trim();
|
|
1969
|
+
const branchArg = branch && branch !== "HEAD" ? branch : "";
|
|
1970
|
+
const commitCount = execSync4(
|
|
1971
|
+
`git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
|
|
1972
|
+
{ encoding: "utf8", timeout: 5e3 }
|
|
1973
|
+
).trim();
|
|
1974
|
+
const count = parseInt(commitCount, 10);
|
|
1975
|
+
if (count === 0) {
|
|
1976
|
+
return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
|
|
1977
|
+
}
|
|
1978
|
+
return null;
|
|
1979
|
+
} catch {
|
|
1980
|
+
return null;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
async function updateTaskStatus(input) {
|
|
1984
|
+
const client = getClient();
|
|
1985
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1986
|
+
const row = await resolveTask(client, input.taskId);
|
|
1987
|
+
const taskId = String(row.id);
|
|
1988
|
+
const taskFile = String(row.task_file);
|
|
1989
|
+
if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
|
|
1990
|
+
process.stderr.write(
|
|
1991
|
+
`[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
|
|
1992
|
+
`
|
|
1993
|
+
);
|
|
1994
|
+
}
|
|
1995
|
+
if (input.status === "done") {
|
|
1996
|
+
const existingRow = await client.execute({
|
|
1997
|
+
sql: "SELECT context, created_at FROM tasks WHERE id = ?",
|
|
1998
|
+
args: [taskId]
|
|
1999
|
+
});
|
|
2000
|
+
if (existingRow.rows.length > 0) {
|
|
2001
|
+
const ctx = existingRow.rows[0];
|
|
2002
|
+
const warning = checkStaleCompletion(ctx.context, ctx.created_at);
|
|
2003
|
+
if (warning) {
|
|
2004
|
+
input.result = input.result ? `\u26A0\uFE0F ${warning}
|
|
2005
|
+
|
|
2006
|
+
${input.result}` : `\u26A0\uFE0F ${warning}`;
|
|
2007
|
+
process.stderr.write(`[tasks] ${warning} (task: ${taskId})
|
|
2008
|
+
`);
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
if (input.status === "in_progress") {
|
|
2013
|
+
const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
|
|
2014
|
+
const claim = await client.execute({
|
|
2015
|
+
sql: `UPDATE tasks
|
|
2016
|
+
SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
|
|
2017
|
+
WHERE id = ? AND status = 'open'`,
|
|
2018
|
+
args: [tmuxSession, now, taskId]
|
|
2019
|
+
});
|
|
2020
|
+
if (claim.rowsAffected === 0) {
|
|
2021
|
+
const current = await client.execute({
|
|
2022
|
+
sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
|
|
2023
|
+
args: [taskId]
|
|
2024
|
+
});
|
|
2025
|
+
const cur = current.rows[0];
|
|
2026
|
+
const status = cur?.status ?? "unknown";
|
|
2027
|
+
const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
|
|
2028
|
+
throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
|
|
2029
|
+
}
|
|
2030
|
+
try {
|
|
2031
|
+
await writeCheckpoint({
|
|
2032
|
+
taskId,
|
|
2033
|
+
step: "claimed",
|
|
2034
|
+
contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
|
|
2035
|
+
});
|
|
2036
|
+
} catch {
|
|
2037
|
+
}
|
|
2038
|
+
return { row, taskFile, now, taskId };
|
|
2039
|
+
}
|
|
2040
|
+
if (input.result) {
|
|
2041
|
+
await client.execute({
|
|
2042
|
+
sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
|
|
2043
|
+
args: [input.status, input.result, now, taskId]
|
|
2044
|
+
});
|
|
2045
|
+
} else {
|
|
2046
|
+
await client.execute({
|
|
2047
|
+
sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
|
|
2048
|
+
args: [input.status, now, taskId]
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
try {
|
|
2052
|
+
await writeCheckpoint({
|
|
2053
|
+
taskId,
|
|
2054
|
+
step: `status_transition:${input.status}`,
|
|
2055
|
+
contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
|
|
2056
|
+
});
|
|
2057
|
+
} catch {
|
|
2058
|
+
}
|
|
2059
|
+
return { row, taskFile, now, taskId };
|
|
2060
|
+
}
|
|
2061
|
+
async function deleteTaskCore(taskId, _baseDir) {
|
|
2062
|
+
const client = getClient();
|
|
2063
|
+
const row = await resolveTask(client, taskId);
|
|
2064
|
+
const id = String(row.id);
|
|
2065
|
+
const taskFile = String(row.task_file);
|
|
2066
|
+
const assignedTo = String(row.assigned_to);
|
|
2067
|
+
const assignedBy = String(row.assigned_by);
|
|
2068
|
+
await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
|
|
2069
|
+
const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
|
|
2070
|
+
return { taskFile, assignedTo, assignedBy, taskSlug };
|
|
2071
|
+
}
|
|
2072
|
+
async function ensureArchitectureDoc(baseDir, projectName) {
|
|
2073
|
+
const archPath = path8.join(baseDir, "exe", "ARCHITECTURE.md");
|
|
2074
|
+
try {
|
|
2075
|
+
if (existsSync8(archPath)) return;
|
|
2076
|
+
const template = [
|
|
2077
|
+
`# ${projectName} \u2014 System Architecture`,
|
|
2078
|
+
"",
|
|
2079
|
+
"> Employees: read this before every task. Update it when you change system structure.",
|
|
2080
|
+
`> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
|
|
2081
|
+
"",
|
|
2082
|
+
"## Overview",
|
|
2083
|
+
"",
|
|
2084
|
+
"<!-- Describe what this system does, its main components, and how they connect. -->",
|
|
2085
|
+
"",
|
|
2086
|
+
"## Key Components",
|
|
2087
|
+
"",
|
|
2088
|
+
"<!-- List the major modules, services, or subsystems. -->",
|
|
2089
|
+
"",
|
|
2090
|
+
"## Data Flow",
|
|
2091
|
+
"",
|
|
2092
|
+
"<!-- How does data move through the system? What writes where? -->",
|
|
2093
|
+
"",
|
|
2094
|
+
"## Invariants",
|
|
2095
|
+
"",
|
|
2096
|
+
"<!-- Rules that must never be violated. What breaks if these are wrong? -->",
|
|
2097
|
+
"",
|
|
2098
|
+
"## Dependencies",
|
|
2099
|
+
"",
|
|
2100
|
+
"<!-- What depends on what? If I change X, what else is affected? -->",
|
|
2101
|
+
""
|
|
2102
|
+
].join("\n");
|
|
2103
|
+
await writeFile3(archPath, template, "utf-8");
|
|
2104
|
+
} catch {
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
async function ensureGitignoreExe(baseDir) {
|
|
2108
|
+
const gitignorePath = path8.join(baseDir, ".gitignore");
|
|
2109
|
+
try {
|
|
2110
|
+
if (existsSync8(gitignorePath)) {
|
|
2111
|
+
const content = readFileSync8(gitignorePath, "utf-8");
|
|
2112
|
+
if (/^\/?exe\/?$/m.test(content)) return;
|
|
2113
|
+
await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
|
|
2114
|
+
} else {
|
|
2115
|
+
await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
|
|
2116
|
+
}
|
|
2117
|
+
} catch {
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
|
|
2121
|
+
var init_tasks_crud = __esm({
|
|
2122
|
+
"src/lib/tasks-crud.ts"() {
|
|
2123
|
+
"use strict";
|
|
2124
|
+
init_database();
|
|
2125
|
+
init_task_scope();
|
|
2126
|
+
DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
|
|
2127
|
+
TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
|
|
2128
|
+
}
|
|
2129
|
+
});
|
|
2130
|
+
|
|
2131
|
+
// src/lib/tasks-review.ts
|
|
2132
|
+
import path9 from "path";
|
|
2133
|
+
import { existsSync as existsSync9, readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
|
|
2134
|
+
async function countPendingReviews(sessionScope) {
|
|
2135
|
+
const client = getClient();
|
|
2136
|
+
if (sessionScope) {
|
|
2137
|
+
const result3 = await client.execute({
|
|
2138
|
+
sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review' AND (session_scope = ? OR session_scope IS NULL)",
|
|
2139
|
+
args: [sessionScope]
|
|
2140
|
+
});
|
|
2141
|
+
return Number(result3.rows[0]?.cnt) || 0;
|
|
2142
|
+
}
|
|
2143
|
+
const result2 = await client.execute({
|
|
2144
|
+
sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
|
|
2145
|
+
args: []
|
|
2146
|
+
});
|
|
2147
|
+
return Number(result2.rows[0]?.cnt) || 0;
|
|
2148
|
+
}
|
|
2149
|
+
async function countNewPendingReviewsSince(sinceIso, sessionScope) {
|
|
2150
|
+
const client = getClient();
|
|
2151
|
+
if (sessionScope) {
|
|
2152
|
+
const result3 = await client.execute({
|
|
2153
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
2154
|
+
WHERE status = 'needs_review' AND updated_at > ?
|
|
2155
|
+
AND (session_scope = ? OR session_scope IS NULL)`,
|
|
2156
|
+
args: [sinceIso, sessionScope]
|
|
2157
|
+
});
|
|
2158
|
+
return Number(result3.rows[0]?.cnt) || 0;
|
|
2159
|
+
}
|
|
2160
|
+
const result2 = await client.execute({
|
|
2161
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
2162
|
+
WHERE status = 'needs_review' AND updated_at > ?`,
|
|
2163
|
+
args: [sinceIso]
|
|
2164
|
+
});
|
|
2165
|
+
return Number(result2.rows[0]?.cnt) || 0;
|
|
2166
|
+
}
|
|
2167
|
+
async function listPendingReviews(limit, sessionScope) {
|
|
2168
|
+
const client = getClient();
|
|
2169
|
+
if (sessionScope) {
|
|
2170
|
+
const result3 = await client.execute({
|
|
2171
|
+
sql: `SELECT title, assigned_to, project_name FROM tasks
|
|
2172
|
+
WHERE status = 'needs_review'
|
|
2173
|
+
AND (session_scope = ? OR session_scope IS NULL)
|
|
2174
|
+
ORDER BY priority ASC, created_at DESC LIMIT ?`,
|
|
2175
|
+
args: [sessionScope, limit]
|
|
2176
|
+
});
|
|
2177
|
+
return result3.rows;
|
|
2178
|
+
}
|
|
2179
|
+
const result2 = await client.execute({
|
|
2180
|
+
sql: `SELECT title, assigned_to, project_name FROM tasks
|
|
2181
|
+
WHERE status = 'needs_review'
|
|
2182
|
+
ORDER BY priority ASC, created_at DESC LIMIT ?`,
|
|
2183
|
+
args: [limit]
|
|
2184
|
+
});
|
|
2185
|
+
return result2.rows;
|
|
2186
|
+
}
|
|
2187
|
+
async function cleanupOrphanedReviews() {
|
|
2188
|
+
const client = getClient();
|
|
2189
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2190
|
+
const r1 = await client.execute({
|
|
2191
|
+
sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
|
|
2192
|
+
WHERE status IN ('open', 'needs_review', 'in_progress')
|
|
2193
|
+
AND assigned_by = 'system'
|
|
2194
|
+
AND title LIKE 'Review:%'
|
|
2195
|
+
AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
|
|
2196
|
+
args: [now]
|
|
2197
|
+
});
|
|
2198
|
+
const r1b = await client.execute({
|
|
2199
|
+
sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
|
|
2200
|
+
WHERE status IN ('open', 'needs_review')
|
|
2201
|
+
AND title LIKE 'Review:%completed%'
|
|
2202
|
+
AND (parent_task_id IS NULL OR parent_task_id NOT IN (SELECT id FROM tasks WHERE status IN ('open', 'in_progress', 'needs_review', 'blocked')))`,
|
|
2203
|
+
args: [now]
|
|
2204
|
+
});
|
|
2205
|
+
const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
|
|
2206
|
+
const r2 = await client.execute({
|
|
2207
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
2208
|
+
WHERE status = 'needs_review'
|
|
2209
|
+
AND result IS NOT NULL
|
|
2210
|
+
AND updated_at < ?`,
|
|
2211
|
+
args: [now, staleThreshold]
|
|
2212
|
+
});
|
|
2213
|
+
const total = r1.rowsAffected + (r1b?.rowsAffected ?? 0) + r2.rowsAffected;
|
|
2214
|
+
if (total > 0) {
|
|
2215
|
+
process.stderr.write(
|
|
2216
|
+
`[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r1b?.rowsAffected ?? 0} orphan + ${r2.rowsAffected} stale
|
|
2217
|
+
`
|
|
2218
|
+
);
|
|
2219
|
+
}
|
|
2220
|
+
return total;
|
|
2221
|
+
}
|
|
2222
|
+
function getReviewChecklist(role, agent, taskSlug) {
|
|
2223
|
+
const roleLower = role.toLowerCase();
|
|
2224
|
+
if (roleLower.includes("engineer") || roleLower === "principal engineer") {
|
|
2225
|
+
return {
|
|
2226
|
+
lens: "Code Quality (Engineer)",
|
|
2227
|
+
checklist: [
|
|
2228
|
+
"1. Do all tests pass? Any new tests needed?",
|
|
2229
|
+
"2. Is the code clean \u2014 no dead code, no TODOs left?",
|
|
2230
|
+
"3. Does it follow existing patterns and conventions in the codebase?",
|
|
2231
|
+
"4. Any regressions in the test suite?"
|
|
2232
|
+
]
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
if (roleLower === "cto" || roleLower.includes("architect")) {
|
|
2236
|
+
return {
|
|
2237
|
+
lens: "Architecture (CTO)",
|
|
2238
|
+
checklist: [
|
|
2239
|
+
"1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
|
|
2240
|
+
"2. Is it backward compatible? Any breaking changes?",
|
|
2241
|
+
"3. Does it introduce technical debt? Is that debt justified?",
|
|
2242
|
+
"4. Security implications? Any new attack surface?",
|
|
2243
|
+
"5. Does it scale? Performance considerations?",
|
|
2244
|
+
"6. Coordination: does this affect other employees' work or other projects?"
|
|
2245
|
+
]
|
|
2246
|
+
};
|
|
2247
|
+
}
|
|
2248
|
+
if (roleLower === "coo" || roleLower.includes("operations")) {
|
|
2249
|
+
return {
|
|
2250
|
+
lens: "Strategic (COO)",
|
|
2251
|
+
checklist: [
|
|
2252
|
+
"1. Does this serve the project mission?",
|
|
2253
|
+
"2. Is this the right work at the right time?",
|
|
2254
|
+
"3. Does the architectural assessment make sense for the business?",
|
|
2255
|
+
"4. Any cross-project implications?"
|
|
2256
|
+
]
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
return {
|
|
2260
|
+
lens: "General",
|
|
2261
|
+
checklist: [
|
|
2262
|
+
"1. Read the original task's acceptance criteria",
|
|
2263
|
+
`2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
|
|
2264
|
+
"3. Verify code changes match requirements",
|
|
2265
|
+
"4. Check if tests were added/updated",
|
|
2266
|
+
`5. Look for output files in exe/output/${agent}-${taskSlug}*`
|
|
2267
|
+
]
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
async function cleanupReviewFile(row, taskFile, _baseDir) {
|
|
2271
|
+
if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
|
|
2272
|
+
try {
|
|
2273
|
+
const client = getClient();
|
|
2274
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2275
|
+
const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
|
|
2276
|
+
if (parentId) {
|
|
2277
|
+
const result2 = await client.execute({
|
|
2278
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
|
|
2279
|
+
args: [now, parentId]
|
|
2280
|
+
});
|
|
2281
|
+
if (result2.rowsAffected > 0) {
|
|
2282
|
+
process.stderr.write(
|
|
2283
|
+
`[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
|
|
2284
|
+
`
|
|
2285
|
+
);
|
|
2286
|
+
}
|
|
2287
|
+
} else {
|
|
2288
|
+
const fileName = taskFile.split("/").pop() ?? "";
|
|
2289
|
+
const reviewPrefix = fileName.replace(".md", "");
|
|
2290
|
+
const parts = reviewPrefix.split("-");
|
|
2291
|
+
if (parts.length >= 3 && parts[0] === "review") {
|
|
2292
|
+
const agent = parts[1];
|
|
2293
|
+
const slug = parts.slice(2).join("-");
|
|
2294
|
+
const originalTaskFile = `exe/${agent}/${slug}.md`;
|
|
2295
|
+
const result2 = await client.execute({
|
|
2296
|
+
sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
|
|
2297
|
+
args: [now, originalTaskFile]
|
|
2298
|
+
});
|
|
2299
|
+
if (result2.rowsAffected > 0) {
|
|
2300
|
+
process.stderr.write(
|
|
2301
|
+
`[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
|
|
2302
|
+
`
|
|
2303
|
+
);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
} catch (err) {
|
|
2308
|
+
process.stderr.write(
|
|
2309
|
+
`[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
|
|
2310
|
+
`
|
|
2311
|
+
);
|
|
2312
|
+
}
|
|
2313
|
+
try {
|
|
2314
|
+
const cacheDir = path9.join(EXE_AI_DIR, "session-cache");
|
|
2315
|
+
if (existsSync9(cacheDir)) {
|
|
2316
|
+
for (const f of readdirSync2(cacheDir)) {
|
|
2317
|
+
if (f.startsWith("review-notified-")) {
|
|
2318
|
+
unlinkSync2(path9.join(cacheDir, f));
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
} catch {
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
var init_tasks_review = __esm({
|
|
2326
|
+
"src/lib/tasks-review.ts"() {
|
|
2327
|
+
"use strict";
|
|
2328
|
+
init_database();
|
|
2329
|
+
init_config();
|
|
2330
|
+
init_employees();
|
|
2331
|
+
init_notifications();
|
|
2332
|
+
init_tmux_routing();
|
|
2333
|
+
init_session_key();
|
|
2334
|
+
init_state_bus();
|
|
2335
|
+
}
|
|
2336
|
+
});
|
|
2337
|
+
|
|
2338
|
+
// src/lib/tasks-chain.ts
|
|
2339
|
+
import path10 from "path";
|
|
2340
|
+
import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
|
|
2341
|
+
async function cascadeUnblock(taskId, baseDir, now) {
|
|
2342
|
+
const client = getClient();
|
|
2343
|
+
const unblocked = await client.execute({
|
|
2344
|
+
sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
|
|
2345
|
+
WHERE blocked_by = ? AND status = 'blocked'`,
|
|
2346
|
+
args: [now, taskId]
|
|
2347
|
+
});
|
|
2348
|
+
if (baseDir && unblocked.rowsAffected > 0) {
|
|
2349
|
+
const ubScope = sessionScopeFilter();
|
|
2350
|
+
const unblockedRows = await client.execute({
|
|
2351
|
+
sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?${ubScope.sql}`,
|
|
2352
|
+
args: [now, ...ubScope.args]
|
|
2353
|
+
});
|
|
2354
|
+
for (const ur of unblockedRows.rows) {
|
|
2355
|
+
try {
|
|
2356
|
+
const ubFile = path10.join(baseDir, String(ur.task_file));
|
|
2357
|
+
let ubContent = await readFile3(ubFile, "utf-8");
|
|
2358
|
+
ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
|
|
2359
|
+
ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
|
|
2360
|
+
await writeFile4(ubFile, ubContent, "utf-8");
|
|
2361
|
+
} catch {
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
async function findNextTask(assignedTo) {
|
|
2367
|
+
const client = getClient();
|
|
2368
|
+
const ntScope = sessionScopeFilter();
|
|
2369
|
+
const nextResult = await client.execute({
|
|
2370
|
+
sql: `SELECT title, task_file, priority FROM tasks
|
|
2371
|
+
WHERE assigned_to = ? AND status = 'open'${ntScope.sql}
|
|
2372
|
+
ORDER BY priority ASC, created_at ASC
|
|
2373
|
+
LIMIT 1`,
|
|
2374
|
+
args: [assignedTo, ...ntScope.args]
|
|
2375
|
+
});
|
|
2376
|
+
if (nextResult.rows.length === 1) {
|
|
2377
|
+
const nr = nextResult.rows[0];
|
|
2378
|
+
return {
|
|
2379
|
+
title: String(nr.title),
|
|
2380
|
+
priority: String(nr.priority),
|
|
2381
|
+
taskFile: String(nr.task_file)
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
return void 0;
|
|
2385
|
+
}
|
|
2386
|
+
async function checkSubtaskCompletion(parentTaskId, projectName) {
|
|
2387
|
+
const client = getClient();
|
|
2388
|
+
const scScope = sessionScopeFilter();
|
|
2389
|
+
const remaining = await client.execute({
|
|
2390
|
+
sql: `SELECT COUNT(*) as cnt FROM tasks
|
|
2391
|
+
WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')${scScope.sql}`,
|
|
2392
|
+
args: [parentTaskId, ...scScope.args]
|
|
2393
|
+
});
|
|
2394
|
+
const cnt = Number(remaining.rows[0]?.cnt ?? 1);
|
|
2395
|
+
if (cnt === 0) {
|
|
2396
|
+
const parentRow = await client.execute({
|
|
2397
|
+
sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
|
|
2398
|
+
args: [parentTaskId]
|
|
2399
|
+
});
|
|
2400
|
+
if (parentRow.rows.length === 1) {
|
|
2401
|
+
const pr = parentRow.rows[0];
|
|
2402
|
+
const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
|
|
2403
|
+
await writeNotification({
|
|
2404
|
+
agentId: String(pr.assigned_to),
|
|
2405
|
+
agentRole: "system",
|
|
2406
|
+
event: "subtasks_complete",
|
|
2407
|
+
project: parentProject,
|
|
2408
|
+
summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
|
|
2409
|
+
taskFile: String(pr.task_file)
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
var init_tasks_chain = __esm({
|
|
2415
|
+
"src/lib/tasks-chain.ts"() {
|
|
2416
|
+
"use strict";
|
|
2417
|
+
init_database();
|
|
2418
|
+
init_notifications();
|
|
2419
|
+
init_task_scope();
|
|
2420
|
+
}
|
|
2421
|
+
});
|
|
2422
|
+
|
|
2423
|
+
// src/lib/project-name.ts
|
|
2424
|
+
import { execSync as execSync5 } from "child_process";
|
|
2425
|
+
import path11 from "path";
|
|
2426
|
+
function getProjectName(cwd) {
|
|
2427
|
+
const dir = cwd ?? process.cwd();
|
|
2428
|
+
if (_cached2 && _cachedCwd === dir) return _cached2;
|
|
2429
|
+
try {
|
|
2430
|
+
let repoRoot;
|
|
2431
|
+
try {
|
|
2432
|
+
const gitCommonDir = execSync5("git rev-parse --path-format=absolute --git-common-dir", {
|
|
2433
|
+
cwd: dir,
|
|
2434
|
+
encoding: "utf8",
|
|
2435
|
+
timeout: 2e3,
|
|
2436
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2437
|
+
}).trim();
|
|
2438
|
+
repoRoot = path11.dirname(gitCommonDir);
|
|
2439
|
+
} catch {
|
|
2440
|
+
repoRoot = execSync5("git rev-parse --show-toplevel", {
|
|
2441
|
+
cwd: dir,
|
|
2442
|
+
encoding: "utf8",
|
|
2443
|
+
timeout: 2e3,
|
|
2444
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
2445
|
+
}).trim();
|
|
2446
|
+
}
|
|
2447
|
+
_cached2 = path11.basename(repoRoot);
|
|
2448
|
+
_cachedCwd = dir;
|
|
2449
|
+
return _cached2;
|
|
2450
|
+
} catch {
|
|
2451
|
+
_cached2 = path11.basename(dir);
|
|
2452
|
+
_cachedCwd = dir;
|
|
2453
|
+
return _cached2;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
var _cached2, _cachedCwd;
|
|
2457
|
+
var init_project_name = __esm({
|
|
2458
|
+
"src/lib/project-name.ts"() {
|
|
2459
|
+
"use strict";
|
|
2460
|
+
_cached2 = null;
|
|
2461
|
+
_cachedCwd = null;
|
|
2462
|
+
}
|
|
2463
|
+
});
|
|
2464
|
+
|
|
2465
|
+
// src/lib/session-scope.ts
|
|
2466
|
+
var session_scope_exports = {};
|
|
2467
|
+
__export(session_scope_exports, {
|
|
2468
|
+
assertSessionScope: () => assertSessionScope,
|
|
2469
|
+
findSessionForProject: () => findSessionForProject,
|
|
2470
|
+
getSessionProject: () => getSessionProject
|
|
2471
|
+
});
|
|
2472
|
+
function getSessionProject(sessionName) {
|
|
2473
|
+
const sessions = listSessions();
|
|
2474
|
+
const entry = sessions.find((s) => s.windowName === sessionName);
|
|
2475
|
+
if (!entry) return null;
|
|
2476
|
+
const parts = entry.projectDir.split("/").filter(Boolean);
|
|
2477
|
+
return parts[parts.length - 1] ?? null;
|
|
2478
|
+
}
|
|
2479
|
+
function findSessionForProject(projectName) {
|
|
2480
|
+
const sessions = listSessions();
|
|
2481
|
+
for (const s of sessions) {
|
|
2482
|
+
const proj = s.projectDir.split("/").filter(Boolean).pop();
|
|
2483
|
+
if (proj === projectName && s.agentId === "exe") return s;
|
|
2484
|
+
}
|
|
2485
|
+
return null;
|
|
2486
|
+
}
|
|
2487
|
+
function assertSessionScope(actionType, targetProject) {
|
|
2488
|
+
try {
|
|
2489
|
+
const currentProject = getProjectName();
|
|
2490
|
+
const exeSession2 = resolveExeSession();
|
|
2491
|
+
if (!exeSession2) {
|
|
2492
|
+
return { allowed: true, reason: "no_session" };
|
|
2493
|
+
}
|
|
2494
|
+
if (currentProject === targetProject) {
|
|
2495
|
+
return {
|
|
2496
|
+
allowed: true,
|
|
2497
|
+
reason: "same_session",
|
|
2498
|
+
currentProject,
|
|
2499
|
+
targetProject
|
|
2500
|
+
};
|
|
2501
|
+
}
|
|
2502
|
+
process.stderr.write(
|
|
2503
|
+
`[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
|
|
2504
|
+
`
|
|
2505
|
+
);
|
|
2506
|
+
return {
|
|
2507
|
+
allowed: false,
|
|
2508
|
+
reason: "cross_session_denied",
|
|
2509
|
+
currentProject,
|
|
2510
|
+
targetProject,
|
|
2511
|
+
targetSession: findSessionForProject(targetProject)?.windowName
|
|
2512
|
+
};
|
|
2513
|
+
} catch {
|
|
2514
|
+
return { allowed: true, reason: "no_session" };
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
var init_session_scope = __esm({
|
|
2518
|
+
"src/lib/session-scope.ts"() {
|
|
2519
|
+
"use strict";
|
|
2520
|
+
init_session_registry();
|
|
2521
|
+
init_project_name();
|
|
2522
|
+
init_tmux_routing();
|
|
2523
|
+
}
|
|
2524
|
+
});
|
|
2525
|
+
|
|
2526
|
+
// src/lib/tasks-notify.ts
|
|
2527
|
+
async function dispatchTaskToEmployee(input) {
|
|
2528
|
+
if (input.assignedTo === "exe") return { dispatched: "skipped" };
|
|
2529
|
+
let crossProject = false;
|
|
2530
|
+
if (input.projectName) {
|
|
2531
|
+
try {
|
|
2532
|
+
const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
|
|
2533
|
+
const check = assertSessionScope2("dispatch_task", input.projectName);
|
|
2534
|
+
if (check.reason === "cross_session_denied") {
|
|
2535
|
+
crossProject = true;
|
|
2536
|
+
return { dispatched: "skipped", crossProject: true };
|
|
2537
|
+
}
|
|
2538
|
+
} catch {
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
try {
|
|
2542
|
+
const transport = getTransport();
|
|
2543
|
+
const exeSession2 = resolveExeSession();
|
|
2544
|
+
if (!exeSession2) return { dispatched: "session_missing" };
|
|
2545
|
+
const sessionName = employeeSessionName(input.assignedTo, exeSession2);
|
|
2546
|
+
if (transport.isAlive(sessionName)) {
|
|
2547
|
+
const result2 = sendIntercom(sessionName);
|
|
2548
|
+
const dispatched = result2 === "acknowledged" || result2 === "debounced" || result2 === "queued" ? "verified" : result2 === "delivered" ? "sent_unverified" : "session_dead";
|
|
2549
|
+
return { dispatched, session: sessionName, crossProject };
|
|
2550
|
+
} else {
|
|
2551
|
+
const projectDir2 = input.projectDir ?? process.cwd();
|
|
2552
|
+
const result2 = ensureEmployee(input.assignedTo, exeSession2, projectDir2, {
|
|
2553
|
+
autoInstance: isMultiInstance(input.assignedTo)
|
|
2554
|
+
});
|
|
2555
|
+
if (result2.status === "failed") {
|
|
2556
|
+
process.stderr.write(
|
|
2557
|
+
`[dispatch] Failed to spawn ${input.assignedTo}: ${result2.error}
|
|
2558
|
+
`
|
|
2559
|
+
);
|
|
2560
|
+
return { dispatched: "session_missing" };
|
|
2561
|
+
}
|
|
2562
|
+
return { dispatched: "spawned", session: result2.sessionName, crossProject };
|
|
2563
|
+
}
|
|
2564
|
+
} catch {
|
|
2565
|
+
return { dispatched: "session_missing" };
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
function notifyTaskDone() {
|
|
2569
|
+
try {
|
|
2570
|
+
const key = getSessionKey();
|
|
2571
|
+
if (key && !process.env.VITEST) notifyParentExe(key);
|
|
2572
|
+
} catch {
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
async function markTaskNotificationsRead(taskFile) {
|
|
2576
|
+
try {
|
|
2577
|
+
await markAsReadByTaskFile(taskFile);
|
|
2578
|
+
} catch {
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
var init_tasks_notify = __esm({
|
|
2582
|
+
"src/lib/tasks-notify.ts"() {
|
|
2583
|
+
"use strict";
|
|
2584
|
+
init_tmux_routing();
|
|
2585
|
+
init_session_key();
|
|
2586
|
+
init_notifications();
|
|
2587
|
+
init_transport();
|
|
2588
|
+
init_employees();
|
|
2589
|
+
}
|
|
2590
|
+
});
|
|
2591
|
+
|
|
2592
|
+
// src/lib/behaviors.ts
|
|
2593
|
+
import crypto4 from "crypto";
|
|
2594
|
+
async function storeBehavior(opts) {
|
|
2595
|
+
const client = getClient();
|
|
2596
|
+
const id = crypto4.randomUUID();
|
|
2597
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2598
|
+
await client.execute({
|
|
2599
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
|
|
2600
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
2601
|
+
args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
|
|
2602
|
+
});
|
|
2603
|
+
return id;
|
|
2604
|
+
}
|
|
2605
|
+
var init_behaviors = __esm({
|
|
2606
|
+
"src/lib/behaviors.ts"() {
|
|
2607
|
+
"use strict";
|
|
2608
|
+
init_database();
|
|
2609
|
+
}
|
|
2610
|
+
});
|
|
2611
|
+
|
|
2612
|
+
// src/lib/skill-learning.ts
|
|
2613
|
+
var skill_learning_exports = {};
|
|
2614
|
+
__export(skill_learning_exports, {
|
|
2615
|
+
captureAndLearn: () => captureAndLearn,
|
|
2616
|
+
captureTrajectory: () => captureTrajectory,
|
|
2617
|
+
editDistance: () => editDistance,
|
|
2618
|
+
extractSkill: () => extractSkill,
|
|
2619
|
+
extractTrajectory: () => extractTrajectory,
|
|
2620
|
+
findSimilarTrajectories: () => findSimilarTrajectories,
|
|
2621
|
+
hashSignature: () => hashSignature,
|
|
2622
|
+
storeTrajectory: () => storeTrajectory,
|
|
2623
|
+
sweepTrajectories: () => sweepTrajectories
|
|
2624
|
+
});
|
|
2625
|
+
import crypto5 from "crypto";
|
|
2626
|
+
async function extractTrajectory(taskId, agentId) {
|
|
2627
|
+
const client = getClient();
|
|
2628
|
+
const result2 = await client.execute({
|
|
2629
|
+
sql: `SELECT tool_name, raw_text
|
|
2630
|
+
FROM memories
|
|
2631
|
+
WHERE task_id = ? AND agent_id = ?
|
|
2632
|
+
ORDER BY timestamp ASC`,
|
|
2633
|
+
args: [taskId, agentId]
|
|
2634
|
+
});
|
|
2635
|
+
if (result2.rows.length === 0) return [];
|
|
2636
|
+
const rawTools = result2.rows.map((r) => {
|
|
2637
|
+
const toolName = String(r.tool_name);
|
|
2638
|
+
if (toolName === "Bash") {
|
|
2639
|
+
const text = String(r.raw_text);
|
|
2640
|
+
const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
|
|
2641
|
+
return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
|
|
2642
|
+
}
|
|
2643
|
+
return toolName;
|
|
2644
|
+
});
|
|
2645
|
+
const signature = [];
|
|
2646
|
+
for (const tool of rawTools) {
|
|
2647
|
+
if (signature.length === 0 || signature[signature.length - 1] !== tool) {
|
|
2648
|
+
signature.push(tool);
|
|
2649
|
+
}
|
|
325
2650
|
}
|
|
326
|
-
|
|
2651
|
+
return signature;
|
|
2652
|
+
}
|
|
2653
|
+
function hashSignature(signature) {
|
|
2654
|
+
return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
|
|
2655
|
+
}
|
|
2656
|
+
async function storeTrajectory(opts) {
|
|
2657
|
+
const client = getClient();
|
|
2658
|
+
const id = crypto5.randomUUID();
|
|
2659
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2660
|
+
const signatureHash = hashSignature(opts.signature);
|
|
2661
|
+
await client.execute({
|
|
2662
|
+
sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
|
|
2663
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2664
|
+
args: [
|
|
2665
|
+
id,
|
|
2666
|
+
opts.taskId,
|
|
2667
|
+
opts.agentId,
|
|
2668
|
+
opts.projectName,
|
|
2669
|
+
opts.taskTitle,
|
|
2670
|
+
JSON.stringify(opts.signature),
|
|
2671
|
+
signatureHash,
|
|
2672
|
+
opts.signature.length,
|
|
2673
|
+
now
|
|
2674
|
+
]
|
|
2675
|
+
});
|
|
2676
|
+
return id;
|
|
2677
|
+
}
|
|
2678
|
+
async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
|
|
2679
|
+
const client = getClient();
|
|
2680
|
+
const hash = hashSignature(signature);
|
|
2681
|
+
const result2 = await client.execute({
|
|
2682
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
2683
|
+
FROM trajectories
|
|
2684
|
+
WHERE signature_hash = ?
|
|
2685
|
+
ORDER BY created_at DESC
|
|
2686
|
+
LIMIT 20`,
|
|
2687
|
+
args: [hash]
|
|
2688
|
+
});
|
|
2689
|
+
const mapRow = (r) => ({
|
|
2690
|
+
id: String(r.id),
|
|
2691
|
+
taskId: String(r.task_id),
|
|
2692
|
+
agentId: String(r.agent_id),
|
|
2693
|
+
projectName: String(r.project_name),
|
|
2694
|
+
taskTitle: String(r.task_title),
|
|
2695
|
+
signature: JSON.parse(String(r.signature)),
|
|
2696
|
+
signatureHash: String(r.signature_hash),
|
|
2697
|
+
toolCount: Number(r.tool_count),
|
|
2698
|
+
skillId: r.skill_id ? String(r.skill_id) : null,
|
|
2699
|
+
createdAt: String(r.created_at)
|
|
2700
|
+
});
|
|
2701
|
+
const matches = result2.rows.map(mapRow);
|
|
2702
|
+
if (matches.length >= threshold) return matches;
|
|
2703
|
+
const nearResult = await client.execute({
|
|
2704
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
|
|
2705
|
+
FROM trajectories
|
|
2706
|
+
WHERE tool_count BETWEEN ? AND ?
|
|
2707
|
+
AND signature_hash != ?
|
|
2708
|
+
ORDER BY created_at DESC
|
|
2709
|
+
LIMIT 50`,
|
|
2710
|
+
args: [
|
|
2711
|
+
Math.max(1, signature.length - 3),
|
|
2712
|
+
signature.length + 3,
|
|
2713
|
+
hash
|
|
2714
|
+
]
|
|
2715
|
+
});
|
|
2716
|
+
for (const r of nearResult.rows) {
|
|
2717
|
+
const candidateSig = JSON.parse(String(r.signature));
|
|
2718
|
+
if (editDistance(signature, candidateSig) <= 2) {
|
|
2719
|
+
matches.push(mapRow(r));
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
return matches;
|
|
2723
|
+
}
|
|
2724
|
+
async function captureTrajectory(opts) {
|
|
2725
|
+
const signature = await extractTrajectory(opts.taskId, opts.agentId);
|
|
2726
|
+
if (signature.length < 3) {
|
|
2727
|
+
return { trajectoryId: "", similarCount: 0, similar: [] };
|
|
2728
|
+
}
|
|
2729
|
+
const trajectoryId = await storeTrajectory({
|
|
2730
|
+
taskId: opts.taskId,
|
|
2731
|
+
agentId: opts.agentId,
|
|
2732
|
+
projectName: opts.projectName,
|
|
2733
|
+
taskTitle: opts.taskTitle,
|
|
2734
|
+
signature
|
|
2735
|
+
});
|
|
2736
|
+
const similar = await findSimilarTrajectories(
|
|
2737
|
+
signature,
|
|
2738
|
+
opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
|
|
2739
|
+
);
|
|
2740
|
+
return { trajectoryId, similarCount: similar.length, similar };
|
|
2741
|
+
}
|
|
2742
|
+
function buildExtractionPrompt(trajectories) {
|
|
2743
|
+
const items = trajectories.map((t, i) => {
|
|
2744
|
+
const sig = t.signature.join(" \u2192 ");
|
|
2745
|
+
return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
|
|
2746
|
+
Signature: ${sig}`;
|
|
2747
|
+
}).join("\n\n");
|
|
2748
|
+
return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
|
|
327
2749
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
2750
|
+
${items}
|
|
2751
|
+
|
|
2752
|
+
Extract the reusable procedure. Format your response EXACTLY like this:
|
|
2753
|
+
|
|
2754
|
+
SKILL: {name \u2014 short, descriptive}
|
|
2755
|
+
TRIGGER: {when to use this \u2014 one sentence}
|
|
2756
|
+
STEPS:
|
|
2757
|
+
1. ...
|
|
2758
|
+
2. ...
|
|
2759
|
+
PITFALLS: {common mistakes to avoid}
|
|
2760
|
+
|
|
2761
|
+
Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
|
|
2762
|
+
}
|
|
2763
|
+
async function extractSkill(trajectories, model) {
|
|
2764
|
+
if (trajectories.length === 0) return null;
|
|
2765
|
+
const config = await loadConfig();
|
|
2766
|
+
const skillModel = model ?? config.skillModel;
|
|
2767
|
+
const Anthropic = (await import("@anthropic-ai/sdk")).default;
|
|
2768
|
+
const client = new Anthropic();
|
|
2769
|
+
const prompt = buildExtractionPrompt(trajectories);
|
|
2770
|
+
const response = await client.messages.create({
|
|
2771
|
+
model: skillModel,
|
|
2772
|
+
max_tokens: 500,
|
|
2773
|
+
messages: [{ role: "user", content: prompt }]
|
|
2774
|
+
});
|
|
2775
|
+
const textBlock = response.content.find((b) => b.type === "text");
|
|
2776
|
+
const skillText = textBlock?.text;
|
|
2777
|
+
if (!skillText) return null;
|
|
2778
|
+
const agentId = trajectories[0].agentId;
|
|
2779
|
+
const projectName = trajectories[0].projectName;
|
|
2780
|
+
const skillId = await storeBehavior({
|
|
2781
|
+
agentId,
|
|
2782
|
+
content: skillText,
|
|
2783
|
+
domain: "skill",
|
|
2784
|
+
projectName
|
|
2785
|
+
});
|
|
2786
|
+
const dbClient = getClient();
|
|
2787
|
+
for (const t of trajectories) {
|
|
2788
|
+
await dbClient.execute({
|
|
2789
|
+
sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
|
|
2790
|
+
args: [skillId, t.id]
|
|
2791
|
+
});
|
|
2792
|
+
}
|
|
2793
|
+
process.stderr.write(
|
|
2794
|
+
`[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
|
|
2795
|
+
`
|
|
2796
|
+
);
|
|
2797
|
+
return skillId;
|
|
2798
|
+
}
|
|
2799
|
+
async function captureAndLearn(opts) {
|
|
2800
|
+
try {
|
|
2801
|
+
const config = await loadConfig();
|
|
2802
|
+
if (!config.skillLearning) return;
|
|
2803
|
+
const { trajectoryId, similarCount, similar } = await captureTrajectory({
|
|
2804
|
+
...opts,
|
|
2805
|
+
skillThreshold: config.skillThreshold
|
|
2806
|
+
});
|
|
2807
|
+
if (!trajectoryId) return;
|
|
2808
|
+
if (similarCount >= config.skillThreshold) {
|
|
2809
|
+
const unprocessed = similar.filter((t) => !t.skillId);
|
|
2810
|
+
if (unprocessed.length >= config.skillThreshold) {
|
|
2811
|
+
extractSkill(unprocessed, config.skillModel).catch((err) => {
|
|
2812
|
+
process.stderr.write(
|
|
2813
|
+
`[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
|
|
2814
|
+
`
|
|
2815
|
+
);
|
|
2816
|
+
});
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
} catch (err) {
|
|
2820
|
+
process.stderr.write(
|
|
2821
|
+
`[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
|
|
2822
|
+
`
|
|
2823
|
+
);
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
async function sweepTrajectories(threshold, model) {
|
|
2827
|
+
const config = await loadConfig();
|
|
2828
|
+
if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
|
|
2829
|
+
const t = threshold ?? config.skillThreshold;
|
|
2830
|
+
const client = getClient();
|
|
2831
|
+
const result2 = await client.execute({
|
|
2832
|
+
sql: `SELECT signature_hash, COUNT(*) as cnt
|
|
2833
|
+
FROM trajectories
|
|
2834
|
+
WHERE skill_id IS NULL
|
|
2835
|
+
GROUP BY signature_hash
|
|
2836
|
+
HAVING cnt >= ?
|
|
2837
|
+
ORDER BY cnt DESC
|
|
2838
|
+
LIMIT 10`,
|
|
2839
|
+
args: [t]
|
|
2840
|
+
});
|
|
2841
|
+
let clustersProcessed = 0;
|
|
2842
|
+
let skillsExtracted = 0;
|
|
2843
|
+
for (const row of result2.rows) {
|
|
2844
|
+
const hash = String(row.signature_hash);
|
|
2845
|
+
const trajResult = await client.execute({
|
|
2846
|
+
sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
|
|
2847
|
+
FROM trajectories
|
|
2848
|
+
WHERE signature_hash = ? AND skill_id IS NULL
|
|
2849
|
+
ORDER BY created_at DESC
|
|
2850
|
+
LIMIT 10`,
|
|
2851
|
+
args: [hash]
|
|
2852
|
+
});
|
|
2853
|
+
const trajectories = trajResult.rows.map((r) => ({
|
|
2854
|
+
id: String(r.id),
|
|
2855
|
+
taskId: String(r.task_id),
|
|
2856
|
+
agentId: String(r.agent_id),
|
|
2857
|
+
projectName: String(r.project_name),
|
|
2858
|
+
taskTitle: String(r.task_title),
|
|
2859
|
+
signature: JSON.parse(String(r.signature)),
|
|
2860
|
+
signatureHash: String(r.signature_hash),
|
|
2861
|
+
toolCount: Number(r.tool_count),
|
|
2862
|
+
skillId: null,
|
|
2863
|
+
createdAt: String(r.created_at)
|
|
2864
|
+
}));
|
|
2865
|
+
if (trajectories.length >= t) {
|
|
2866
|
+
clustersProcessed++;
|
|
2867
|
+
const skillId = await extractSkill(trajectories, model ?? config.skillModel);
|
|
2868
|
+
if (skillId) skillsExtracted++;
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
return { clustersProcessed, skillsExtracted };
|
|
2872
|
+
}
|
|
2873
|
+
function editDistance(a, b) {
|
|
2874
|
+
const m = a.length;
|
|
2875
|
+
const n = b.length;
|
|
2876
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
2877
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
2878
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
2879
|
+
for (let i = 1; i <= m; i++) {
|
|
2880
|
+
for (let j = 1; j <= n; j++) {
|
|
2881
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
2882
|
+
dp[i][j] = Math.min(
|
|
2883
|
+
dp[i - 1][j] + 1,
|
|
2884
|
+
dp[i][j - 1] + 1,
|
|
2885
|
+
dp[i - 1][j - 1] + cost
|
|
2886
|
+
);
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
return dp[m][n];
|
|
2890
|
+
}
|
|
2891
|
+
var DEFAULT_SKILL_THRESHOLD;
|
|
2892
|
+
var init_skill_learning = __esm({
|
|
2893
|
+
"src/lib/skill-learning.ts"() {
|
|
332
2894
|
"use strict";
|
|
333
|
-
|
|
2895
|
+
init_database();
|
|
2896
|
+
init_behaviors();
|
|
2897
|
+
init_config();
|
|
2898
|
+
DEFAULT_SKILL_THRESHOLD = 3;
|
|
334
2899
|
}
|
|
335
2900
|
});
|
|
336
2901
|
|
|
337
|
-
// src/lib/
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
2902
|
+
// src/lib/tasks.ts
|
|
2903
|
+
var tasks_exports = {};
|
|
2904
|
+
__export(tasks_exports, {
|
|
2905
|
+
cleanupOrphanedReviews: () => cleanupOrphanedReviews,
|
|
2906
|
+
countNewPendingReviewsSince: () => countNewPendingReviewsSince,
|
|
2907
|
+
countPendingReviews: () => countPendingReviews,
|
|
2908
|
+
createTask: () => createTask,
|
|
2909
|
+
createTaskCore: () => createTaskCore,
|
|
2910
|
+
deleteTask: () => deleteTask,
|
|
2911
|
+
deleteTaskCore: () => deleteTaskCore,
|
|
2912
|
+
ensureArchitectureDoc: () => ensureArchitectureDoc,
|
|
2913
|
+
ensureGitignoreExe: () => ensureGitignoreExe,
|
|
2914
|
+
getReviewChecklist: () => getReviewChecklist,
|
|
2915
|
+
listPendingReviews: () => listPendingReviews,
|
|
2916
|
+
listTasks: () => listTasks,
|
|
2917
|
+
resolveTask: () => resolveTask,
|
|
2918
|
+
slugify: () => slugify,
|
|
2919
|
+
updateTask: () => updateTask,
|
|
2920
|
+
updateTaskStatus: () => updateTaskStatus,
|
|
2921
|
+
writeCheckpoint: () => writeCheckpoint
|
|
2922
|
+
});
|
|
2923
|
+
import path12 from "path";
|
|
2924
|
+
import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, unlinkSync as unlinkSync3 } from "fs";
|
|
2925
|
+
async function createTask(input) {
|
|
2926
|
+
const result2 = await createTaskCore(input);
|
|
2927
|
+
if (!input.skipDispatch && result2.status !== "blocked" && !process.env.VITEST) {
|
|
2928
|
+
dispatchTaskToEmployee({
|
|
2929
|
+
assignedTo: input.assignedTo,
|
|
2930
|
+
title: input.title,
|
|
2931
|
+
priority: input.priority,
|
|
2932
|
+
taskFile: result2.taskFile,
|
|
2933
|
+
initialStatus: result2.status,
|
|
2934
|
+
projectName: input.projectName
|
|
2935
|
+
});
|
|
2936
|
+
}
|
|
2937
|
+
return result2;
|
|
2938
|
+
}
|
|
2939
|
+
async function updateTask(input) {
|
|
2940
|
+
const { row, taskFile, now, taskId } = await updateTaskStatus(input);
|
|
2941
|
+
try {
|
|
2942
|
+
const agent = String(row.assigned_to);
|
|
2943
|
+
const cacheDir = path12.join(EXE_AI_DIR, "session-cache");
|
|
2944
|
+
const cachePath = path12.join(cacheDir, `current-task-${agent}.json`);
|
|
2945
|
+
if (input.status === "in_progress") {
|
|
2946
|
+
mkdirSync4(cacheDir, { recursive: true });
|
|
2947
|
+
writeFileSync4(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
|
|
2948
|
+
} else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
|
|
2949
|
+
try {
|
|
2950
|
+
unlinkSync3(cachePath);
|
|
2951
|
+
} catch {
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
} catch {
|
|
2955
|
+
}
|
|
2956
|
+
if (input.status === "done") {
|
|
2957
|
+
await cleanupReviewFile(row, taskFile, input.baseDir);
|
|
2958
|
+
}
|
|
2959
|
+
if (input.status === "done" || input.status === "cancelled") {
|
|
348
2960
|
try {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
2961
|
+
const client = getClient();
|
|
2962
|
+
const taskTitle = String(row.title);
|
|
2963
|
+
const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
2964
|
+
await client.execute({
|
|
2965
|
+
sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
|
|
2966
|
+
WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
|
|
2967
|
+
args: [now, `%left '${escaped}' as in\\_progress%`]
|
|
2968
|
+
});
|
|
2969
|
+
} catch {
|
|
2970
|
+
}
|
|
2971
|
+
try {
|
|
2972
|
+
const client = getClient();
|
|
2973
|
+
const cascaded = await client.execute({
|
|
2974
|
+
sql: `UPDATE tasks SET status = 'done', updated_at = ?
|
|
2975
|
+
WHERE parent_task_id = ? AND status = 'needs_review'`,
|
|
2976
|
+
args: [now, taskId]
|
|
2977
|
+
});
|
|
2978
|
+
if (cascaded.rowsAffected > 0) {
|
|
2979
|
+
process.stderr.write(
|
|
2980
|
+
`[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
|
|
2981
|
+
`
|
|
2982
|
+
);
|
|
2983
|
+
}
|
|
352
2984
|
} catch {
|
|
353
|
-
return legacyDir;
|
|
354
2985
|
}
|
|
355
2986
|
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
fileGrepEnabled: true,
|
|
380
|
-
splashEffect: true,
|
|
381
|
-
consolidationEnabled: true,
|
|
382
|
-
consolidationIntervalMs: 6 * 60 * 60 * 1e3,
|
|
383
|
-
consolidationModel: "claude-haiku-4-5-20251001",
|
|
384
|
-
consolidationMaxCallsPerRun: 20,
|
|
385
|
-
selfQueryRouter: true,
|
|
386
|
-
selfQueryModel: "claude-haiku-4-5-20251001",
|
|
387
|
-
rerankerEnabled: true,
|
|
388
|
-
scalingRoadmap: {
|
|
389
|
-
rerankerAutoTrigger: {
|
|
390
|
-
enabled: true,
|
|
391
|
-
broadQueryMinCardinality: 5e4,
|
|
392
|
-
fetchTopK: 150,
|
|
393
|
-
returnTopK: 5
|
|
2987
|
+
const isTerminal = input.status === "done" || input.status === "needs_review";
|
|
2988
|
+
if (isTerminal) {
|
|
2989
|
+
const isExe = String(row.assigned_to) === "exe";
|
|
2990
|
+
if (!isExe) {
|
|
2991
|
+
notifyTaskDone();
|
|
2992
|
+
}
|
|
2993
|
+
await markTaskNotificationsRead(taskFile);
|
|
2994
|
+
if (input.status === "done") {
|
|
2995
|
+
try {
|
|
2996
|
+
await cascadeUnblock(taskId, input.baseDir, now);
|
|
2997
|
+
} catch {
|
|
2998
|
+
}
|
|
2999
|
+
orgBus.emit({
|
|
3000
|
+
type: "task_completed",
|
|
3001
|
+
taskId,
|
|
3002
|
+
employee: String(row.assigned_to),
|
|
3003
|
+
result: input.result ?? "",
|
|
3004
|
+
timestamp: now
|
|
3005
|
+
});
|
|
3006
|
+
if (row.parent_task_id) {
|
|
3007
|
+
try {
|
|
3008
|
+
await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
|
|
3009
|
+
} catch {
|
|
394
3010
|
}
|
|
395
|
-
},
|
|
396
|
-
graphRagEnabled: true,
|
|
397
|
-
wikiEnabled: false,
|
|
398
|
-
wikiUrl: "",
|
|
399
|
-
wikiApiKey: "",
|
|
400
|
-
wikiSyncIntervalMs: 30 * 60 * 1e3,
|
|
401
|
-
wikiWorkspaceMapping: {
|
|
402
|
-
exe: "Executive",
|
|
403
|
-
yoshi: "Engineering",
|
|
404
|
-
mari: "Marketing",
|
|
405
|
-
tom: "Engineering",
|
|
406
|
-
sasha: "Production"
|
|
407
|
-
},
|
|
408
|
-
wikiAutoUpdate: true,
|
|
409
|
-
wikiAutoUpdateThreshold: 0.5,
|
|
410
|
-
wikiAutoUpdateCreateNew: true,
|
|
411
|
-
skillLearning: true,
|
|
412
|
-
skillThreshold: 3,
|
|
413
|
-
skillModel: "claude-haiku-4-5-20251001",
|
|
414
|
-
exeHeartbeat: {
|
|
415
|
-
enabled: true,
|
|
416
|
-
intervalSeconds: 60,
|
|
417
|
-
staleInProgressThresholdHours: 2
|
|
418
|
-
},
|
|
419
|
-
sessionLifecycle: {
|
|
420
|
-
idleKillEnabled: true,
|
|
421
|
-
idleKillTicksRequired: 3,
|
|
422
|
-
idleKillIntercomAckWindowMs: 1e4,
|
|
423
|
-
maxAutoInstances: 10
|
|
424
|
-
},
|
|
425
|
-
autoUpdate: {
|
|
426
|
-
checkOnBoot: true,
|
|
427
|
-
autoInstall: false,
|
|
428
|
-
checkIntervalMs: 24 * 60 * 60 * 1e3
|
|
429
3011
|
}
|
|
430
|
-
}
|
|
3012
|
+
}
|
|
431
3013
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
3014
|
+
if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
|
|
3015
|
+
Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
|
|
3016
|
+
({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
|
|
3017
|
+
taskId,
|
|
3018
|
+
agentId: String(row.assigned_to),
|
|
3019
|
+
projectName: String(row.project_name),
|
|
3020
|
+
taskTitle: String(row.title)
|
|
3021
|
+
})
|
|
3022
|
+
).catch((err) => {
|
|
3023
|
+
process.stderr.write(
|
|
3024
|
+
`[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
|
|
3025
|
+
`
|
|
3026
|
+
);
|
|
3027
|
+
});
|
|
445
3028
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
3029
|
+
let nextTask;
|
|
3030
|
+
if (isTerminal && String(row.assigned_to) !== "exe") {
|
|
3031
|
+
try {
|
|
3032
|
+
nextTask = await findNextTask(String(row.assigned_to));
|
|
3033
|
+
} catch {
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
return {
|
|
3037
|
+
id: String(row.id),
|
|
3038
|
+
title: String(row.title),
|
|
3039
|
+
assignedTo: String(row.assigned_to),
|
|
3040
|
+
assignedBy: String(row.assigned_by),
|
|
3041
|
+
projectName: String(row.project_name),
|
|
3042
|
+
priority: String(row.priority),
|
|
3043
|
+
status: input.status,
|
|
3044
|
+
taskFile,
|
|
3045
|
+
createdAt: String(row.created_at),
|
|
3046
|
+
updatedAt: now,
|
|
3047
|
+
budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
|
|
3048
|
+
budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
|
|
3049
|
+
tokensUsed: Number(row.tokens_used ?? 0),
|
|
3050
|
+
tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
|
|
3051
|
+
nextTask
|
|
3052
|
+
};
|
|
3053
|
+
}
|
|
3054
|
+
async function deleteTask(taskId, baseDir) {
|
|
3055
|
+
const client = getClient();
|
|
3056
|
+
const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
|
|
3057
|
+
const reviewer = assignedBy || "exe";
|
|
3058
|
+
const reviewSlug = `review-${assignedTo}-${taskSlug}`;
|
|
3059
|
+
const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
|
|
3060
|
+
await client.execute({
|
|
3061
|
+
sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
|
|
3062
|
+
args: [reviewFile, `exe/exe/${reviewSlug}.md`]
|
|
3063
|
+
});
|
|
3064
|
+
await markAsReadByTaskFile(taskFile);
|
|
3065
|
+
await markAsReadByTaskFile(reviewFile);
|
|
3066
|
+
}
|
|
3067
|
+
var init_tasks = __esm({
|
|
3068
|
+
"src/lib/tasks.ts"() {
|
|
456
3069
|
"use strict";
|
|
3070
|
+
init_database();
|
|
457
3071
|
init_config();
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
enterprise: { devices: -1, employees: -1, memories: -1 }
|
|
467
|
-
};
|
|
3072
|
+
init_notifications();
|
|
3073
|
+
init_state_bus();
|
|
3074
|
+
init_tasks_crud();
|
|
3075
|
+
init_tasks_review();
|
|
3076
|
+
init_tasks_crud();
|
|
3077
|
+
init_tasks_chain();
|
|
3078
|
+
init_tasks_review();
|
|
3079
|
+
init_tasks_notify();
|
|
468
3080
|
}
|
|
469
3081
|
});
|
|
470
3082
|
|
|
471
|
-
// src/lib/
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
3083
|
+
// src/lib/capacity-monitor.ts
|
|
3084
|
+
var capacity_monitor_exports = {};
|
|
3085
|
+
__export(capacity_monitor_exports, {
|
|
3086
|
+
CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
|
|
3087
|
+
_resetLastRelaunchCache: () => _resetLastRelaunchCache,
|
|
3088
|
+
_resetPendingCapacityKills: () => _resetPendingCapacityKills,
|
|
3089
|
+
confirmCapacityKill: () => confirmCapacityKill,
|
|
3090
|
+
createOrRefreshResumeTask: () => createOrRefreshResumeTask,
|
|
3091
|
+
extractContextPercent: () => extractContextPercent,
|
|
3092
|
+
isAtCapacity: () => isAtCapacity,
|
|
3093
|
+
isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
|
|
3094
|
+
pollCapacityDead: () => pollCapacityDead
|
|
3095
|
+
});
|
|
3096
|
+
function resumeTaskTitle(agentId) {
|
|
3097
|
+
return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
|
|
3098
|
+
}
|
|
3099
|
+
function buildResumeContext(agentId, openTasks) {
|
|
3100
|
+
const taskList = openTasks.map(
|
|
3101
|
+
(r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
|
|
3102
|
+
).join("\n");
|
|
3103
|
+
return [
|
|
3104
|
+
"## Context",
|
|
3105
|
+
"",
|
|
3106
|
+
`${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
|
|
3107
|
+
"Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
|
|
3108
|
+
"",
|
|
3109
|
+
`You have ${openTasks.length} open task(s). Work through them in priority order:`,
|
|
3110
|
+
"",
|
|
3111
|
+
taskList,
|
|
3112
|
+
"",
|
|
3113
|
+
"Read each task file and chain through them. Build and commit after each one."
|
|
3114
|
+
].join("\n");
|
|
3115
|
+
}
|
|
3116
|
+
function filterPaneContent(paneOutput) {
|
|
3117
|
+
return paneOutput.split("\n").filter((line) => {
|
|
3118
|
+
if (CONTENT_LINE_PREFIX.test(line)) return false;
|
|
3119
|
+
for (const marker of CONTENT_LINE_MARKERS) {
|
|
3120
|
+
if (line.includes(marker)) return false;
|
|
3121
|
+
}
|
|
3122
|
+
for (const re of SOURCE_CODE_MARKERS) {
|
|
3123
|
+
if (re.test(line)) return false;
|
|
3124
|
+
}
|
|
3125
|
+
return true;
|
|
3126
|
+
}).join("\n");
|
|
3127
|
+
}
|
|
3128
|
+
function extractContextPercent(paneOutput) {
|
|
3129
|
+
const match = paneOutput.match(CC_CONTEXT_BAR_RE);
|
|
3130
|
+
if (!match) return null;
|
|
3131
|
+
const parsed = Number.parseInt(match[2], 10);
|
|
3132
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
3133
|
+
}
|
|
3134
|
+
function isAtCapacity(paneOutput) {
|
|
3135
|
+
const filtered = filterPaneContent(paneOutput);
|
|
3136
|
+
return CAPACITY_PATTERNS.some((p) => p.test(filtered));
|
|
3137
|
+
}
|
|
3138
|
+
function confirmCapacityKill(agentId, now = Date.now()) {
|
|
3139
|
+
const pendingSince = _pendingCapacityKill.get(agentId);
|
|
3140
|
+
if (pendingSince === void 0) {
|
|
3141
|
+
_pendingCapacityKill.set(agentId, now);
|
|
3142
|
+
return false;
|
|
495
3143
|
}
|
|
3144
|
+
if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
|
|
3145
|
+
_pendingCapacityKill.set(agentId, now);
|
|
3146
|
+
return false;
|
|
3147
|
+
}
|
|
3148
|
+
_pendingCapacityKill.delete(agentId);
|
|
3149
|
+
return true;
|
|
496
3150
|
}
|
|
497
|
-
function
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
3151
|
+
function _resetPendingCapacityKills() {
|
|
3152
|
+
_pendingCapacityKill.clear();
|
|
3153
|
+
}
|
|
3154
|
+
function _resetLastRelaunchCache() {
|
|
3155
|
+
_lastRelaunch.clear();
|
|
3156
|
+
}
|
|
3157
|
+
async function lastResumeCreatedAtMs(agentId) {
|
|
3158
|
+
const client = getClient();
|
|
3159
|
+
const cmScope = sessionScopeFilter();
|
|
3160
|
+
const result2 = await client.execute({
|
|
3161
|
+
sql: `SELECT MAX(created_at) AS last_created_at
|
|
3162
|
+
FROM tasks
|
|
3163
|
+
WHERE assigned_to = ? AND title LIKE ?${cmScope.sql}`,
|
|
3164
|
+
args: [agentId, `${RESUME_TITLE_PREFIX} %`, ...cmScope.args]
|
|
3165
|
+
});
|
|
3166
|
+
const raw = result2.rows[0]?.last_created_at;
|
|
3167
|
+
if (raw === null || raw === void 0) return null;
|
|
3168
|
+
const parsed = Date.parse(String(raw));
|
|
3169
|
+
return Number.isNaN(parsed) ? null : parsed;
|
|
508
3170
|
}
|
|
509
|
-
function
|
|
510
|
-
const
|
|
511
|
-
if (
|
|
512
|
-
const
|
|
513
|
-
|
|
3171
|
+
async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
|
|
3172
|
+
const cached = _lastRelaunch.get(agentId);
|
|
3173
|
+
if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
|
|
3174
|
+
const persisted = await lastResumeCreatedAtMs(agentId);
|
|
3175
|
+
if (persisted === null) return false;
|
|
3176
|
+
if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
|
|
3177
|
+
_lastRelaunch.set(agentId, persisted);
|
|
3178
|
+
return true;
|
|
3179
|
+
}
|
|
3180
|
+
async function createOrRefreshResumeTask(agentId, projectDir2, openTasks) {
|
|
3181
|
+
const client = getClient();
|
|
3182
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3183
|
+
const context = buildResumeContext(agentId, openTasks);
|
|
3184
|
+
const rdScope = sessionScopeFilter();
|
|
3185
|
+
const existing = await client.execute({
|
|
3186
|
+
sql: `SELECT id FROM tasks
|
|
3187
|
+
WHERE assigned_to = ?
|
|
3188
|
+
AND title LIKE ?
|
|
3189
|
+
AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})${rdScope.sql}
|
|
3190
|
+
ORDER BY created_at DESC
|
|
3191
|
+
LIMIT 1`,
|
|
3192
|
+
args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES, ...rdScope.args]
|
|
3193
|
+
});
|
|
3194
|
+
if (existing.rows.length > 0) {
|
|
3195
|
+
const taskId = String(existing.rows[0].id);
|
|
3196
|
+
await client.execute({
|
|
3197
|
+
sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
|
|
3198
|
+
args: [context, now, taskId]
|
|
3199
|
+
});
|
|
3200
|
+
return { created: false, taskId };
|
|
3201
|
+
}
|
|
3202
|
+
const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
|
|
3203
|
+
const task = await createTask2({
|
|
3204
|
+
title: resumeTaskTitle(agentId),
|
|
3205
|
+
assignedTo: agentId,
|
|
3206
|
+
assignedBy: "system",
|
|
3207
|
+
projectName: projectDir2.split("/").pop() ?? "unknown",
|
|
3208
|
+
priority: "p0",
|
|
3209
|
+
context,
|
|
3210
|
+
baseDir: projectDir2
|
|
3211
|
+
});
|
|
3212
|
+
return { created: true, taskId: task.id };
|
|
3213
|
+
}
|
|
3214
|
+
async function pollCapacityDead() {
|
|
3215
|
+
const transport = getTransport();
|
|
3216
|
+
const relaunched = [];
|
|
3217
|
+
const registered = listSessions().filter(
|
|
3218
|
+
(s) => s.agentId !== "exe"
|
|
3219
|
+
);
|
|
3220
|
+
if (registered.length === 0) return [];
|
|
3221
|
+
let liveSessions;
|
|
514
3222
|
try {
|
|
515
|
-
|
|
516
|
-
const raw = readFileSync6(filePath, "utf8");
|
|
517
|
-
const employees = JSON.parse(raw);
|
|
518
|
-
count = Array.isArray(employees) ? employees.length : 0;
|
|
519
|
-
}
|
|
3223
|
+
liveSessions = transport.listSessions();
|
|
520
3224
|
} catch {
|
|
521
|
-
|
|
522
|
-
`Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
|
|
523
|
-
);
|
|
3225
|
+
return [];
|
|
524
3226
|
}
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
3227
|
+
for (const entry of registered) {
|
|
3228
|
+
const { windowName, agentId, projectDir: projectDir2 } = entry;
|
|
3229
|
+
if (!liveSessions.includes(windowName)) continue;
|
|
3230
|
+
if (await isWithinRelaunchCooldown(agentId)) continue;
|
|
3231
|
+
let pane;
|
|
3232
|
+
try {
|
|
3233
|
+
pane = transport.capturePane(windowName, 15);
|
|
3234
|
+
} catch {
|
|
3235
|
+
continue;
|
|
3236
|
+
}
|
|
3237
|
+
if (!isAtCapacity(pane)) continue;
|
|
3238
|
+
const ctxPct = extractContextPercent(pane);
|
|
3239
|
+
if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
|
|
3240
|
+
process.stderr.write(
|
|
3241
|
+
`[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
|
|
3242
|
+
`
|
|
3243
|
+
);
|
|
3244
|
+
continue;
|
|
3245
|
+
}
|
|
3246
|
+
if (!confirmCapacityKill(agentId)) {
|
|
3247
|
+
process.stderr.write(
|
|
3248
|
+
`[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
|
|
3249
|
+
`
|
|
3250
|
+
);
|
|
3251
|
+
continue;
|
|
3252
|
+
}
|
|
3253
|
+
const verify = await verifyPaneAtCapacity(windowName);
|
|
3254
|
+
if (!verify.atCapacity) {
|
|
3255
|
+
process.stderr.write(
|
|
3256
|
+
`[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
|
|
3257
|
+
`
|
|
3258
|
+
);
|
|
3259
|
+
void recordSessionKill({
|
|
3260
|
+
sessionName: windowName,
|
|
3261
|
+
agentId,
|
|
3262
|
+
reason: "capacity_false_positive_blocked"
|
|
3263
|
+
});
|
|
3264
|
+
continue;
|
|
3265
|
+
}
|
|
3266
|
+
process.stderr.write(
|
|
3267
|
+
`[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
|
|
3268
|
+
`
|
|
528
3269
|
);
|
|
3270
|
+
try {
|
|
3271
|
+
transport.kill(windowName);
|
|
3272
|
+
void recordSessionKill({
|
|
3273
|
+
sessionName: windowName,
|
|
3274
|
+
agentId,
|
|
3275
|
+
reason: "capacity"
|
|
3276
|
+
});
|
|
3277
|
+
const client = getClient();
|
|
3278
|
+
const rlScope = sessionScopeFilter();
|
|
3279
|
+
const openTasks = await client.execute({
|
|
3280
|
+
sql: `SELECT id, title, priority, task_file, status
|
|
3281
|
+
FROM tasks
|
|
3282
|
+
WHERE assigned_to = ? AND status IN ('open', 'in_progress')${rlScope.sql}
|
|
3283
|
+
ORDER BY
|
|
3284
|
+
CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
|
|
3285
|
+
created_at ASC
|
|
3286
|
+
LIMIT 10`,
|
|
3287
|
+
args: [agentId, ...rlScope.args]
|
|
3288
|
+
});
|
|
3289
|
+
if (openTasks.rows.length === 0) {
|
|
3290
|
+
process.stderr.write(
|
|
3291
|
+
`[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
|
|
3292
|
+
`
|
|
3293
|
+
);
|
|
3294
|
+
continue;
|
|
3295
|
+
}
|
|
3296
|
+
const { created } = await createOrRefreshResumeTask(
|
|
3297
|
+
agentId,
|
|
3298
|
+
projectDir2,
|
|
3299
|
+
openTasks.rows
|
|
3300
|
+
);
|
|
3301
|
+
if (created) {
|
|
3302
|
+
await writeNotification({
|
|
3303
|
+
agentId: "system",
|
|
3304
|
+
agentRole: "daemon",
|
|
3305
|
+
event: "capacity_relaunch",
|
|
3306
|
+
project: projectDir2.split("/").pop() ?? "unknown",
|
|
3307
|
+
summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
|
|
3308
|
+
});
|
|
3309
|
+
}
|
|
3310
|
+
_lastRelaunch.set(agentId, Date.now());
|
|
3311
|
+
if (created) relaunched.push(agentId);
|
|
3312
|
+
} catch (err) {
|
|
3313
|
+
process.stderr.write(
|
|
3314
|
+
`[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
|
|
3315
|
+
`
|
|
3316
|
+
);
|
|
3317
|
+
}
|
|
529
3318
|
}
|
|
3319
|
+
return relaunched;
|
|
530
3320
|
}
|
|
531
|
-
var
|
|
532
|
-
var
|
|
533
|
-
"src/lib/
|
|
3321
|
+
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;
|
|
3322
|
+
var init_capacity_monitor = __esm({
|
|
3323
|
+
"src/lib/capacity-monitor.ts"() {
|
|
534
3324
|
"use strict";
|
|
3325
|
+
init_session_registry();
|
|
3326
|
+
init_transport();
|
|
3327
|
+
init_notifications();
|
|
535
3328
|
init_database();
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
3329
|
+
init_session_kill_telemetry();
|
|
3330
|
+
init_tmux_routing();
|
|
3331
|
+
init_task_scope();
|
|
3332
|
+
CAPACITY_PATTERNS = [
|
|
3333
|
+
/conversation is too long/i,
|
|
3334
|
+
/maximum context length/i,
|
|
3335
|
+
/context window.*(?:limit|exceed|full)/i,
|
|
3336
|
+
/reached.*(?:token|context).*limit/i
|
|
3337
|
+
];
|
|
3338
|
+
CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
|
|
3339
|
+
CONTENT_LINE_MARKERS = [
|
|
3340
|
+
"RESUME:",
|
|
3341
|
+
"intercom",
|
|
3342
|
+
"capacity-monitor",
|
|
3343
|
+
"CAPACITY_PATTERNS",
|
|
3344
|
+
"isAtCapacity",
|
|
3345
|
+
"CONTENT_LINE_MARKERS",
|
|
3346
|
+
"pollCapacityDead",
|
|
3347
|
+
"confirmCapacityKill",
|
|
3348
|
+
"session_kills",
|
|
3349
|
+
"capacity-monitor.test"
|
|
3350
|
+
];
|
|
3351
|
+
SOURCE_CODE_MARKERS = [
|
|
3352
|
+
/["'`/].*(?:maximum context length|conversation is too long)/i,
|
|
3353
|
+
/(?:maximum context length|conversation is too long).*["'`/]/i
|
|
3354
|
+
];
|
|
3355
|
+
RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
|
|
3356
|
+
_lastRelaunch = /* @__PURE__ */ new Map();
|
|
3357
|
+
RESUME_TITLE_PREFIX = "RESUME:";
|
|
3358
|
+
RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
|
|
3359
|
+
RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
|
|
3360
|
+
CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
|
|
3361
|
+
_pendingCapacityKill = /* @__PURE__ */ new Map();
|
|
3362
|
+
CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
|
|
3363
|
+
CTX_FLOOR_PERCENT = 50;
|
|
546
3364
|
}
|
|
547
3365
|
});
|
|
548
3366
|
|
|
549
3367
|
// src/lib/tmux-routing.ts
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
3368
|
+
var tmux_routing_exports = {};
|
|
3369
|
+
__export(tmux_routing_exports, {
|
|
3370
|
+
acquireSpawnLock: () => acquireSpawnLock,
|
|
3371
|
+
employeeSessionName: () => employeeSessionName,
|
|
3372
|
+
ensureEmployee: () => ensureEmployee,
|
|
3373
|
+
extractRootExe: () => extractRootExe,
|
|
3374
|
+
findFreeInstance: () => findFreeInstance,
|
|
3375
|
+
getDispatchedBy: () => getDispatchedBy,
|
|
3376
|
+
getMySession: () => getMySession,
|
|
3377
|
+
getParentExe: () => getParentExe,
|
|
3378
|
+
getSessionState: () => getSessionState,
|
|
3379
|
+
isEmployeeAlive: () => isEmployeeAlive,
|
|
3380
|
+
isExeSession: () => isExeSession,
|
|
3381
|
+
isSessionBusy: () => isSessionBusy,
|
|
3382
|
+
notifyParentExe: () => notifyParentExe,
|
|
3383
|
+
parseParentExe: () => parseParentExe,
|
|
3384
|
+
registerParentExe: () => registerParentExe,
|
|
3385
|
+
releaseSpawnLock: () => releaseSpawnLock,
|
|
3386
|
+
resolveExeSession: () => resolveExeSession,
|
|
3387
|
+
sendIntercom: () => sendIntercom,
|
|
3388
|
+
spawnEmployee: () => spawnEmployee,
|
|
3389
|
+
verifyPaneAtCapacity: () => verifyPaneAtCapacity
|
|
3390
|
+
});
|
|
3391
|
+
import { execFileSync as execFileSync2, execSync as execSync6 } from "child_process";
|
|
3392
|
+
import { readFileSync as readFileSync9, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync } from "fs";
|
|
3393
|
+
import path13 from "path";
|
|
3394
|
+
import os5 from "os";
|
|
554
3395
|
import { fileURLToPath } from "url";
|
|
555
|
-
import { unlinkSync } from "fs";
|
|
3396
|
+
import { unlinkSync as unlinkSync4 } from "fs";
|
|
556
3397
|
function spawnLockPath(sessionName) {
|
|
557
|
-
return
|
|
3398
|
+
return path13.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
|
|
558
3399
|
}
|
|
559
3400
|
function isProcessAlive(pid) {
|
|
560
3401
|
try {
|
|
@@ -565,13 +3406,13 @@ function isProcessAlive(pid) {
|
|
|
565
3406
|
}
|
|
566
3407
|
}
|
|
567
3408
|
function acquireSpawnLock(sessionName) {
|
|
568
|
-
if (!
|
|
569
|
-
|
|
3409
|
+
if (!existsSync10(SPAWN_LOCK_DIR)) {
|
|
3410
|
+
mkdirSync5(SPAWN_LOCK_DIR, { recursive: true });
|
|
570
3411
|
}
|
|
571
3412
|
const lockFile = spawnLockPath(sessionName);
|
|
572
|
-
if (
|
|
3413
|
+
if (existsSync10(lockFile)) {
|
|
573
3414
|
try {
|
|
574
|
-
const lock = JSON.parse(
|
|
3415
|
+
const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
|
|
575
3416
|
const age = Date.now() - lock.timestamp;
|
|
576
3417
|
if (isProcessAlive(lock.pid) && age < 6e4) {
|
|
577
3418
|
return false;
|
|
@@ -579,25 +3420,25 @@ function acquireSpawnLock(sessionName) {
|
|
|
579
3420
|
} catch {
|
|
580
3421
|
}
|
|
581
3422
|
}
|
|
582
|
-
|
|
3423
|
+
writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
|
|
583
3424
|
return true;
|
|
584
3425
|
}
|
|
585
3426
|
function releaseSpawnLock(sessionName) {
|
|
586
3427
|
try {
|
|
587
|
-
|
|
3428
|
+
unlinkSync4(spawnLockPath(sessionName));
|
|
588
3429
|
} catch {
|
|
589
3430
|
}
|
|
590
3431
|
}
|
|
591
3432
|
function resolveBehaviorsExporterScript() {
|
|
592
3433
|
try {
|
|
593
3434
|
const thisFile = fileURLToPath(import.meta.url);
|
|
594
|
-
const scriptPath =
|
|
595
|
-
|
|
3435
|
+
const scriptPath = path13.join(
|
|
3436
|
+
path13.dirname(thisFile),
|
|
596
3437
|
"..",
|
|
597
3438
|
"bin",
|
|
598
3439
|
"exe-export-behaviors.js"
|
|
599
3440
|
);
|
|
600
|
-
return
|
|
3441
|
+
return existsSync10(scriptPath) ? scriptPath : null;
|
|
601
3442
|
} catch {
|
|
602
3443
|
return null;
|
|
603
3444
|
}
|
|
@@ -647,18 +3488,47 @@ function employeeSessionName(employee, exeSession2, instance) {
|
|
|
647
3488
|
}
|
|
648
3489
|
return name;
|
|
649
3490
|
}
|
|
3491
|
+
function parseParentExe(sessionName, agentId) {
|
|
3492
|
+
const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3493
|
+
const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
|
|
3494
|
+
const match = sessionName.match(regex);
|
|
3495
|
+
return match?.[1] ?? null;
|
|
3496
|
+
}
|
|
650
3497
|
function extractRootExe(name) {
|
|
651
3498
|
const match = name.match(/(exe\d+)$/);
|
|
652
3499
|
return match?.[1] ?? null;
|
|
653
3500
|
}
|
|
3501
|
+
function registerParentExe(sessionKey, parentExe, dispatchedBy) {
|
|
3502
|
+
if (!existsSync10(SESSION_CACHE)) {
|
|
3503
|
+
mkdirSync5(SESSION_CACHE, { recursive: true });
|
|
3504
|
+
}
|
|
3505
|
+
const rootExe = extractRootExe(parentExe) ?? parentExe;
|
|
3506
|
+
const filePath = path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
|
|
3507
|
+
writeFileSync5(filePath, JSON.stringify({
|
|
3508
|
+
parentExe: rootExe,
|
|
3509
|
+
dispatchedBy: dispatchedBy || rootExe,
|
|
3510
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3511
|
+
}));
|
|
3512
|
+
}
|
|
654
3513
|
function getParentExe(sessionKey) {
|
|
655
3514
|
try {
|
|
656
|
-
const data = JSON.parse(
|
|
3515
|
+
const data = JSON.parse(readFileSync9(path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
657
3516
|
return data.parentExe || null;
|
|
658
3517
|
} catch {
|
|
659
3518
|
return null;
|
|
660
3519
|
}
|
|
661
3520
|
}
|
|
3521
|
+
function getDispatchedBy(sessionKey) {
|
|
3522
|
+
try {
|
|
3523
|
+
const data = JSON.parse(readFileSync9(
|
|
3524
|
+
path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
|
|
3525
|
+
"utf8"
|
|
3526
|
+
));
|
|
3527
|
+
return data.dispatchedBy ?? data.parentExe ?? null;
|
|
3528
|
+
} catch {
|
|
3529
|
+
return null;
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
662
3532
|
function resolveExeSession() {
|
|
663
3533
|
const mySession = getMySession();
|
|
664
3534
|
if (!mySession) return null;
|
|
@@ -684,18 +3554,44 @@ function findFreeInstance(employeeName2, exeSession2, maxInstances = 10, isAlive
|
|
|
684
3554
|
}
|
|
685
3555
|
return null;
|
|
686
3556
|
}
|
|
3557
|
+
async function verifyPaneAtCapacity(sessionName) {
|
|
3558
|
+
const transport = getTransport();
|
|
3559
|
+
if (!transport.isAlive(sessionName)) {
|
|
3560
|
+
return { atCapacity: false, reason: `session ${sessionName} is not alive` };
|
|
3561
|
+
}
|
|
3562
|
+
let pane;
|
|
3563
|
+
try {
|
|
3564
|
+
pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
|
|
3565
|
+
} catch (err) {
|
|
3566
|
+
return {
|
|
3567
|
+
atCapacity: false,
|
|
3568
|
+
reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
|
|
3569
|
+
};
|
|
3570
|
+
}
|
|
3571
|
+
const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
|
|
3572
|
+
if (!isAtCapacity2(pane)) {
|
|
3573
|
+
return {
|
|
3574
|
+
atCapacity: false,
|
|
3575
|
+
reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
|
|
3576
|
+
};
|
|
3577
|
+
}
|
|
3578
|
+
return {
|
|
3579
|
+
atCapacity: true,
|
|
3580
|
+
reason: "capacity banner matched in recent pane output"
|
|
3581
|
+
};
|
|
3582
|
+
}
|
|
687
3583
|
function readDebounceState() {
|
|
688
3584
|
try {
|
|
689
|
-
if (!
|
|
690
|
-
return JSON.parse(
|
|
3585
|
+
if (!existsSync10(DEBOUNCE_FILE)) return {};
|
|
3586
|
+
return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
|
|
691
3587
|
} catch {
|
|
692
3588
|
return {};
|
|
693
3589
|
}
|
|
694
3590
|
}
|
|
695
3591
|
function writeDebounceState(state) {
|
|
696
3592
|
try {
|
|
697
|
-
if (!
|
|
698
|
-
|
|
3593
|
+
if (!existsSync10(SESSION_CACHE)) mkdirSync5(SESSION_CACHE, { recursive: true });
|
|
3594
|
+
writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
|
|
699
3595
|
} catch {
|
|
700
3596
|
}
|
|
701
3597
|
}
|
|
@@ -740,6 +3636,10 @@ function getSessionState(sessionName) {
|
|
|
740
3636
|
return "offline";
|
|
741
3637
|
}
|
|
742
3638
|
}
|
|
3639
|
+
function isSessionBusy(sessionName) {
|
|
3640
|
+
const state = getSessionState(sessionName);
|
|
3641
|
+
return state === "thinking" || state === "tool";
|
|
3642
|
+
}
|
|
743
3643
|
function isExeSession(sessionName) {
|
|
744
3644
|
return /^exe\d*$/.test(sessionName);
|
|
745
3645
|
}
|
|
@@ -785,6 +3685,28 @@ function sendIntercom(targetSession) {
|
|
|
785
3685
|
return "failed";
|
|
786
3686
|
}
|
|
787
3687
|
}
|
|
3688
|
+
function notifyParentExe(sessionKey) {
|
|
3689
|
+
const target = getDispatchedBy(sessionKey);
|
|
3690
|
+
if (!target) {
|
|
3691
|
+
process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
|
|
3692
|
+
`);
|
|
3693
|
+
return false;
|
|
3694
|
+
}
|
|
3695
|
+
process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
|
|
3696
|
+
`);
|
|
3697
|
+
const result2 = sendIntercom(target);
|
|
3698
|
+
if (result2 === "failed") {
|
|
3699
|
+
const rootExe = resolveExeSession();
|
|
3700
|
+
if (rootExe && rootExe !== target) {
|
|
3701
|
+
process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
|
|
3702
|
+
`);
|
|
3703
|
+
const fallback = sendIntercom(rootExe);
|
|
3704
|
+
return fallback !== "failed";
|
|
3705
|
+
}
|
|
3706
|
+
return false;
|
|
3707
|
+
}
|
|
3708
|
+
return true;
|
|
3709
|
+
}
|
|
788
3710
|
function ensureEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
789
3711
|
if (employeeName2 === "exe") {
|
|
790
3712
|
return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
|
|
@@ -858,26 +3780,26 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
858
3780
|
const transport = getTransport();
|
|
859
3781
|
const sessionName = employeeSessionName(employeeName2, exeSession2, opts?.instance);
|
|
860
3782
|
const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName2}${opts.instance}` : employeeName2;
|
|
861
|
-
const logDir =
|
|
862
|
-
const logFile =
|
|
863
|
-
if (!
|
|
864
|
-
|
|
3783
|
+
const logDir = path13.join(os5.homedir(), ".exe-os", "session-logs");
|
|
3784
|
+
const logFile = path13.join(logDir, `${instanceLabel}-${Date.now()}.log`);
|
|
3785
|
+
if (!existsSync10(logDir)) {
|
|
3786
|
+
mkdirSync5(logDir, { recursive: true });
|
|
865
3787
|
}
|
|
866
3788
|
transport.kill(sessionName);
|
|
867
3789
|
let cleanupSuffix = "";
|
|
868
3790
|
try {
|
|
869
3791
|
const thisFile = fileURLToPath(import.meta.url);
|
|
870
|
-
const cleanupScript =
|
|
871
|
-
if (
|
|
3792
|
+
const cleanupScript = path13.join(path13.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
|
|
3793
|
+
if (existsSync10(cleanupScript)) {
|
|
872
3794
|
cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName2}" "${exeSession2}"`;
|
|
873
3795
|
}
|
|
874
3796
|
} catch {
|
|
875
3797
|
}
|
|
876
3798
|
try {
|
|
877
|
-
const claudeJsonPath =
|
|
3799
|
+
const claudeJsonPath = path13.join(os5.homedir(), ".claude.json");
|
|
878
3800
|
let claudeJson = {};
|
|
879
3801
|
try {
|
|
880
|
-
claudeJson = JSON.parse(
|
|
3802
|
+
claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
|
|
881
3803
|
} catch {
|
|
882
3804
|
}
|
|
883
3805
|
if (!claudeJson.projects) claudeJson.projects = {};
|
|
@@ -885,17 +3807,17 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
885
3807
|
const trustDir = opts?.cwd ?? projectDir2;
|
|
886
3808
|
if (!projects[trustDir]) projects[trustDir] = {};
|
|
887
3809
|
projects[trustDir].hasTrustDialogAccepted = true;
|
|
888
|
-
|
|
3810
|
+
writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
|
|
889
3811
|
} catch {
|
|
890
3812
|
}
|
|
891
3813
|
try {
|
|
892
|
-
const settingsDir =
|
|
3814
|
+
const settingsDir = path13.join(os5.homedir(), ".claude", "projects");
|
|
893
3815
|
const normalizedKey = (opts?.cwd ?? projectDir2).replace(/\//g, "-").replace(/^-/, "");
|
|
894
|
-
const projSettingsDir =
|
|
895
|
-
const settingsPath =
|
|
3816
|
+
const projSettingsDir = path13.join(settingsDir, normalizedKey);
|
|
3817
|
+
const settingsPath = path13.join(projSettingsDir, "settings.json");
|
|
896
3818
|
let settings = {};
|
|
897
3819
|
try {
|
|
898
|
-
settings = JSON.parse(
|
|
3820
|
+
settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
|
|
899
3821
|
} catch {
|
|
900
3822
|
}
|
|
901
3823
|
const perms = settings.permissions ?? {};
|
|
@@ -923,8 +3845,8 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
923
3845
|
if (changed) {
|
|
924
3846
|
perms.allow = allow;
|
|
925
3847
|
settings.permissions = perms;
|
|
926
|
-
|
|
927
|
-
|
|
3848
|
+
mkdirSync5(projSettingsDir, { recursive: true });
|
|
3849
|
+
writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
928
3850
|
}
|
|
929
3851
|
} catch {
|
|
930
3852
|
}
|
|
@@ -936,8 +3858,8 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
936
3858
|
let behaviorsFlag = "";
|
|
937
3859
|
let legacyFallbackWarned = false;
|
|
938
3860
|
if (!useExeAgent && !useBinSymlink) {
|
|
939
|
-
const identityPath =
|
|
940
|
-
|
|
3861
|
+
const identityPath = path13.join(
|
|
3862
|
+
os5.homedir(),
|
|
941
3863
|
".exe-os",
|
|
942
3864
|
"identity",
|
|
943
3865
|
`${employeeName2}.md`
|
|
@@ -946,13 +3868,13 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
946
3868
|
const hasAgentFlag = claudeSupportsAgentFlag();
|
|
947
3869
|
if (hasAgentFlag) {
|
|
948
3870
|
identityFlag = ` --agent ${employeeName2}`;
|
|
949
|
-
} else if (
|
|
3871
|
+
} else if (existsSync10(identityPath)) {
|
|
950
3872
|
identityFlag = ` --append-system-prompt-file ${identityPath}`;
|
|
951
3873
|
legacyFallbackWarned = true;
|
|
952
3874
|
}
|
|
953
3875
|
const behaviorsFile = exportBehaviorsSync(
|
|
954
3876
|
employeeName2,
|
|
955
|
-
|
|
3877
|
+
path13.basename(spawnCwd),
|
|
956
3878
|
sessionName
|
|
957
3879
|
);
|
|
958
3880
|
if (behaviorsFile) {
|
|
@@ -967,16 +3889,16 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
967
3889
|
}
|
|
968
3890
|
let sessionContextFlag = "";
|
|
969
3891
|
try {
|
|
970
|
-
const ctxDir =
|
|
971
|
-
|
|
972
|
-
const ctxFile =
|
|
3892
|
+
const ctxDir = path13.join(os5.homedir(), ".exe-os", "session-cache");
|
|
3893
|
+
mkdirSync5(ctxDir, { recursive: true });
|
|
3894
|
+
const ctxFile = path13.join(ctxDir, `session-context-${sessionName}.md`);
|
|
973
3895
|
const ctxContent = [
|
|
974
3896
|
`## Session Context`,
|
|
975
3897
|
`You are running in tmux session: ${sessionName}.`,
|
|
976
3898
|
`Your parent exe session is ${exeSession2}.`,
|
|
977
3899
|
`Your employees (if any) use the -${exeSession2} suffix (e.g., tom-${exeSession2}).`
|
|
978
3900
|
].join("\n");
|
|
979
|
-
|
|
3901
|
+
writeFileSync5(ctxFile, ctxContent);
|
|
980
3902
|
sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
|
|
981
3903
|
} catch {
|
|
982
3904
|
}
|
|
@@ -1014,8 +3936,8 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
1014
3936
|
transport.pipeLog(sessionName, logFile);
|
|
1015
3937
|
try {
|
|
1016
3938
|
const mySession = getMySession();
|
|
1017
|
-
const dispatchInfo =
|
|
1018
|
-
|
|
3939
|
+
const dispatchInfo = path13.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
|
|
3940
|
+
writeFileSync5(dispatchInfo, JSON.stringify({
|
|
1019
3941
|
dispatchedBy: mySession,
|
|
1020
3942
|
rootExe: exeSession2,
|
|
1021
3943
|
provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
|
|
@@ -1026,7 +3948,7 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
1026
3948
|
let booted = false;
|
|
1027
3949
|
for (let i = 0; i < 30; i++) {
|
|
1028
3950
|
try {
|
|
1029
|
-
|
|
3951
|
+
execSync6("sleep 0.5");
|
|
1030
3952
|
} catch {
|
|
1031
3953
|
}
|
|
1032
3954
|
try {
|
|
@@ -1066,7 +3988,7 @@ function spawnEmployee(employeeName2, exeSession2, projectDir2, opts) {
|
|
|
1066
3988
|
releaseSpawnLock(sessionName);
|
|
1067
3989
|
return { sessionName };
|
|
1068
3990
|
}
|
|
1069
|
-
var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, VALID_SESSION_NAME, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
|
|
3991
|
+
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;
|
|
1070
3992
|
var init_tmux_routing = __esm({
|
|
1071
3993
|
"src/lib/tmux-routing.ts"() {
|
|
1072
3994
|
"use strict";
|
|
@@ -1078,20 +4000,573 @@ var init_tmux_routing = __esm({
|
|
|
1078
4000
|
init_provider_table();
|
|
1079
4001
|
init_intercom_queue();
|
|
1080
4002
|
init_plan_limits();
|
|
1081
|
-
SPAWN_LOCK_DIR =
|
|
1082
|
-
SESSION_CACHE =
|
|
4003
|
+
SPAWN_LOCK_DIR = path13.join(os5.homedir(), ".exe-os", "spawn-locks");
|
|
4004
|
+
SESSION_CACHE = path13.join(os5.homedir(), ".exe-os", "session-cache");
|
|
1083
4005
|
BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
|
|
1084
4006
|
VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
|
|
4007
|
+
VERIFY_PANE_LINES = 200;
|
|
1085
4008
|
INTERCOM_DEBOUNCE_MS = 3e4;
|
|
1086
|
-
INTERCOM_LOG2 =
|
|
1087
|
-
DEBOUNCE_FILE =
|
|
4009
|
+
INTERCOM_LOG2 = path13.join(os5.homedir(), ".exe-os", "intercom.log");
|
|
4010
|
+
DEBOUNCE_FILE = path13.join(SESSION_CACHE, "intercom-debounce.json");
|
|
1088
4011
|
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
1089
4012
|
BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
|
|
1090
4013
|
}
|
|
1091
4014
|
});
|
|
1092
4015
|
|
|
4016
|
+
// src/lib/shard-manager.ts
|
|
4017
|
+
var shard_manager_exports = {};
|
|
4018
|
+
__export(shard_manager_exports, {
|
|
4019
|
+
disposeShards: () => disposeShards,
|
|
4020
|
+
ensureShardSchema: () => ensureShardSchema,
|
|
4021
|
+
getReadyShardClient: () => getReadyShardClient,
|
|
4022
|
+
getShardClient: () => getShardClient,
|
|
4023
|
+
getShardsDir: () => getShardsDir,
|
|
4024
|
+
initShardManager: () => initShardManager,
|
|
4025
|
+
isShardingEnabled: () => isShardingEnabled,
|
|
4026
|
+
listShards: () => listShards,
|
|
4027
|
+
shardExists: () => shardExists
|
|
4028
|
+
});
|
|
4029
|
+
import path15 from "path";
|
|
4030
|
+
import { existsSync as existsSync12, mkdirSync as mkdirSync6, readdirSync as readdirSync3 } from "fs";
|
|
4031
|
+
import { createClient as createClient2 } from "@libsql/client";
|
|
4032
|
+
function initShardManager(encryptionKey) {
|
|
4033
|
+
_encryptionKey = encryptionKey;
|
|
4034
|
+
if (!existsSync12(SHARDS_DIR)) {
|
|
4035
|
+
mkdirSync6(SHARDS_DIR, { recursive: true });
|
|
4036
|
+
}
|
|
4037
|
+
_shardingEnabled = true;
|
|
4038
|
+
}
|
|
4039
|
+
function isShardingEnabled() {
|
|
4040
|
+
return _shardingEnabled;
|
|
4041
|
+
}
|
|
4042
|
+
function getShardsDir() {
|
|
4043
|
+
return SHARDS_DIR;
|
|
4044
|
+
}
|
|
4045
|
+
function getShardClient(projectName) {
|
|
4046
|
+
if (!_encryptionKey) {
|
|
4047
|
+
throw new Error("Shard manager not initialized. Call initShardManager() first.");
|
|
4048
|
+
}
|
|
4049
|
+
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
4050
|
+
if (!safeName) {
|
|
4051
|
+
throw new Error(`Invalid project name for shard: "${projectName}"`);
|
|
4052
|
+
}
|
|
4053
|
+
const cached = _shards.get(safeName);
|
|
4054
|
+
if (cached) return cached;
|
|
4055
|
+
const dbPath = path15.join(SHARDS_DIR, `${safeName}.db`);
|
|
4056
|
+
const client = createClient2({
|
|
4057
|
+
url: `file:${dbPath}`,
|
|
4058
|
+
encryptionKey: _encryptionKey
|
|
4059
|
+
});
|
|
4060
|
+
_shards.set(safeName, client);
|
|
4061
|
+
return client;
|
|
4062
|
+
}
|
|
4063
|
+
function shardExists(projectName) {
|
|
4064
|
+
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
4065
|
+
return existsSync12(path15.join(SHARDS_DIR, `${safeName}.db`));
|
|
4066
|
+
}
|
|
4067
|
+
function listShards() {
|
|
4068
|
+
if (!existsSync12(SHARDS_DIR)) return [];
|
|
4069
|
+
return readdirSync3(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
4070
|
+
}
|
|
4071
|
+
async function ensureShardSchema(client) {
|
|
4072
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
4073
|
+
await client.execute("PRAGMA busy_timeout = 30000");
|
|
4074
|
+
try {
|
|
4075
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
4076
|
+
} catch {
|
|
4077
|
+
}
|
|
4078
|
+
await client.executeMultiple(`
|
|
4079
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
4080
|
+
id TEXT PRIMARY KEY,
|
|
4081
|
+
agent_id TEXT NOT NULL,
|
|
4082
|
+
agent_role TEXT NOT NULL,
|
|
4083
|
+
session_id TEXT NOT NULL,
|
|
4084
|
+
timestamp TEXT NOT NULL,
|
|
4085
|
+
tool_name TEXT NOT NULL,
|
|
4086
|
+
project_name TEXT NOT NULL,
|
|
4087
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
4088
|
+
raw_text TEXT NOT NULL,
|
|
4089
|
+
vector F32_BLOB(1024),
|
|
4090
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
4091
|
+
);
|
|
4092
|
+
|
|
4093
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
|
|
4094
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
|
|
4095
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
|
|
4096
|
+
`);
|
|
4097
|
+
await client.executeMultiple(`
|
|
4098
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
4099
|
+
raw_text,
|
|
4100
|
+
content='memories',
|
|
4101
|
+
content_rowid='rowid'
|
|
4102
|
+
);
|
|
4103
|
+
|
|
4104
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
4105
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
4106
|
+
END;
|
|
4107
|
+
|
|
4108
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
4109
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
4110
|
+
END;
|
|
4111
|
+
|
|
4112
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
4113
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
4114
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
4115
|
+
END;
|
|
4116
|
+
`);
|
|
4117
|
+
for (const col of [
|
|
4118
|
+
"ALTER TABLE memories ADD COLUMN task_id TEXT",
|
|
4119
|
+
"ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
|
|
4120
|
+
"ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
|
|
4121
|
+
"ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
|
|
4122
|
+
"ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
|
|
4123
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
|
|
4124
|
+
"ALTER TABLE memories ADD COLUMN content_hash TEXT",
|
|
4125
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
|
|
4126
|
+
"ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
|
|
4127
|
+
"ALTER TABLE memories ADD COLUMN last_accessed TEXT",
|
|
4128
|
+
// Wiki linkage columns (must match database.ts)
|
|
4129
|
+
"ALTER TABLE memories ADD COLUMN workspace_id TEXT",
|
|
4130
|
+
"ALTER TABLE memories ADD COLUMN document_id TEXT",
|
|
4131
|
+
"ALTER TABLE memories ADD COLUMN user_id TEXT",
|
|
4132
|
+
"ALTER TABLE memories ADD COLUMN char_offset INTEGER",
|
|
4133
|
+
"ALTER TABLE memories ADD COLUMN page_number INTEGER",
|
|
4134
|
+
// Source provenance columns (must match database.ts)
|
|
4135
|
+
"ALTER TABLE memories ADD COLUMN source_path TEXT",
|
|
4136
|
+
"ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
|
|
4137
|
+
"ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
|
|
4138
|
+
"ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
|
|
4139
|
+
]) {
|
|
4140
|
+
try {
|
|
4141
|
+
await client.execute(col);
|
|
4142
|
+
} catch {
|
|
4143
|
+
}
|
|
4144
|
+
}
|
|
4145
|
+
for (const idx of [
|
|
4146
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
|
|
4147
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
|
|
4148
|
+
]) {
|
|
4149
|
+
try {
|
|
4150
|
+
await client.execute(idx);
|
|
4151
|
+
} catch {
|
|
4152
|
+
}
|
|
4153
|
+
}
|
|
4154
|
+
try {
|
|
4155
|
+
await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
|
|
4156
|
+
} catch {
|
|
4157
|
+
}
|
|
4158
|
+
for (const idx of [
|
|
4159
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
|
|
4160
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
|
|
4161
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
|
|
4162
|
+
]) {
|
|
4163
|
+
try {
|
|
4164
|
+
await client.execute(idx);
|
|
4165
|
+
} catch {
|
|
4166
|
+
}
|
|
4167
|
+
}
|
|
4168
|
+
await client.executeMultiple(`
|
|
4169
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
4170
|
+
id TEXT PRIMARY KEY,
|
|
4171
|
+
name TEXT NOT NULL,
|
|
4172
|
+
type TEXT NOT NULL,
|
|
4173
|
+
first_seen TEXT NOT NULL,
|
|
4174
|
+
last_seen TEXT NOT NULL,
|
|
4175
|
+
properties TEXT DEFAULT '{}',
|
|
4176
|
+
UNIQUE(name, type)
|
|
4177
|
+
);
|
|
4178
|
+
|
|
4179
|
+
CREATE TABLE IF NOT EXISTS relationships (
|
|
4180
|
+
id TEXT PRIMARY KEY,
|
|
4181
|
+
source_entity_id TEXT NOT NULL,
|
|
4182
|
+
target_entity_id TEXT NOT NULL,
|
|
4183
|
+
type TEXT NOT NULL,
|
|
4184
|
+
weight REAL DEFAULT 1.0,
|
|
4185
|
+
timestamp TEXT NOT NULL,
|
|
4186
|
+
properties TEXT DEFAULT '{}',
|
|
4187
|
+
UNIQUE(source_entity_id, target_entity_id, type)
|
|
4188
|
+
);
|
|
4189
|
+
|
|
4190
|
+
CREATE TABLE IF NOT EXISTS entity_memories (
|
|
4191
|
+
entity_id TEXT NOT NULL,
|
|
4192
|
+
memory_id TEXT NOT NULL,
|
|
4193
|
+
PRIMARY KEY (entity_id, memory_id)
|
|
4194
|
+
);
|
|
4195
|
+
|
|
4196
|
+
CREATE TABLE IF NOT EXISTS relationship_memories (
|
|
4197
|
+
relationship_id TEXT NOT NULL,
|
|
4198
|
+
memory_id TEXT NOT NULL,
|
|
4199
|
+
PRIMARY KEY (relationship_id, memory_id)
|
|
4200
|
+
);
|
|
4201
|
+
|
|
4202
|
+
CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
|
|
4203
|
+
CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
|
|
4204
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
|
|
4205
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
|
|
4206
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
|
|
4207
|
+
|
|
4208
|
+
CREATE TABLE IF NOT EXISTS hyperedges (
|
|
4209
|
+
id TEXT PRIMARY KEY,
|
|
4210
|
+
label TEXT NOT NULL,
|
|
4211
|
+
relation TEXT NOT NULL,
|
|
4212
|
+
confidence REAL DEFAULT 1.0,
|
|
4213
|
+
timestamp TEXT NOT NULL
|
|
4214
|
+
);
|
|
4215
|
+
|
|
4216
|
+
CREATE TABLE IF NOT EXISTS hyperedge_nodes (
|
|
4217
|
+
hyperedge_id TEXT NOT NULL,
|
|
4218
|
+
entity_id TEXT NOT NULL,
|
|
4219
|
+
PRIMARY KEY (hyperedge_id, entity_id)
|
|
4220
|
+
);
|
|
4221
|
+
`);
|
|
4222
|
+
for (const col of [
|
|
4223
|
+
"ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
|
|
4224
|
+
"ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
|
|
4225
|
+
]) {
|
|
4226
|
+
try {
|
|
4227
|
+
await client.execute(col);
|
|
4228
|
+
} catch {
|
|
4229
|
+
}
|
|
4230
|
+
}
|
|
4231
|
+
}
|
|
4232
|
+
async function getReadyShardClient(projectName) {
|
|
4233
|
+
const client = getShardClient(projectName);
|
|
4234
|
+
await ensureShardSchema(client);
|
|
4235
|
+
return client;
|
|
4236
|
+
}
|
|
4237
|
+
function disposeShards() {
|
|
4238
|
+
for (const [, client] of _shards) {
|
|
4239
|
+
client.close();
|
|
4240
|
+
}
|
|
4241
|
+
_shards.clear();
|
|
4242
|
+
_shardingEnabled = false;
|
|
4243
|
+
_encryptionKey = null;
|
|
4244
|
+
}
|
|
4245
|
+
var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
|
|
4246
|
+
var init_shard_manager = __esm({
|
|
4247
|
+
"src/lib/shard-manager.ts"() {
|
|
4248
|
+
"use strict";
|
|
4249
|
+
init_config();
|
|
4250
|
+
SHARDS_DIR = path15.join(EXE_AI_DIR, "shards");
|
|
4251
|
+
_shards = /* @__PURE__ */ new Map();
|
|
4252
|
+
_encryptionKey = null;
|
|
4253
|
+
_shardingEnabled = false;
|
|
4254
|
+
}
|
|
4255
|
+
});
|
|
4256
|
+
|
|
4257
|
+
// src/lib/platform-procedures.ts
|
|
4258
|
+
var PLATFORM_PROCEDURES, PLATFORM_PROCEDURE_TITLES;
|
|
4259
|
+
var init_platform_procedures = __esm({
|
|
4260
|
+
"src/lib/platform-procedures.ts"() {
|
|
4261
|
+
"use strict";
|
|
4262
|
+
PLATFORM_PROCEDURES = [
|
|
4263
|
+
// --- Foundation: what is exe-os ---
|
|
4264
|
+
{
|
|
4265
|
+
title: "What is exe-os \u2014 the operating model every agent must understand",
|
|
4266
|
+
domain: "architecture",
|
|
4267
|
+
priority: "p0",
|
|
4268
|
+
content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO (exe), CTO (yoshi), CMO (mari), engineers (tom), content (sasha). Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
|
|
4269
|
+
},
|
|
4270
|
+
{
|
|
4271
|
+
title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
|
|
4272
|
+
domain: "architecture",
|
|
4273
|
+
priority: "p0",
|
|
4274
|
+
content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code. The founder opens CC, runs /exe to boot the COO. exe manages employees in tmux sessions. Each exeN is a separate CC window/project. Employees (yoshi, tom, mari) run in their own tmux panes via create_task auto-spawn. The founder talks to exe; exe orchestrates the team. CC is the shell, exe-os is the brain."
|
|
4275
|
+
},
|
|
4276
|
+
{
|
|
4277
|
+
title: "Sessions explained \u2014 what exeN means and how projects work",
|
|
4278
|
+
domain: "architecture",
|
|
4279
|
+
priority: "p0",
|
|
4280
|
+
content: "Each exeN (exe1, exe2, exe3) is an isolated project session. exe1 might be exe-os development, exe2 might be exe-wiki. Each session spawns its own employees: exe1\u2192yoshi-exe1\u2192tom-exe1. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
|
|
4281
|
+
},
|
|
4282
|
+
// --- Hierarchy and dispatch ---
|
|
4283
|
+
{
|
|
4284
|
+
title: "Chain of command \u2014 who talks to whom",
|
|
4285
|
+
domain: "workflow",
|
|
4286
|
+
priority: "p0",
|
|
4287
|
+
content: "Founder \u2192 exe (COO) \u2192 yoshi (CTO) / mari (CMO). Yoshi \u2192 tom (engineer). Mari \u2192 sasha (content). Never skip levels: exe never assigns directly to tom. Tom never reports directly to exe. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
|
|
4288
|
+
},
|
|
4289
|
+
{
|
|
4290
|
+
title: "Single dispatch path \u2014 create_task only",
|
|
4291
|
+
domain: "workflow",
|
|
4292
|
+
priority: "p0",
|
|
4293
|
+
content: "create_task is the ONLY way to dispatch work to another agent. No direct ensureEmployee calls, no manual tmux spawns, no send_message for actionable work. create_task \u2192 system auto-spawns \u2192 session correctly named. ONE PATH. No backdoors. No exceptions."
|
|
4294
|
+
},
|
|
4295
|
+
// --- Session isolation ---
|
|
4296
|
+
{
|
|
4297
|
+
title: "Session scoping \u2014 stay in your exe boundary",
|
|
4298
|
+
domain: "security",
|
|
4299
|
+
priority: "p0",
|
|
4300
|
+
content: "Session scoping is mandatory. Managers dispatch to workers within their own exe session ONLY. exe1\u2192yoshi-exe1\u2192tom-exe1. exe2\u2192yoshi-exe2\u2192tom2-exe2. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating exe session."
|
|
4301
|
+
},
|
|
4302
|
+
{
|
|
4303
|
+
title: "Session isolation \u2014 never touch another session's work",
|
|
4304
|
+
domain: "workflow",
|
|
4305
|
+
priority: "p0",
|
|
4306
|
+
content: `Sessions are isolated. exeN owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another exe session. (2) Never review work from a different session \u2014 report "belongs to exeN" and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: yoshi-exe1 works ONLY on exe1 tasks. Cross-session work is a system violation.`
|
|
4307
|
+
},
|
|
4308
|
+
// --- Engineering: session scoping in code ---
|
|
4309
|
+
{
|
|
4310
|
+
title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
|
|
4311
|
+
domain: "architecture",
|
|
4312
|
+
priority: "p0",
|
|
4313
|
+
content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching current exeN. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ exe sessions simultaneously."
|
|
4314
|
+
},
|
|
4315
|
+
// --- Hard constraints ---
|
|
4316
|
+
{
|
|
4317
|
+
title: "What you CANNOT do in exe-os \u2014 hard constraints",
|
|
4318
|
+
domain: "security",
|
|
4319
|
+
priority: "p0",
|
|
4320
|
+
content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 exe reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
|
|
4321
|
+
},
|
|
4322
|
+
// --- Operations ---
|
|
4323
|
+
{
|
|
4324
|
+
title: "Managers must supervise deployed workers",
|
|
4325
|
+
domain: "workflow",
|
|
4326
|
+
priority: "p0",
|
|
4327
|
+
content: `Every manager (COO/CTO/CMO) who dispatches work to a worker MUST actively monitor them. Check tmux capture-pane every 10 minutes. Verify they're working, not stuck. If idle at prompt with in_progress task \u2192 send intercom. If stuck \u2192 unblock or escalate. "Standing by" without checking is negligence.`
|
|
4328
|
+
},
|
|
4329
|
+
{
|
|
4330
|
+
title: "COO boot health check \u2014 memory, cloud sync, daemon on every launch",
|
|
4331
|
+
domain: "workflow",
|
|
4332
|
+
priority: "p0",
|
|
4333
|
+
content: "On every /exe boot, COO MUST check system health BEFORE other work: (1) daemon \u2014 is exed PID alive, (2) cloud sync \u2014 grep workers.log for recent cloud-sync errors, (3) memory count \u2014 total in DB, (4) sync delta \u2014 local vs cloud storage_bytes. Report as 4-line status table. If ANY check fails, surface to founder immediately. Do not proceed to tasks until health confirmed."
|
|
4334
|
+
},
|
|
4335
|
+
{
|
|
4336
|
+
title: "exe-build-adv mandatory for 3+ files",
|
|
4337
|
+
domain: "workflow",
|
|
4338
|
+
priority: "p0",
|
|
4339
|
+
content: "exe-build-adv is MANDATORY for ALL work touching 3+ files. Run /exe-build-adv --auto BEFORE implementation. Pipeline: Spec \u2192 AC \u2192 Tests \u2192 Evaluate \u2192 Fix. No multi-file feature ships without pipeline artifacts. No exceptions \u2014 managers reject work without them."
|
|
4340
|
+
},
|
|
4341
|
+
{
|
|
4342
|
+
title: "Desktop and TUI are the same product",
|
|
4343
|
+
domain: "architecture",
|
|
4344
|
+
priority: "p0",
|
|
4345
|
+
content: "Desktop and TUI are the SAME product in different renderers. Same data contracts, same interactions, same acceptance criteria. Desktop tab specs in ARCHITECTURE.md ARE the TUI specs. When building TUI, cross-reference Desktop spec. Different tab names, identical behavior. Never treat them as separate products."
|
|
4346
|
+
},
|
|
4347
|
+
// --- Orchestration golden path ---
|
|
4348
|
+
{
|
|
4349
|
+
title: "Task lifecycle \u2014 the golden path every agent follows",
|
|
4350
|
+
domain: "workflow",
|
|
4351
|
+
priority: "p0",
|
|
4352
|
+
content: "create_task is dispatch + delivery. Task lifecycle: open \u2192 in_progress (you start) \u2192 done (update_task when finished) \u2192 needs_review (reviewer nudged) \u2192 closed (COO only via close_task). DB is the reliable delivery \u2014 intercom is just a speedup nudge. If you finish a task, self-chain: check for next task immediately (step 7). Never wait for a nudge. Never say 'standing by.'"
|
|
4353
|
+
},
|
|
4354
|
+
{
|
|
4355
|
+
title: "Intercom is a speedup, not delivery \u2014 DB is the source of truth",
|
|
4356
|
+
domain: "architecture",
|
|
4357
|
+
priority: "p0",
|
|
4358
|
+
content: "Tasks live in the DB. Intercom (tmux send-keys) is fire-and-forget \u2014 it may fail, get garbled, or arrive mid-work. Never rely on intercom for task delivery. The UserPromptSubmit hook checks the DB for new tasks on every prompt. Your operating procedures step 7 says check for next work. The daemon nudges idle agents as a speedup. If you have no tasks, you found them all."
|
|
4359
|
+
}
|
|
4360
|
+
];
|
|
4361
|
+
PLATFORM_PROCEDURE_TITLES = new Set(
|
|
4362
|
+
PLATFORM_PROCEDURES.map((p) => p.title)
|
|
4363
|
+
);
|
|
4364
|
+
}
|
|
4365
|
+
});
|
|
4366
|
+
|
|
4367
|
+
// src/lib/global-procedures.ts
|
|
4368
|
+
var global_procedures_exports = {};
|
|
4369
|
+
__export(global_procedures_exports, {
|
|
4370
|
+
deactivateGlobalProcedure: () => deactivateGlobalProcedure,
|
|
4371
|
+
getGlobalProceduresBlock: () => getGlobalProceduresBlock,
|
|
4372
|
+
loadGlobalProcedures: () => loadGlobalProcedures,
|
|
4373
|
+
storeGlobalProcedure: () => storeGlobalProcedure
|
|
4374
|
+
});
|
|
4375
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
4376
|
+
async function loadGlobalProcedures() {
|
|
4377
|
+
const client = getClient();
|
|
4378
|
+
const result2 = await client.execute({
|
|
4379
|
+
sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
|
|
4380
|
+
args: []
|
|
4381
|
+
});
|
|
4382
|
+
const allRows = result2.rows;
|
|
4383
|
+
const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
|
|
4384
|
+
if (customerOnly.length > 0) {
|
|
4385
|
+
_customerCache = customerOnly.map((p) => `### ${p.title}
|
|
4386
|
+
${p.content}`).join("\n\n");
|
|
4387
|
+
} else {
|
|
4388
|
+
_customerCache = "";
|
|
4389
|
+
}
|
|
4390
|
+
_cacheLoaded = true;
|
|
4391
|
+
return customerOnly;
|
|
4392
|
+
}
|
|
4393
|
+
function getGlobalProceduresBlock() {
|
|
4394
|
+
const sections = [];
|
|
4395
|
+
if (_platformCache) sections.push(_platformCache);
|
|
4396
|
+
if (_cacheLoaded && _customerCache) sections.push(_customerCache);
|
|
4397
|
+
if (sections.length === 0) return "";
|
|
4398
|
+
return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
|
|
4399
|
+
|
|
4400
|
+
${sections.join("\n\n")}
|
|
4401
|
+
`;
|
|
4402
|
+
}
|
|
4403
|
+
async function storeGlobalProcedure(input) {
|
|
4404
|
+
const id = randomUUID2();
|
|
4405
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4406
|
+
const client = getClient();
|
|
4407
|
+
await client.execute({
|
|
4408
|
+
sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
|
|
4409
|
+
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
4410
|
+
args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
|
|
4411
|
+
});
|
|
4412
|
+
await loadGlobalProcedures();
|
|
4413
|
+
return id;
|
|
4414
|
+
}
|
|
4415
|
+
async function deactivateGlobalProcedure(id) {
|
|
4416
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4417
|
+
const client = getClient();
|
|
4418
|
+
const result2 = await client.execute({
|
|
4419
|
+
sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
|
|
4420
|
+
args: [now, id]
|
|
4421
|
+
});
|
|
4422
|
+
await loadGlobalProcedures();
|
|
4423
|
+
return result2.rowsAffected > 0;
|
|
4424
|
+
}
|
|
4425
|
+
var _customerCache, _cacheLoaded, _platformCache;
|
|
4426
|
+
var init_global_procedures = __esm({
|
|
4427
|
+
"src/lib/global-procedures.ts"() {
|
|
4428
|
+
"use strict";
|
|
4429
|
+
init_database();
|
|
4430
|
+
init_platform_procedures();
|
|
4431
|
+
_customerCache = "";
|
|
4432
|
+
_cacheLoaded = false;
|
|
4433
|
+
_platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
|
|
4434
|
+
${p.content}`).join("\n\n");
|
|
4435
|
+
}
|
|
4436
|
+
});
|
|
4437
|
+
|
|
1093
4438
|
// src/bin/exe-dispatch.ts
|
|
1094
4439
|
init_tmux_routing();
|
|
4440
|
+
init_tasks_crud();
|
|
4441
|
+
|
|
4442
|
+
// src/lib/store.ts
|
|
4443
|
+
init_database();
|
|
4444
|
+
|
|
4445
|
+
// src/lib/keychain.ts
|
|
4446
|
+
import { readFile as readFile4, writeFile as writeFile5, unlink, mkdir as mkdir4, chmod as chmod2 } from "fs/promises";
|
|
4447
|
+
import { existsSync as existsSync11 } from "fs";
|
|
4448
|
+
import path14 from "path";
|
|
4449
|
+
import os6 from "os";
|
|
4450
|
+
import crypto6 from "crypto";
|
|
4451
|
+
var SERVICE = "exe-mem";
|
|
4452
|
+
var ACCOUNT = "master-key";
|
|
4453
|
+
function getKeyDir() {
|
|
4454
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path14.join(os6.homedir(), ".exe-os");
|
|
4455
|
+
}
|
|
4456
|
+
function getKeyPath() {
|
|
4457
|
+
return path14.join(getKeyDir(), "master.key");
|
|
4458
|
+
}
|
|
4459
|
+
async function tryKeytar() {
|
|
4460
|
+
try {
|
|
4461
|
+
return await import("keytar");
|
|
4462
|
+
} catch {
|
|
4463
|
+
return null;
|
|
4464
|
+
}
|
|
4465
|
+
}
|
|
4466
|
+
async function getMasterKey() {
|
|
4467
|
+
const keytar = await tryKeytar();
|
|
4468
|
+
if (keytar) {
|
|
4469
|
+
try {
|
|
4470
|
+
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
4471
|
+
if (stored) {
|
|
4472
|
+
return Buffer.from(stored, "base64");
|
|
4473
|
+
}
|
|
4474
|
+
} catch {
|
|
4475
|
+
}
|
|
4476
|
+
}
|
|
4477
|
+
const keyPath = getKeyPath();
|
|
4478
|
+
if (!existsSync11(keyPath)) {
|
|
4479
|
+
return null;
|
|
4480
|
+
}
|
|
4481
|
+
try {
|
|
4482
|
+
const content = await readFile4(keyPath, "utf-8");
|
|
4483
|
+
return Buffer.from(content.trim(), "base64");
|
|
4484
|
+
} catch {
|
|
4485
|
+
return null;
|
|
4486
|
+
}
|
|
4487
|
+
}
|
|
4488
|
+
|
|
4489
|
+
// src/lib/store.ts
|
|
4490
|
+
init_config();
|
|
4491
|
+
init_state_bus();
|
|
4492
|
+
var INIT_MAX_RETRIES = 3;
|
|
4493
|
+
var INIT_RETRY_DELAY_MS = 1e3;
|
|
4494
|
+
function isBusyError2(err) {
|
|
4495
|
+
if (err instanceof Error) {
|
|
4496
|
+
const msg = err.message.toLowerCase();
|
|
4497
|
+
return msg.includes("sqlite_busy") || msg.includes("database is locked");
|
|
4498
|
+
}
|
|
4499
|
+
return false;
|
|
4500
|
+
}
|
|
4501
|
+
async function retryOnBusy2(fn, label) {
|
|
4502
|
+
for (let attempt = 0; attempt <= INIT_MAX_RETRIES; attempt++) {
|
|
4503
|
+
try {
|
|
4504
|
+
return await fn();
|
|
4505
|
+
} catch (err) {
|
|
4506
|
+
if (!isBusyError2(err) || attempt === INIT_MAX_RETRIES) throw err;
|
|
4507
|
+
process.stderr.write(
|
|
4508
|
+
`[store] SQLITE_BUSY during ${label}, retry ${attempt + 1}/${INIT_MAX_RETRIES}
|
|
4509
|
+
`
|
|
4510
|
+
);
|
|
4511
|
+
await new Promise((r) => setTimeout(r, INIT_RETRY_DELAY_MS * (attempt + 1)));
|
|
4512
|
+
}
|
|
4513
|
+
}
|
|
4514
|
+
throw new Error("unreachable");
|
|
4515
|
+
}
|
|
4516
|
+
var _pendingRecords = [];
|
|
4517
|
+
var _batchSize = 20;
|
|
4518
|
+
var _flushIntervalMs = 1e4;
|
|
4519
|
+
var _flushTimer = null;
|
|
4520
|
+
var _flushing = false;
|
|
4521
|
+
var _nextVersion = 1;
|
|
4522
|
+
async function initStore(options) {
|
|
4523
|
+
if (_flushTimer !== null) {
|
|
4524
|
+
clearInterval(_flushTimer);
|
|
4525
|
+
_flushTimer = null;
|
|
4526
|
+
}
|
|
4527
|
+
_pendingRecords = [];
|
|
4528
|
+
_flushing = false;
|
|
4529
|
+
_batchSize = options?.batchSize ?? 20;
|
|
4530
|
+
_flushIntervalMs = options?.flushIntervalMs ?? 1e4;
|
|
4531
|
+
let dbPath = options?.dbPath;
|
|
4532
|
+
if (!dbPath) {
|
|
4533
|
+
const config = await loadConfig();
|
|
4534
|
+
dbPath = config.dbPath;
|
|
4535
|
+
}
|
|
4536
|
+
let masterKey = options?.masterKey ?? null;
|
|
4537
|
+
if (!masterKey) {
|
|
4538
|
+
masterKey = await getMasterKey();
|
|
4539
|
+
if (!masterKey) {
|
|
4540
|
+
throw new Error(
|
|
4541
|
+
"No encryption key found. Run /exe-setup to generate one."
|
|
4542
|
+
);
|
|
4543
|
+
}
|
|
4544
|
+
}
|
|
4545
|
+
const hexKey = masterKey.toString("hex");
|
|
4546
|
+
await initTurso({
|
|
4547
|
+
dbPath,
|
|
4548
|
+
encryptionKey: hexKey
|
|
4549
|
+
});
|
|
4550
|
+
await retryOnBusy2(() => ensureSchema(), "ensureSchema");
|
|
4551
|
+
try {
|
|
4552
|
+
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
4553
|
+
initShardManager2(hexKey);
|
|
4554
|
+
} catch {
|
|
4555
|
+
}
|
|
4556
|
+
const client = getClient();
|
|
4557
|
+
const vResult = await retryOnBusy2(
|
|
4558
|
+
() => client.execute("SELECT MAX(version) as max_v FROM memories"),
|
|
4559
|
+
"version-query"
|
|
4560
|
+
);
|
|
4561
|
+
_nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
4562
|
+
try {
|
|
4563
|
+
const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
|
|
4564
|
+
await loadGlobalProcedures2();
|
|
4565
|
+
} catch {
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
|
|
4569
|
+
// src/bin/exe-dispatch.ts
|
|
1095
4570
|
var employeeName = process.argv[2];
|
|
1096
4571
|
if (!employeeName) {
|
|
1097
4572
|
console.error("Usage: exe-dispatch <employeeName> [projectDir]");
|
|
@@ -1107,5 +4582,23 @@ if (!exeSession) {
|
|
|
1107
4582
|
}));
|
|
1108
4583
|
process.exit(1);
|
|
1109
4584
|
}
|
|
4585
|
+
try {
|
|
4586
|
+
await initStore();
|
|
4587
|
+
await createTaskCore({
|
|
4588
|
+
title: `Dispatch: ${employeeName} (CLI)`,
|
|
4589
|
+
assignedTo: employeeName,
|
|
4590
|
+
assignedBy: "exe",
|
|
4591
|
+
projectName: "exe-os",
|
|
4592
|
+
priority: "p1",
|
|
4593
|
+
context: "Session dispatched via exe-dispatch CLI. Agent will pick up queued tasks via intercom.",
|
|
4594
|
+
baseDir: projectDir,
|
|
4595
|
+
skipDispatch: true
|
|
4596
|
+
});
|
|
4597
|
+
} catch (err) {
|
|
4598
|
+
process.stderr.write(
|
|
4599
|
+
`[exe-dispatch] Task creation failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
|
|
4600
|
+
`
|
|
4601
|
+
);
|
|
4602
|
+
}
|
|
1110
4603
|
var result = ensureEmployee(employeeName, exeSession, projectDir);
|
|
1111
4604
|
console.log(JSON.stringify(result));
|