tinytown 0.10.0

A simple, fast multi-agent orchestration system using Redis for message passing
Documentation
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
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
/*
 * Copyright (c) 2024-Present, Jeremy Plichta
 * Licensed under the MIT License
 */

//! Integration tests for the tinytown orchestration system.
//!
//! These tests verify the core functionality of tinytown including:
//! - Town initialization and configuration
//! - Agent creation and state management
//! - Message passing through Redis channels
//! - Task assignment and lifecycle management

use std::time::Duration;
use tempfile::TempDir;
use tinytown::message::MessageType;
use tinytown::{
    Agent, AgentId, AgentState, AgentType, Message, Priority, Task, TaskId, TaskService, TaskState,
    Town,
};
use uuid::Uuid;

/// Wrapper that holds both Town and TempDir, cleaning up Redis on drop
struct TownGuard {
    town: Town,
    temp_dir: TempDir,
}

impl Drop for TownGuard {
    fn drop(&mut self) {
        cleanup_redis(&self.temp_dir);
    }
}

impl std::ops::Deref for TownGuard {
    type Target = Town;
    fn deref(&self) -> &Self::Target {
        &self.town
    }
}

/// Helper function to create a temporary town for testing.
/// Returns a TownGuard that cleans up Redis when dropped.
/// Uses the default Redis mode so CI does not depend on per-test socket startup.
async fn create_test_town(name: &str) -> Result<TownGuard, Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name(name);
    let town = Town::init(temp_dir.path(), &town_name).await?;
    Ok(TownGuard { town, temp_dir })
}

/// Helper to kill Redis when test ends (only for per-town Redis, not central)
fn cleanup_redis(temp_dir: &TempDir) {
    let pid_file = temp_dir.path().join(".tt/redis.pid");
    if let Ok(pid_str) = std::fs::read_to_string(&pid_file)
        && let Ok(pid) = pid_str.trim().parse::<i32>()
    {
        unsafe {
            // Use SIGKILL to ensure Redis dies immediately
            libc::kill(pid, libc::SIGKILL);
        }
    }
}

fn unique_town_name(prefix: &str) -> String {
    format!("{prefix}-{}", Uuid::new_v4())
}

fn reserve_unused_port() -> Result<u16, Box<dyn std::error::Error>> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
    let port = listener.local_addr()?.port();
    drop(listener);
    Ok(port)
}

// ============================================================================
// TOWN INITIALIZATION AND CONFIGURATION TESTS
// ============================================================================

/// Test that a town can be initialized with proper directory structure.
#[tokio::test]
async fn test_town_initialization() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let town_path = temp_dir.path();
    let town_name = unique_town_name("test-town");
    let town = Town::init(town_path, &town_name).await?;

    // All runtime artifacts go under .tt/
    assert!(town_path.join(".tt").exists());
    assert!(town_path.join(".tt/agents").exists());
    assert!(town_path.join(".tt/logs").exists());
    assert!(town_path.join(".tt/tasks").exists());
    assert!(town_path.join("tinytown.toml").exists());

    let config = town.config();
    assert_eq!(config.name, town_name);
    assert_eq!(config.root, town_path);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that a town can be connected to after initialization.
#[tokio::test]
async fn test_town_connect() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let town_path = temp_dir.path();
    let town_name = unique_town_name("connect-test");

    let _town1 = Town::init(town_path, &town_name).await?;
    let town2 = Town::connect(town_path).await?;

    let config = town2.config();
    assert_eq!(config.name, town_name);

    drop(town2);
    drop(_town1);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that supervisor/conductor aliases resolve to the well-known mailbox.
#[tokio::test]
async fn test_supervisor_aliases_resolve_without_spawned_agent()
-> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("supervisor-alias-test").await?;
    let msg = Message::new(
        AgentId::supervisor(),
        AgentId::supervisor(),
        MessageType::Informational {
            summary: "Human decision needed".to_string(),
        },
    );
    town.channel().send(&msg).await?;

    assert_eq!(town.agent("supervisor").await?.id(), AgentId::supervisor());
    assert_eq!(town.agent("conductor").await?.id(), AgentId::supervisor());
    assert_eq!(town.agent("Conductor").await?.id(), AgentId::supervisor());

    let supervisor_inbox = tinytown::MessageService::get_inbox(&town, "supervisor").await?;
    let conductor_inbox = tinytown::MessageService::get_inbox(&town, "conductor").await?;

    assert_eq!(supervisor_inbox.total_messages, 1);
    assert_eq!(conductor_inbox.total_messages, 1);
    assert_eq!(supervisor_inbox.agent_id, AgentId::supervisor());
    assert_eq!(conductor_inbox.agent_id, AgentId::supervisor());
    assert_eq!(
        supervisor_inbox.messages[0].summary,
        "Human decision needed"
    );
    assert_eq!(conductor_inbox.messages[0].summary, "Human decision needed");

    Ok(())
}

/// Test that reserved supervisor/conductor mailbox names cannot be spawned as agents.
#[tokio::test]
async fn test_reserved_supervisor_names_cannot_be_spawned() -> Result<(), Box<dyn std::error::Error>>
{
    let town = create_test_town("supervisor-reserved-name-test").await?;

    assert!(matches!(
        town.spawn_agent("supervisor", "claude").await,
        Err(tinytown::Error::Config(_))
    ));
    assert!(matches!(
        town.spawn_agent("conductor", "claude").await,
        Err(tinytown::Error::Config(_))
    ));
    assert!(town.spawn_agent("conductor-helper", "claude").await.is_ok());

    Ok(())
}

// ============================================================================
// AGENT CREATION AND STATE MANAGEMENT TESTS
// ============================================================================

/// Test that an agent can be spawned and has correct initial state.
#[tokio::test]
async fn test_agent_spawn() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-spawn-test").await?;

    let agent_handle = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent_handle.id();
    assert_ne!(agent_id, AgentId::supervisor());

    let agent_state = agent_handle.state().await?;
    assert!(agent_state.is_some());

    let agent = agent_state.unwrap();
    assert_eq!(agent.name, "worker-1");
    assert_eq!(agent.cli, "claude");
    assert_eq!(agent.agent_type, AgentType::Worker);
    assert_eq!(agent.state, AgentState::Starting);
    assert_eq!(agent.tasks_completed, 0);

    Ok(())
}

/// Test that multiple agents can be spawned independently.
#[tokio::test]
async fn test_multiple_agents_spawn() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("multi-agent-test").await?;

    let agent1 = town.spawn_agent("worker-1", "claude").await?;
    let agent2 = town.spawn_agent("worker-2", "gemini").await?;
    let agent3 = town.spawn_agent("worker-3", "claude").await?;

    assert_ne!(agent1.id(), agent2.id());
    assert_ne!(agent2.id(), agent3.id());
    assert_ne!(agent1.id(), agent3.id());

    let state1 = agent1.state().await?;
    let state2 = agent2.state().await?;
    let state3 = agent3.state().await?;

    assert!(state1.is_some());
    assert!(state2.is_some());
    assert!(state3.is_some());

    Ok(())
}

/// Test that agent state can be updated and persisted.
#[tokio::test]
async fn test_agent_state_update() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-state-test").await?;

    let _agent_handle = town.spawn_agent("worker-1", "claude").await?;

    let mut agent = Agent::new("worker-1", "claude", AgentType::Worker);
    agent.state = AgentState::Idle;
    agent.tasks_completed = 5;

    town.channel().set_agent_state(&agent).await?;

    let retrieved = town.channel().get_agent_state(agent.id).await?;
    assert!(retrieved.is_some());

    let retrieved_agent = retrieved.unwrap();
    assert_eq!(retrieved_agent.state, AgentState::Idle);
    assert_eq!(retrieved_agent.tasks_completed, 5);

    Ok(())
}

// ============================================================================
// MESSAGE PASSING THROUGH REDIS CHANNELS TESTS
// ============================================================================

/// Test that a message can be sent to an agent's inbox.
#[tokio::test]
async fn test_message_send() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-send-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    let msg = Message::new(AgentId::supervisor(), agent_id, MessageType::Ping);

    town.channel().send(&msg).await?;

    let inbox_len = agent.inbox_len().await?;
    assert_eq!(inbox_len, 1);

    Ok(())
}

/// Test that messages can be received from an agent's inbox.
#[tokio::test]
async fn test_message_receive() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-receive-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    let original_msg = Message::new(AgentId::supervisor(), agent_id, MessageType::Ping);
    town.channel().send(&original_msg).await?;

    // Use try_receive instead of blocking receive
    let received = town.channel().try_receive(agent_id).await?;

    assert!(received.is_some());
    let msg = received.unwrap();
    assert_eq!(msg.id, original_msg.id);
    assert_eq!(msg.from, AgentId::supervisor());
    assert_eq!(msg.to, agent_id);

    Ok(())
}

/// Test that message priority affects queue ordering.
#[tokio::test]
async fn test_message_priority() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-priority-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    let low_msg = Message::new(AgentId::supervisor(), agent_id, MessageType::Ping)
        .with_priority(Priority::Low);

    let high_msg = Message::new(AgentId::supervisor(), agent_id, MessageType::Pong)
        .with_priority(Priority::High);

    town.channel().send(&low_msg).await?;
    town.channel().send(&high_msg).await?;

    // High priority messages are pushed to front (lpush), so try_receive gets them first
    let first = town.channel().try_receive(agent_id).await?.unwrap();

    assert_eq!(first.id, high_msg.id);

    Ok(())
}

/// Test that non-blocking message receive works correctly.
#[tokio::test]
async fn test_message_try_receive() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-try-receive-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    let empty = town.channel().try_receive(agent_id).await?;
    assert!(empty.is_none());

    let msg = Message::new(AgentId::supervisor(), agent_id, MessageType::Ping);
    town.channel().send(&msg).await?;

    let received = town.channel().try_receive(agent_id).await?;
    assert!(received.is_some());
    assert_eq!(received.unwrap().id, msg.id);

    Ok(())
}

/// Test that message correlation IDs work for request/response patterns.
#[tokio::test]
async fn test_message_correlation() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-correlation-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    let request = Message::new(AgentId::supervisor(), agent_id, MessageType::StatusRequest);
    let request_id = request.id;

    let response = Message::new(
        agent_id,
        AgentId::supervisor(),
        MessageType::StatusResponse {
            state: "idle".to_string(),
            current_task: None,
        },
    )
    .with_correlation(request_id);

    assert_eq!(response.correlation_id, Some(request_id));

    Ok(())
}

// ============================================================================
// TASK ASSIGNMENT AND LIFECYCLE TESTS
// ============================================================================

/// Test that a task can be created with proper initial state.
#[tokio::test]
async fn test_task_creation() -> Result<(), Box<dyn std::error::Error>> {
    let task = Task::new("Fix the bug in auth.rs");

    assert_eq!(task.description, "Fix the bug in auth.rs");
    assert_eq!(task.state, TaskState::Pending);
    assert!(task.assigned_to.is_none());
    assert!(task.result.is_none());
    assert!(task.completed_at.is_none());

    Ok(())
}

/// Test that a task can be assigned to an agent.
#[tokio::test]
async fn test_task_assignment() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("task-assignment-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let mut task = Task::new("Implement feature X");
    task.assign(agent.id());

    let task_id = agent.assign(task).await?;

    let stored_task = town.channel().get_task(task_id).await?;
    assert!(stored_task.is_some());

    let stored = stored_task.unwrap();
    assert_eq!(stored.description, "Implement feature X");
    assert_eq!(stored.state, TaskState::Assigned);
    assert_eq!(stored.assigned_to, Some(agent.id()));

    Ok(())
}

/// Test that multiple tasks can be assigned to an agent.
#[tokio::test]
async fn test_multiple_task_assignment() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("multi-task-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let task1 = Task::new("Task 1");
    let task2 = Task::new("Task 2");
    let task3 = Task::new("Task 3");

    let id1 = agent.assign(task1).await?;
    let id2 = agent.assign(task2).await?;
    let id3 = agent.assign(task3).await?;

    let stored1 = town.channel().get_task(id1).await?;
    let stored2 = town.channel().get_task(id2).await?;
    let stored3 = town.channel().get_task(id3).await?;

    assert!(stored1.is_some());
    assert!(stored2.is_some());
    assert!(stored3.is_some());

    assert_eq!(stored1.unwrap().description, "Task 1");
    assert_eq!(stored2.unwrap().description, "Task 2");
    assert_eq!(stored3.unwrap().description, "Task 3");

    Ok(())
}

/// Test that task state transitions work correctly.
#[tokio::test]
async fn test_task_state_transitions() -> Result<(), Box<dyn std::error::Error>> {
    let _town = create_test_town("task-state-test").await?;

    let mut task = Task::new("Test task");

    assert_eq!(task.state, TaskState::Pending);

    let agent_id = AgentId::new();
    task.assign(agent_id);
    assert_eq!(task.state, TaskState::Assigned);
    assert_eq!(task.assigned_to, Some(agent_id));

    task.start();
    assert_eq!(task.state, TaskState::Running);
    assert!(task.started_at.is_some()); // Verify started_at is set when task becomes in-flight

    task.complete("Task completed successfully");
    assert_eq!(task.state, TaskState::Completed);
    assert_eq!(task.result, Some("Task completed successfully".to_string()));
    assert!(task.completed_at.is_some());

    Ok(())
}

/// Test that task failure state works correctly.
#[tokio::test]
async fn test_task_failure() -> Result<(), Box<dyn std::error::Error>> {
    let mut task = Task::new("Failing task");

    task.assign(AgentId::new());
    task.start();
    task.fail("Connection timeout");

    assert_eq!(task.state, TaskState::Failed);
    assert_eq!(task.result, Some("Connection timeout".to_string()));
    assert!(task.completed_at.is_some());

    Ok(())
}

/// Test that tasks can have tags for filtering.
#[tokio::test]
async fn test_task_tags() -> Result<(), Box<dyn std::error::Error>> {
    let task = Task::new("Implement API endpoint").with_tags(vec!["backend", "api", "urgent"]);

    assert_eq!(task.tags.len(), 3);
    assert!(task.tags.contains(&"backend".to_string()));
    assert!(task.tags.contains(&"api".to_string()));
    assert!(task.tags.contains(&"urgent".to_string()));

    Ok(())
}

/// Test that tasks can have parent tasks for hierarchical organization.
#[tokio::test]
async fn test_task_hierarchy() -> Result<(), Box<dyn std::error::Error>> {
    let parent_id = TaskId::new();
    let child_task = Task::new("Subtask").with_parent(parent_id);

    assert_eq!(child_task.parent_id, Some(parent_id));

    Ok(())
}

/// Test that task state is persisted in Redis.
#[tokio::test]
async fn test_task_persistence() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("task-persistence-test").await?;

    let mut task = Task::new("Persistent task");
    let agent_id = AgentId::new();
    task.assign(agent_id);

    town.channel().set_task(&task).await?;

    let retrieved = town.channel().get_task(task.id).await?;
    assert!(retrieved.is_some());

    let retrieved_task = retrieved.unwrap();
    assert_eq!(retrieved_task.description, "Persistent task");
    assert_eq!(retrieved_task.state, TaskState::Assigned);
    assert_eq!(retrieved_task.assigned_to, Some(agent_id));

    Ok(())
}

