1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
|
package executor
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/thepeterstone/claudomator/internal/storage"
"github.com/thepeterstone/claudomator/internal/task"
)
// capturingHandler is a slog.Handler that records log records for assertions.
type capturingHandler struct {
mu sync.Mutex
records []slog.Record
}
func (h *capturingHandler) Enabled(_ context.Context, _ slog.Level) bool { return true }
func (h *capturingHandler) Handle(_ context.Context, r slog.Record) error {
h.mu.Lock()
defer h.mu.Unlock()
h.records = append(h.records, r)
return nil
}
func (h *capturingHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return h }
func (h *capturingHandler) WithGroup(name string) slog.Handler { return h }
func (h *capturingHandler) hasMessageContaining(substr string) bool {
h.mu.Lock()
defer h.mu.Unlock()
for _, r := range h.records {
if strings.Contains(r.Message, substr) {
return true
}
}
return false
}
// failingStore wraps a real DB but returns an error for UpdateTaskState calls.
type failingStore struct {
*storage.DB
updateStateErr error
}
func (f *failingStore) UpdateTaskState(id string, newState task.State) error {
return f.updateStateErr
}
// mockRunner implements Runner for testing.
type mockRunner struct {
mu sync.Mutex
calls int
delay time.Duration
err error
exitCode int
onRun func(*task.Task, *storage.Execution) error
}
func (m *mockRunner) Run(ctx context.Context, t *task.Task, e *storage.Execution) error {
m.mu.Lock()
m.calls++
cb := m.onRun
m.mu.Unlock()
if m.delay > 0 {
select {
case <-time.After(m.delay):
case <-ctx.Done():
return ctx.Err()
}
}
if cb != nil {
return cb(t, e)
}
if m.err != nil {
e.ExitCode = m.exitCode
return m.err
}
return nil
}
func (m *mockRunner) callCount() int {
m.mu.Lock()
defer m.mu.Unlock()
return m.calls
}
func testStore(t *testing.T) *storage.DB {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
db, err := storage.Open(dbPath)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
return db
}
func makeTask(id string) *task.Task {
now := time.Now().UTC()
return &task.Task{
ID: id, Name: "Test " + id,
Agent: task.AgentConfig{Type: "claude", Instructions: "test"},
Priority: task.PriorityNormal,
Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
Tags: []string{},
DependsOn: []string{},
State: task.StateQueued,
CreatedAt: now, UpdatedAt: now,
}
}
func TestPickAgent_PrefersLessActiveAgent(t *testing.T) {
status := SystemStatus{
ActiveTasks: map[string]int{"claude": 3, "gemini": 1},
RateLimited: map[string]bool{"claude": false, "gemini": false},
}
if got := pickAgent(status); got != "gemini" {
t.Errorf("expected gemini (fewer active tasks), got %s", got)
}
}
func TestPickAgent_SkipsRateLimitedAgent(t *testing.T) {
status := SystemStatus{
ActiveTasks: map[string]int{"claude": 0, "gemini": 5},
RateLimited: map[string]bool{"claude": true, "gemini": false},
}
if got := pickAgent(status); got != "gemini" {
t.Errorf("expected gemini (claude rate limited), got %s", got)
}
}
func TestPickAgent_FallsBackWhenAllRateLimited(t *testing.T) {
status := SystemStatus{
ActiveTasks: map[string]int{"claude": 2, "gemini": 5},
RateLimited: map[string]bool{"claude": true, "gemini": true},
}
// Falls back to least active regardless of rate limit.
if got := pickAgent(status); got != "claude" {
t.Errorf("expected claude (fewer active tasks among all), got %s", got)
}
}
func TestPickAgent_TieBreakPrefersFirstAlpha(t *testing.T) {
status := SystemStatus{
ActiveTasks: map[string]int{"claude": 2, "gemini": 2},
RateLimited: map[string]bool{"claude": false, "gemini": false},
}
got := pickAgent(status)
if got != "claude" && got != "gemini" {
t.Errorf("unexpected agent %q on tie", got)
}
}
func TestPool_Submit_TopLevel_GoesToReady(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("ps-1") // no ParentTaskID → top-level
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Errorf("expected no error, got: %v", result.Err)
}
if result.Execution.Status != "READY" {
t.Errorf("status: want READY, got %q", result.Execution.Status)
}
got, _ := store.GetTask("ps-1")
if got.State != task.StateReady {
t.Errorf("task state: want READY, got %v", got.State)
}
}
func TestPool_Submit_Subtask_GoesToCompleted(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("sub-1")
tk.ParentTaskID = "parent-99" // subtask
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Errorf("expected no error, got: %v", result.Err)
}
if result.Execution.Status != "COMPLETED" {
t.Errorf("status: want COMPLETED, got %q", result.Execution.Status)
}
got, _ := store.GetTask("sub-1")
if got.State != task.StateCompleted {
t.Errorf("task state: want COMPLETED, got %v", got.State)
}
}
func TestPool_Submit_Failure(t *testing.T) {
store := testStore(t)
runner := &mockRunner{err: fmt.Errorf("boom"), exitCode: 1}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("pf-1")
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
result := <-pool.Results()
if result.Err == nil {
t.Fatal("expected error")
}
if result.Execution.Status != "FAILED" {
t.Errorf("status: want FAILED, got %q", result.Execution.Status)
}
}
// TestPool_UpdateTaskState_DBError_IsLoggedAndResultDelivered verifies that
// when UpdateTaskState returns an error, the error is logged with structured
// context (taskID, state) and the execution result is still sent to resultCh.
func TestPool_UpdateTaskState_DBError_IsLoggedAndResultDelivered(t *testing.T) {
db := testStore(t)
store := &failingStore{DB: db, updateStateErr: fmt.Errorf("db write failed")}
handler := &capturingHandler{}
logger := slog.New(handler)
runner := &mockRunner{err: fmt.Errorf("runner error")}
runners := map[string]Runner{"claude": runner}
pool := NewPool(2, runners, store, logger)
tk := makeTask("dberr-1")
db.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
select {
case result := <-pool.Results():
// Result must still arrive despite the DB error.
if result == nil {
t.Fatal("expected non-nil result")
}
if result.TaskID != tk.ID {
t.Errorf("taskID: want %q, got %q", tk.ID, result.TaskID)
}
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for result — result not delivered despite DB error")
}
if !handler.hasMessageContaining("failed to update task state") {
t.Error("expected 'failed to update task state' log entry, but none found")
}
}
func TestPool_Submit_Timeout(t *testing.T) {
store := testStore(t)
runner := &mockRunner{delay: 5 * time.Second}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("pt-1")
tk.Timeout.Duration = 50 * time.Millisecond
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
result := <-pool.Results()
if result.Execution.Status != "TIMED_OUT" {
t.Errorf("status: want TIMED_OUT, got %q", result.Execution.Status)
}
}
func TestPool_Submit_Cancellation(t *testing.T) {
store := testStore(t)
runner := &mockRunner{delay: 5 * time.Second}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
ctx, cancel := context.WithCancel(context.Background())
tk := makeTask("pc-1")
store.CreateTask(tk)
pool.Submit(ctx, tk)
time.Sleep(20 * time.Millisecond)
cancel()
result := <-pool.Results()
if result.Execution.Status != "CANCELLED" {
t.Errorf("status: want CANCELLED, got %q", result.Execution.Status)
}
}
func TestPool_Cancel_StopsRunningTask(t *testing.T) {
store := testStore(t)
runner := &mockRunner{delay: 5 * time.Second}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("cancel-1")
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
time.Sleep(20 * time.Millisecond) // let goroutine start
if ok := pool.Cancel("cancel-1"); !ok {
t.Fatal("Cancel returned false for a running task")
}
result := <-pool.Results()
if result.Execution.Status != "CANCELLED" {
t.Errorf("status: want CANCELLED, got %q", result.Execution.Status)
}
}
func TestPool_Cancel_UnknownTask_ReturnsFalse(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
if ok := pool.Cancel("nonexistent"); ok {
t.Error("Cancel returned true for unknown task")
}
}
// TestPool_QueuedWhenAtCapacity verifies that Submit enqueues a task rather than
// returning an error when the pool is at capacity. Both tasks should eventually complete.
func TestPool_QueuedWhenAtCapacity(t *testing.T) {
store := testStore(t)
runner := &mockRunner{delay: 100 * time.Millisecond}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(1, runners, store, logger)
tk1 := makeTask("queue-1")
store.CreateTask(tk1)
if err := pool.Submit(context.Background(), tk1); err != nil {
t.Fatalf("first submit: %v", err)
}
// Second submit must succeed (queued) even though pool slot is taken.
tk2 := makeTask("queue-2")
store.CreateTask(tk2)
if err := pool.Submit(context.Background(), tk2); err != nil {
t.Fatalf("second submit: %v — expected task to be queued, not rejected", err)
}
// Both tasks must complete.
for i := 0; i < 2; i++ {
r := <-pool.Results()
if r.Err != nil {
t.Errorf("task %s error: %v", r.TaskID, r.Err)
}
}
}
// logPatherMockRunner is a mockRunner that also implements LogPather,
// and captures the StdoutPath seen when Run() is called.
type logPatherMockRunner struct {
mockRunner
logDir string
capturedPath string
}
func (m *logPatherMockRunner) ExecLogDir(execID string) string {
return filepath.Join(m.logDir, execID)
}
func (m *logPatherMockRunner) Run(ctx context.Context, t *task.Task, e *storage.Execution) error {
m.mu.Lock()
m.capturedPath = e.StdoutPath
m.mu.Unlock()
return m.mockRunner.Run(ctx, t, e)
}
// TestPool_Execute_LogPathsPreSetBeforeRun verifies that when the runner
// implements LogPather, log paths are set on the execution before Run() is
// called — so they land in the DB at CreateExecution time, not just at
// UpdateExecution time.
func TestPool_Execute_LogPathsPreSetBeforeRun(t *testing.T) {
store := testStore(t)
runner := &logPatherMockRunner{logDir: t.TempDir()}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("lp-1")
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
runner.mu.Lock()
captured := runner.capturedPath
runner.mu.Unlock()
if captured == "" {
t.Fatal("StdoutPath was empty when Run() was called; expected pre-set path")
}
if !strings.HasSuffix(captured, "stdout.log") {
t.Errorf("expected stdout.log suffix, got: %s", captured)
}
// Path in the returned execution record should match.
if result.Execution.StdoutPath != captured {
t.Errorf("execution StdoutPath %q != captured %q", result.Execution.StdoutPath, captured)
}
}
// TestPool_Execute_NoLogPather_PathsEmptyBeforeRun verifies that a runner
// without LogPather doesn't panic and paths remain empty until Run() sets them.
func TestPool_Execute_NoLogPather_PathsEmptyBeforeRun(t *testing.T) {
store := testStore(t)
runner := &mockRunner{} // does NOT implement LogPather
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("nolp-1")
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Fatalf("unexpected error: %v", result.Err)
}
}
func TestPool_ConcurrentExecution(t *testing.T) {
store := testStore(t)
runner := &mockRunner{delay: 50 * time.Millisecond}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(3, runners, store, logger)
for i := 0; i < 3; i++ {
tk := makeTask(fmt.Sprintf("cc-%d", i))
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit %d: %v", i, err)
}
}
for i := 0; i < 3; i++ {
result := <-pool.Results()
if result.Execution.Status != "READY" {
t.Errorf("task %s: want READY, got %q", result.TaskID, result.Execution.Status)
}
}
if runner.callCount() != 3 {
t.Errorf("calls: want 3, got %d", runner.callCount())
}
}
func TestWithFailureHistory_NoFailures_ReturnsUnchanged(t *testing.T) {
tk := makeTask("no-fail")
result := withFailureHistory(tk, nil, nil)
if result != tk {
t.Error("expected same pointer when no prior executions")
}
}
func TestWithFailureHistory_WithError_ReturnsUnchanged(t *testing.T) {
tk := makeTask("err-case")
result := withFailureHistory(tk, nil, fmt.Errorf("db error"))
if result != tk {
t.Error("expected same pointer when ListExecutions errors")
}
}
func TestWithFailureHistory_InjectsFailedHistory(t *testing.T) {
tk := makeTask("with-fail")
tk.Agent.Instructions = "do the work"
execs := []*storage.Execution{
{ID: "e1", Status: "FAILED", ErrorMsg: "sandbox: uncommitted changes", StartTime: time.Now()},
{ID: "e2", Status: "COMPLETED", ErrorMsg: "", StartTime: time.Now()}, // not a failure, should be ignored
}
result := withFailureHistory(tk, execs, nil)
if result == tk {
t.Fatal("expected a new task copy, got same pointer")
}
if !strings.Contains(result.Agent.SystemPromptAppend, "Prior Attempt History") {
t.Errorf("expected history header in SystemPromptAppend, got: %q", result.Agent.SystemPromptAppend)
}
if !strings.Contains(result.Agent.SystemPromptAppend, "sandbox: uncommitted changes") {
t.Errorf("expected error message in SystemPromptAppend, got: %q", result.Agent.SystemPromptAppend)
}
// COMPLETED execution should not appear
if strings.Contains(result.Agent.SystemPromptAppend, "e2") {
t.Errorf("COMPLETED execution should not appear in history")
}
// Original instructions unchanged
if result.Agent.Instructions != "do the work" {
t.Errorf("instructions should be unchanged, got: %q", result.Agent.Instructions)
}
}
func TestWithFailureHistory_PreservesExistingSystemPrompt(t *testing.T) {
tk := makeTask("with-prompt")
tk.Agent.SystemPromptAppend = "existing prompt"
execs := []*storage.Execution{
{ID: "e1", Status: "FAILED", ErrorMsg: "some error", StartTime: time.Now()},
}
result := withFailureHistory(tk, execs, nil)
if !strings.Contains(result.Agent.SystemPromptAppend, "Prior Attempt History") {
t.Error("expected history prepended")
}
if !strings.Contains(result.Agent.SystemPromptAppend, "existing prompt") {
t.Error("expected existing prompt preserved")
}
// History must come BEFORE the existing prompt
histIdx := strings.Index(result.Agent.SystemPromptAppend, "Prior Attempt History")
existIdx := strings.Index(result.Agent.SystemPromptAppend, "existing prompt")
if histIdx > existIdx {
t.Error("history should be prepended before existing system prompt")
}
}
func TestPool_FailureHistoryInjectedOnRetry(t *testing.T) {
store := testStore(t)
var capturedPrompt string
runner := &mockRunner{}
runner.onRun = func(t *task.Task, _ *storage.Execution) error {
capturedPrompt = t.Agent.SystemPromptAppend
return nil
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("retry-hist")
store.CreateTask(tk)
// Simulate a prior failed execution.
store.CreateExecution(&storage.Execution{
ID: "prior-exec", TaskID: tk.ID,
StartTime: time.Now(), EndTime: time.Now(),
Status: "FAILED", ErrorMsg: "prior failure reason",
})
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
<-pool.Results()
if !strings.Contains(capturedPrompt, "prior failure reason") {
t.Errorf("expected prior failure in system prompt, got: %q", capturedPrompt)
}
}
func TestPool_RecoverStaleRunning(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
// Create a task already in RUNNING state (simulating a crashed server).
tk := makeTask("stale-1")
tk.State = task.StateRunning
store.CreateTask(tk)
// Add an open execution record (no end time, status RUNNING).
store.CreateExecution(&storage.Execution{
ID: "exec-stale-1", TaskID: tk.ID,
StartTime: time.Now().Add(-5 * time.Minute),
Status: "RUNNING",
})
pool.RecoverStaleRunning(context.Background())
// Execution record should be closed as FAILED.
execs, _ := store.ListExecutions(tk.ID)
var failedExec *storage.Execution
for _, e := range execs {
if e.ID == "exec-stale-1" {
failedExec = e
break
}
}
if failedExec == nil || failedExec.Status != "FAILED" {
t.Errorf("execution status: want FAILED, got %+v", execs)
}
if failedExec.ErrorMsg == "" {
t.Error("expected non-empty error message on recovered execution")
}
// Task should be re-queued for retry and complete.
select {
case result := <-pool.Results():
if result.TaskID != tk.ID {
t.Errorf("unexpected task in results: %s", result.TaskID)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for stale RUNNING task to be re-queued and run")
}
recovered, err := store.GetTask(tk.ID)
if err != nil {
t.Fatalf("get task: %v", err)
}
// Top-level tasks (no parent) go to READY after a successful run.
if recovered.State != task.StateReady {
t.Errorf("state after re-queue: want READY, got %q", recovered.State)
}
}
func TestPool_RecoverStaleQueued_ResubmitsToPool(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": runner}, store, logger)
// Create a task already in QUEUED state (persisted from before a server restart).
tk := makeTask("stale-queued-1")
tk.State = task.StateQueued
store.CreateTask(tk)
pool.RecoverStaleQueued(context.Background())
// Wait for the pool to pick it up and complete it.
select {
case result := <-pool.Results():
if result.TaskID != tk.ID {
t.Errorf("unexpected task in results: %s", result.TaskID)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for stale QUEUED task to complete")
}
got, err := store.GetTask(tk.ID)
if err != nil {
t.Fatalf("get task: %v", err)
}
if got.State != task.StateCompleted && got.State != task.StateReady {
t.Errorf("state: want COMPLETED or READY, got %q", got.State)
}
if runner.callCount() != 1 {
t.Errorf("runner call count: want 1, got %d", runner.callCount())
}
}
func TestPool_RecoverStaleQueued_SkipsNonQueuedTasks(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": runner}, store, logger)
// PENDING task should NOT be resubmitted.
tk := makeTask("pending-1")
tk.State = task.StatePending
store.CreateTask(tk)
pool.RecoverStaleQueued(context.Background())
time.Sleep(50 * time.Millisecond)
if runner.callCount() != 0 {
t.Errorf("runner should not have been called for PENDING task, got %d calls", runner.callCount())
}
}
func TestPool_RecoverStaleBlocked_UnblocksWhenAllSubtasksCompleted(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
// Parent task stuck in BLOCKED state (server restarted after subtasks completed).
parent := makeTask("parent-stale-blocked")
parent.State = task.StateBlocked
store.CreateTask(parent)
// All subtasks completed.
for i := 0; i < 3; i++ {
sub := makeTask(fmt.Sprintf("sub-%d", i))
sub.ParentTaskID = parent.ID
sub.State = task.StateCompleted
store.CreateTask(sub)
}
pool.RecoverStaleBlocked()
got, err := store.GetTask(parent.ID)
if err != nil {
t.Fatalf("get task: %v", err)
}
if got.State != task.StateReady {
t.Errorf("parent state: want READY, got %q", got.State)
}
}
func TestPool_RecoverStaleBlocked_KeepsBlockedWhenSubtaskIncomplete(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
parent := makeTask("parent-still-blocked")
parent.State = task.StateBlocked
store.CreateTask(parent)
sub1 := makeTask("sub-done")
sub1.ParentTaskID = parent.ID
sub1.State = task.StateCompleted
store.CreateTask(sub1)
sub2 := makeTask("sub-running")
sub2.ParentTaskID = parent.ID
sub2.State = task.StateRunning
store.CreateTask(sub2)
pool.RecoverStaleBlocked()
got, err := store.GetTask(parent.ID)
if err != nil {
t.Fatalf("get task: %v", err)
}
if got.State != task.StateBlocked {
t.Errorf("parent state: want BLOCKED, got %q", got.State)
}
}
func TestPool_ActivePerAgent_DeletesZeroEntries(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner, "gemini": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("apa-1")
store.CreateTask(tk) // Agent.Type = "claude"
pool.Submit(context.Background(), tk)
<-pool.Results()
pool.mu.Lock()
_, exists := pool.activePerAgent["claude"]
pool.mu.Unlock()
if exists {
t.Error("activePerAgent should not have a zero-count entry for claude after task completes")
}
}
func TestPool_RateLimited_StaleEntryCleaned(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Inject a stale rate-limit entry (deadline already passed).
pool.mu.Lock()
pool.rateLimited["claude"] = time.Now().Add(-1 * time.Minute)
pool.mu.Unlock()
// Submit a task — the execute() path reads rateLimited during classification.
tk := makeTask("rl-stale-1")
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
<-pool.Results()
pool.mu.Lock()
_, exists := pool.rateLimited["claude"]
pool.mu.Unlock()
if exists {
t.Error("stale rate-limit entry should be deleted after deadline passes")
}
}
// TestPool_Submit_TopLevel_NoSubtasks_GoesReady verifies that a top-level task
// with no subtasks still transitions to READY after successful execution.
func TestPool_Submit_TopLevel_NoSubtasks_GoesReady(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("no-subtasks-1") // no ParentTaskID, no subtasks
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Errorf("expected no error, got: %v", result.Err)
}
if result.Execution.Status != "READY" {
t.Errorf("status: want READY, got %q", result.Execution.Status)
}
got, _ := store.GetTask(tk.ID)
if got.State != task.StateReady {
t.Errorf("task state: want READY, got %v", got.State)
}
}
// TestPool_Submit_TopLevel_WithSubtasks_GoesBlocked verifies that when a
// top-level task finishes successfully but has subtasks, it transitions to
// BLOCKED (waiting for subtasks) rather than READY.
func TestPool_Submit_TopLevel_WithSubtasks_GoesBlocked(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
parent := makeTask("parent-with-subtasks")
store.CreateTask(parent)
// Create a subtask in the store but do NOT submit it.
sub := makeTask("sub-of-parent")
sub.ParentTaskID = parent.ID
store.CreateTask(sub)
if err := pool.Submit(context.Background(), parent); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Errorf("expected no error, got: %v", result.Err)
}
if result.Execution.Status != "BLOCKED" {
t.Errorf("status: want BLOCKED, got %q", result.Execution.Status)
}
got, _ := store.GetTask(parent.ID)
if got.State != task.StateBlocked {
t.Errorf("task state: want BLOCKED, got %v", got.State)
}
}
// TestPool_Submit_LastSubtask_UnblocksParent verifies that when the last
// remaining subtask completes, the parent task transitions from BLOCKED to READY.
func TestPool_Submit_LastSubtask_UnblocksParent(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Parent starts BLOCKED (waiting for subtasks).
parent := makeTask("unblock-parent-1")
parent.State = task.StateBlocked
store.CreateTask(parent)
// First subtask already completed.
sub1 := makeTask("unblock-sub-1a")
sub1.ParentTaskID = parent.ID
sub1.State = task.StateCompleted
store.CreateTask(sub1)
// Second (last) subtask — the one we submit.
sub2 := makeTask("unblock-sub-1b")
sub2.ParentTaskID = parent.ID
store.CreateTask(sub2)
if err := pool.Submit(context.Background(), sub2); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Errorf("expected no error, got: %v", result.Err)
}
if result.Execution.Status != "COMPLETED" {
t.Errorf("subtask status: want COMPLETED, got %q", result.Execution.Status)
}
// Parent must now be READY.
got, err := store.GetTask(parent.ID)
if err != nil {
t.Fatalf("get parent: %v", err)
}
if got.State != task.StateReady {
t.Errorf("parent state: want READY, got %v", got.State)
}
}
// TestPool_Submit_NotLastSubtask_ParentStaysBlocked verifies that when a subtask
// completes but another sibling subtask is still running, the parent stays BLOCKED.
func TestPool_Submit_NotLastSubtask_ParentStaysBlocked(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
parent := makeTask("blocked-parent-2")
parent.State = task.StateBlocked
store.CreateTask(parent)
// First subtask still RUNNING — not done yet.
sub1 := makeTask("blocked-sub-2a")
sub1.ParentTaskID = parent.ID
sub1.State = task.StateRunning
store.CreateTask(sub1)
// Second subtask — the one we submit.
sub2 := makeTask("blocked-sub-2b")
sub2.ParentTaskID = parent.ID
store.CreateTask(sub2)
if err := pool.Submit(context.Background(), sub2); err != nil {
t.Fatalf("submit: %v", err)
}
<-pool.Results()
// Parent must remain BLOCKED because sub1 is still RUNNING.
got, err := store.GetTask(parent.ID)
if err != nil {
t.Fatalf("get parent: %v", err)
}
if got.State != task.StateBlocked {
t.Errorf("parent state: want BLOCKED, got %v", got.State)
}
}
// TestPool_Submit_ParentNotBlocked_NoTransition verifies that completing a subtask
// does not change the parent's state when the parent is not BLOCKED.
func TestPool_Submit_ParentNotBlocked_NoTransition(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Parent is already READY (not BLOCKED).
parent := makeTask("ready-parent-3")
parent.State = task.StateReady
store.CreateTask(parent)
sub1 := makeTask("ready-sub-3a")
sub1.ParentTaskID = parent.ID
store.CreateTask(sub1)
if err := pool.Submit(context.Background(), sub1); err != nil {
t.Fatalf("submit: %v", err)
}
<-pool.Results()
// Parent must remain READY — no spurious state transition.
got, err := store.GetTask(parent.ID)
if err != nil {
t.Fatalf("get parent: %v", err)
}
if got.State != task.StateReady {
t.Errorf("parent state: want READY, got %v", got.State)
}
}
// minimalMockStore is a standalone Store implementation for unit-testing Pool
// methods that do not require a real SQLite database.
type minimalMockStore struct {
mu sync.Mutex
tasks map[string]*task.Task
executions map[string]*storage.Execution
stateUpdates []struct{ id string; state task.State }
questionUpdates []string
changestatCalls []struct {
execID string
stats *task.Changestats
}
subtasksFunc func(parentID string) ([]*task.Task, error)
updateExecErr error
updateStateErr error
}
func newMinimalMockStore() *minimalMockStore {
return &minimalMockStore{
tasks: make(map[string]*task.Task),
executions: make(map[string]*storage.Execution),
}
}
func (m *minimalMockStore) GetTask(id string) (*task.Task, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tasks[id]
if !ok {
return nil, fmt.Errorf("task %q not found", id)
}
return t, nil
}
func (m *minimalMockStore) ListTasks(_ storage.TaskFilter) ([]*task.Task, error) { return nil, nil }
func (m *minimalMockStore) ListSubtasks(parentID string) ([]*task.Task, error) {
if m.subtasksFunc != nil {
return m.subtasksFunc(parentID)
}
return nil, nil
}
func (m *minimalMockStore) ListExecutions(_ string) ([]*storage.Execution, error) { return nil, nil }
func (m *minimalMockStore) CreateExecution(e *storage.Execution) error { return nil }
func (m *minimalMockStore) UpdateExecution(e *storage.Execution) error {
return m.updateExecErr
}
func (m *minimalMockStore) UpdateTaskState(id string, newState task.State) error {
if m.updateStateErr != nil {
return m.updateStateErr
}
m.mu.Lock()
m.stateUpdates = append(m.stateUpdates, struct{ id string; state task.State }{id, newState})
if t, ok := m.tasks[id]; ok {
t.State = newState
}
m.mu.Unlock()
return nil
}
func (m *minimalMockStore) UpdateTaskQuestion(taskID, questionJSON string) error {
m.mu.Lock()
m.questionUpdates = append(m.questionUpdates, questionJSON)
m.mu.Unlock()
return nil
}
func (m *minimalMockStore) UpdateTaskSummary(taskID, summary string) error { return nil }
func (m *minimalMockStore) AppendTaskInteraction(taskID string, _ task.Interaction) error {
return nil
}
func (m *minimalMockStore) UpdateTaskAgent(id string, agent task.AgentConfig) error { return nil }
func (m *minimalMockStore) UpdateExecutionChangestats(execID string, stats *task.Changestats) error {
m.mu.Lock()
m.changestatCalls = append(m.changestatCalls, struct {
execID string
stats *task.Changestats
}{execID, stats})
m.mu.Unlock()
return nil
}
func (m *minimalMockStore) RecordAgentEvent(_ storage.AgentEvent) error { return nil }
func (m *minimalMockStore) GetProject(_ string) (*task.Project, error) { return nil, nil }
func (m *minimalMockStore) GetStory(_ string) (*task.Story, error) { return nil, nil }
func (m *minimalMockStore) ListTasksByStory(_ string) ([]*task.Task, error) { return nil, nil }
func (m *minimalMockStore) UpdateStoryStatus(_ string, _ task.StoryState) error { return nil }
func (m *minimalMockStore) CreateTask(_ *task.Task) error { return nil }
func (m *minimalMockStore) lastStateUpdate() (string, task.State, bool) {
m.mu.Lock()
defer m.mu.Unlock()
if len(m.stateUpdates) == 0 {
return "", "", false
}
u := m.stateUpdates[len(m.stateUpdates)-1]
return u.id, u.state, true
}
func newPoolWithMockStore(store Store) *Pool {
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
return &Pool{
maxConcurrent: 2,
maxPerAgent: 1,
runners: map[string]Runner{"claude": &mockRunner{}},
store: store,
logger: logger,
activePerAgent: make(map[string]int),
rateLimited: make(map[string]time.Time),
cancels: make(map[string]context.CancelFunc),
consecutiveFailures: make(map[string]int),
drained: make(map[string]bool),
resultCh: make(chan *Result, 4),
workCh: make(chan workItem, 4),
doneCh: make(chan struct{}, 2),
Questions: NewQuestionRegistry(),
}
}
// TestHandleRunResult_SharedPath verifies that handleRunResult correctly
// classifies runner errors and transitions task state via the store.
func TestHandleRunResult_SharedPath(t *testing.T) {
t.Run("generic error sets FAILED", func(t *testing.T) {
store := newMinimalMockStore()
pool := newPoolWithMockStore(store)
tk := makeTask("hrr-fail")
store.tasks[tk.ID] = tk
exec := &storage.Execution{ID: "e1", TaskID: tk.ID, Status: "RUNNING"}
ctx := context.Background()
pool.handleRunResult(ctx, tk, exec, fmt.Errorf("something broke"), "claude")
if exec.Status != "FAILED" {
t.Errorf("exec.Status: want FAILED, got %q", exec.Status)
}
if exec.ErrorMsg != "something broke" {
t.Errorf("exec.ErrorMsg: want %q, got %q", "something broke", exec.ErrorMsg)
}
_, state, ok := store.lastStateUpdate()
if !ok || state != task.StateFailed {
t.Errorf("expected UpdateTaskState(FAILED), got state=%v ok=%v", state, ok)
}
result := <-pool.resultCh
if result.Err == nil || result.Execution.Status != "FAILED" {
t.Errorf("unexpected result: %+v", result)
}
})
t.Run("nil error top-level no subtasks sets READY", func(t *testing.T) {
store := newMinimalMockStore()
pool := newPoolWithMockStore(store)
tk := makeTask("hrr-ready")
store.tasks[tk.ID] = tk
exec := &storage.Execution{ID: "e2", TaskID: tk.ID, Status: "RUNNING"}
ctx := context.Background()
pool.handleRunResult(ctx, tk, exec, nil, "claude")
if exec.Status != "READY" {
t.Errorf("exec.Status: want READY, got %q", exec.Status)
}
_, state, ok := store.lastStateUpdate()
if !ok || state != task.StateReady {
t.Errorf("expected UpdateTaskState(READY), got state=%v ok=%v", state, ok)
}
result := <-pool.resultCh
if result.Err != nil || result.Execution.Status != "READY" {
t.Errorf("unexpected result: %+v", result)
}
})
t.Run("nil error subtask sets COMPLETED", func(t *testing.T) {
store := newMinimalMockStore()
pool := newPoolWithMockStore(store)
parent := makeTask("hrr-parent")
parent.State = task.StateBlocked
store.tasks[parent.ID] = parent
tk := makeTask("hrr-sub")
tk.ParentTaskID = parent.ID
store.tasks[tk.ID] = tk
exec := &storage.Execution{ID: "e3", TaskID: tk.ID, Status: "RUNNING"}
ctx := context.Background()
pool.handleRunResult(ctx, tk, exec, nil, "claude")
if exec.Status != "COMPLETED" {
t.Errorf("exec.Status: want COMPLETED, got %q", exec.Status)
}
result := <-pool.resultCh
if result.Err != nil || result.Execution.Status != "COMPLETED" {
t.Errorf("unexpected result: %+v", result)
}
})
t.Run("timeout sets TIMED_OUT", func(t *testing.T) {
store := newMinimalMockStore()
pool := newPoolWithMockStore(store)
tk := makeTask("hrr-timeout")
store.tasks[tk.ID] = tk
exec := &storage.Execution{ID: "e4", TaskID: tk.ID, Status: "RUNNING"}
ctx, cancel := context.WithCancel(context.Background())
cancel() // make ctx.Err() == context.Canceled
// Simulate deadline exceeded by using a deadline-exceeded context.
dctx, dcancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer dcancel()
pool.handleRunResult(dctx, tk, exec, context.DeadlineExceeded, "claude")
if exec.Status != "TIMED_OUT" {
t.Errorf("exec.Status: want TIMED_OUT, got %q", exec.Status)
}
_ = ctx
<-pool.resultCh
})
}
// TestPool_LoadBalancing_OverridesAgentType verifies that load balancing picks
// from registered runners, overriding any pre-set Agent.Type on the task.
func TestPool_LoadBalancing_OverridesAgentType(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Task has a non-existent agent type; load balancing should route to "claude".
tk := makeTask("lb-override")
tk.Agent.Type = "super-ai"
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Fatalf("expected success (load balancing overrides agent type), got: %v", result.Err)
}
if runner.callCount() != 1 {
t.Errorf("expected claude runner to be called once, got %d", runner.callCount())
}
}
// TestPool_SpecificAgent_SkipsLoadBalancing verifies that if a specific
// registered agent is requested (claude or gemini), it is used directly
// and load balancing (pickAgent) is skipped.
func TestPool_SpecificAgent_SkipsLoadBalancing(t *testing.T) {
store := testStore(t)
claudeRunner := &mockRunner{}
geminiRunner := &mockRunner{}
runners := map[string]Runner{
"claude": claudeRunner,
"gemini": geminiRunner,
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(4, runners, store, logger)
// Raise per-agent limit so the concurrency gate doesn't interfere with this test.
// The injected activePerAgent is only to make pickAgent prefer "claude",
// verifying that explicit agent type bypasses load balancing.
pool.maxPerAgent = 10
// Inject 2 active tasks for gemini, 0 for claude.
// pickAgent would normally pick "claude".
pool.mu.Lock()
pool.activePerAgent["gemini"] = 2
pool.mu.Unlock()
tk := makeTask("specific-gemini")
tk.Agent.Type = "gemini"
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
<-pool.Results()
if geminiRunner.callCount() != 1 {
t.Errorf("expected gemini runner to be called once, got %d", geminiRunner.callCount())
}
if claudeRunner.callCount() != 0 {
t.Errorf("expected claude runner to NOT be called, got %d", claudeRunner.callCount())
}
}
// TestPool_SpecificAgent_PersistsToDB verifies that if a specific agent
// is requested, it is persisted to the database before the task runs.
func TestPool_SpecificAgent_PersistsToDB(t *testing.T) {
store := testStore(t)
geminiRunner := &mockRunner{}
runners := map[string]Runner{
"gemini": geminiRunner,
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(4, runners, store, logger)
tk := makeTask("persist-gemini")
tk.Agent.Type = "gemini"
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
<-pool.Results()
// Check the task in the database.
reloaded, err := store.GetTask(tk.ID)
if err != nil {
t.Fatalf("get task: %v", err)
}
if reloaded.Agent.Type != "gemini" {
t.Errorf("expected agent type gemini in DB, got %q", reloaded.Agent.Type)
}
}
// TestExecute_ExtractAndStoreChangestats verifies that when the execution stdout
// contains a git diff --stat summary line, the changestats are parsed and stored.
func TestExecute_ExtractAndStoreChangestats(t *testing.T) {
store := testStore(t)
logDir := t.TempDir()
runner := &logPatherMockRunner{logDir: logDir}
runner.onRun = func(tk *task.Task, e *storage.Execution) error {
if err := os.MkdirAll(filepath.Dir(e.StdoutPath), 0755); err != nil {
return err
}
content := "some output\n5 files changed, 127 insertions(+), 43 deletions(-)\n"
return os.WriteFile(e.StdoutPath, []byte(content), 0644)
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("cs-extract-1")
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Fatalf("unexpected error: %v", result.Err)
}
execs, err := store.ListExecutions(tk.ID)
if err != nil {
t.Fatalf("list executions: %v", err)
}
if len(execs) == 0 {
t.Fatal("no executions found")
}
cs := execs[0].Changestats
if cs == nil {
t.Fatal("expected changestats to be populated, got nil")
}
if cs.FilesChanged != 5 {
t.Errorf("FilesChanged: want 5, got %d", cs.FilesChanged)
}
if cs.LinesAdded != 127 {
t.Errorf("LinesAdded: want 127, got %d", cs.LinesAdded)
}
if cs.LinesRemoved != 43 {
t.Errorf("LinesRemoved: want 43, got %d", cs.LinesRemoved)
}
}
// TestExecute_NoChangestats verifies that when execution output contains no git
// diff stat line, changestats are not stored (remain nil).
func TestExecute_NoChangestats(t *testing.T) {
store := testStore(t)
logDir := t.TempDir()
runner := &logPatherMockRunner{logDir: logDir}
runner.onRun = func(tk *task.Task, e *storage.Execution) error {
if err := os.MkdirAll(filepath.Dir(e.StdoutPath), 0755); err != nil {
return err
}
return os.WriteFile(e.StdoutPath, []byte("no git output here\n"), 0644)
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("cs-none-1")
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Fatalf("unexpected error: %v", result.Err)
}
execs, err := store.ListExecutions(tk.ID)
if err != nil {
t.Fatalf("list executions: %v", err)
}
if len(execs) == 0 {
t.Fatal("no executions found")
}
if execs[0].Changestats != nil {
t.Errorf("expected changestats to be nil for output with no git stats, got %+v", execs[0].Changestats)
}
}
// TestExecute_MalformedChangestats verifies that malformed git-stat-like output
// does not produce changestats (parser returns nil, nothing is stored).
func TestExecute_MalformedChangestats(t *testing.T) {
store := testStore(t)
logDir := t.TempDir()
runner := &logPatherMockRunner{logDir: logDir}
runner.onRun = func(tk *task.Task, e *storage.Execution) error {
if err := os.MkdirAll(filepath.Dir(e.StdoutPath), 0755); err != nil {
return err
}
// Looks like a git stat line but doesn't match the regex.
return os.WriteFile(e.StdoutPath, []byte("lots of cheese changed, many insertions\n"), 0644)
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk := makeTask("cs-malformed-1")
store.CreateTask(tk)
if err := pool.Submit(context.Background(), tk); err != nil {
t.Fatalf("submit: %v", err)
}
result := <-pool.Results()
if result.Err != nil {
t.Fatalf("unexpected error: %v", result.Err)
}
execs, err := store.ListExecutions(tk.ID)
if err != nil {
t.Fatalf("list executions: %v", err)
}
if len(execs) == 0 {
t.Fatal("no executions found")
}
if execs[0].Changestats != nil {
t.Errorf("expected nil changestats for malformed output, got %+v", execs[0].Changestats)
}
}
func TestPool_MaxPerAgent_BlocksSecondTask(t *testing.T) {
store := testStore(t)
var mu sync.Mutex
concurrentRuns := 0
maxConcurrent := 0
runner := &mockRunner{
delay: 100 * time.Millisecond,
onRun: func(tk *task.Task, e *storage.Execution) error {
mu.Lock()
concurrentRuns++
if concurrentRuns > maxConcurrent {
maxConcurrent = concurrentRuns
}
mu.Unlock()
time.Sleep(100 * time.Millisecond)
mu.Lock()
concurrentRuns--
mu.Unlock()
return nil
},
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger) // pool size 2, but maxPerAgent=1
pool.requeueDelay = 50 * time.Millisecond // speed up test
tk1 := makeTask("mpa-1")
tk2 := makeTask("mpa-2")
store.CreateTask(tk1)
store.CreateTask(tk2)
pool.Submit(context.Background(), tk1)
pool.Submit(context.Background(), tk2)
for i := 0; i < 2; i++ {
select {
case <-pool.Results():
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for result")
}
}
mu.Lock()
got := maxConcurrent
mu.Unlock()
if got > 1 {
t.Errorf("maxPerAgent=1 violated: %d claude tasks ran concurrently", got)
}
}
func TestPool_MaxPerAgent_AllowsDifferentAgents(t *testing.T) {
store := testStore(t)
var mu sync.Mutex
concurrentRuns := 0
maxConcurrent := 0
makeSlowRunner := func() *mockRunner {
return &mockRunner{
onRun: func(tk *task.Task, e *storage.Execution) error {
mu.Lock()
concurrentRuns++
if concurrentRuns > maxConcurrent {
maxConcurrent = concurrentRuns
}
mu.Unlock()
time.Sleep(80 * time.Millisecond)
mu.Lock()
concurrentRuns--
mu.Unlock()
return nil
},
}
}
runners := map[string]Runner{
"claude": makeSlowRunner(),
"gemini": makeSlowRunner(),
}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
tk1 := makeTask("da-1")
tk1.Agent.Type = "claude"
tk2 := makeTask("da-2")
tk2.Agent.Type = "gemini"
store.CreateTask(tk1)
store.CreateTask(tk2)
pool.Submit(context.Background(), tk1)
pool.Submit(context.Background(), tk2)
for i := 0; i < 2; i++ {
select {
case <-pool.Results():
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for result")
}
}
mu.Lock()
got := maxConcurrent
mu.Unlock()
if got < 2 {
t.Errorf("different agents should run concurrently; max concurrent was %d", got)
}
}
func TestPool_ConsecutiveFailures_DrainAtTwo(t *testing.T) {
store := testStore(t)
runner := &mockRunner{err: fmt.Errorf("boom")}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Submit two failing tasks
for _, id := range []string{"cf-1", "cf-2"} {
tk := makeTask(id)
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
<-pool.Results() // drain
}
pool.mu.Lock()
drained := pool.drained["claude"]
failures := pool.consecutiveFailures["claude"]
pool.mu.Unlock()
if !drained {
t.Error("expected claude to be drained after 2 consecutive failures")
}
if failures < 2 {
t.Errorf("expected consecutiveFailures >= 2, got %d", failures)
}
// The second task should have a drain question set
tk2, err := store.GetTask("cf-2")
if err != nil {
t.Fatalf("GetTask: %v", err)
}
if tk2.QuestionJSON == "" {
t.Error("expected drain question to be set on task after drain")
}
}
func TestPool_ConsecutiveFailures_ResetOnSuccess(t *testing.T) {
store := testStore(t)
callCount := 0
runner := &mockRunner{
onRun: func(tk *task.Task, e *storage.Execution) error {
callCount++
if callCount == 1 {
return fmt.Errorf("first failure")
}
return nil // second call succeeds
},
}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// First task fails
tk1 := makeTask("rs-1")
store.CreateTask(tk1)
pool.Submit(context.Background(), tk1)
<-pool.Results()
pool.mu.Lock()
failsBefore := pool.consecutiveFailures["claude"]
pool.mu.Unlock()
if failsBefore != 1 {
t.Errorf("expected 1 failure after first task, got %d", failsBefore)
}
// Second task succeeds
tk2 := makeTask("rs-2")
store.CreateTask(tk2)
pool.Submit(context.Background(), tk2)
<-pool.Results()
pool.mu.Lock()
failsAfter := pool.consecutiveFailures["claude"]
isDrained := pool.drained["claude"]
pool.mu.Unlock()
if failsAfter != 0 {
t.Errorf("expected consecutiveFailures reset to 0 after success, got %d", failsAfter)
}
if isDrained {
t.Error("expected drained to be false after success")
}
}
func TestPool_CheckStoryCompletion_AllComplete(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
// Create a story in IN_PROGRESS state.
now := time.Now().UTC()
story := &task.Story{
ID: "story-comp-1",
Name: "Completion Test",
Status: task.StoryInProgress,
CreatedAt: now,
UpdatedAt: now,
}
if err := store.CreateStory(story); err != nil {
t.Fatalf("CreateStory: %v", err)
}
// Create two story tasks and drive them through valid transitions to COMPLETED.
for i, id := range []string{"sctask-1", "sctask-2"} {
tk := makeTask(id)
tk.StoryID = "story-comp-1"
tk.ParentTaskID = "fake-parent" // so it goes to COMPLETED
tk.State = task.StatePending
if err := store.CreateTask(tk); err != nil {
t.Fatalf("CreateTask %d: %v", i, err)
}
for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateCompleted} {
if err := store.UpdateTaskState(id, s); err != nil {
t.Fatalf("UpdateTaskState %s → %s: %v", id, s, err)
}
}
}
pool.checkStoryCompletion(context.Background(), "story-comp-1")
got, err := store.GetStory("story-comp-1")
if err != nil {
t.Fatalf("GetStory: %v", err)
}
if got.Status != task.StoryShippable {
t.Errorf("story status: want SHIPPABLE, got %v", got.Status)
}
}
func TestPool_CheckStoryCompletion_PartialComplete(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
now := time.Now().UTC()
story := &task.Story{
ID: "story-partial-1",
Name: "Partial Test",
Status: task.StoryInProgress,
CreatedAt: now,
UpdatedAt: now,
}
if err := store.CreateStory(story); err != nil {
t.Fatalf("CreateStory: %v", err)
}
// First task driven to COMPLETED.
tk1 := makeTask("sptask-1")
tk1.StoryID = "story-partial-1"
tk1.ParentTaskID = "fake-parent"
store.CreateTask(tk1)
for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateCompleted} {
store.UpdateTaskState("sptask-1", s)
}
// Second task still in PENDING (not done).
tk2 := makeTask("sptask-2")
tk2.StoryID = "story-partial-1"
tk2.ParentTaskID = "fake-parent"
store.CreateTask(tk2)
pool.checkStoryCompletion(context.Background(), "story-partial-1")
got, err := store.GetStory("story-partial-1")
if err != nil {
t.Fatalf("GetStory: %v", err)
}
if got.Status != task.StoryInProgress {
t.Errorf("story status: want IN_PROGRESS (no transition), got %v", got.Status)
}
}
func TestPool_Undrain_ResumesExecution(t *testing.T) {
store := testStore(t)
// Force drain state
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
pool.mu.Lock()
pool.drained["claude"] = true
pool.consecutiveFailures["claude"] = 3
pool.mu.Unlock()
// Undrain
pool.UndrainingAgent("claude")
pool.mu.Lock()
drained := pool.drained["claude"]
failures := pool.consecutiveFailures["claude"]
pool.mu.Unlock()
if drained {
t.Error("expected drained=false after UndrainingAgent")
}
if failures != 0 {
t.Errorf("expected consecutiveFailures=0 after UndrainingAgent, got %d", failures)
}
// Verify a task can now run
tk := makeTask("undrain-1")
store.CreateTask(tk)
pool.Submit(context.Background(), tk)
select {
case result := <-pool.Results():
if result.Err != nil {
t.Errorf("unexpected error after undrain: %v", result.Err)
}
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for task after undrain")
}
}
func TestPool_StoryDeploy_RunsDeployScript(t *testing.T) {
store := testStore(t)
runner := &mockRunner{}
runners := map[string]Runner{"claude": runner}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, runners, store, logger)
// Create a deploy script that writes a marker file.
tmpDir := t.TempDir()
markerFile := filepath.Join(tmpDir, "deployed.marker")
scriptPath := filepath.Join(tmpDir, "deploy.sh")
scriptContent := "#!/bin/sh\ntouch " + markerFile + "\n"
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {
t.Fatalf("write deploy script: %v", err)
}
proj := &task.Project{
ID: "proj-deploy-1",
Name: "Deploy Test Project",
DeployScript: scriptPath,
}
if err := store.CreateProject(proj); err != nil {
t.Fatalf("create project: %v", err)
}
story := &task.Story{
ID: "story-deploy-1",
Name: "Deploy Test Story",
ProjectID: proj.ID,
Status: task.StoryShippable,
}
if err := store.CreateStory(story); err != nil {
t.Fatalf("create story: %v", err)
}
pool.triggerStoryDeploy(context.Background(), story.ID)
if _, err := os.Stat(markerFile); os.IsNotExist(err) {
t.Error("deploy script did not run: marker file not found")
}
got, err := store.GetStory(story.ID)
if err != nil {
t.Fatalf("get story: %v", err)
}
if got.Status != task.StoryDeployed {
t.Errorf("story status: want DEPLOYED, got %q", got.Status)
}
}
func TestPool_PostDeploy_CreatesValidationTask(t *testing.T) {
store := testStore(t)
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger)
now := time.Now().UTC()
validationSpec := `{"type":"smoke","steps":["curl /health"],"success_criteria":"status 200"}`
story := &task.Story{
ID: "story-postdeploy-1",
Name: "Post Deploy Test",
Status: task.StoryDeployed,
ValidationJSON: validationSpec,
CreatedAt: now,
UpdatedAt: now,
}
if err := store.CreateStory(story); err != nil {
t.Fatalf("CreateStory: %v", err)
}
pool.createValidationTask(context.Background(), story.ID)
// Story should now be VALIDATING.
got, err := store.GetStory(story.ID)
if err != nil {
t.Fatalf("GetStory: %v", err)
}
if got.Status != task.StoryValidating {
t.Errorf("story status: want VALIDATING, got %q", got.Status)
}
// A validation task should have been created.
tasks, err := store.ListTasksByStory(story.ID)
if err != nil {
t.Fatalf("ListTasksByStory: %v", err)
}
if len(tasks) == 0 {
t.Fatal("expected a validation task to be created, got none")
}
vtask := tasks[0]
if !strings.Contains(strings.ToLower(vtask.Name), "validation") {
t.Errorf("task name %q does not contain 'validation'", vtask.Name)
}
if vtask.StoryID != story.ID {
t.Errorf("task story_id: want %q, got %q", story.ID, vtask.StoryID)
}
if !strings.Contains(vtask.Agent.Instructions, "smoke") {
t.Errorf("task instructions %q do not reference validation spec content", vtask.Agent.Instructions)
}
}
|