/// Test that the tracked current task resolves the persisted Tinytown task ID,
/// even when the task description contains another UUID-like value.
#[tokio::test]
async fn test_current_task_resolves_real_task_id_over_description_uuid()
-> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("current-task-real-id-test").await?;
    let agent = town.spawn_agent("frontend", "claude").await?;

    let mission_uuid = "c7d2e4dd-30e5-48e5-8bfc-95d5f14b13bf";
    let mut task = Task::new(format!(
        "Mission {}: implement GitHub issue #5 and keep the UI stable",
        mission_uuid
    ));
    task.assign(agent.id());

    let task_id = agent.assign(task).await?;
    assert_ne!(task_id.to_string(), mission_uuid);

    TaskService::set_current_for_agent(town.channel(), agent.id(), task_id).await?;

    let current = TaskService::current_for_agent(town.channel(), agent.id())
        .await?
        .expect("tracked current task");

    assert_eq!(current.id, task_id);
    assert!(current.description.contains(mission_uuid));
    assert_eq!(current.assigned_to, Some(agent.id()));
    assert_eq!(current.state, TaskState::Assigned);

    Ok(())
}

/// Test that completing the tracked current task clears the pointer and increments agent stats.
#[tokio::test]
async fn test_complete_clears_current_task_and_increments_agent_stats()
-> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("current-task-complete-test").await?;
    let agent = town.spawn_agent("backend", "claude").await?;

    let mut task = Task::new("Implement API endpoint");
    task.assign(agent.id());
    let task_id = agent.assign(task).await?;

    TaskService::set_current_for_agent(town.channel(), agent.id(), task_id).await?;

    let completion = TaskService::complete(
        town.channel(),
        task_id,
        Some("Implemented API endpoint".to_string()),
    )
    .await?
    .expect("completed task");

    assert_eq!(completion.task.id, task_id);
    assert_eq!(completion.task.state, TaskState::Completed);
    assert_eq!(completion.result, "Implemented API endpoint");
    assert!(completion.cleared_current_task);
    assert_eq!(completion.tasks_completed, Some(1));

    let agent_state = town
        .channel()
        .get_agent_state(agent.id())
        .await?
        .expect("agent state");
    assert_eq!(agent_state.current_task, None);
    assert_eq!(agent_state.tasks_completed, 1);

    let current = TaskService::current_for_agent(town.channel(), agent.id()).await?;
    assert!(current.is_none());

    let stored_task = town
        .channel()
        .get_task(task_id)
        .await?
        .expect("stored completed task");
    assert_eq!(stored_task.state, TaskState::Completed);
    assert_eq!(
        stored_task.result,
        Some("Implemented API endpoint".to_string())
    );

    Ok(())
}

// ============================================================================
// INTEGRATION TESTS - COMBINED WORKFLOWS
// ============================================================================

/// Test a complete workflow: spawn agent, assign task, send messages.
#[tokio::test]
async fn test_complete_workflow() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("complete-workflow-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let mut task = Task::new("Implement new feature");
    task.assign(agent.id());
    let task_id = agent.assign(task).await?;

    let stored_task = town.channel().get_task(task_id).await?;
    assert!(stored_task.is_some());
    assert_eq!(stored_task.unwrap().state, TaskState::Assigned);

    agent.send(MessageType::StatusRequest).await?;

    // assign() sends a TaskAssign message, and send() sends a StatusRequest message
    let inbox_len = agent.inbox_len().await?;
    assert_eq!(inbox_len, 2);

    Ok(())
}

/// Test agent state transitions through message handling.
#[tokio::test]
async fn test_agent_state_transitions() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-transitions-test").await?;

    let agent_handle = town.spawn_agent("worker-1", "claude").await?;

    let initial = agent_handle.state().await?;
    assert_eq!(initial.unwrap().state, AgentState::Starting);

    let mut agent = Agent::new("worker-1", "claude", AgentType::Worker);
    agent.id = agent_handle.id();
    agent.state = AgentState::Idle;
    town.channel().set_agent_state(&agent).await?;

    let idle = agent_handle.state().await?;
    assert_eq!(idle.unwrap().state, AgentState::Idle);

    agent.state = AgentState::Working;
    town.channel().set_agent_state(&agent).await?;

    let working = agent_handle.state().await?;
    assert_eq!(working.unwrap().state, AgentState::Working);

    Ok(())
}

/// Test task lifecycle with agent interaction.
#[tokio::test]
async fn test_task_lifecycle_with_agent() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("task-lifecycle-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let mut task = Task::new("Complete task");
    assert_eq!(task.state, TaskState::Pending);

    task.assign(agent.id());
    assert_eq!(task.state, TaskState::Assigned);

    town.channel().set_task(&task).await?;

    task.start();
    town.channel().set_task(&task).await?;

    let running = town.channel().get_task(task.id).await?;
    assert_eq!(running.unwrap().state, TaskState::Running);

    task.complete("Successfully completed");
    town.channel().set_task(&task).await?;

    let completed = town.channel().get_task(task.id).await?;
    let completed_task = completed.unwrap();
    assert_eq!(completed_task.state, TaskState::Completed);
    assert_eq!(
        completed_task.result,
        Some("Successfully completed".to_string())
    );

    Ok(())
}

/// Test message inbox behavior with multiple messages.
#[tokio::test]
async fn test_message_inbox_ordering() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("inbox-ordering-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    for i in 0..3 {
        let msg = Message::new(
            AgentId::supervisor(),
            agent_id,
            MessageType::Custom {
                kind: "test".to_string(),
                payload: format!("message-{}", i),
            },
        );
        town.channel().send(&msg).await?;
    }

    let inbox_len = agent.inbox_len().await?;
    assert_eq!(inbox_len, 3);

    let _msg1 = town.channel().try_receive(agent_id).await?.unwrap();
    let _msg2 = town.channel().try_receive(agent_id).await?.unwrap();
    let _msg3 = town.channel().try_receive(agent_id).await?.unwrap();

    let final_len = agent.inbox_len().await?;
    assert_eq!(final_len, 0);

    Ok(())
}

/// Test that agent wait functionality works (with timeout).
#[tokio::test]
async fn test_agent_wait_timeout() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-wait-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let mut agent_state = Agent::new("worker-1", "claude", AgentType::Worker);
    agent_state.id = agent.id();
    agent_state.state = AgentState::Idle;
    town.channel().set_agent_state(&agent_state).await?;

    let start = std::time::Instant::now();
    agent.wait().await?;
    let elapsed = start.elapsed();

    assert!(elapsed < Duration::from_secs(1));

    Ok(())
}

// ============================================================================
// ERROR HANDLING TESTS
// ============================================================================

/// Test that invalid task retrieval returns None.
#[tokio::test]
async fn test_task_not_found() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("task-not-found-test").await?;

    let fake_id = TaskId::new();
    let result = town.channel().get_task(fake_id).await?;

    assert!(result.is_none());

    Ok(())
}

/// Test that invalid agent retrieval returns None.
#[tokio::test]
async fn test_agent_state_not_found() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-state-not-found-test").await?;

    let fake_id = AgentId::new();
    let result = town.channel().get_agent_state(fake_id).await?;

    assert!(result.is_none());

    Ok(())
}

/// Test that message receive timeout works correctly.
#[tokio::test]
async fn test_message_receive_timeout() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("message-timeout-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let start = std::time::Instant::now();
    let result = town
        .channel()
        .receive(agent.id(), Duration::from_millis(100))
        .await?;
    let elapsed = start.elapsed();

    assert!(result.is_none());
    assert!(elapsed >= Duration::from_millis(100));

    Ok(())
}

// ============================================================================
// EDGE CASES AND STRESS TESTS
// ============================================================================

/// Test that task state is terminal when completed.
#[tokio::test]
async fn test_task_terminal_states() -> Result<(), Box<dyn std::error::Error>> {
    let mut task1 = Task::new("Task 1");
    task1.complete("Done");
    assert!(task1.state.is_terminal());

    let mut task2 = Task::new("Task 2");
    task2.fail("Error");
    assert!(task2.state.is_terminal());

    let task3 = Task::new("Task 3");
    assert!(!task3.state.is_terminal());

    Ok(())
}

/// Test that agent state can be checked for work acceptance.
#[tokio::test]
async fn test_agent_can_accept_work() -> Result<(), Box<dyn std::error::Error>> {
    assert!(AgentState::Idle.can_accept_work());
    assert!(!AgentState::Working.can_accept_work());
    assert!(!AgentState::Paused.can_accept_work());
    assert!(!AgentState::Starting.can_accept_work());

    Ok(())
}

/// Test that agent state is terminal when stopped or errored.
#[tokio::test]
async fn test_agent_terminal_states() -> Result<(), Box<dyn std::error::Error>> {
    assert!(AgentState::Stopped.is_terminal());
    assert!(AgentState::Error.is_terminal());
    assert!(!AgentState::Idle.is_terminal());
    assert!(!AgentState::Working.is_terminal());

    Ok(())
}

/// Test creating many agents in sequence.
#[tokio::test]
async fn test_many_agents() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("many-agents-test").await?;

    let mut agent_ids = Vec::new();

    for i in 0..10 {
        let agent = town.spawn_agent(&format!("worker-{}", i), "claude").await?;
        agent_ids.push(agent.id());
    }

    let unique_count = agent_ids
        .iter()
        .collect::<std::collections::HashSet<_>>()
        .len();
    assert_eq!(unique_count, 10);

    Ok(())
}

/// Test creating many tasks in sequence.
#[tokio::test]
async fn test_many_tasks() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("many-tasks-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;

    let mut task_ids = Vec::new();

    for i in 0..20 {
        let task = Task::new(format!("Task {}", i));
        let task_id = agent.assign(task).await?;
        task_ids.push(task_id);
    }

    let unique_count = task_ids
        .iter()
        .collect::<std::collections::HashSet<_>>()
        .len();
    assert_eq!(unique_count, 20);

    Ok(())
}

/// Test sending many messages in sequence.
#[tokio::test]
async fn test_many_messages() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("many-messages-test").await?;

    let agent = town.spawn_agent("worker-1", "claude").await?;
    let agent_id = agent.id();

    for i in 0..50 {
        let msg = Message::new(
            AgentId::supervisor(),
            agent_id,
            MessageType::Custom {
                kind: "test".to_string(),
                payload: format!("msg-{}", i),
            },
        );
        town.channel().send(&msg).await?;
    }

    let inbox_len = agent.inbox_len().await?;
    assert_eq!(inbox_len, 50);

    Ok(())
}

// ============================================================================
// TASK PLANNING DSL TESTS
// ============================================================================

/// Test that tasks.toml can be initialized.
#[tokio::test]
async fn test_plan_init_tasks_file() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;

    // Initialize tasks file
    tinytown::plan::init_tasks_file(temp_dir.path())?;

    // Check file exists
    let tasks_file = temp_dir.path().join("tasks.toml");
    assert!(tasks_file.exists());

    // Load and verify structure
    let tasks = tinytown::plan::load_tasks_file(temp_dir.path())?;
    assert_eq!(tasks.meta.description, "Task plan for this project");
    assert_eq!(tasks.tasks.len(), 1);
    assert_eq!(tasks.tasks[0].id, "example-1");
    assert_eq!(tasks.tasks[0].status, "pending");

    Ok(())
}

/// Test loading and saving tasks file.
#[tokio::test]
async fn test_plan_load_save_tasks_file() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::plan::{TaskEntry, TasksFile, TasksMeta};

    let temp_dir = TempDir::new()?;

    // Create a custom tasks file
    let tasks = TasksFile {
        meta: TasksMeta {
            description: "Test plan".to_string(),
            default_agent: Some("developer".to_string()),
        },
        tasks: vec![
            TaskEntry {
                id: "task-1".to_string(),
                description: "Build the API".to_string(),
                agent: Some("backend".to_string()),
                status: "pending".to_string(),
                tags: vec!["api".to_string(), "backend".to_string()],
                parent: None,
            },
            TaskEntry {
                id: "task-2".to_string(),
                description: "Write tests".to_string(),
                agent: Some("tester".to_string()),
                status: "pending".to_string(),
                tags: vec!["tests".to_string()],
                parent: Some("task-1".to_string()),
            },
        ],
    };

    // Save
    tinytown::plan::save_tasks_file(temp_dir.path(), &tasks)?;

    // Load back
    let loaded = tinytown::plan::load_tasks_file(temp_dir.path())?;

    assert_eq!(loaded.meta.description, "Test plan");
    assert_eq!(loaded.meta.default_agent, Some("developer".to_string()));
    assert_eq!(loaded.tasks.len(), 2);
    assert_eq!(loaded.tasks[0].id, "task-1");
    assert_eq!(loaded.tasks[0].agent, Some("backend".to_string()));
    assert_eq!(loaded.tasks[1].parent, Some("task-1".to_string()));

    Ok(())
}

/// Test pushing tasks from file to Redis.
#[tokio::test]
async fn test_plan_push_to_redis() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("plan-push-test").await?;
    let town_path = town.config().root.clone();

    // Initialize and modify tasks file
    tinytown::plan::init_tasks_file(&town_path)?;

    let tasks = tinytown::plan::TasksFile {
        meta: tinytown::plan::TasksMeta {
            description: "Push test".to_string(),
            default_agent: None,
        },
        tasks: vec![tinytown::plan::TaskEntry {
            id: "push-task-1".to_string(),
            description: "Task to push".to_string(),
            agent: None,
            status: "pending".to_string(),
            tags: vec!["test".to_string()],
            parent: None,
        }],
    };
    tinytown::plan::save_tasks_file(&town_path, &tasks)?;

    // Push to Redis
    let count = tinytown::plan::push_tasks_to_redis(&town_path, town.channel()).await?;
    assert_eq!(count, 1);

    Ok(())
}

/// Test that default_cli is used when spawning without --cli.
#[tokio::test]
async fn test_default_cli_config() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::GlobalConfig;

    let town = create_test_town("default-cli-test").await?;

    // Config should have a default_cli that matches global config
    let config = town.config();
    let global = GlobalConfig::load().unwrap_or_default();
    assert!(!config.default_cli.is_empty());
    assert_eq!(
        config.default_cli,
        config.resolve_cli_name(&global.default_cli)
    );
    assert_eq!(
        config.conductor_cli_name(),
        global
            .conductor_cli
            .as_deref()
            .unwrap_or(global.default_cli.as_str())
    );

    // Agent CLIs should include built-in presets
    assert!(config.agent_clis.contains_key("claude"));
    assert!(config.agent_clis.contains_key("auggie"));
    assert!(config.agent_clis.contains_key("codex"));

    Ok(())
}

// ============================================================================
// RECOVERY FEATURE TESTS (tt recover)
// ============================================================================

/// Test that orphaned agents (in Working state with old heartbeat) can be detected.
#[tokio::test]
async fn test_detect_orphaned_agents_working_state() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("recovery-working-test").await?;

    // Create an agent and set it to Working state
    let agent_handle = town.spawn_agent("orphaned-worker", "claude").await?;
    let agent_id = agent_handle.id();

    // Get the agent and set it to Working state with old heartbeat
    let mut agent = Agent::new("orphaned-worker", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Working;
    // Set heartbeat to 3 minutes ago (stale - over 2 min threshold)
    agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(3);
    town.channel().set_agent_state(&agent).await?;

    // Verify the agent is in Working state
    let agents = town.list_agents().await;
    let orphaned = agents.iter().find(|a| a.id == agent_id);
    assert!(orphaned.is_some());
    assert_eq!(orphaned.unwrap().state, AgentState::Working);

    // The agent should be considered stale (heartbeat > 2 min ago)
    let heartbeat_age = chrono::Utc::now() - orphaned.unwrap().last_heartbeat;
    assert!(heartbeat_age.num_seconds() > 120);

    Ok(())
}

/// Test that agents in Starting state with old heartbeat are considered orphaned.
#[tokio::test]
async fn test_detect_orphaned_agents_starting_state() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("recovery-starting-test").await?;

    // Create an agent in Starting state with old heartbeat
    let agent_handle = town.spawn_agent("stuck-starting", "auggie").await?;
    let agent_id = agent_handle.id();

    let mut agent = Agent::new("stuck-starting", "auggie", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Starting;
    agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(5);
    town.channel().set_agent_state(&agent).await?;

    // Verify state is as expected
    let state = agent_handle.state().await?;
    assert!(state.is_some());
    assert_eq!(state.unwrap().state, AgentState::Starting);

    Ok(())
}

/// Test that agents in non-active states are not considered orphaned.
#[tokio::test]
async fn test_non_active_agents_not_orphaned() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("recovery-non-active-test").await?;

    // Create agents in various non-recoverable states
    let stopped_handle = town.spawn_agent("stopped-agent", "claude").await?;
    let paused_handle = town.spawn_agent("paused-agent", "claude").await?;

    let mut stopped_agent = Agent::new("stopped-agent", "claude", AgentType::Worker);
    stopped_agent.id = stopped_handle.id();
    stopped_agent.state = AgentState::Stopped;
    stopped_agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(10);
    town.channel().set_agent_state(&stopped_agent).await?;

    let mut paused_agent = Agent::new("paused-agent", "claude", AgentType::Worker);
    paused_agent.id = paused_handle.id();
    paused_agent.state = AgentState::Paused;
    paused_agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(10);
    town.channel().set_agent_state(&paused_agent).await?;

    // Verify states - none of these should be considered recoverable.
    let agents = town.list_agents().await;

    for agent in &agents {
        let is_active_state = matches!(
            agent.state,
            AgentState::Working | AgentState::Starting | AgentState::Idle | AgentState::Draining
        );
        assert!(
            !is_active_state,
            "Agent {} should not be in a recoverable state",
            agent.name
        );
    }

    Ok(())
}

/// Test that agent state can be transitioned from Working to Stopped (recovery action).
#[tokio::test]
async fn test_recover_agent_to_stopped() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("recovery-transition-test").await?;

    let agent_handle = town.spawn_agent("recoverable", "claude").await?;
    let agent_id = agent_handle.id();

    // Set to Working state
    let mut agent = Agent::new("recoverable", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Working;
    agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(3);
    town.channel().set_agent_state(&agent).await?;

    // Verify initial state
    let state_before = agent_handle.state().await?;
    assert_eq!(state_before.unwrap().state, AgentState::Working);

    // Simulate recovery action: change state to Stopped
    agent.state = AgentState::Stopped;
    town.channel().set_agent_state(&agent).await?;

    // Verify recovery worked
    let state_after = agent_handle.state().await?;
    assert_eq!(state_after.unwrap().state, AgentState::Stopped);

    Ok(())
}

/// Test that RecoveryService recovers stale Idle agents after a reboot-like heartbeat gap.
#[tokio::test]
async fn test_recovery_service_recovers_stale_idle_agent() -> Result<(), Box<dyn std::error::Error>>
{
    let town = create_test_town("recovery-idle-service-test").await?;

    let agent_handle = town.spawn_agent("recoverable-idle", "claude").await?;
    let agent_id = agent_handle.id();

    let mut agent = Agent::new("recoverable-idle", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Idle;
    agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::minutes(3);
    town.channel().set_agent_state(&agent).await?;

    let recover_result = tinytown::RecoveryService::recover(&town, town.root()).await?;

    assert_eq!(recover_result.agents_recovered, 1);
    assert_eq!(recover_result.recovered_agents.len(), 1);
    assert_eq!(recover_result.recovered_agents[0].id, agent_id);
    assert_eq!(recover_result.recovered_agents[0].state, AgentState::Idle);

    let recovered_state = agent_handle.state().await?;
    assert_eq!(recovered_state.unwrap().state, AgentState::Stopped);

    Ok(())
}

/// Test that healthy Idle agents are not recovered.
#[tokio::test]
async fn test_recovery_service_skips_healthy_idle_agent() -> Result<(), Box<dyn std::error::Error>>
{
    let town = create_test_town("recovery-idle-healthy-test").await?;

    let agent_handle = town.spawn_agent("healthy-idle", "claude").await?;
    let agent_id = agent_handle.id();

    let mut agent = Agent::new("healthy-idle", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Idle;
    agent.last_heartbeat = chrono::Utc::now() - chrono::Duration::seconds(30);
    town.channel().set_agent_state(&agent).await?;

    let recover_result = tinytown::RecoveryService::recover(&town, town.root()).await?;

    assert_eq!(recover_result.agents_recovered, 0);

    let state_after = agent_handle.state().await?;
    assert_eq!(state_after.unwrap().state, AgentState::Idle);

    Ok(())
}

/// Test that no agents are orphaned when all are healthy.
#[tokio::test]
async fn test_no_orphans_when_healthy() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("recovery-healthy-test").await?;

    // Create agents with recent heartbeats
    let handle1 = town.spawn_agent("healthy-1", "claude").await?;
    let handle2 = town.spawn_agent("healthy-2", "auggie").await?;

    // Set to Working with recent heartbeat (within 2 min threshold)
    let mut agent1 = Agent::new("healthy-1", "claude", AgentType::Worker);
    agent1.id = handle1.id();
    agent1.state = AgentState::Working;
    agent1.last_heartbeat = chrono::Utc::now() - chrono::Duration::seconds(30);
    town.channel().set_agent_state(&agent1).await?;

    let mut agent2 = Agent::new("healthy-2", "auggie", AgentType::Worker);
    agent2.id = handle2.id();
    agent2.state = AgentState::Idle;
    agent2.last_heartbeat = chrono::Utc::now();
    town.channel().set_agent_state(&agent2).await?;

    // Check all agents - count orphaned recoverable agents with stale heartbeat.
    let agents = town.list_agents().await;
    let mut orphan_count = 0;

    for agent in &agents {
        let is_active = matches!(
            agent.state,
            AgentState::Working | AgentState::Starting | AgentState::Idle | AgentState::Draining
        );
        if is_active {
            let heartbeat_age = chrono::Utc::now() - agent.last_heartbeat;
            if heartbeat_age.num_seconds() > 120 {
                orphan_count += 1;
            }
        }
    }

    assert_eq!(
        orphan_count, 0,
        "No agents should be orphaned when heartbeats are recent"
    );

    Ok(())
}

// ============================================================================
// TOWNS REGISTRY TESTS (tt towns, tt init registration)
// ============================================================================

/// Test that towns.toml format is valid.
#[tokio::test]
async fn test_towns_toml_format() -> Result<(), Box<dyn std::error::Error>> {
    // Verify that the towns.toml format can be parsed
    let toml_content = r#"
[[towns]]
path = "/path/to/town1"
name = "my-town"

[[towns]]
path = "/path/to/town2"
name = "another-town"
"#;

    #[derive(Debug, Clone, serde::Deserialize)]
    struct TownEntry {
        path: String,
        name: String,
    }

    #[derive(Debug, Clone, serde::Deserialize)]
    struct TownsFile {
        towns: Vec<TownEntry>,
    }

    let parsed: TownsFile = toml::from_str(toml_content)?;
    assert_eq!(parsed.towns.len(), 2);
    assert_eq!(parsed.towns[0].name, "my-town");
    assert_eq!(parsed.towns[0].path, "/path/to/town1");
    assert_eq!(parsed.towns[1].name, "another-town");
    assert_eq!(parsed.towns[1].path, "/path/to/town2");

    Ok(())
}

/// Test that empty towns.toml is valid.
#[tokio::test]
async fn test_empty_towns_toml() -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Debug, Clone, serde::Deserialize, Default)]
    struct TownsFile {
        #[serde(default)]
        towns: Vec<TownEntry>,
    }

    #[allow(dead_code)]
    #[derive(Debug, Clone, serde::Deserialize)]
    struct TownEntry {
        path: String,
        name: String,
    }

    // Empty file or just whitespace should parse to default
    let empty_content = "";
    let parsed: TownsFile = toml::from_str(empty_content).unwrap_or_default();
    assert_eq!(parsed.towns.len(), 0);

    // File with just towns = [] should also work
    let explicit_empty = "towns = []";
    let parsed2: TownsFile = toml::from_str(explicit_empty)?;
    assert_eq!(parsed2.towns.len(), 0);

    Ok(())
}

/// Test that global config directory constant is accessible.
#[tokio::test]
async fn test_global_config_dir_constant() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::global_config::GLOBAL_CONFIG_DIR;

    assert_eq!(GLOBAL_CONFIG_DIR, ".tt");

    Ok(())
}

/// Test that GlobalConfig Default trait works (note: serde defaults are separate).
#[tokio::test]
async fn test_global_config_defaults() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::global_config::GlobalConfig;

    // Default trait gives empty strings (Rust default)
    let config = GlobalConfig::default();
    assert!(config.agent_clis.is_empty());

    // The load() method uses serde defaults when file doesn't exist
    // We can test that GlobalConfig can be serialized/deserialized with defaults
    let toml_str = r#"
default_cli = "claude"
conductor_cli = "codex"
"#;
    let parsed: GlobalConfig = toml::from_str(toml_str)?;
    assert_eq!(parsed.default_cli, "claude");
    assert_eq!(parsed.conductor_cli.as_deref(), Some("codex"));

    Ok(())
}

/// Test that a town config can override the conductor CLI separately from worker defaults.
#[tokio::test]
async fn test_town_config_supports_separate_conductor_cli() -> Result<(), Box<dyn std::error::Error>>
{
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let town_path = temp_dir.path();
    let config_path = town_path.join("tinytown.toml");

    std::fs::write(
        &config_path,
        r#"
name = "split-cli-test"
default_cli = "codex-mini"
conductor_cli = "codex"
"#,
    )?;

    let config = Config::load(town_path)?;
    assert_eq!(config.default_cli, "codex-mini");
    assert_eq!(config.conductor_cli.as_deref(), Some("codex"));
    assert_eq!(config.conductor_cli_name(), "codex");

    Ok(())
}

/// Test that town initialization creates expected directories.
#[tokio::test]
async fn test_town_init_creates_structure() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let town_path = temp_dir.path();
    let town_name = unique_town_name("init-structure-test");

    let _town = Town::init(town_path, &town_name).await?;

    // Verify expected directories exist (all under .tt/)
    assert!(town_path.join(".tt").exists());
    assert!(town_path.join(".tt/agents").exists());
    assert!(town_path.join(".tt/logs").exists());
    assert!(town_path.join(".tt/tasks").exists());

    // Verify config file exists (note: uses .toml now, not .json)
    let toml_config = town_path.join("tinytown.toml");
    let json_config = town_path.join("tinytown.json");
    assert!(toml_config.exists() || json_config.exists());

    drop(_town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that towns can be connected to and have proper status.
#[tokio::test]
async fn test_town_status_info() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("status-info-test").await?;

    // Spawn some agents
    let _agent1 = town.spawn_agent("worker-1", "claude").await?;
    let _agent2 = town.spawn_agent("worker-2", "auggie").await?;

    // List agents should return them
    let agents = town.list_agents().await;
    assert_eq!(agents.len(), 2);

    // Config should have expected values
    let config = town.config();
    assert!(config.name.starts_with("status-info-test-"));

    Ok(())
}

/// Test that town can report agent activity states for recovery.
#[tokio::test]
async fn test_town_agent_activity_report() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("activity-report-test").await?;

    // Create agents in different states
    let active_handle = town.spawn_agent("active-worker", "claude").await?;
    let idle_handle = town.spawn_agent("idle-worker", "claude").await?;

    // Set up states
    let mut active_agent = Agent::new("active-worker", "claude", AgentType::Worker);
    active_agent.id = active_handle.id();
    active_agent.state = AgentState::Working;
    active_agent.last_heartbeat = chrono::Utc::now();
    town.channel().set_agent_state(&active_agent).await?;

    let mut idle_agent = Agent::new("idle-worker", "claude", AgentType::Worker);
    idle_agent.id = idle_handle.id();
    idle_agent.state = AgentState::Idle;
    idle_agent.last_heartbeat = chrono::Utc::now();
    town.channel().set_agent_state(&idle_agent).await?;

    // Get agents and count by state
    let agents = town.list_agents().await;
    let working_count = agents
        .iter()
        .filter(|a| a.state == AgentState::Working)
        .count();
    let idle_count = agents
        .iter()
        .filter(|a| a.state == AgentState::Idle)
        .count();

    assert_eq!(working_count, 1);
    assert_eq!(idle_count, 1);

    Ok(())
}

// ============================================================================
// BACKLOG AND RECOVERY TESTS
// ============================================================================

/// Test that tasks can be added, listed, and claimed from the backlog.
#[tokio::test]
async fn test_backlog_add_list_claim() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("backlog-test").await?;

    let channel = town.channel();

    // Initially, backlog should be empty
    let backlog = channel.backlog_list().await?;
    assert!(backlog.is_empty());
    assert_eq!(channel.backlog_len().await?, 0);

    // Add tasks to the backlog
    let task1_id = TaskId::new();
    let task2_id = TaskId::new();
    let task3_id = TaskId::new();

    channel.backlog_push(task1_id).await?;
    channel.backlog_push(task2_id).await?;
    channel.backlog_push(task3_id).await?;

    // Verify backlog has 3 tasks
    assert_eq!(channel.backlog_len().await?, 3);
    let backlog = channel.backlog_list().await?;
    assert_eq!(backlog.len(), 3);
    assert_eq!(backlog[0], task1_id);
    assert_eq!(backlog[1], task2_id);
    assert_eq!(backlog[2], task3_id);

    // Pop (claim) a task from the backlog (FIFO)
    let claimed = channel.backlog_pop().await?;
    assert!(claimed.is_some());
    assert_eq!(claimed.unwrap(), task1_id);
    assert_eq!(channel.backlog_len().await?, 2);

    // Remove a specific task
    let removed = channel.backlog_remove(task3_id).await?;
    assert!(removed);
    assert_eq!(channel.backlog_len().await?, 1);

    // Verify only task2 remains
    let backlog = channel.backlog_list().await?;
    assert_eq!(backlog.len(), 1);
    assert_eq!(backlog[0], task2_id);

    // Pop remaining task
    let claimed = channel.backlog_pop().await?;
    assert_eq!(claimed, Some(task2_id));

    // Backlog should be empty now
    assert_eq!(channel.backlog_len().await?, 0);
    let empty_pop = channel.backlog_pop().await?;
    assert!(empty_pop.is_none());

    Ok(())
}

/// Test that tasks can be reclaimed (drained) from a dead agent's inbox.
#[tokio::test]
async fn test_reclaim_from_dead_agent() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("reclaim-test").await?;

    let channel = town.channel();

    // Create an agent and send some messages to it
    let agent_handle = town.spawn_agent("dead-worker", "claude").await?;
    let agent_id = agent_handle.id();

    // Send multiple messages to the agent
    let msg1 = Message::new(AgentId::supervisor(), agent_id, MessageType::Ping);
    let msg2 = Message::new(
        AgentId::supervisor(),
        agent_id,
        MessageType::TaskAssign {
            task_id: "task-1".to_string(),
        },
    );
    let msg3 = Message::new(
        AgentId::supervisor(),
        agent_id,
        MessageType::TaskAssign {
            task_id: "task-2".to_string(),
        },
    );

    channel.send(&msg1).await?;
    channel.send(&msg2).await?;
    channel.send(&msg3).await?;

    // Verify messages are in inbox
    let inbox_len = agent_handle.inbox_len().await?;
    assert_eq!(inbox_len, 3);

    // Simulate agent death by setting state to Stopped
    let mut agent = Agent::new("dead-worker", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Stopped;
    channel.set_agent_state(&agent).await?;

    // Drain the inbox (reclaim messages)
    let drained = channel.drain_inbox(agent_id).await?;
    assert_eq!(drained.len(), 3);
    assert_eq!(drained[0].id, msg1.id);
    assert_eq!(drained[1].id, msg2.id);
    assert_eq!(drained[2].id, msg3.id);

    // Inbox should be empty after drain
    let inbox_len = agent_handle.inbox_len().await?;
    assert_eq!(inbox_len, 0);

    Ok(())
}

/// Test that drained messages can be moved to the backlog.
#[tokio::test]
async fn test_reclaim_to_backlog() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("reclaim-backlog-test").await?;

    let channel = town.channel();

    // Create an agent and send task messages
    let agent_handle = town.spawn_agent("failing-worker", "claude").await?;
    let agent_id = agent_handle.id();

    // Create task IDs and send as TaskAssign messages
    let task1_id = TaskId::new();
    let task2_id = TaskId::new();
    let msg1 = Message::new(
        AgentId::supervisor(),
        agent_id,
        MessageType::TaskAssign {
            task_id: task1_id.to_string(),
        },
    );
    let msg2 = Message::new(
        AgentId::supervisor(),
        agent_id,
        MessageType::TaskAssign {
            task_id: task2_id.to_string(),
        },
    );

    channel.send(&msg1).await?;
    channel.send(&msg2).await?;

    // Simulate agent death
    let mut agent = Agent::new("failing-worker", "claude", AgentType::Worker);
    agent.id = agent_id;
    agent.state = AgentState::Error;
    channel.set_agent_state(&agent).await?;

    // Drain inbox and move task IDs to backlog
    let drained = channel.drain_inbox(agent_id).await?;
    for msg in &drained {
        if let MessageType::TaskAssign { task_id: task_str } = &msg.msg_type
            && let Ok(task_id) = task_str.parse::<TaskId>()
        {
            channel.backlog_push(task_id).await?;
        }
    }

    // Verify tasks are in backlog
    let backlog = channel.backlog_list().await?;
    assert_eq!(backlog.len(), 2);
    assert_eq!(backlog[0], task1_id);
    assert_eq!(backlog[1], task2_id);

    Ok(())
}

/// Test that a message can be moved from one agent to another.
#[tokio::test]
async fn test_move_message_to_inbox() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("move-message-test").await?;

    let channel = town.channel();

    // Create two agents
    let agent1 = town.spawn_agent("worker-1", "claude").await?;
    let agent2 = town.spawn_agent("worker-2", "claude").await?;
    let agent1_id = agent1.id();
    let agent2_id = agent2.id();

    // Send a message to agent1
    let original_msg = Message::new(
        AgentId::supervisor(),
        agent1_id,
        MessageType::TaskAssign {
            task_id: "important-task".to_string(),
        },
    );
    channel.send(&original_msg).await?;

    // Verify message is in agent1's inbox
    assert_eq!(agent1.inbox_len().await?, 1);
    assert_eq!(agent2.inbox_len().await?, 0);

    // Drain from agent1 and move to agent2
    let drained = channel.drain_inbox(agent1_id).await?;
    assert_eq!(drained.len(), 1);

    // Move the message to agent2
    channel
        .move_message_to_inbox(&drained[0], agent2_id)
        .await?;

    // Verify message moved
    assert_eq!(agent1.inbox_len().await?, 0);
    assert_eq!(agent2.inbox_len().await?, 1);

    // Receive from agent2 and verify content preserved
    let received = channel.try_receive(agent2_id).await?;
    assert!(received.is_some());
    let msg = received.unwrap();
    match msg.msg_type {
        MessageType::TaskAssign { task_id } => assert_eq!(task_id, "important-task"),
        _ => panic!("Expected TaskAssign message type"),
    }

    Ok(())
}

// ============================================================================
// TCP REDIS CONFIGURATION TESTS
// ============================================================================

/// Test that redis_url() returns Unix socket URL when use_socket is true.
#[tokio::test]
async fn test_redis_url_unix_socket() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Explicitly set Unix socket mode (may not be default if global config uses central Redis)
    config.redis = RedisConfig {
        url: None,
        use_socket: true,
        socket_path: "redis.sock".to_string(),
        host: "127.0.0.1".to_string(),
        port: 6379,
        persist: false,
        aof_path: "redis.aof".to_string(),
        password: None,
        tls_enabled: false,
        tls_cert: None,
        tls_key: None,
        tls_ca_cert: None,
        bind: "127.0.0.1".to_string(),
    };

    assert!(config.redis.use_socket);
    let url = config.redis_url();
    assert!(
        url.starts_with("unix://"),
        "Expected unix:// URL, got: {}",
        url
    );
    assert!(
        url.contains("redis.sock"),
        "Expected socket path in URL, got: {}",
        url
    );

    Ok(())
}

/// Test that redis_url() returns TCP URL without password.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_tcp_no_password() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up env var first
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TCP mode without password
    config.redis = RedisConfig {
        use_socket: false,
        host: "127.0.0.1".to_string(),
        port: 6380,
        password: None,
        tls_enabled: false,
        ..Default::default()
    };

    let url = config.redis_url();
    assert_eq!(url, "redis://127.0.0.1:6380", "Unexpected URL: {}", url);

    Ok(())
}

/// Test that redis_url() returns TCP URL with password.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_tcp_with_password() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up env var first
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TCP mode with password
    config.redis = RedisConfig {
        use_socket: false,
        host: "localhost".to_string(),
        port: 6379,
        password: Some("secret123".to_string()),
        tls_enabled: false,
        ..Default::default()
    };

    let url = config.redis_url();
    assert_eq!(
        url, "redis://:secret123@localhost:6379",
        "Unexpected URL: {}",
        url
    );

    Ok(())
}

/// Test that redis_url() returns TLS URL (rediss scheme) when TLS is enabled.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_tls_enabled() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up env var first
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TLS mode
    config.redis = RedisConfig {
        use_socket: false,
        host: "redis.example.com".to_string(),
        port: 6379,
        password: Some("tls-password".to_string()),
        tls_enabled: true,
        ..Default::default()
    };

    let url = config.redis_url();
    assert!(
        url.starts_with("rediss://"),
        "Expected rediss:// scheme, got: {}",
        url
    );
    assert_eq!(url, "rediss://:tls-password@redis.example.com:6379");

    Ok(())
}

/// Test is_remote_redis() correctly identifies local vs remote Redis.
#[tokio::test]
async fn test_is_remote_redis() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Unix socket is not remote
    config.redis.use_socket = true;
    assert!(
        !config.is_remote_redis(),
        "Unix socket should not be remote"
    );

    // localhost is not remote
    config.redis = RedisConfig {
        use_socket: false,
        host: "localhost".to_string(),
        port: 6379,
        ..Default::default()
    };
    assert!(!config.is_remote_redis(), "localhost should not be remote");

    // 127.0.0.1 is not remote
    config.redis.host = "127.0.0.1".to_string();
    assert!(!config.is_remote_redis(), "127.0.0.1 should not be remote");

    // 127.0.1.1 is not remote (any 127.x.x.x)
    config.redis.host = "127.0.1.1".to_string();
    assert!(!config.is_remote_redis(), "127.x.x.x should not be remote");

    // External host IS remote
    config.redis.host = "redis.example.com".to_string();
    assert!(
        config.is_remote_redis(),
        "redis.example.com should be remote"
    );

    // IP address IS remote
    config.redis.host = "192.168.1.100".to_string();
    assert!(config.is_remote_redis(), "192.168.1.100 should be remote");

    Ok(())
}

/// Test that default RedisConfig has expected defaults.
#[tokio::test]
async fn test_redis_config_defaults() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::config::RedisConfig;

    let config = RedisConfig::default();

    assert!(
        config.url.is_none(),
        "Explicit URL should be unset by default"
    );

    // Unix socket is default (under .tt/)
    assert!(config.use_socket, "Default should use Unix socket");
    assert_eq!(config.socket_path, ".tt/redis.sock");

    // TCP defaults
    assert_eq!(config.host, "127.0.0.1");
    assert_eq!(config.port, 6379);

    // Security defaults - disabled by default
    assert!(
        config.password.is_none(),
        "Password should be None by default"
    );
    assert!(!config.tls_enabled, "TLS should be disabled by default");
    assert!(config.tls_cert.is_none());
    assert!(config.tls_key.is_none());
    assert!(config.tls_ca_cert.is_none());

    // Bind defaults to localhost for security
    assert_eq!(config.bind, "127.0.0.1");

    Ok(())
}

/// Test redis_url() uses env var password over config password.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_password_env_var_override() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up any existing env var first
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TCP mode with config password
    config.redis = RedisConfig {
        use_socket: false,
        host: "localhost".to_string(),
        port: 6379,
        password: Some("config-password".to_string()),
        tls_enabled: false,
        ..Default::default()
    };

    // Set env var to override
    // Safety: This is a serial test
    unsafe {
        std::env::set_var("TINYTOWN_REDIS_PASSWORD", "env-password");
    }

    // redis_password() should return env var
    assert_eq!(
        config.redis_password(),
        Some("env-password".to_string()),
        "Env var should override config password"
    );

    // URL should use env var password
    let url = config.redis_url();
    assert!(
        url.contains("env-password"),
        "URL should use env var password, got: {}",
        url
    );
    assert!(
        !url.contains("config-password"),
        "URL should NOT use config password, got: {}",
        url
    );

    // Clean up env var
    // Safety: This is a single-threaded test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    // Now it should use config password
    assert_eq!(
        config.redis_password(),
        Some("config-password".to_string()),
        "After removing env var, should use config password"
    );

    Ok(())
}

/// Test that redis_url_redacted() properly masks passwords.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_redacted_masks_password() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up any env var first to ensure test isolation
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TCP mode with password
    config.redis = RedisConfig {
        use_socket: false,
        host: "redis.example.com".to_string(),
        port: 6379,
        password: Some("super-secret-password".to_string()),
        tls_enabled: false,
        ..Default::default()
    };

    // redis_url() contains real password
    let real_url = config.redis_url();
    assert!(
        real_url.contains("super-secret-password"),
        "Real URL should contain password"
    );

    // redis_url_redacted() should mask it
    let redacted_url = config.redis_url_redacted();
    assert!(
        !redacted_url.contains("super-secret-password"),
        "Redacted URL should NOT contain password"
    );
    assert!(
        redacted_url.contains("****"),
        "Redacted URL should contain mask: {}",
        redacted_url
    );
    assert_eq!(redacted_url, "redis://:****@redis.example.com:6379");

    // TLS mode should also be redacted properly
    config.redis.tls_enabled = true;
    let redacted_tls = config.redis_url_redacted();
    assert!(redacted_tls.starts_with("rediss://"));
    assert!(redacted_tls.contains("****"));
    assert!(!redacted_tls.contains("super-secret-password"));

    Ok(())
}

/// Test that redis_url_redacted() returns normal URL when no password is set.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_redacted_no_password() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;
    use tinytown::config::RedisConfig;

    // Clean up any env var first to ensure test isolation
    // Safety: This is a serial test
    unsafe {
        std::env::remove_var("TINYTOWN_REDIS_PASSWORD");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());

    // Configure TCP mode without password
    config.redis = RedisConfig {
        use_socket: false,
        host: "localhost".to_string(),
        port: 6379,
        password: None,
        tls_enabled: false,
        ..Default::default()
    };

    // Both should be the same when no password
    let real_url = config.redis_url();
    let redacted_url = config.redis_url_redacted();
    assert_eq!(real_url, redacted_url, "URLs should match when no password");
    assert_eq!(real_url, "redis://localhost:6379");

    Ok(())
}

/// Test that an explicit Redis URL from config takes precedence over host/port fields.
#[tokio::test]
async fn test_redis_url_config_override() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());
    config.redis.use_socket = false;
    config.redis.host = "should-not-be-used".to_string();
    config.redis.port = 6399;
    config.redis.url = Some("redis://override.example.com:6381/2".to_string());

    assert_eq!(config.redis_url(), "redis://override.example.com:6381/2");
    assert!(config.is_remote_redis());

    Ok(())
}

/// Test that explicit Redis URLs redact passwords while preserving usernames.
#[tokio::test]
async fn test_redis_url_redacted_masks_explicit_url_password()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());
    config.redis.url = Some("rediss://default:cloud-secret@redis.example.com:6380/0".to_string());

    assert_eq!(
        config.redis_url_redacted(),
        "rediss://default:****@redis.example.com:6380/0"
    );
    assert!(!config.redis_url_redacted().contains("cloud-secret"));

    Ok(())
}

/// Test that explicit Redis URLs preserve already-encoded usernames when masking passwords.
#[tokio::test]
async fn test_redis_url_redacted_preserves_encoded_username()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());
    config.redis.url =
        Some("rediss://user%40name:cloud-secret@redis.example.com:6380/0".to_string());

    assert_eq!(
        config.redis_url_redacted(),
        "rediss://user%40name:****@redis.example.com:6380/0"
    );
    assert!(!config.redis_url_redacted().contains("%2540"));

    Ok(())
}

/// Test that malformed explicit Redis URLs still redact credentials in logs.
#[tokio::test]
async fn test_redis_url_redacted_masks_malformed_explicit_url_password()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());
    config.redis.url = Some("redis://default:cloud-secret@".to_string());

    assert_eq!(config.redis_url_redacted(), "redis://default:****@");
    assert!(!config.redis_url_redacted().contains("cloud-secret"));

    Ok(())
}

/// Test that REDIS_URL env var overrides config and marks Redis as external.
#[tokio::test]
#[serial_test::serial]
async fn test_redis_url_env_override() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    unsafe {
        std::env::remove_var("REDIS_URL");
    }

    let temp_dir = TempDir::new()?;
    let mut config = Config::new("test-town", temp_dir.path());
    config.redis.url = Some("redis://config.example.com:6379".to_string());

    unsafe {
        std::env::set_var("REDIS_URL", "redis://env.example.com:6380/5");
    }

    assert_eq!(config.redis_url(), "redis://env.example.com:6380/5");
    assert_eq!(
        config.redis_url_redacted(),
        "redis://env.example.com:6380/5"
    );
    assert!(config.is_remote_redis());

    unsafe {
        std::env::remove_var("REDIS_URL");
    }

    Ok(())
}

/// Test that init_with_config skips local redis startup when an explicit URL is configured.
#[tokio::test]
async fn test_town_init_with_explicit_redis_url_skips_local_startup()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let source_dir = TempDir::new()?;
    let source_town = Town::init(source_dir.path(), unique_town_name("redis-source")).await?;
    let source_url = source_town.config().redis_url();

    let target_dir = TempDir::new()?;
    let mut config = Config::new(unique_town_name("redis-target"), target_dir.path());
    config.redis.url = Some(source_url);
    config.redis.host = "invalid-host".to_string();
    config.redis.port = 1;
    config.redis.use_socket = false;

    let target_town = Town::init_with_config(config).await?;
    assert!(target_town.config().is_remote_redis());
    assert!(!target_dir.path().join(".tt/redis.pid").exists());

    Ok(())
}

/// Test that REDIS_URL env override skips local startup and is used for connection.
#[tokio::test]
#[serial_test::serial]
async fn test_town_init_with_redis_url_env_override_skips_local_startup()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    unsafe {
        std::env::remove_var("REDIS_URL");
    }

    let source_dir = TempDir::new()?;
    let source_town = Town::init(source_dir.path(), unique_town_name("redis-env-source")).await?;

    unsafe {
        std::env::set_var("REDIS_URL", source_town.config().redis_url());
    }

    let target_dir = TempDir::new()?;
    let mut config = Config::new(unique_town_name("redis-env-target"), target_dir.path());
    config.redis.host = "invalid-host".to_string();
    config.redis.port = 1;
    config.redis.use_socket = false;

    let target_town = Town::init_with_config(config).await?;
    assert!(target_town.config().is_remote_redis());
    assert!(!target_dir.path().join(".tt/redis.pid").exists());

    unsafe {
        std::env::remove_var("REDIS_URL");
    }

    Ok(())
}

/// Test that unreachable explicit Redis URLs fail with a clear error.
#[tokio::test]
async fn test_town_init_with_unreachable_explicit_redis_url_returns_clear_error()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::{Config, Error};

    let temp_dir = TempDir::new()?;
    let mut config = Config::new(unique_town_name("redis-fail"), temp_dir.path());
    let unused_port = reserve_unused_port()?;
    config.redis.url = Some(format!("redis://127.0.0.1:{unused_port}"));

    match Town::init_with_config(config).await {
        Err(Error::Config(message)) => {
            assert!(
                message.contains("Failed to connect to configured Redis"),
                "unexpected message: {message}"
            );
            assert!(
                message.contains(&format!("redis://127.0.0.1:{unused_port}")),
                "unexpected message: {message}"
            );
        }
        Ok(_) => panic!("expected config error, got successful town init"),
        Err(other) => panic!("expected config error, got {other}"),
    }

    Ok(())
}

// ============================================================================
// MISSION MODULE TESTS
// ============================================================================

/// Test MissionId creation and parsing.
#[test]
fn test_mission_id_creation_and_parsing() {
    use tinytown::mission::{MissionId, WatchId, WorkItemId};
    use uuid::Uuid;

    // Test MissionId
    let id1 = MissionId::new();
    let id2 = MissionId::new();
    assert_ne!(id1, id2, "Each new ID should be unique");

    // Test from_uuid
    let uuid = Uuid::new_v4();
    let id_from_uuid = MissionId::from_uuid(uuid);
    assert_eq!(format!("{}", id_from_uuid), format!("{}", uuid));

    // Test Display and FromStr roundtrip
    let id_str = id1.to_string();
    let parsed: MissionId = id_str.parse().expect("Should parse MissionId");
    assert_eq!(id1, parsed);

    // Test Default
    let default_id = MissionId::default();
    assert_ne!(default_id, id1, "Default should create new ID");

    // Test WorkItemId similarly
    let work_id = WorkItemId::new();
    let work_str = work_id.to_string();
    let parsed_work: WorkItemId = work_str.parse().expect("Should parse WorkItemId");
    assert_eq!(work_id, parsed_work);

    // Test WatchId similarly
    let watch_id = WatchId::new();
    let watch_str = watch_id.to_string();
    let parsed_watch: WatchId = watch_str.parse().expect("Should parse WatchId");
    assert_eq!(watch_id, parsed_watch);
}

/// Test ObjectiveRef display formatting.
#[test]
fn test_objective_ref_display() {
    use tinytown::mission::ObjectiveRef;

    let issue_ref = ObjectiveRef::Issue {
        owner: "redis-field-engineering".into(),
        repo: "tinytown".into(),
        number: 42,
    };
    assert_eq!(
        format!("{}", issue_ref),
        "redis-field-engineering/tinytown#42"
    );

    let doc_ref = ObjectiveRef::Doc {
        path: "docs/design.md".into(),
    };
    assert_eq!(format!("{}", doc_ref), "docs/design.md");
}

/// Test MissionRun creation and state transitions.
#[test]
fn test_mission_run_state_transitions() {
    use tinytown::mission::{MissionRun, MissionState, ObjectiveRef};

    let objectives = vec![ObjectiveRef::Issue {
        owner: "owner".into(),
        repo: "repo".into(),
        number: 1,
    }];

    let mut mission = MissionRun::new(objectives.clone());
    assert_eq!(mission.state, MissionState::Planning);
    assert!(mission.blocked_reason.is_none());
    assert_eq!(mission.objective_refs.len(), 1);

    // Test start transition
    mission.start();
    assert_eq!(mission.state, MissionState::Running);

    // Test block transition
    mission.block("Waiting for CI");
    assert_eq!(mission.state, MissionState::Blocked);
    assert_eq!(mission.blocked_reason.as_deref(), Some("Waiting for CI"));

    // Test complete transition
    mission.complete();
    assert_eq!(mission.state, MissionState::Completed);
    assert!(mission.blocked_reason.is_none());

    // Test fail transition (from fresh mission)
    let mut mission2 = MissionRun::new(objectives);
    mission2.fail("Unrecoverable error");
    assert_eq!(mission2.state, MissionState::Failed);
    assert_eq!(
        mission2.blocked_reason.as_deref(),
        Some("Unrecoverable error")
    );
}

/// Test MissionRun with custom policy.
#[test]
fn test_mission_run_with_policy() {
    use tinytown::mission::{MissionPolicy, MissionRun, ObjectiveRef};

    let objectives = vec![ObjectiveRef::Doc {
        path: "README.md".into(),
    }];
    let policy = MissionPolicy {
        max_parallel_items: 5,
        reviewer_required: false,
        auto_merge: true,
        watch_interval_secs: 60,
    };

    let mission = MissionRun::new(objectives).with_policy(policy.clone());
    assert_eq!(mission.policy.max_parallel_items, 5);
    assert!(!mission.policy.reviewer_required);
    assert!(mission.policy.auto_merge);
    assert_eq!(mission.policy.watch_interval_secs, 60);
}

/// Test WorkItem creation and state transitions.
#[test]
fn test_work_item_state_transitions() {
    use tinytown::AgentId;
    use tinytown::mission::{MissionId, WorkItem, WorkKind, WorkStatus};

    let mission_id = MissionId::new();
    let mut work_item = WorkItem::new(mission_id, "Implement feature", WorkKind::Implement);

    assert_eq!(work_item.status, WorkStatus::Pending);
    assert!(!work_item.status.is_terminal());
    assert!(!work_item.status.is_ready());
    assert!(work_item.assigned_to.is_none());
    assert!(work_item.artifact_refs.is_empty());

    // Test mark_ready
    work_item.mark_ready();
    assert_eq!(work_item.status, WorkStatus::Ready);
    assert!(work_item.status.is_ready());

    // Test assign
    let agent_id = AgentId::new();
    work_item.assign(agent_id);
    assert_eq!(work_item.status, WorkStatus::Assigned);
    assert_eq!(work_item.assigned_to, Some(agent_id));

    // Test start
    work_item.start();
    assert_eq!(work_item.status, WorkStatus::Running);

    // Test block
    work_item.block();
    assert_eq!(work_item.status, WorkStatus::Blocked);

    // Test complete
    work_item.complete(vec!["https://github.com/owner/repo/pull/1".into()]);
    assert_eq!(work_item.status, WorkStatus::Done);
    assert!(work_item.status.is_terminal());
    assert_eq!(work_item.artifact_refs.len(), 1);
}

/// Test WorkItem builder methods.
#[test]
fn test_work_item_builder_methods() {
    use tinytown::mission::{MissionId, WorkItem, WorkItemId, WorkKind};

    let mission_id = MissionId::new();
    let dep1 = WorkItemId::new();
    let dep2 = WorkItemId::new();

    let work_item = WorkItem::new(mission_id, "Test feature", WorkKind::Test)
        .with_dependencies(vec![dep1, dep2])
        .with_owner_role("tester")
        .with_source_ref("owner/repo#42");

    assert_eq!(work_item.depends_on.len(), 2);
    assert!(work_item.depends_on.contains(&dep1));
    assert!(work_item.depends_on.contains(&dep2));
    assert_eq!(work_item.owner_role.as_deref(), Some("tester"));
    assert_eq!(work_item.source_ref.as_deref(), Some("owner/repo#42"));
    assert_eq!(work_item.kind, WorkKind::Test);
}

/// Test WatchItem creation and check scheduling.
#[test]
fn test_watch_item_scheduling() {
    use tinytown::mission::{
        MissionId, TriggerAction, WatchItem, WatchKind, WatchStatus, WorkItemId,
    };

    let mission_id = MissionId::new();
    let work_item_id = WorkItemId::new();

    // Create watch with 1 second interval for test
    let watch = WatchItem::new(
        mission_id,
        work_item_id,
        WatchKind::PrChecks,
        "https://github.com/owner/repo/pull/1",
        1,
    );

    assert_eq!(watch.status, WatchStatus::Active);
    assert_eq!(watch.kind, WatchKind::PrChecks);
    assert!(watch.last_check_at.is_none());
    assert_eq!(watch.consecutive_failures, 0);

    // Test with_trigger
    let watch_with_trigger = WatchItem::new(
        mission_id,
        work_item_id,
        WatchKind::ReviewComments,
        "pr/1",
        60,
    )
    .with_trigger(TriggerAction::NotifyReviewer);

    assert_eq!(watch_with_trigger.on_trigger, TriggerAction::NotifyReviewer);
}

/// Test WatchItem check recording.
#[test]
fn test_watch_item_check_recording() {
    use chrono::Utc;
    use tinytown::mission::{MissionId, WatchItem, WatchKind, WorkItemId};

    let mission_id = MissionId::new();
    let work_item_id = WorkItemId::new();

    let mut watch = WatchItem::new(mission_id, work_item_id, WatchKind::PrChecks, "pr/1", 60);

    // Record successful check
    let before_check = Utc::now();
    watch.record_check();
    assert!(watch.last_check_at.is_some());
    assert!(watch.last_check_at.unwrap() >= before_check);
    assert_eq!(watch.consecutive_failures, 0);
    // Next due should be ~60 seconds from now
    assert!(watch.next_due_at > before_check);

    // Record failures with backoff
    watch.record_failure();
    assert_eq!(watch.consecutive_failures, 1);

    watch.record_failure();
    assert_eq!(watch.consecutive_failures, 2);

    watch.record_failure();
    assert_eq!(watch.consecutive_failures, 3);
}

/// Test WatchItem snooze and complete.
#[test]
fn test_watch_item_snooze_and_complete() {
    use chrono::Utc;
    use tinytown::mission::{MissionId, WatchItem, WatchKind, WatchStatus, WorkItemId};

    let mission_id = MissionId::new();
    let work_item_id = WorkItemId::new();

    let mut watch = WatchItem::new(
        mission_id,
        work_item_id,
        WatchKind::Mergeability,
        "pr/1",
        60,
    );

    // Test snooze
    watch.snooze(300);
    assert_eq!(watch.status, WatchStatus::Snoozed);
    assert!(watch.next_due_at > Utc::now());

    // Test complete
    watch.complete();
    assert_eq!(watch.status, WatchStatus::Done);
}

/// Test WorkKind and WorkStatus variants.
#[test]
fn test_work_kind_and_status_variants() {
    use tinytown::mission::{WorkKind, WorkStatus};

    // Test all WorkKind variants exist
    let kinds = [
        WorkKind::Design,
        WorkKind::Implement,
        WorkKind::Test,
        WorkKind::Review,
        WorkKind::MergeGate,
        WorkKind::Followup,
    ];
    assert_eq!(kinds.len(), 6);
    assert_eq!(WorkKind::default(), WorkKind::Implement);

    // Test all WorkStatus variants
    let statuses = [
        WorkStatus::Pending,
        WorkStatus::Ready,
        WorkStatus::Assigned,
        WorkStatus::Running,
        WorkStatus::Blocked,
        WorkStatus::Done,
    ];
    assert_eq!(statuses.len(), 6);
    assert_eq!(WorkStatus::default(), WorkStatus::Pending);

    // Test is_terminal for each status
    assert!(!WorkStatus::Pending.is_terminal());
    assert!(!WorkStatus::Ready.is_terminal());
    assert!(!WorkStatus::Assigned.is_terminal());
    assert!(!WorkStatus::Running.is_terminal());
    assert!(!WorkStatus::Blocked.is_terminal());
    assert!(WorkStatus::Done.is_terminal());

    // Test is_ready for each status
    assert!(!WorkStatus::Pending.is_ready());
    assert!(WorkStatus::Ready.is_ready());
    assert!(!WorkStatus::Assigned.is_ready());
}

/// Test MissionState, WatchKind, WatchStatus, and TriggerAction defaults.
#[test]
fn test_enum_defaults() {
    use tinytown::mission::{MissionState, TriggerAction, WatchKind, WatchStatus};

    assert_eq!(MissionState::default(), MissionState::Planning);
    assert_eq!(WatchKind::default(), WatchKind::PrChecks);
    assert_eq!(WatchStatus::default(), WatchStatus::Active);
    assert_eq!(TriggerAction::default(), TriggerAction::CreateFixTask);
}

/// Test MissionPolicy default values.
#[test]
fn test_mission_policy_defaults() {
    use tinytown::mission::MissionPolicy;

    let policy = MissionPolicy::default();
    assert_eq!(policy.max_parallel_items, 2);
    assert!(policy.reviewer_required);
    assert!(!policy.auto_merge);
    assert_eq!(policy.watch_interval_secs, 180);
}

// ============================================================================
// MISSION STORAGE TESTS
// ============================================================================

/// Test MissionStorage save and get operations for MissionRun.
#[tokio::test]
async fn test_mission_storage_save_and_get_mission() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionState, MissionStorage, ObjectiveRef};

    let town = create_test_town("mission-storage-basic").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let objectives = vec![ObjectiveRef::Issue {
        owner: "owner".into(),
        repo: "repo".into(),
        number: 42,
    }];

    let mission = MissionRun::new(objectives);
    let mission_id = mission.id;

    // Save mission
    storage.save_mission(&mission).await?;

    // Get mission
    let retrieved = storage.get_mission(mission_id).await?;
    assert!(retrieved.is_some());
    let retrieved = retrieved.unwrap();
    assert_eq!(retrieved.id, mission_id);
    assert_eq!(retrieved.state, MissionState::Planning);
    assert_eq!(retrieved.objective_refs.len(), 1);

    Ok(())
}

/// Test MissionStorage delete operation.
#[tokio::test]
async fn test_mission_storage_delete_mission() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionStorage, ObjectiveRef};

    let town = create_test_town("mission-storage-delete").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    let mission_id = mission.id;

    storage.save_mission(&mission).await?;

    // Verify it exists
    assert!(storage.get_mission(mission_id).await?.is_some());

    // Delete
    let deleted = storage.delete_mission(mission_id).await?;
    assert!(deleted);

    // Verify it's gone
    assert!(storage.get_mission(mission_id).await?.is_none());

    // Delete non-existent should return false
    let deleted_again = storage.delete_mission(mission_id).await?;
    assert!(!deleted_again);

    Ok(())
}

/// Test MissionStorage active set operations.
#[tokio::test]
async fn test_mission_storage_active_set() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionStorage, ObjectiveRef};

    let town = create_test_town("mission-storage-active").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    // Initially empty
    let active = storage.list_active().await?;
    assert!(active.is_empty());

    // Create and add two missions to active set
    let mission1 = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "doc1.md".into(),
    }]);
    let mission2 = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "doc2.md".into(),
    }]);
    let id1 = mission1.id;
    let id2 = mission2.id;

    storage.save_mission(&mission1).await?;
    storage.save_mission(&mission2).await?;
    storage.add_active(id1).await?;
    storage.add_active(id2).await?;

    // List active
    let active = storage.list_active().await?;
    assert_eq!(active.len(), 2);
    assert!(active.contains(&id1));
    assert!(active.contains(&id2));

    // Remove one
    storage.remove_active(id1).await?;
    let active = storage.list_active().await?;
    assert_eq!(active.len(), 1);
    assert!(!active.contains(&id1));
    assert!(active.contains(&id2));

    Ok(())
}

/// Test MissionStorage WorkItem operations.
#[tokio::test]
async fn test_mission_storage_work_items() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionStorage, ObjectiveRef, WorkItem, WorkKind};

    let town = create_test_town("mission-storage-work").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    let mission_id = mission.id;
    storage.save_mission(&mission).await?;

    // Create and save work items
    let work1 = WorkItem::new(mission_id, "Design feature", WorkKind::Design);
    let work2 = WorkItem::new(mission_id, "Implement feature", WorkKind::Implement);
    let work1_id = work1.id;
    let work2_id = work2.id;

    storage.save_work_item(&work1).await?;
    storage.save_work_item(&work2).await?;

    // Get individual work item
    let retrieved = storage.get_work_item(mission_id, work1_id).await?;
    assert!(retrieved.is_some());
    assert_eq!(retrieved.unwrap().title, "Design feature");

    // List all work items
    let items = storage.list_work_items(mission_id).await?;
    assert_eq!(items.len(), 2);

    // Delete one
    let deleted = storage.delete_work_item(mission_id, work1_id).await?;
    assert!(deleted);

    let items = storage.list_work_items(mission_id).await?;
    assert_eq!(items.len(), 1);
    assert_eq!(items[0].id, work2_id);

    Ok(())
}

/// Test that mission scheduler assignments create persisted TaskAssign messages.
#[tokio::test]
async fn test_mission_scheduler_assigns_persisted_tasks() -> Result<(), Box<dyn std::error::Error>>
{
    use tinytown::mission::{
        MissionRun, MissionScheduler, MissionStorage, ObjectiveRef, WorkItem, WorkKind,
    };

    let town = create_test_town("mission-scheduler-task-assign").await?;
    let agent_handle = town.spawn_agent("backend-worker", "claude").await?;

    let mut agent = Agent::new("backend-worker", "claude", AgentType::Worker);
    agent.id = agent_handle.id();
    agent.state = AgentState::Idle;
    town.channel().set_agent_state(&agent).await?;

    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let mut mission = MissionRun::new(vec![ObjectiveRef::Issue {
        owner: "owner".into(),
        repo: "repo".into(),
        number: 42,
    }]);
    mission.policy.reviewer_required = false;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut work_item = WorkItem::new(mission.id, "Implement feature", WorkKind::Implement);
    work_item.mark_ready();
    let work_item_id = work_item.id;
    storage.save_work_item(&work_item).await?;

    let scheduler = MissionScheduler::with_defaults(storage.clone(), town.channel().clone());
    let result = scheduler.tick().await?;
    assert_eq!(result.total_assigned, 1);

    let inbox = town.channel().peek_inbox(agent_handle.id(), 10).await?;
    assert_eq!(inbox.len(), 1);

    let task_id = match &inbox[0].msg_type {
        MessageType::TaskAssign { task_id } => task_id.parse::<TaskId>()?,
        other => panic!("expected TaskAssign, got {:?}", other),
    };

    let task = town
        .channel()
        .get_task(task_id)
        .await?
        .expect("stored task");
    assert_eq!(task.assigned_to, Some(agent_handle.id()));
    assert!(
        task.description
            .contains("[Mission Work Item] Implement feature")
    );
    assert!(task.tags.iter().any(|tag| tag == "mission-work-item"));
    assert!(
        task.tags
            .iter()
            .any(|tag| tag == &format!("mission:{}", mission.id))
    );
    assert!(
        task.tags
            .iter()
            .any(|tag| tag == &format!("work-item:{}", work_item_id))
    );

    Ok(())
}

/// Test MissionStorage WatchItem operations.
#[tokio::test]
async fn test_mission_storage_watch_items() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionStorage, ObjectiveRef, WatchItem, WatchKind, WorkItem, WorkKind,
    };

    let town = create_test_town("mission-storage-watch").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    let mission_id = mission.id;
    storage.save_mission(&mission).await?;

    let work = WorkItem::new(mission_id, "Implement", WorkKind::Implement);
    let work_id = work.id;
    storage.save_work_item(&work).await?;

    // Create and save watch item
    let watch = WatchItem::new(mission_id, work_id, WatchKind::PrChecks, "pr/123", 60);
    let watch_id = watch.id;
    storage.save_watch_item(&watch).await?;

    // Get watch item
    let retrieved = storage.get_watch_item(mission_id, watch_id).await?;
    assert!(retrieved.is_some());
    assert_eq!(retrieved.unwrap().target_ref, "pr/123");

    // List watch items
    let watches = storage.list_watch_items(mission_id).await?;
    assert_eq!(watches.len(), 1);

    // Delete watch
    let deleted = storage.delete_watch_item(mission_id, watch_id).await?;
    assert!(deleted);
    assert!(storage.list_watch_items(mission_id).await?.is_empty());

    Ok(())
}

/// Test MissionStorage event logging.
#[tokio::test]
async fn test_mission_storage_events() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionStorage, ObjectiveRef};

    let town = create_test_town("mission-storage-events").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    let mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    let mission_id = mission.id;
    storage.save_mission(&mission).await?;

    // Log some events
    storage.log_event(mission_id, "Mission started").await?;
    storage.log_event(mission_id, "Work item assigned").await?;
    storage.log_event(mission_id, "PR created").await?;

    // Get events (they should be in reverse order - newest first)
    let events = storage.get_events(mission_id, 10).await?;
    assert_eq!(events.len(), 3);

    // Events should contain timestamps and messages
    assert!(events[0].contains("PR created"));
    assert!(events[1].contains("Work item assigned"));
    assert!(events[2].contains("Mission started"));

    Ok(())
}

/// Test MissionStorage list_all_missions operation.
#[tokio::test]
async fn test_mission_storage_list_all() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{MissionRun, MissionStorage, ObjectiveRef};

    let town = create_test_town("mission-storage-list-all").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    // Create multiple missions
    let mission1 = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "doc1.md".into(),
    }]);
    let mission2 = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "doc2.md".into(),
    }]);
    let mission3 = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "doc3.md".into(),
    }]);

    storage.save_mission(&mission1).await?;
    storage.save_mission(&mission2).await?;
    storage.save_mission(&mission3).await?;

    // List all missions
    let all = storage.list_all_missions().await?;
    assert_eq!(all.len(), 3);

    // Verify IDs are present
    let ids: Vec<_> = all.iter().map(|m| m.id).collect();
    assert!(ids.contains(&mission1.id));
    assert!(ids.contains(&mission2.id));
    assert!(ids.contains(&mission3.id));

    Ok(())
}

/// Test MissionStorage list_due_watches across active missions.
#[tokio::test]
async fn test_mission_storage_list_due_watches() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionStorage, ObjectiveRef, WatchItem, WatchKind, WorkItem, WorkKind,
    };

    let town = create_test_town("mission-storage-due-watches").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    // Create mission with watch items
    let mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    let mission_id = mission.id;
    storage.save_mission(&mission).await?;
    storage.add_active(mission_id).await?;

    let work = WorkItem::new(mission_id, "Implement", WorkKind::Implement);
    let work_id = work.id;
    storage.save_work_item(&work).await?;

    // Create a watch that is due (interval of 0 means immediately due)
    let watch = WatchItem::new(mission_id, work_id, WatchKind::PrChecks, "pr/123", 0);
    storage.save_watch_item(&watch).await?;

    // List due watches
    let due = storage.list_due_watches().await?;
    assert_eq!(due.len(), 1);
    assert_eq!(due[0].target_ref, "pr/123");

    Ok(())
}

/// Test mission and work item update flow.
#[tokio::test]
async fn test_mission_storage_update_flow() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionState, MissionStorage, ObjectiveRef, WorkItem, WorkKind, WorkStatus,
    };

    let town = create_test_town("mission-storage-update").await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), town.channel().town_name());

    // Create and save mission
    let mut mission = MissionRun::new(vec![ObjectiveRef::Issue {
        owner: "owner".into(),
        repo: "repo".into(),
        number: 1,
    }]);
    let mission_id = mission.id;
    storage.save_mission(&mission).await?;

    // Update mission state
    mission.start();
    storage.save_mission(&mission).await?;

    let retrieved = storage.get_mission(mission_id).await?.unwrap();
    assert_eq!(retrieved.state, MissionState::Running);

    // Create and update work item
    let mut work = WorkItem::new(mission_id, "Task", WorkKind::Implement);
    let work_id = work.id;
    storage.save_work_item(&work).await?;

    work.mark_ready();
    storage.save_work_item(&work).await?;

    let retrieved_work = storage.get_work_item(mission_id, work_id).await?.unwrap();
    assert_eq!(retrieved_work.status, WorkStatus::Ready);

    Ok(())
}

/// Test that a worker submission creates review work and PR watches.
#[tokio::test]
async fn test_mission_record_submission_creates_review_task_and_watches()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionScheduler, MissionStorage, ObjectiveRef, WatchKind, WorkItem,
        WorkItemCompletion, WorkKind,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-record-submission");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let worker = town.spawn_agent("backend-worker", "claude").await?;
    let reviewer = town.spawn_agent("reviewer", "claude").await?;

    let mut worker_state = Agent::new("backend-worker", "claude", AgentType::Worker);
    worker_state.id = worker.id();
    worker_state.state = AgentState::Idle;
    town.channel().set_agent_state(&worker_state).await?;

    let mut reviewer_state = Agent::new("reviewer", "claude", AgentType::Worker);
    reviewer_state.id = reviewer.id();
    reviewer_state.state = AgentState::Idle;
    town.channel().set_agent_state(&reviewer_state).await?;

    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);
    let mut mission = MissionRun::new(vec![ObjectiveRef::Issue {
        owner: "owner".into(),
        repo: "repo".into(),
        number: 1,
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.assign(worker.id());
    storage.save_work_item(&item).await?;

    let scheduler = MissionScheduler::with_defaults(storage.clone(), town.channel().clone());
    let completion = scheduler
        .record_submission(
            mission.id,
            item.id,
            vec![
                "task:123".into(),
                "Opened PR https://github.com/test/repo/pull/42".into(),
            ],
        )
        .await?;
    assert_eq!(completion, WorkItemCompletion::WaitingForReview);

    let watches = storage.list_watch_items(mission.id).await?;
    assert_eq!(watches.len(), 4);
    assert!(
        watches
            .iter()
            .any(|watch| watch.kind == WatchKind::PrChecks)
    );
    assert!(
        watches
            .iter()
            .any(|watch| watch.kind == WatchKind::BugbotComments)
    );
    assert!(
        watches
            .iter()
            .any(|watch| watch.kind == WatchKind::ReviewComments)
    );
    assert!(
        watches
            .iter()
            .any(|watch| watch.kind == WatchKind::Mergeability)
    );

    let review_tasks: Vec<_> = town
        .channel()
        .list_tasks()
        .await?
        .into_iter()
        .filter(|task| task.tags.iter().any(|tag| tag == "mission-review-task"))
        .collect();
    assert_eq!(review_tasks.len(), 1);
    assert_eq!(review_tasks[0].assigned_to, Some(reviewer.id()));

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that reviewer approval finalizes a work item when no watches remain.
#[tokio::test]
async fn test_mission_reviewer_approval_finalizes_item() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionScheduler, MissionStorage, ObjectiveRef, WorkItem, WorkItemCompletion,
        WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-review-approve");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["task:1"]);
    storage.save_work_item(&item).await?;

    let scheduler = MissionScheduler::with_defaults(storage.clone(), town.channel().clone());
    let completion = scheduler
        .approve_submission(mission.id, item.id, vec!["approved: looks good".into()])
        .await?;
    assert_eq!(completion, WorkItemCompletion::Completed);

    let updated = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated.status, WorkStatus::Done);
    assert!(updated.reviewer_approved);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that a failing watch creates a persisted fix task through the dispatcher.
#[tokio::test]
async fn test_mission_dispatcher_creates_fix_task_from_failing_watch()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage,
        MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewState, WatchItem, WatchKind, WorkItem,
        WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-fix");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let worker = town.spawn_agent("backend-worker", "claude").await?;
    let mut worker_state = Agent::new("backend-worker", "claude", AgentType::Worker);
    worker_state.id = worker.id();
    worker_state.state = AgentState::Idle;
    town.channel().set_agent_state(&worker_state).await?;

    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);
    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.assign(worker.id());
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/99"]);
    storage.save_work_item(&item).await?;

    let watch = WatchItem::new(mission.id, item.id, WatchKind::PrChecks, "test/repo#99", 0);
    storage.save_watch_item(&watch).await?;

    let mut github = MockGitHubClient::new();
    github.set_pr_checks(
        "test",
        "repo",
        99,
        PrCheckResult {
            pr_number: 99,
            repo: "test/repo".into(),
            status: CheckStatus::Failure,
            checks: vec![],
            mergeable: false,
            review_state: ReviewState::Pending,
            blocking_comments: vec!["CI failed".into()],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    let result = dispatcher.tick(None).await?;
    assert_eq!(result.watch_result.watches_triggered, 1);

    let fix_tasks: Vec<_> = town
        .channel()
        .list_tasks()
        .await?
        .into_iter()
        .filter(|task| task.tags.iter().any(|tag| tag == "mission-fix-task"))
        .collect();
    assert_eq!(fix_tasks.len(), 1);
    assert_eq!(fix_tasks[0].assigned_to, Some(worker.id()));

    let updated_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_ne!(updated_watch.status, tinytown::mission::WatchStatus::Active);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Blocked);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that the dispatcher finalizes a submitted item after CI passes.
#[tokio::test]
async fn test_mission_dispatcher_finalizes_after_successful_watch()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage,
        MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewState, TriggerAction, WatchItem,
        WatchKind, WatchStatus, WorkItem, WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-success");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = false;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/7"]);
    storage.save_work_item(&item).await?;

    let watch = WatchItem::new(mission.id, item.id, WatchKind::PrChecks, "test/repo#7", 0)
        .with_trigger(TriggerAction::AdvancePipeline);
    storage.save_watch_item(&watch).await?;

    let mut github = MockGitHubClient::new();
    github.set_pr_checks(
        "test",
        "repo",
        7,
        PrCheckResult {
            pr_number: 7,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::NotRequired,
            blocking_comments: vec![],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    let result = dispatcher.tick(None).await?;
    assert_eq!(result.watch_result.watches_completed, 1);

    let updated_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_eq!(updated_watch.status, WatchStatus::Done);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Done);

    let updated_mission = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(
        updated_mission.state,
        tinytown::mission::MissionState::Completed
    );

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that clean bugbot/review watches self-resolve once PR checks succeed.
#[tokio::test]
async fn test_mission_dispatcher_self_resolves_clean_comment_watches()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage,
        MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewState, TriggerAction, WatchItem,
        WatchKind, WatchStatus, WorkItem, WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-comment-clean");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = false;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/13"]);
    storage.save_work_item(&item).await?;

    let bugbot_watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::BugbotComments,
        "test/repo#13",
        0,
    )
    .with_trigger(TriggerAction::CreateFixTask);
    let review_watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::ReviewComments,
        "test/repo#13",
        0,
    )
    .with_trigger(TriggerAction::CreateFixTask);
    storage.save_watch_item(&bugbot_watch).await?;
    storage.save_watch_item(&review_watch).await?;

    let mut github = MockGitHubClient::new();
    github.set_pr_checks(
        "test",
        "repo",
        13,
        PrCheckResult {
            pr_number: 13,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::NotRequired,
            blocking_comments: vec![],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    let result = dispatcher.tick(None).await?;
    assert_eq!(result.watch_result.watches_completed, 2);

    let updated_bugbot = storage
        .get_watch_item(mission.id, bugbot_watch.id)
        .await?
        .unwrap();
    assert_eq!(updated_bugbot.status, WatchStatus::Done);

    let updated_review = storage
        .get_watch_item(mission.id, review_watch.id)
        .await?
        .unwrap();
    assert_eq!(updated_review.status, WatchStatus::Done);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Done);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that comment watches self-resolve after previously reported issues are cleared.
#[tokio::test]
async fn test_mission_dispatcher_self_resolves_triggered_comment_watches()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        BugbotComment, CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun,
        MissionStorage, MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewComment, ReviewState,
        TriggerAction, WatchItem, WatchKind, WatchStatus, WorkItem, WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-comment-resolve");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = false;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/17"]);
    storage.save_work_item(&item).await?;

    let bugbot_watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::BugbotComments,
        "test/repo#17",
        60,
    )
    .with_trigger(TriggerAction::CreateFixTask);
    let review_watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::ReviewComments,
        "test/repo#17",
        60,
    )
    .with_trigger(TriggerAction::CreateFixTask);
    storage.save_watch_item(&bugbot_watch).await?;
    storage.save_watch_item(&review_watch).await?;

    let mut failing_github = MockGitHubClient::new();
    failing_github.set_pr_checks(
        "test",
        "repo",
        17,
        PrCheckResult {
            pr_number: 17,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::ChangesRequested,
            blocking_comments: vec!["changes requested".into()],
        },
    );
    failing_github.reviews.insert(
        "test/repo#17".into(),
        vec![ReviewComment {
            author: "reviewer".into(),
            body: "Please fix this".into(),
            is_actionable: true,
        }],
    );
    failing_github.bugbot_comments.insert(
        "test/repo#17".into(),
        vec![BugbotComment {
            bot_name: "bugbot".into(),
            severity: "high".into(),
            description: "Security issue".into(),
            file_path: Some("src/lib.rs".into()),
        }],
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        failing_github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    let first_result = dispatcher.tick(None).await?;
    assert_eq!(first_result.watch_result.watches_triggered, 2);

    let mut snoozed_bugbot = storage
        .get_watch_item(mission.id, bugbot_watch.id)
        .await?
        .unwrap();
    assert_eq!(snoozed_bugbot.status, WatchStatus::Snoozed);
    snoozed_bugbot.next_due_at = chrono::Utc::now() - chrono::Duration::seconds(1);
    storage.save_watch_item(&snoozed_bugbot).await?;

    let mut snoozed_review = storage
        .get_watch_item(mission.id, review_watch.id)
        .await?
        .unwrap();
    assert_eq!(snoozed_review.status, WatchStatus::Snoozed);
    snoozed_review.next_due_at = chrono::Utc::now() - chrono::Duration::seconds(1);
    storage.save_watch_item(&snoozed_review).await?;

    let mut clean_github = MockGitHubClient::new();
    clean_github.set_pr_checks(
        "test",
        "repo",
        17,
        PrCheckResult {
            pr_number: 17,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::Approved,
            blocking_comments: vec![],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        clean_github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    let second_result = dispatcher.tick(None).await?;
    assert_eq!(second_result.watch_result.watches_completed, 2);

    let updated_bugbot = storage
        .get_watch_item(mission.id, bugbot_watch.id)
        .await?
        .unwrap();
    assert_eq!(updated_bugbot.status, WatchStatus::Done);

    let updated_review = storage
        .get_watch_item(mission.id, review_watch.id)
        .await?
        .unwrap();
    assert_eq!(updated_review.status, WatchStatus::Done);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Done);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that snoozed watches are picked up again once their due time arrives.
#[tokio::test]
async fn test_mission_dispatcher_rechecks_snoozed_watch() -> Result<(), Box<dyn std::error::Error>>
{
    use tinytown::mission::{
        CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage,
        MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewState, TriggerAction, WatchItem,
        WatchKind, WatchStatus, WorkItem, WorkKind,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-snooze");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/99"]);
    storage.save_work_item(&item).await?;

    let watch = WatchItem::new(mission.id, item.id, WatchKind::PrChecks, "test/repo#99", 60)
        .with_trigger(TriggerAction::CreateFixTask);
    storage.save_watch_item(&watch).await?;

    let mut failing_github = MockGitHubClient::new();
    failing_github.set_pr_checks(
        "test",
        "repo",
        99,
        PrCheckResult {
            pr_number: 99,
            repo: "test/repo".into(),
            status: CheckStatus::Failure,
            checks: vec![],
            mergeable: false,
            review_state: ReviewState::Pending,
            blocking_comments: vec!["CI failed".into()],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        failing_github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(None).await?;

    let mut snoozed_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_eq!(snoozed_watch.status, WatchStatus::Snoozed);

    snoozed_watch.next_due_at = chrono::Utc::now() - chrono::Duration::seconds(1);
    storage.save_watch_item(&snoozed_watch).await?;

    let mut succeeding_github = MockGitHubClient::new();
    succeeding_github.set_pr_checks(
        "test",
        "repo",
        99,
        PrCheckResult {
            pr_number: 99,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::NotRequired,
            blocking_comments: vec![],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        succeeding_github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(None).await?;

    let updated_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_eq!(updated_watch.status, WatchStatus::Done);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that mergeability watches do not bypass reviewer approval gates.
#[tokio::test]
async fn test_mission_dispatcher_mergeability_respects_reviewer_gate()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        CheckStatus, DispatcherConfig, MissionDispatcher, MissionRun, MissionState, MissionStorage,
        MockGitHubClient, ObjectiveRef, PrCheckResult, ReviewState, TriggerAction, WatchItem,
        WatchKind, WatchStatus, WorkItem, WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-mergeability");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = true;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["https://github.com/test/repo/pull/7"]);
    storage.save_work_item(&item).await?;

    let watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::Mergeability,
        "test/repo#7",
        0,
    )
    .with_trigger(TriggerAction::AdvancePipeline);
    storage.save_watch_item(&watch).await?;

    let mut github = MockGitHubClient::new();
    github.set_pr_checks(
        "test",
        "repo",
        7,
        PrCheckResult {
            pr_number: 7,
            repo: "test/repo".into(),
            status: CheckStatus::Success,
            checks: vec![],
            mergeable: true,
            review_state: ReviewState::Pending,
            blocking_comments: vec![],
        },
    );

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        github,
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(None).await?;

    let updated_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_eq!(updated_watch.status, WatchStatus::Done);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Blocked);
    assert!(!updated_item.reviewer_approved);

    let updated_mission = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated_mission.state, MissionState::Running);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that scheduler completion only applies to blocked waiting items.
#[tokio::test]
async fn test_mission_scheduler_does_not_finalize_running_items_with_artifacts()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        MissionRun, MissionScheduler, MissionState, MissionStorage, ObjectiveRef, WorkItem,
        WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-running-item");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = false;
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.status = WorkStatus::Running;
    item.record_artifacts(["https://github.com/test/repo/pull/11"]);
    storage.save_work_item(&item).await?;

    let scheduler = MissionScheduler::with_defaults(storage.clone(), town.channel().clone());
    scheduler.tick_missions(&[mission.id]).await?;

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Running);

    let updated_mission = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated_mission.state, MissionState::Running);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that the dispatcher asks the conductor for help when ready work cannot be assigned.
#[tokio::test]
async fn test_mission_dispatcher_escalates_to_conductor_when_stuck()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage, MockGitHubClient,
        ObjectiveRef, WorkItem, WorkKind,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-help");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.mark_ready();
    storage.save_work_item(&item).await?;

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(None).await?;

    let inbox = town.channel().peek_inbox(AgentId::supervisor(), 10).await?;
    assert!(inbox.iter().any(|message| {
        matches!(
            &message.msg_type,
            MessageType::Query { question } if question.contains("[Mission Help Needed]")
        )
    }));

    let updated = storage.get_mission(mission.id).await?.unwrap();
    assert!(updated.dispatcher_last_help_request_at.is_some());
    assert!(updated.dispatcher_last_help_request_reason.is_some());
    // A fresh first escalation counts as attempt #1.
    assert_eq!(updated.dispatcher_help_request_attempts, 1);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Verifies the dispatcher applies exponential backoff to repeated
/// "mission help needed" prompts whose reason has not changed, and
/// resets the attempt counter when the reason differs.
#[tokio::test]
async fn test_mission_dispatcher_help_request_backoff() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        DispatcherConfig, MissionDispatcher, MissionRun, MissionStorage, MockGitHubClient,
        ObjectiveRef, WorkItem, WorkKind,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-backoff");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.start();
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.mark_ready();
    storage.save_work_item(&item).await?;

    // A very large base interval guarantees the time-based branch never
    // fires within the test, so we can assert the backoff logic purely
    // from the attempt counter and reason-change behaviour.
    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            help_repeat_interval_secs: 86_400,
            help_repeat_backoff_cap: 8,
        },
    );

    dispatcher.tick(None).await?;
    let after_first = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(after_first.dispatcher_help_request_attempts, 1);

    // Second tick with the same reason must NOT send a new prompt and
    // must NOT bump the attempt counter (backoff window blocks resend).
    let inbox_before = town
        .channel()
        .peek_inbox(AgentId::supervisor(), 50)
        .await?
        .len();
    dispatcher.tick(None).await?;
    let inbox_after = town
        .channel()
        .peek_inbox(AgentId::supervisor(), 50)
        .await?
        .len();
    assert_eq!(
        inbox_after, inbox_before,
        "dispatcher should not rebroadcast within the backoff window"
    );
    let after_second = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(after_second.dispatcher_help_request_attempts, 1);

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that the dispatcher consumes conductor notes from the control channel.
#[tokio::test]
async fn test_mission_dispatcher_processes_conductor_note() -> Result<(), Box<dyn std::error::Error>>
{
    use tinytown::mission::{
        DispatcherConfig, MissionControlMessage, MissionDispatcher, MissionRun, MissionState,
        MissionStorage, MockGitHubClient, ObjectiveRef,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-note");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.block("Waiting on operator");
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let note = MissionControlMessage::new(mission.id, "conductor", "resume and retry now");
    let note_id = note.id.clone();
    storage.save_control_message(&note).await?;

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(Some(mission.id)).await?;

    let updated = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated.state, MissionState::Running);
    assert!(updated.dispatcher_last_progress_at.is_some());

    let messages = storage.list_control_messages(mission.id).await?;
    let processed = messages
        .into_iter()
        .find(|message| message.id == note_id)
        .expect("control note should exist");
    assert!(processed.processed_at.is_some());

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that invalid resume notes cannot revive failed missions.
#[tokio::test]
async fn test_mission_dispatcher_ignores_resume_note_for_failed_mission()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        DispatcherConfig, MissionControlMessage, MissionDispatcher, MissionRun, MissionState,
        MissionStorage, MockGitHubClient, ObjectiveRef,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-resume-failed");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.fail("Unrecoverable error");
    storage.save_mission(&mission).await?;

    let note = MissionControlMessage::new(mission.id, "conductor", "resume and retry now");
    let note_id = note.id.clone();
    storage.save_control_message(&note).await?;

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(Some(mission.id)).await?;

    let updated = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated.state, MissionState::Failed);
    assert_eq!(
        updated.blocked_reason.as_deref(),
        Some("Unrecoverable error")
    );

    let messages = storage.list_control_messages(mission.id).await?;
    let processed = messages
        .into_iter()
        .find(|message| message.id == note_id)
        .expect("control note should exist");
    assert!(processed.processed_at.is_some());

    let events = storage.get_events(mission.id, 10).await?;
    assert!(
        events
            .iter()
            .any(|event| event.contains("ignored resume directive"))
    );

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that invalid pause notes do not overwrite an already blocked mission.
#[tokio::test]
async fn test_mission_dispatcher_ignores_pause_note_for_blocked_mission()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        DispatcherConfig, MissionControlMessage, MissionDispatcher, MissionRun, MissionState,
        MissionStorage, MockGitHubClient, ObjectiveRef,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-pause-blocked");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.block("Waiting on operator");
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let note = MissionControlMessage::new(mission.id, "conductor", "pause until tomorrow");
    let note_id = note.id.clone();
    storage.save_control_message(&note).await?;

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(Some(mission.id)).await?;

    let updated = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated.state, MissionState::Blocked);
    assert_eq!(
        updated.blocked_reason.as_deref(),
        Some("Waiting on operator")
    );

    let messages = storage.list_control_messages(mission.id).await?;
    let processed = messages
        .into_iter()
        .find(|message| message.id == note_id)
        .expect("control note should exist");
    assert!(processed.processed_at.is_some());

    let events = storage.get_events(mission.id, 10).await?;
    assert!(
        events
            .iter()
            .any(|event| event.contains("ignored pause directive"))
    );

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

/// Test that a resume directive force-completes blocking watches so work can finalize.
#[tokio::test]
async fn test_mission_dispatcher_resume_note_completes_blocking_watches()
-> Result<(), Box<dyn std::error::Error>> {
    use tinytown::mission::{
        DispatcherConfig, MissionControlMessage, MissionDispatcher, MissionRun, MissionState,
        MissionStorage, MockGitHubClient, ObjectiveRef, TriggerAction, WatchItem, WatchKind,
        WatchStatus, WorkItem, WorkKind, WorkStatus,
    };

    let temp_dir = TempDir::new()?;
    let town_name = unique_town_name("mission-dispatch-resume-watches");
    let town = Town::init(temp_dir.path(), &town_name).await?;
    let storage = MissionStorage::new(town.channel().conn().clone(), &town_name);

    let mut mission = MissionRun::new(vec![ObjectiveRef::Doc {
        path: "test.md".into(),
    }]);
    mission.policy.reviewer_required = false;
    mission.block("Waiting on external watch");
    storage.save_mission(&mission).await?;
    storage.add_active(mission.id).await?;

    let mut item = WorkItem::new(mission.id, "Implement auth", WorkKind::Implement);
    item.block();
    item.record_artifacts(["test/repo#21"]);
    storage.save_work_item(&item).await?;

    let watch = WatchItem::new(
        mission.id,
        item.id,
        WatchKind::PrChecks,
        "test/repo#21",
        3600,
    )
    .with_trigger(TriggerAction::AdvancePipeline);
    storage.save_watch_item(&watch).await?;

    let note = MissionControlMessage::new(mission.id, "conductor", "resume and finish now");
    storage.save_control_message(&note).await?;

    let dispatcher = MissionDispatcher::new(
        storage.clone(),
        town.channel().clone(),
        MockGitHubClient::new(),
        DispatcherConfig {
            tick_interval_secs: 1,
            lock_ttl_secs: 30,
            ..DispatcherConfig::default()
        },
    );
    dispatcher.tick(Some(mission.id)).await?;

    let updated_watch = storage.get_watch_item(mission.id, watch.id).await?.unwrap();
    assert_eq!(updated_watch.status, WatchStatus::Done);

    let updated_item = storage.get_work_item(mission.id, item.id).await?.unwrap();
    assert_eq!(updated_item.status, WorkStatus::Done);

    let updated_mission = storage.get_mission(mission.id).await?.unwrap();
    assert_eq!(updated_mission.state, MissionState::Completed);
    assert!(updated_mission.blocked_reason.is_none());

    drop(town);
    cleanup_redis(&temp_dir);
    Ok(())
}

// ============================================================================
// DOCKET STREAM (REDIS STREAMS) TESTS
// ============================================================================

/// Test that the docket consumer group can be created.
#[tokio::test]
async fn test_docket_ensure_group() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-group-test").await?;
    let channel = town.channel();

    // Creating the group should succeed
    channel.docket_ensure_group().await?;

    // Creating again should be idempotent (BUSYGROUP handled)
    channel.docket_ensure_group().await?;

    Ok(())
}

/// Test that tasks can be added to the docket stream via XADD.
#[tokio::test]
async fn test_docket_push() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-push-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    let task_id = TaskId::new();
    let entry_id = channel
        .docket_push(
            task_id,
            "Implement feature X",
            "normal",
            "conductor",
            "worker-1",
        )
        .await?;

    // Entry ID should be a valid stream ID (e.g., "1234567890-0")
    assert!(
        entry_id.contains('-'),
        "Entry ID should contain '-': {}",
        entry_id
    );

    // Stream should have one entry
    let len = channel.docket_len().await?;
    assert_eq!(len, 1);

    Ok(())
}

/// Test that multiple tasks can be pushed and counted.
#[tokio::test]
async fn test_docket_push_multiple() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-push-multi-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    for i in 0..5 {
        let task_id = TaskId::new();
        channel
            .docket_push(
                task_id,
                &format!("Task {}", i),
                "normal",
                "conductor",
                "worker-1",
            )
            .await?;
    }

    let len = channel.docket_len().await?;
    assert_eq!(len, 5);

    Ok(())
}

/// Test that a consumer can read from the docket stream via XREADGROUP.
#[tokio::test]
async fn test_docket_read() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-read-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    let task_id = TaskId::new();
    channel
        .docket_push(task_id, "Build the API", "high", "conductor", "agent-1")
        .await?;

    // Read with a short block timeout
    let result = channel.docket_read("agent-1", 100).await?;
    assert!(result.is_some(), "Should have read an entry");

    let (entry_id, fields) = result.unwrap();
    assert!(entry_id.contains('-'));
    assert_eq!(fields.get("task_id").unwrap(), &task_id.to_string());
    assert_eq!(fields.get("type").unwrap(), "task_assign");
    assert_eq!(fields.get("message").unwrap(), "Build the API");
    assert_eq!(fields.get("priority").unwrap(), "high");
    assert_eq!(fields.get("from").unwrap(), "conductor");
    assert_eq!(fields.get("to").unwrap(), "agent-1");
    assert!(fields.contains_key("timestamp"));

    Ok(())
}

/// Test that XREADGROUP returns None when no entries are available.
#[tokio::test]
async fn test_docket_read_empty() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-read-empty-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    // Read with a very short timeout — should return None
    let result = channel.docket_read("agent-1", 50).await?;
    assert!(result.is_none(), "Should return None when stream is empty");

    Ok(())
}

/// Test that XACK removes entries from the pending list.
#[tokio::test]
async fn test_docket_ack() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-ack-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    let task_id = TaskId::new();
    channel
        .docket_push(task_id, "Fix the bug", "normal", "conductor", "worker-1")
        .await?;

    // Read the entry (creates a pending entry)
    let (entry_id, _fields) = channel
        .docket_read("worker-1", 100)
        .await?
        .expect("should read entry");

    // Before ACK, pending count should be 1
    let pending_before = channel.docket_pending_count().await?;
    assert_eq!(pending_before, 1, "Should have 1 pending entry before ACK");

    // Acknowledge
    channel.docket_ack(&entry_id).await?;

    // After ACK, pending count should be 0
    let pending_after = channel.docket_pending_count().await?;
    assert_eq!(pending_after, 0, "Should have 0 pending entries after ACK");

    Ok(())
}

/// Test that unacked entries show up in XPENDING.
#[tokio::test]
async fn test_docket_pending_visibility() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-pending-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    // Push 3 tasks
    for i in 0..3 {
        let task_id = TaskId::new();
        channel
            .docket_push(
                task_id,
                &format!("Task {}", i),
                "normal",
                "conductor",
                "worker-1",
            )
            .await?;
    }

    // Read all 3 (creates 3 pending entries)
    for _ in 0..3 {
        channel.docket_read("worker-1", 100).await?;
    }

    // All 3 should be pending
    let pending = channel.docket_pending_count().await?;
    assert_eq!(pending, 3, "Should have 3 pending entries");

    Ok(())
}

/// Test that task lifecycle events can be logged to the docket events stream.
#[tokio::test]
async fn test_docket_log_event() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-event-test").await?;
    let channel = town.channel();

    let task_id = TaskId::new();

    // Log various lifecycle events
    let id1 = channel
        .docket_log_event(task_id, "assigned", "Assigned to worker-1")
        .await?;
    let id2 = channel
        .docket_log_event(task_id, "started", "Worker began processing")
        .await?;
    let id3 = channel
        .docket_log_event(task_id, "completed", "Task finished successfully")
        .await?;

    // All entries should have valid stream IDs
    assert!(id1.contains('-'));
    assert!(id2.contains('-'));
    assert!(id3.contains('-'));

    // IDs should be monotonically increasing
    assert!(id2 > id1, "Event IDs should be ordered");
    assert!(id3 > id2, "Event IDs should be ordered");

    Ok(())
}

/// Test the full docket lifecycle: push → read → ack → events.
#[tokio::test]
async fn test_docket_full_lifecycle() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-lifecycle-test").await?;
    let channel = town.channel();

    // 1. Initialize consumer group
    channel.docket_ensure_group().await?;

    // 2. Push a task
    let task_id = TaskId::new();
    let _push_id = channel
        .docket_push(
            task_id,
            "Deploy to production",
            "high",
            "conductor",
            "deployer",
        )
        .await?;

    assert_eq!(channel.docket_len().await?, 1);

    // 3. Consumer reads the task
    let (entry_id, fields) = channel
        .docket_read("deployer", 100)
        .await?
        .expect("should read the task");

    assert_eq!(fields.get("task_id").unwrap(), &task_id.to_string());
    assert_eq!(fields.get("message").unwrap(), "Deploy to production");

    // 4. Task is now pending (in-flight)
    assert_eq!(channel.docket_pending_count().await?, 1);

    // 5. Log progress events
    channel
        .docket_log_event(task_id, "started", "Beginning deployment")
        .await?;
    channel
        .docket_log_event(task_id, "progress", "50% complete")
        .await?;

    // 6. Acknowledge completion
    channel.docket_ack(&entry_id).await?;
    channel
        .docket_log_event(task_id, "completed", "Deployment successful")
        .await?;

    // 7. No more pending
    assert_eq!(channel.docket_pending_count().await?, 0);

    // 8. Stream still has the entry (for replay/audit)
    assert_eq!(channel.docket_len().await?, 1);

    Ok(())
}

/// Test that the use_streams config toggle exists and defaults to false.
#[tokio::test]
async fn test_use_streams_config_default() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("use-streams-config-test").await?;
    let config = town.config();

    // Default should be false (List-based backlog)
    assert!(!config.use_streams, "use_streams should default to false");

    Ok(())
}

/// Test that use_streams can be parsed from config TOML.
#[tokio::test]
async fn test_use_streams_config_parse() -> Result<(), Box<dyn std::error::Error>> {
    use tempfile::TempDir;
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let config_path = temp_dir.path().join("tinytown.toml");

    std::fs::write(
        &config_path,
        r#"
name = "stream-test"
use_streams = true
"#,
    )?;

    let config = Config::load(temp_dir.path())?;
    assert!(
        config.use_streams,
        "use_streams should be true when set in config"
    );

    Ok(())
}

/// Test that agent idle timeout can be parsed from config TOML.
#[tokio::test]
async fn test_agent_idle_timeout_config_parse() -> Result<(), Box<dyn std::error::Error>> {
    use tinytown::Config;

    let temp_dir = TempDir::new()?;
    let config_path = temp_dir.path().join("tinytown.toml");

    std::fs::write(
        &config_path,
        r#"
name = "agent-timeout-test"

[agent]
idle_timeout_secs = 42
"#,
    )?;

    let config = Config::load(temp_dir.path())?;
    assert_eq!(config.agent.idle_timeout_secs, 42);

    Ok(())
}

/// Test that the worker loop exits cleanly after the idle timeout elapses.
#[tokio::test]
async fn test_agent_loop_exits_cleanly_after_idle_timeout() -> Result<(), Box<dyn std::error::Error>>
{
    let town = create_test_town("agent-loop-idle-timeout").await?;
    let town_path = town.config().root.clone();

    let mut config = tinytown::Config::load(&town_path)?;
    config.agent.idle_timeout_secs = 1;
    config.save()?;

    let handle = town.spawn_agent("idle-worker", "claude").await?;
    let agent_id = handle.id();

    let status = tokio::task::spawn_blocking(move || {
        std::process::Command::new(env!("CARGO_BIN_EXE_tt"))
            .arg("--town")
            .arg(&town_path)
            .arg("agent-loop")
            .arg("idle-worker")
            .arg(agent_id.to_string())
            .arg("100")
            .status()
    })
    .await??;

    assert!(status.success(), "agent-loop should exit cleanly");

    let agent = town
        .channel()
        .get_agent_state(agent_id)
        .await?
        .expect("idle worker should still be registered");
    assert_eq!(agent.state, AgentState::Stopped);

    Ok(())
}

/// Test that a stale terminal current_task does not block worker idle timeout.
#[tokio::test]
async fn test_agent_loop_ignores_stale_terminal_current_task()
-> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("agent-loop-stale-current-task").await?;
    let town_path = town.config().root.clone();

    let mut config = tinytown::Config::load(&town_path)?;
    config.agent.idle_timeout_secs = 1;
    config.save()?;

    let handle = town.spawn_agent("idle-worker", "claude").await?;
    let agent_id = handle.id();
    let mut task = Task::new("Already finished task");
    task.assign(agent_id);
    task.complete("done");
    town.channel().set_task(&task).await?;

    let mut agent = town
        .channel()
        .get_agent_state(agent_id)
        .await?
        .expect("idle worker should exist");
    agent.state = AgentState::Idle;
    agent.current_task = Some(task.id);
    town.channel().set_agent_state(&agent).await?;

    let status = tokio::task::spawn_blocking(move || {
        std::process::Command::new(env!("CARGO_BIN_EXE_tt"))
            .arg("--town")
            .arg(&town_path)
            .arg("agent-loop")
            .arg("idle-worker")
            .arg(agent_id.to_string())
            .arg("100")
            .status()
    })
    .await??;

    assert!(status.success(), "agent-loop should exit cleanly");

    let agent = town
        .channel()
        .get_agent_state(agent_id)
        .await?
        .expect("idle worker should still be registered");
    assert_eq!(agent.state, AgentState::Stopped);
    assert_eq!(agent.current_task, None);

    Ok(())
}

/// Test that multiple consumers can read from the same docket stream.
#[tokio::test]
async fn test_docket_multiple_consumers() -> Result<(), Box<dyn std::error::Error>> {
    let town = create_test_town("docket-multi-consumer-test").await?;
    let channel = town.channel();

    channel.docket_ensure_group().await?;

    // Push 2 tasks
    let task1 = TaskId::new();
    let task2 = TaskId::new();
    channel
        .docket_push(task1, "Task A", "normal", "conductor", "any")
        .await?;
    channel
        .docket_push(task2, "Task B", "normal", "conductor", "any")
        .await?;

    // Two different consumers read from the same group
    let read1 = channel.docket_read("consumer-1", 100).await?;
    let read2 = channel.docket_read("consumer-2", 100).await?;

    assert!(read1.is_some(), "Consumer 1 should get a task");
    assert!(read2.is_some(), "Consumer 2 should get a task");

    let (id1, fields1) = read1.unwrap();
    let (id2, fields2) = read2.unwrap();

    // They should get different tasks (consumer group distributes)
    assert_ne!(
        fields1.get("task_id"),
        fields2.get("task_id"),
        "Each consumer should get a different task"
    );

    // Both pending
    assert_eq!(channel.docket_pending_count().await?, 2);

    // Ack both
    channel.docket_ack(&id1).await?;
    channel.docket_ack(&id2).await?;
    assert_eq!(channel.docket_pending_count().await?, 0);

    Ok(())
}