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
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
/*
 * Copyright (c) 2024-Present, Jeremy Plichta
 * Licensed under the MIT License
 */

//! Tinytown CLI - Simple multi-agent orchestration.

use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand};
use tracing::{info, warn};
use tracing_subscriber::EnvFilter;

use tinytown::{GlobalConfig, Result, Task, Town, plan};

const TT_AGENT_ID_ENV: &str = "TINYTOWN_AGENT_ID";
const TT_AGENT_NAME_ENV: &str = "TINYTOWN_AGENT_NAME";

/// Build a shell command to run an agent CLI with a prompt/instruction file.
/// Different CLIs have different ways to accept input:
/// - auggie: uses --instruction-file flag
/// - claude, codex, etc.: accept input via stdin (pipe or redirect)
fn build_cli_command(cli_name: &str, cli_cmd: &str, prompt_file: &std::path::Path) -> String {
    if cli_name == "auggie" {
        // Auggie uses --instruction-file flag
        format!("{} --instruction-file '{}'", cli_cmd, prompt_file.display())
    } else {
        // Other CLIs accept input via stdin
        format!("cat '{}' | {}", prompt_file.display(), cli_cmd)
    }
}

fn idle_timeout_elapsed(
    agent: &tinytown::Agent,
    idle_timeout_secs: u64,
    now: chrono::DateTime<chrono::Utc>,
) -> bool {
    idle_timeout_secs > 0
        && agent.current_task.is_none()
        && now
            .signed_duration_since(agent.last_active_at)
            .num_seconds()
            >= idle_timeout_secs as i64
}

fn idle_poll_interval(idle_timeout_secs: u64) -> std::time::Duration {
    let secs = if idle_timeout_secs == 0 {
        5
    } else {
        idle_timeout_secs.clamp(1, 5)
    };
    std::time::Duration::from_secs(secs)
}

async fn clear_terminal_current_task(
    channel: &tinytown::Channel,
    agent: &mut tinytown::Agent,
) -> Result<()> {
    let Some(task_id) = agent.current_task else {
        return Ok(());
    };

    let should_clear = match channel.get_task(task_id).await? {
        Some(task) => task.state.is_terminal(),
        None => true,
    };

    if should_clear {
        agent.current_task = None;
    }

    Ok(())
}

fn spawn_agent_loop_background(
    exe: &Path,
    town_path: &Path,
    agent_name: &str,
    agent_id: &str,
    max_rounds: u32,
    log_path: &Path,
) -> Result<()> {
    let log_file = std::fs::File::create(log_path)?;
    let mut cmd = std::process::Command::new(exe);
    cmd.arg("--town")
        .arg(town_path)
        .arg("agent-loop")
        .arg(agent_name)
        .arg(agent_id)
        .arg(max_rounds.to_string())
        .stdin(std::process::Stdio::null())
        .stdout(log_file.try_clone()?)
        .stderr(log_file);

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;

        unsafe {
            cmd.pre_exec(|| {
                if libc::setsid() == -1 {
                    return Err(std::io::Error::last_os_error());
                }

                libc::signal(libc::SIGHUP, libc::SIG_IGN);
                Ok(())
            });
        }
    }

    cmd.spawn()?;
    Ok(())
}

async fn resolve_agent_id_for_current_task(
    town: &Town,
    agent: Option<&str>,
) -> Result<tinytown::AgentId> {
    if let Some(agent_ref) = agent {
        if let Ok(agent_id) = agent_ref.parse::<tinytown::AgentId>()
            && town.channel().get_agent_state(agent_id).await?.is_some()
        {
            return Ok(agent_id);
        }

        return Ok(town.agent(agent_ref).await?.id());
    }

    if let Ok(agent_id) = std::env::var(TT_AGENT_ID_ENV)
        && let Ok(parsed_id) = agent_id.parse::<tinytown::AgentId>()
        && town.channel().get_agent_state(parsed_id).await?.is_some()
    {
        return Ok(parsed_id);
    }

    if let Ok(agent_name) = std::env::var(TT_AGENT_NAME_ENV) {
        return Ok(town.agent(&agent_name).await?.id());
    }

    Err(tinytown::Error::AgentNotFound(
        "No current agent context found. Pass an agent name/id or run this from an agent loop."
            .to_string(),
    ))
}

/// Resolve the sender identity for outbound messages.
///
/// Resolution order:
/// 1. Explicit `--from` value (UUID, agent name, or "supervisor"/"conductor").
/// 2. `TINYTOWN_AGENT_ID` env var (set by `tt agent-loop` when spawning a CLI).
/// 3. `TINYTOWN_AGENT_NAME` env var.
/// 4. `AgentId::supervisor()` (default for user-driven `tt send`).
async fn resolve_sender_id(town: &Town, explicit: Option<&str>) -> Result<tinytown::AgentId> {
    if let Some(raw) = explicit {
        if let Ok(id) = raw.parse::<tinytown::AgentId>() {
            return Ok(id);
        }
        return Ok(town.agent(raw).await?.id());
    }

    if let Ok(agent_id) = std::env::var(TT_AGENT_ID_ENV)
        && let Ok(parsed_id) = agent_id.parse::<tinytown::AgentId>()
    {
        return Ok(parsed_id);
    }

    if let Ok(agent_name) = std::env::var(TT_AGENT_NAME_ENV)
        && let Ok(handle) = town.agent(&agent_name).await
    {
        return Ok(handle.id());
    }

    Ok(tinytown::AgentId::supervisor())
}

fn is_supervisor_alias(name: &str) -> bool {
    matches!(name.to_lowercase().as_str(), "supervisor" | "conductor")
}

fn validate_spawn_agent_name(name: &str) -> Result<()> {
    if is_supervisor_alias(name) {
        return Err(tinytown::Error::Config(format!(
            "'{}' is reserved for the well-known supervisor/conductor mailbox",
            name
        )));
    }

    Ok(())
}

fn inbox_preview_prefix(msg_type: &tinytown::MessageType) -> &'static str {
    match classify_message(msg_type) {
        MessageCategory::Task => "[T]",
        MessageCategory::Query => "[Q]",
        MessageCategory::Informational => "[I]",
        MessageCategory::Confirmation => "[C]",
        MessageCategory::OtherActionable => "[!]",
    }
}

async fn sampled_inbox(
    channel: &tinytown::Channel,
    agent_id: tinytown::AgentId,
    sample_limit: usize,
) -> Result<(usize, Vec<tinytown::Message>, MessageBreakdown)> {
    let inbox_len = channel.inbox_len(agent_id).await?;
    if inbox_len == 0 {
        return Ok((0, Vec::new(), MessageBreakdown::default()));
    }

    let messages = channel
        .peek_inbox(agent_id, std::cmp::min(inbox_len, sample_limit) as isize)
        .await?;
    let mut breakdown = MessageBreakdown::default();
    for msg in &messages {
        breakdown.count(&msg.msg_type);
    }

    Ok((inbox_len, messages, breakdown))
}

async fn print_all_inbox_section(
    channel: &tinytown::Channel,
    heading: &str,
    inbox_len: usize,
    messages: &[tinytown::Message],
    breakdown: MessageBreakdown,
) {
    info!("  {}:", heading);
    info!(
        "    [T] {} tasks requiring action",
        breakdown.tasks + breakdown.other_actionable
    );
    info!("    [Q] {} queries awaiting response", breakdown.queries);
    info!("    [I] {} informational", breakdown.informational);
    info!("    [C] {} confirmations", breakdown.confirmations);

    let mut shown = 0;
    for msg in messages {
        if !matches!(
            classify_message(&msg.msg_type),
            MessageCategory::Task | MessageCategory::Query | MessageCategory::OtherActionable
        ) {
            continue;
        }
        if shown >= 5 {
            break;
        }

        let summary = describe_message(channel, &msg.msg_type).await;
        info!(
            "    • {} {}",
            inbox_preview_prefix(&msg.msg_type),
            truncate_summary(&summary, 90)
        );
        shown += 1;
    }

    if shown == 0 {
        for msg in messages.iter().take(3) {
            let summary = describe_message(channel, &msg.msg_type).await;
            info!(
                "    • {} {}",
                inbox_preview_prefix(&msg.msg_type),
                truncate_summary(&summary, 90)
            );
            shown += 1;
        }
    }

    if inbox_len > shown {
        info!("    …plus {} more message(s)", inbox_len - shown);
    }

    info!("");
}

async fn track_current_task_for_round(
    channel: &tinytown::Channel,
    agent_id: tinytown::AgentId,
    actionable_messages: &[(tinytown::Message, bool)],
) -> Result<()> {
    let task_ids: Vec<_> = actionable_messages
        .iter()
        .filter_map(|(msg, _)| match &msg.msg_type {
            tinytown::MessageType::TaskAssign { task_id } => task_id.parse().ok(),
            _ => None,
        })
        .collect();

    if task_ids.len() != 1 {
        return Ok(());
    }

    tinytown::TaskService::set_current_for_agent(channel, agent_id, task_ids[0]).await
}

async fn format_actionable_section(
    channel: &tinytown::Channel,
    actionable_messages: &[(tinytown::Message, bool)],
) -> String {
    let mut section = String::from("## Actionable Messages (already popped)\n\n");

    for (idx, (msg, urgent)) in actionable_messages.iter().enumerate() {
        let priority = if *urgent { "URGENT" } else { "normal" };
        match &msg.msg_type {
            tinytown::MessageType::TaskAssign { task_id } => {
                let description = if let Ok(tid) = task_id.parse::<tinytown::TaskId>() {
                    match channel.get_task(tid).await {
                        Ok(Some(task)) => truncate_summary(&task.description, 160),
                        _ => "Task details unavailable".to_string(),
                    }
                } else {
                    "Task details unavailable".to_string()
                };
                section.push_str(&format!(
                    "{}. [{}] task assignment from {}\n   Task ID: {}\n   Description: {}\n   Complete with: tt task complete {} --result \"what was done\"\n   Ignore any mission/work-item UUIDs in the description; the Task ID above is the real Tinytown task id.\n",
                    idx + 1,
                    priority,
                    msg.from,
                    task_id,
                    description,
                    task_id
                ));
            }
            _ => {
                let summary =
                    truncate_summary(&describe_message(channel, &msg.msg_type).await, 120);
                section.push_str(&format!(
                    "{}. [{}] from {}: {}\n",
                    idx + 1,
                    priority,
                    msg.from,
                    summary
                ));
            }
        }
    }

    section
}

#[derive(Parser)]
#[command(name = "tt")]
#[command(author, version, about = "Tinytown - Simple multi-agent orchestration using Redis", long_about = None)]
struct Cli {
    /// Town directory (defaults to current directory)
    #[arg(short, long, global = true, default_value = ".")]
    town: PathBuf,

    /// Enable verbose logging
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Bootstrap: Download and build Redis (delegates to an AI agent)
    Bootstrap {
        /// Redis version to install (default: latest)
        #[arg(default_value = "latest")]
        version: String,

        /// Agent CLI to use for bootstrapping (uses default_cli from global config if not specified)
        #[arg(short, long)]
        cli: Option<String>,
    },

    /// Initialize a new town
    Init {
        /// Town name
        #[arg(short, long)]
        name: Option<String>,
    },

    /// Spawn a new agent
    Spawn {
        /// Agent name
        name: String,

        /// CLI to use (uses default_cli from config if not specified)
        #[arg(short, long)]
        cli: Option<String>,

        /// Maximum rounds before agent stops (default: runs until done)
        #[arg(long, default_value = "10")]
        max_rounds: u32,

        /// Run in foreground (don't background the process)
        #[arg(long)]
        foreground: bool,

        /// Explicit role ID (e.g., "worker", "reviewer", "researcher")
        #[arg(long)]
        role: Option<String>,

        /// Human-facing nickname (separate from canonical name)
        #[arg(long)]
        nickname: Option<String>,

        /// Parent agent name or ID (for delegated subtasks)
        #[arg(long)]
        parent: Option<String>,
    },

    /// Run agent loop (internal - called by spawn)
    #[command(hide = true)]
    AgentLoop {
        /// Agent name
        name: String,

        /// Agent ID
        id: String,

        /// Maximum rounds
        max_rounds: u32,
    },

    /// List all agents
    List,

    /// Assign a task to an agent
    Assign {
        /// Agent name
        agent: String,

        /// Task description
        task: String,
    },

    /// Show town status
    Status {
        /// Show deep status with recent agent activity
        #[arg(long)]
        deep: bool,

        /// Show detailed task breakdown by state and agent
        #[arg(long)]
        tasks: bool,
    },

    /// Keep a connection open to the town
    Start,

    /// Request all agents in the town to stop gracefully
    Stop,

    /// Reset all town state (clear all agents, tasks, messages)
    Reset {
        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,

        /// Only reset agent-related state (agents and inboxes), preserving tasks
        #[arg(long)]
        agents_only: bool,
    },

    /// Stop a specific agent gracefully
    Kill {
        /// Agent name to stop
        agent: String,
    },

    /// Interrupt (pause) a running agent
    Interrupt {
        /// Agent name to interrupt
        agent: String,
    },

    /// Wait for an agent to reach a terminal state
    Wait {
        /// Agent name to wait for
        agent: String,

        /// Timeout in seconds (default: wait forever)
        #[arg(long)]
        timeout: Option<u64>,
    },

    /// Resume a paused agent
    Resume {
        /// Agent name to resume
        agent: String,
    },

    /// Close an agent gracefully (drain current work, then stop)
    Close {
        /// Agent name to close
        agent: String,
    },

    /// Remove stopped/stale agents from Redis
    Prune {
        /// Remove ALL agents (not just stopped ones)
        #[arg(long)]
        all: bool,
    },

    /// Manage individual tasks
    Task {
        #[command(subcommand)]
        action: TaskAction,
    },

    /// Check agent inbox(es)
    Inbox {
        /// Agent name (optional with --all)
        agent: Option<String>,

        /// Show pending messages for all agents
        #[arg(long, short)]
        all: bool,
    },

    /// Send a message to an agent
    Send {
        /// Target agent name
        to: String,

        /// Message content
        message: String,

        /// Sender agent name or UUID. Defaults to the current agent context
        /// (TINYTOWN_AGENT_ID / TINYTOWN_AGENT_NAME when set) or "supervisor".
        #[arg(long)]
        from: Option<String>,

        /// Mark message as a query requiring a response
        #[arg(long, conflicts_with_all = ["info", "ack"])]
        query: bool,

        /// Mark message as informational (FYI)
        #[arg(long, conflicts_with_all = ["query", "ack"])]
        info: bool,

        /// Mark message as an acknowledgment
        #[arg(long, conflicts_with_all = ["query", "info"])]
        ack: bool,

        /// Send as urgent (processed before regular inbox)
        #[arg(long)]
        urgent: bool,
    },

    /// Start the conductor (interactive orchestration mode)
    Conductor,

    /// Plan tasks without starting agents (edit tasks.toml)
    Plan {
        /// Initialize a new tasks.toml file
        #[arg(short, long)]
        init: bool,
    },

    /// Sync tasks.toml with Redis
    Sync {
        /// Direction: 'push' (file→Redis) or 'pull' (Redis→file)
        #[arg(default_value = "push")]
        direction: String,
    },

    /// Save Redis state to AOF file (for version control)
    Save,

    /// Restore Redis state from AOF file
    Restore,

    /// View or set global configuration (~/.tt/config.toml)
    Config {
        /// Config key to get or set (e.g., default_cli)
        key: Option<String>,

        /// Value to set (if omitted, shows current value)
        value: Option<String>,
    },

    /// Show recent agent communication history
    History {
        /// Maximum number of events to show (default: 30)
        #[arg(short = 'n', long, default_value = "30")]
        limit: usize,

        /// Filter by agent name
        #[arg(short, long)]
        agent: Option<String>,
    },

    /// Detect and clean up crashed/orphaned agents
    Recover,

    /// List all registered towns
    Towns,

    /// Manage the global task backlog
    Backlog {
        #[command(subcommand)]
        action: BacklogAction,
    },

    /// Recover orphaned tasks from dead agents
    Reclaim {
        /// Move orphaned tasks to the backlog
        #[arg(long)]
        to_backlog: bool,

        /// Move orphaned tasks to a specific agent
        #[arg(long, value_name = "AGENT")]
        to: Option<String>,

        /// Reclaim only from a specific dead agent
        #[arg(long, value_name = "AGENT")]
        from: Option<String>,
    },

    /// Restart a stopped agent with fresh rounds
    Restart {
        /// Agent name to restart
        agent: String,

        /// Maximum rounds for restarted agent
        #[arg(long, default_value = "10")]
        rounds: u32,

        /// Run in foreground (don't background the process)
        #[arg(long)]
        foreground: bool,
    },

    /// Authentication management for townhall
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },

    /// Migrate old Redis keys to town-isolated format
    Migrate {
        /// Preview migration without making changes
        #[arg(long)]
        dry_run: bool,

        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,

        /// Migrate JSON string storage to Redis Hash format
        #[arg(long)]
        hash: bool,
    },

    /// Autonomous multi-issue mission mode
    Mission {
        #[command(subcommand)]
        action: MissionAction,
    },

    /// Tail the Redis Stream event log
    Events {
        /// Number of recent events to show (default: 20)
        #[arg(short, long, default_value = "20")]
        count: usize,

        /// Filter by agent name
        #[arg(long)]
        agent: Option<String>,

        /// Filter by mission ID
        #[arg(long)]
        mission: Option<String>,

        /// Follow mode: continuously poll for new events
        #[arg(short, long)]
        follow: bool,
    },
}

#[derive(Subcommand)]
enum AuthAction {
    /// Generate a new API key and its hash
    GenKey,
}

#[derive(Subcommand)]
enum MissionAction {
    /// Start a new mission with one or more GitHub issues
    Start {
        /// GitHub issue numbers or URLs (e.g., "23" or "owner/repo#23")
        #[arg(long = "issue", short = 'i', value_name = "ISSUE")]
        issues: Vec<String>,

        /// Document paths to include as objectives
        #[arg(long = "doc", short = 'd', value_name = "PATH")]
        docs: Vec<String>,

        /// Maximum parallel work items (default: 2)
        #[arg(long, default_value = "2")]
        max_parallel: u32,

        /// Disable reviewer requirement
        #[arg(long)]
        no_reviewer: bool,
    },

    /// Show status of active missions
    Status {
        /// Specific mission ID to show
        #[arg(long, short = 'r')]
        run: Option<String>,

        /// Show detailed work item status
        #[arg(long)]
        work: bool,

        /// Show watch items
        #[arg(long)]
        watch: bool,

        /// Show dispatcher/operator-control details
        #[arg(long)]
        dispatcher: bool,
    },

    /// Resume a stopped or blocked mission
    Resume {
        /// Mission run ID to resume
        run_id: String,
    },

    /// Run the persistent mission dispatcher loop
    Dispatch {
        /// Specific mission run ID to dispatch
        #[arg(long, short = 'r')]
        run: Option<String>,

        /// Run a single dispatcher tick and exit
        #[arg(long)]
        once: bool,
    },

    /// Send an operator note/directive to the dispatcher for a mission
    Note {
        /// Mission run ID to target
        run_id: String,

        /// Note or directive body
        message: String,
    },

    /// Stop an active mission
    Stop {
        /// Mission run ID to stop
        run_id: String,

        /// Force stop without graceful cleanup
        #[arg(long)]
        force: bool,
    },

    /// List all missions (including completed)
    List {
        /// Include completed/failed missions
        #[arg(long)]
        all: bool,
    },
}

#[derive(Subcommand)]
enum BacklogAction {
    /// Add a task to the backlog
    Add {
        /// Task description
        description: String,

        /// Optional tags (comma-separated)
        #[arg(long)]
        tags: Option<String>,
    },

    /// List all tasks in the backlog
    List,

    /// Claim a task from the backlog and assign to an agent
    Claim {
        /// Task ID to claim
        task_id: String,

        /// Agent name to assign the task to
        agent: String,
    },

    /// Assign all backlog tasks to an agent
    AssignAll {
        /// Agent name to assign all tasks to
        agent: String,
    },

    /// Remove a task from the backlog
    Remove {
        /// Task ID to remove
        task_id: String,
    },
}

#[derive(Subcommand)]
enum TaskAction {
    /// Mark a task as completed
    Complete {
        /// Task ID to mark as completed
        task_id: String,

        /// Optional result/summary message
        #[arg(long)]
        result: Option<String>,
    },

    /// Show details of a specific task
    Show {
        /// Task ID to show
        task_id: String,
    },

    /// Show the tracked current task for an agent
    Current {
        /// Agent name or ID (optional inside an agent loop)
        agent: Option<String>,
    },

    /// List all tasks
    List {
        /// Filter by state (pending, assigned, running, completed, failed, cancelled)
        #[arg(long)]
        state: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MessageCategory {
    Task,
    Query,
    Informational,
    Confirmation,
    OtherActionable,
}

#[derive(Debug, Default, Clone, Copy)]
struct MessageBreakdown {
    tasks: usize,
    queries: usize,
    informational: usize,
    confirmations: usize,
    other_actionable: usize,
}

impl MessageBreakdown {
    fn count(&mut self, msg_type: &tinytown::MessageType) {
        match classify_message(msg_type) {
            MessageCategory::Task => self.tasks += 1,
            MessageCategory::Query => self.queries += 1,
            MessageCategory::Informational => self.informational += 1,
            MessageCategory::Confirmation => self.confirmations += 1,
            MessageCategory::OtherActionable => self.other_actionable += 1,
        }
    }

    fn actionable_count(&self) -> usize {
        self.tasks + self.queries + self.other_actionable
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BacklogRole {
    Frontend,
    Backend,
    Tester,
    Reviewer,
    Docs,
    Devops,
    Security,
    General,
}

fn classify_backlog_role(agent_name: &str) -> BacklogRole {
    let role = agent_name.to_lowercase();
    if role.contains("front")
        || role.contains("ui")
        || role.contains("web")
        || role.contains("client")
    {
        BacklogRole::Frontend
    } else if role.contains("back") || role.contains("api") || role.contains("server") {
        BacklogRole::Backend
    } else if role.contains("test") || role.contains("qa") {
        BacklogRole::Tester
    } else if role.contains("review") || role.contains("audit") {
        BacklogRole::Reviewer
    } else if role.contains("doc") || role.contains("writer") {
        BacklogRole::Docs
    } else if role.contains("devops")
        || role.contains("ops")
        || role.contains("infra")
        || role.contains("deploy")
    {
        BacklogRole::Devops
    } else if role.contains("security") || role == "sec" {
        BacklogRole::Security
    } else {
        BacklogRole::General
    }
}

fn backlog_role_keywords(agent_name: &str) -> &'static [&'static str] {
    match classify_backlog_role(agent_name) {
        BacklogRole::Frontend => &["frontend", "ui", "web", "client", "ux"],
        BacklogRole::Backend => &["backend", "api", "server", "database", "data"],
        BacklogRole::Tester => &["test", "qa", "validation", "regression"],
        BacklogRole::Reviewer => &[
            "review",
            "reviewer",
            "qa",
            "security",
            "audit",
            "validation",
        ],
        BacklogRole::Docs => &["docs", "doc", "documentation", "spec", "readme"],
        BacklogRole::Devops => &["devops", "ops", "infra", "deploy", "ci", "reliability"],
        BacklogRole::Security => &["security", "sec", "vulnerability", "hardening", "audit"],
        BacklogRole::General => &[],
    }
}

fn classify_custom_message(kind: &str, payload: &str) -> MessageCategory {
    let kind = kind.to_lowercase();
    let payload = payload.to_lowercase();
    let token = format!("{} {}", kind, payload);

    if token.contains("ack")
        || token.contains("thanks")
        || token.contains("thank you")
        || token.contains("received")
        || token.contains("approved")
    {
        return MessageCategory::Confirmation;
    }

    if token.contains("info")
        || token.contains("fyi")
        || token.contains("status")
        || token.contains("update")
    {
        return MessageCategory::Informational;
    }

    if token.contains("query") || token.contains("question") {
        return MessageCategory::Query;
    }

    MessageCategory::Task
}

fn classify_message(msg_type: &tinytown::MessageType) -> MessageCategory {
    match msg_type {
        tinytown::MessageType::TaskAssign { .. } | tinytown::MessageType::Task { .. } => {
            MessageCategory::Task
        }
        tinytown::MessageType::Query { .. } | tinytown::MessageType::StatusRequest => {
            MessageCategory::Query
        }
        tinytown::MessageType::Informational { .. }
        | tinytown::MessageType::TaskDone { .. }
        | tinytown::MessageType::TaskFailed { .. }
        | tinytown::MessageType::StatusResponse { .. }
        | tinytown::MessageType::Ping
        | tinytown::MessageType::Pong => MessageCategory::Informational,
        tinytown::MessageType::Confirmation { .. } => MessageCategory::Confirmation,
        tinytown::MessageType::Custom { kind, payload } => classify_custom_message(kind, payload),
        tinytown::MessageType::Shutdown => MessageCategory::OtherActionable,
    }
}

fn parse_confirmation_type(message: &str) -> tinytown::ConfirmationType {
    let trimmed = message.trim();
    let lower = trimmed.to_lowercase();

    if lower.starts_with("rejected:") {
        let reason = trimmed
            .split_once(':')
            .map(|(_, reason)| reason.trim().to_string())
            .filter(|reason| !reason.is_empty())
            .unwrap_or_else(|| "No reason provided".to_string());
        return tinytown::ConfirmationType::Rejected { reason };
    }

    if lower.starts_with("received") {
        return tinytown::ConfirmationType::Received;
    }

    if lower.starts_with("approved") {
        return tinytown::ConfirmationType::Approved;
    }

    if lower.contains("thanks") || lower.contains("thank you") {
        return tinytown::ConfirmationType::Thanks;
    }

    tinytown::ConfirmationType::Acknowledged
}

fn summarize_message(msg_type: &tinytown::MessageType) -> String {
    match msg_type {
        tinytown::MessageType::TaskAssign { task_id } => format!("task assignment {}", task_id),
        tinytown::MessageType::Task { description } => description.clone(),
        tinytown::MessageType::Query { question } => format!("question: {}", question),
        tinytown::MessageType::Informational { summary } => summary.clone(),
        tinytown::MessageType::Confirmation { ack_type } => match ack_type {
            tinytown::ConfirmationType::Received => "received".to_string(),
            tinytown::ConfirmationType::Acknowledged => "acknowledged".to_string(),
            tinytown::ConfirmationType::Thanks => "thanks".to_string(),
            tinytown::ConfirmationType::Approved => "approved".to_string(),
            tinytown::ConfirmationType::Rejected { reason } => {
                format!("rejected: {}", reason)
            }
        },
        tinytown::MessageType::TaskDone { task_id, result } => {
            format!("task {} done: {}", task_id, result)
        }
        tinytown::MessageType::TaskFailed { task_id, error } => {
            format!("task {} failed: {}", task_id, error)
        }
        tinytown::MessageType::StatusRequest => "status requested".to_string(),
        tinytown::MessageType::StatusResponse {
            state,
            current_task,
        } => {
            if let Some(task) = current_task {
                format!("status {} ({})", state, task)
            } else {
                format!("status {}", state)
            }
        }
        tinytown::MessageType::Ping => "ping".to_string(),
        tinytown::MessageType::Pong => "pong".to_string(),
        tinytown::MessageType::Shutdown => "shutdown requested".to_string(),
        tinytown::MessageType::Custom { kind, payload } => format!("[{}] {}", kind, payload),
    }
}

async fn describe_message(channel: &tinytown::Channel, msg_type: &tinytown::MessageType) -> String {
    match msg_type {
        tinytown::MessageType::TaskAssign { task_id } => {
            if let Ok(tid) = task_id.parse::<tinytown::TaskId>()
                && let Ok(Some(task)) = channel.get_task(tid).await
            {
                format!("task {}: {}", task_id, task.description)
            } else {
                format!("task {}", task_id)
            }
        }
        _ => summarize_message(msg_type),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MissionTaskKind {
    Work,
    Review,
    Fix,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MissionTaskBinding {
    mission_id: tinytown::mission::MissionId,
    work_item_id: tinytown::mission::WorkItemId,
    kind: MissionTaskKind,
}

fn mission_task_binding(tags: &[String]) -> Option<MissionTaskBinding> {
    let mission_id = tags
        .iter()
        .find_map(|tag| tag.strip_prefix("mission:"))
        .and_then(|value| value.parse().ok())?;
    let work_item_id = tags
        .iter()
        .find_map(|tag| tag.strip_prefix("work-item:"))
        .and_then(|value| value.parse().ok())?;
    let kind = if tags.iter().any(|tag| tag == "mission-review-task") {
        MissionTaskKind::Review
    } else if tags.iter().any(|tag| tag == "mission-fix-task") {
        MissionTaskKind::Fix
    } else {
        MissionTaskKind::Work
    };
    Some(MissionTaskBinding {
        mission_id,
        work_item_id,
        kind,
    })
}

fn truncate_summary(text: &str, max_chars: usize) -> String {
    let first_line = text.lines().next().unwrap_or(text).trim();
    if first_line.chars().count() <= max_chars {
        first_line.to_string()
    } else {
        let truncated: String = first_line
            .chars()
            .take(max_chars.saturating_sub(3))
            .collect();
        format!("{}...", truncated)
    }
}

/// Clean up a raw log line for display in `tt status --deep`.
///
/// Extracts meaningful content from tracing-formatted logs like:
/// `[2m2026-03-09T20:03:14.667655Z[0m [32m INFO[0m [2mtt[0m[2m:[0m    ✅ Round 1 complete`
///
/// Returns None if the line should be skipped (e.g., internal waiting loops).
fn clean_log_line(line: &str) -> Option<String> {
    // Strip ANSI escape codes
    let stripped = strip_ansi_codes(line);

    // Skip empty lines
    if stripped.trim().is_empty() {
        return None;
    }

    // Skip internal waiting loop messages (noise)
    if stripped.contains("Inbox empty, waiting") {
        return None;
    }

    // Skip Redis version messages
    if stripped.contains("Redis version") && stripped.contains("detected") {
        return None;
    }

    // Skip repetitive round marker lines (just noise in logs)
    // Pattern: "📍 Round X/Y" without any other content
    let trimmed = stripped.trim();
    if trimmed.starts_with("📍 Round ") && !trimmed.contains("complete") {
        return None;
    }

    // Skip standalone "tt:" lines (empty log content)
    if trimmed == "tt:" || trimmed.ends_with(" tt:") {
        return None;
    }

    // Skip "Running auggie..." lines (repetitive, expected behavior)
    if trimmed.contains("Running auggie") {
        return None;
    }

    // Skip "Rounds completed:" status lines (redundant with round complete messages)
    if trimmed.contains("📊 Rounds completed:") {
        return None;
    }

    // Skip batching status lines (low-value noise)
    if trimmed.contains("📬 batched:") {
        return None;
    }

    // Skip repetitive backlog prompting messages (consolidate with round info)
    if trimmed.contains("prompting backlog review") || trimmed.contains("prompting claim review") {
        return None;
    }

    // Try to extract the actual message content from tracing format
    // Format: "2026-03-09T20:03:14.667655Z  INFO tt:    ✅ Round 1 complete"
    // Or: "📍 Round 2/15"
    let content = extract_log_content(&stripped);

    if content.is_empty() {
        return None;
    }

    // Skip if extracted content is just "tt:" (sometimes logs have empty content)
    if content == "tt:" {
        return None;
    }

    Some(content)
}

/// Strip ANSI escape codes from a string.
fn strip_ansi_codes(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Skip escape sequence: ESC [ ... m
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                // Skip until we hit 'm' (end of color code)
                for ch in chars.by_ref() {
                    if ch == 'm' {
                        break;
                    }
                }
            }
        } else {
            result.push(c);
        }
    }

    result
}

/// Clean up old round log files for an agent.
///
/// Removes all files matching pattern: `{agent_name}_round_{N}.log`
/// Returns the number of files deleted.
fn clean_agent_round_logs(log_dir: &std::path::Path, agent_name: &str) -> usize {
    let prefix = format!("{}_round_", agent_name);
    let mut deleted = 0;

    if let Ok(entries) = std::fs::read_dir(log_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str())
                && filename.starts_with(&prefix)
                && filename.ends_with(".log")
                && std::fs::remove_file(&path).is_ok()
            {
                deleted += 1;
            }
        }
    }

    deleted
}

/// Find the latest round log file for an agent.
///
/// Searches for files matching pattern: `{agent_name}_round_{N}.log`
/// Returns the path and round number of the file with the highest round number.
fn find_latest_round_log(
    log_dir: &std::path::Path,
    agent_name: &str,
) -> Option<(u32, std::path::PathBuf)> {
    let prefix = format!("{}_round_", agent_name);
    let mut latest: Option<(u32, std::path::PathBuf)> = None;

    if let Ok(entries) = std::fs::read_dir(log_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if let Some(filename) = path.file_name().and_then(|n| n.to_str())
                && filename.starts_with(&prefix)
                && filename.ends_with(".log")
            {
                // Extract round number from filename
                let num_part = &filename[prefix.len()..filename.len() - 4]; // Remove prefix and ".log"
                if let Ok(round_num) = num_part.parse::<u32>() {
                    match &latest {
                        Some((current_max, _)) if round_num > *current_max => {
                            latest = Some((round_num, path));
                        }
                        None => {
                            latest = Some((round_num, path));
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    latest
}

/// Extract the meaningful content from a tracing log line.
fn extract_log_content(line: &str) -> String {
    let trimmed = line.trim();

    // If it starts with an emoji or marker, it's already clean content
    if trimmed.starts_with('📍')
        || trimmed.starts_with('')
        || trimmed.starts_with('')
        || trimmed.starts_with('🔄')
        || trimmed.starts_with('📬')
        || trimmed.starts_with('🤖')
        || trimmed.starts_with('📊')
        || trimmed.starts_with('🛑')
        || trimmed.starts_with('📋')
    {
        return trimmed.to_string();
    }

    // Try to find the message after the log level indicator
    // Patterns: "INFO tt:" or "WARN tt:" or just the timestamp pattern
    if let Some(pos) = trimmed.find(" INFO ") {
        let after_info = &trimmed[pos + 6..];
        // Skip module path like "tt:" or "tinytown::town:"
        if let Some(colon_pos) = after_info.find(':') {
            let content = after_info[colon_pos + 1..].trim();
            if !content.is_empty() {
                return content.to_string();
            }
        }
        return after_info.trim().to_string();
    }

    if let Some(pos) = trimmed.find(" WARN ") {
        let after_warn = &trimmed[pos + 6..];
        if let Some(colon_pos) = after_warn.find(':') {
            let content = after_warn[colon_pos + 1..].trim();
            if !content.is_empty() {
                return format!("⚠️ {}", content);
            }
        }
        return format!("⚠️ {}", after_warn.trim());
    }

    if let Some(pos) = trimmed.find(" ERROR ") {
        let after_error = &trimmed[pos + 7..];
        if let Some(colon_pos) = after_error.find(':') {
            let content = after_error[colon_pos + 1..].trim();
            if !content.is_empty() {
                return format!("{}", content);
            }
        }
        return format!("{}", after_error.trim());
    }

    // If it looks like a timestamp at the start, try to skip it
    // Pattern: "2026-03-09T20:03:14.667655Z ..."
    if trimmed.len() > 27
        && trimmed.chars().nth(4) == Some('-')
        && trimmed.chars().nth(10) == Some('T')
    {
        let rest = trimmed[27..].trim();
        if !rest.is_empty() {
            return rest.to_string();
        }
    }

    // Return as-is if we couldn't parse it
    trimmed.to_string()
}

fn backlog_role_hint(agent_name: &str) -> &'static str {
    match classify_backlog_role(agent_name) {
        BacklogRole::Frontend => "Prioritize tasks tagged frontend/ui/web/client.",
        BacklogRole::Backend => "Prioritize tasks tagged backend/api/server/database.",
        BacklogRole::Tester => "Prioritize tasks tagged test/qa/validation/regression.",
        BacklogRole::Reviewer => "Prioritize review/quality/security validation tasks.",
        BacklogRole::Docs => "Prioritize documentation/spec/readme tasks.",
        BacklogRole::Devops => "Prioritize infrastructure/ci/deploy/reliability tasks.",
        BacklogRole::Security => "Prioritize security/vulnerability/hardening tasks.",
        BacklogRole::General => {
            "Prioritize tasks matching your current specialization and capabilities."
        }
    }
}

fn backlog_task_matches_role(task: &tinytown::Task, agent_name: &str) -> bool {
    let keywords = backlog_role_keywords(agent_name);
    if keywords.is_empty() {
        return true;
    }

    let normalized_tags: Vec<String> = task.tags.iter().map(|tag| tag.to_lowercase()).collect();
    if normalized_tags
        .iter()
        .any(|tag| keywords.iter().any(|keyword| tag == keyword))
    {
        return true;
    }

    let description = task.description.to_lowercase();
    keywords.iter().any(|keyword| description.contains(keyword))
}

struct BacklogSnapshot {
    total_backlog: usize,
    total_matching: usize,
    tasks: Vec<(tinytown::TaskId, Task)>,
}

async fn backlog_snapshot_for_agent(
    channel: &tinytown::Channel,
    agent_name: &str,
    limit: usize,
) -> Result<BacklogSnapshot> {
    let backlog_ids = channel.backlog_list().await?;
    let mut tasks = Vec::new();
    let mut total_matching = 0usize;

    for task_id in backlog_ids {
        if let Some(task) = channel.get_task(task_id).await?
            && backlog_task_matches_role(&task, agent_name)
        {
            total_matching += 1;
            if tasks.len() < limit {
                tasks.push((task_id, task));
            }
        }
    }

    Ok(BacklogSnapshot {
        total_backlog: channel.backlog_len().await?,
        total_matching,
        tasks,
    })
}

/// Bootstrap Redis by delegating to an AI coding agent.
///
/// The agent fetches the release from GitHub, downloads source, and builds it.
fn bootstrap_redis(version: &str, cli: &str) -> Result<()> {
    use std::process::Command;

    let tt_dir = dirs::home_dir()
        .map(|h| h.join(".tt"))
        .unwrap_or_else(|| std::path::PathBuf::from(".tt"));

    info!("🚀 Bootstrapping Redis {} to {}", version, tt_dir.display());
    info!("   Using {} to download and build Redis...", cli);
    info!("");

    // Create .tt directory
    std::fs::create_dir_all(&tt_dir)?;

    let version_instruction = if version == "latest" {
        "Find the latest stable release version number from https://github.com/redis/redis/releases (e.g., 8.0.2)".to_string()
    } else {
        format!("Use Redis version {}", version)
    };

    let prompt = format!(
        r#"# Task: Download and Build Redis

{version_instruction}

## Steps

1. Go to https://github.com/redis/redis/releases
2. Find the release version (e.g., 8.0.2)
3. Download the source tarball (.tar.gz) to {tt_dir}/versions/
4. Extract it to {tt_dir}/versions/redis-<version>/ (e.g., redis-8.0.2)
5. cd into the extracted directory and run `make` to build Redis
6. Create {tt_dir}/bin/ directory if it doesn't exist
7. Create symlinks in {tt_dir}/bin/ pointing to the built binaries:
   - ln -sf {tt_dir}/versions/redis-<version>/src/redis-server {tt_dir}/bin/redis-server
   - ln -sf {tt_dir}/versions/redis-<version>/src/redis-cli {tt_dir}/bin/redis-cli

## Target Directory

Base directory: {tt_dir}
Version directory: {tt_dir}/versions/redis-<version>/
Symlinks: {tt_dir}/bin/redis-server, {tt_dir}/bin/redis-cli

## Important

- Use curl or wget to download
- The source URL format is: https://github.com/redis/redis/archive/refs/tags/<version>.tar.gz
- After building, verify with: {tt_dir}/bin/redis-server --version
- The symlinks allow easy switching between versions

## When Done

Print the installed version and confirm the symlinks are working.
"#,
        version_instruction = version_instruction,
        tt_dir = tt_dir.display()
    );

    // Write prompt to temp file
    let prompt_file = tt_dir.join("bootstrap_prompt.md");
    std::fs::write(&prompt_file, &prompt)?;

    // Get the CLI command
    let cli_cmd = match cli {
        "claude" => "claude --print --dangerously-skip-permissions",
        "auggie" => "auggie --print",
        "codex" => "codex exec --dangerously-bypass-approvals-and-sandbox",
        "codex-mini" => {
            "codex exec --dangerously-bypass-approvals-and-sandbox -m gpt-5.4-mini -c model_reasoning_effort=\"medium\""
        }
        "aider" => "aider --yes --no-auto-commits --message",
        _ => cli, // Allow custom commands
    };

    let shell_cmd = build_cli_command(cli, cli_cmd, &prompt_file);
    info!("📋 Running: {}", shell_cmd);
    info!("   (This may take a few minutes to download and compile)");
    info!("");

    // Run the AI agent
    let status = Command::new("sh")
        .args(["-c", &shell_cmd])
        .current_dir(&tt_dir)
        .status()?;

    // Clean up prompt file
    let _ = std::fs::remove_file(&prompt_file);

    if status.success() {
        let redis_bin = tt_dir.join("bin/redis-server");
        if redis_bin.exists() {
            // Get version from the installed binary
            let version_output = Command::new(&redis_bin)
                .arg("--version")
                .output()
                .ok()
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .unwrap_or_default();

            info!("");
            info!("✅ Redis installed successfully!");
            info!("   Location: {}", redis_bin.display());
            if !version_output.is_empty() {
                info!("   {}", version_output.trim());
            }

            // Initialize global config with password if not already set
            match GlobalConfig::load_or_init() {
                Ok(config) => {
                    info!("");
                    info!("📋 Global config initialized:");
                    info!("   Config: ~/.tt/config.toml");
                    info!("   Default CLI: {}", config.default_cli);
                    info!(
                        "   Central Redis: {}:{} (password protected)",
                        config.redis.host, config.redis.port
                    );
                }
                Err(e) => {
                    warn!("⚠️  Could not initialize global config: {}", e);
                }
            }

            info!("");
            info!("   Tinytown will automatically use this Redis.");
            info!("   Run: tt init");
        } else {
            info!("");
            info!("⚠️  Agent finished but redis-server not found at expected location.");
            info!("   Expected: {}", redis_bin.display());
            info!(
                "   Check {}/versions/ for build artifacts.",
                tt_dir.display()
            );
            info!("   You may need to run 'tt bootstrap' again or build manually.");
        }
    } else {
        info!("");
        info!("❌ Bootstrap failed. Check the output above for errors.");
        info!("   You can also install Redis manually:");
        info!("   - macOS: brew install redis");
        info!("   - Ubuntu: sudo apt install redis-server");
        info!("   - From source: https://redis.io/docs/latest/operate/oss_and_stack/install/");
    }

    Ok(())
}

/// Derive a town name from git repo and branch, or fall back to directory name.
///
/// Format: `<repo>-<branch>` (e.g., `redisearch-feature-auth`)
fn derive_town_name(town_path: &std::path::Path) -> String {
    use std::process::Command;

    // Try to get git repo name and branch
    let repo_name = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(town_path)
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                String::from_utf8(o.stdout).ok()
            } else {
                None
            }
        })
        .and_then(|path| {
            std::path::Path::new(path.trim())
                .file_name()
                .and_then(|s| s.to_str())
                .map(|s| s.to_string())
        });

    let branch_name = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(town_path)
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                String::from_utf8(o.stdout)
                    .ok()
                    .map(|s| s.trim().to_string())
            } else {
                None
            }
        });

    match (repo_name, branch_name) {
        (Some(repo), Some(branch)) => {
            // Sanitize branch name (replace / with -)
            let branch = branch.replace('/', "-");
            format!("{}-{}", repo, branch)
        }
        (Some(repo), None) => repo,
        _ => {
            // Fall back to directory name
            town_path
                .canonicalize()
                .ok()
                .and_then(|p| {
                    p.file_name()
                        .and_then(|s| s.to_str())
                        .map(|s| s.to_string())
                })
                .unwrap_or_else(|| "tinytown".to_string())
        }
    }
}

/// Register a town in ~/.tt/towns.toml
fn register_town(town_path: &std::path::Path, name: &str) -> Result<()> {
    use tinytown::global_config::GLOBAL_CONFIG_DIR;

    let tt_dir = dirs::home_dir()
        .map(|h| h.join(GLOBAL_CONFIG_DIR))
        .ok_or_else(|| {
            tinytown::Error::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Could not find home directory",
            ))
        })?;

    // Ensure ~/.tt exists
    std::fs::create_dir_all(&tt_dir)?;

    let towns_path = tt_dir.join("towns.toml");
    let abs_path = town_path
        .canonicalize()
        .unwrap_or_else(|_| town_path.to_path_buf());
    let path_str = abs_path.to_string_lossy().to_string();

    // Load existing towns or create new
    let mut towns_file: TownsFile = if towns_path.exists() {
        let content = std::fs::read_to_string(&towns_path)?;
        toml::from_str(&content).unwrap_or_default()
    } else {
        TownsFile::default()
    };

    // Check if already registered (by path)
    if towns_file.towns.iter().any(|t| t.path == path_str) {
        // Update name if different
        for town in &mut towns_file.towns {
            if town.path == path_str && town.name != name {
                town.name = name.to_string();
            }
        }
    } else {
        // Add new entry
        towns_file.towns.push(TownEntry {
            path: path_str,
            name: name.to_string(),
        });
    }

    // Save
    let content = toml::to_string_pretty(&towns_file).map_err(|e| {
        tinytown::Error::Io(std::io::Error::other(format!(
            "Failed to serialize towns.toml: {}",
            e
        )))
    })?;
    std::fs::write(&towns_path, content)?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Setup logging
    let filter = if cli.verbose {
        EnvFilter::new("debug")
    } else {
        EnvFilter::new("info")
    };
    tracing_subscriber::fmt().with_env_filter(filter).init();

    match cli.command {
        Commands::Bootstrap {
            version,
            cli: cli_arg,
        } => {
            // Use CLI arg, or fall back to global config default_cli
            let cli_name = cli_arg.unwrap_or_else(|| {
                GlobalConfig::load()
                    .map(|c| c.default_cli)
                    .unwrap_or_else(|_| "claude".to_string())
            });
            bootstrap_redis(&version, &cli_name)?;
        }

        Commands::Init { name } => {
            let name = name.unwrap_or_else(|| derive_town_name(&cli.town));

            // Initialize global config if needed (ensures password is set)
            let global = GlobalConfig::load_or_init().unwrap_or_default();

            let town = Town::init(&cli.town, &name).await?;
            info!("✨ Initialized town '{}' at {}", name, cli.town.display());

            // Update .gitignore to exclude .tt directory (runtime artifacts)
            let gitignore_path = cli.town.join(".gitignore");
            let tt_entry = ".tt";
            let needs_update = if gitignore_path.exists() {
                let content = std::fs::read_to_string(&gitignore_path).unwrap_or_default();
                !content.lines().any(|line| line.trim() == tt_entry)
            } else {
                true
            };
            if needs_update {
                let mut content = if gitignore_path.exists() {
                    std::fs::read_to_string(&gitignore_path).unwrap_or_default()
                } else {
                    String::new()
                };
                if !content.is_empty() && !content.ends_with('\n') {
                    content.push('\n');
                }
                content.push_str("\n# Tinytown runtime artifacts\n.tt\n");
                std::fs::write(&gitignore_path, content)?;
                info!("📝 Added .tt to .gitignore");
            }

            // Show appropriate message based on Redis mode
            if global.redis.use_central {
                info!(
                    "📡 Using central Redis on {}:{} (shared across towns)",
                    global.redis.host, global.redis.port
                );
            } else {
                info!("📡 Redis running with Unix socket for fast message passing");
            }
            info!("🚀 Run 'tt spawn <name>' to create agents");

            // Register town in ~/.tt/towns.toml
            if let Err(e) = register_town(&cli.town, &name) {
                info!("⚠️  Could not register town in ~/.tt/towns.toml: {}", e);
            }

            // Keep town alive briefly to show it's working
            drop(town);
        }

        Commands::Spawn {
            name,
            cli: cli_arg,
            max_rounds,
            foreground,
            role,
            nickname,
            parent,
        } => {
            let town = Town::connect(&cli.town).await?;
            validate_spawn_agent_name(&name)?;
            // Priority: CLI arg > town config > global config
            let cli_name = cli_arg.unwrap_or_else(|| {
                let town_cli = &town.config().default_cli;
                if !town_cli.is_empty() {
                    town_cli.clone()
                } else {
                    GlobalConfig::load()
                        .map(|c| c.default_cli)
                        .unwrap_or_else(|_| "claude".to_string())
                }
            });
            let cli_name = town.config().resolve_cli_name(&cli_name);
            let agent = town.spawn_agent(&name, &cli_name).await?;
            let agent_id = agent.id();

            // Apply control-plane metadata if provided
            if role.is_some() || nickname.is_some() || parent.is_some() {
                let mut agent_state =
                    town.channel()
                        .get_agent_state(agent_id)
                        .await?
                        .ok_or_else(|| {
                            tinytown::Error::AgentNotFound(format!(
                                "Agent {} state not found after spawn — metadata not persisted",
                                agent_id
                            ))
                        })?;
                if let Some(ref r) = role {
                    agent_state.role_id = Some(r.clone());
                }
                if let Some(ref n) = nickname {
                    agent_state.nickname = Some(n.clone());
                }
                if let Some(ref p) = parent {
                    // Resolve parent by name or ID
                    let parent_id = if let Ok(pid) = p.parse::<tinytown::AgentId>() {
                        pid
                    } else {
                        town.agent(p).await.map(|h| h.id()).map_err(|_| {
                            tinytown::Error::AgentNotFound(format!(
                                "Parent agent '{}' not found",
                                p
                            ))
                        })?
                    };
                    agent_state.parent_agent_id = Some(parent_id);
                }
                town.channel().set_agent_state(&agent_state).await?;
            }

            let agent_id = agent_id.to_string();

            info!("🤖 Spawned agent '{}' using CLI '{}'", name, cli_name);
            info!("   ID: {}", agent_id);

            // Get the path to this executable
            let exe = std::env::current_exe()?;
            let town_path = cli.town.canonicalize().unwrap_or(cli.town.clone());

            // Clean up old round log files to prevent stale data in 'tt status --deep'
            // This handles the case where an agent is respawned with the same name
            let log_dir = town_path.join(".tt/logs");
            if log_dir.exists() {
                let cleaned = clean_agent_round_logs(&log_dir, &name);
                if cleaned > 0 {
                    info!("   Cleaned {} old round log file(s)", cleaned);
                }
            }

            if foreground {
                // Run agent loop in foreground
                info!("🔄 Running agent loop (max {} rounds)...", max_rounds);
                drop(town); // Release connection before running loop

                let status = std::process::Command::new(&exe)
                    .arg("--town")
                    .arg(&town_path)
                    .arg("agent-loop")
                    .arg(&name)
                    .arg(&agent_id)
                    .arg(max_rounds.to_string())
                    .stdin(std::process::Stdio::inherit())
                    .stdout(std::process::Stdio::inherit())
                    .stderr(std::process::Stdio::inherit())
                    .status()?;

                if status.success() {
                    info!("✅ Agent '{}' completed", name);
                } else {
                    info!("❌ Agent '{}' exited with error", name);
                }
            } else {
                // Background the agent process
                info!(
                    "🔄 Starting agent loop in background (max {} rounds)...",
                    max_rounds
                );
                info!("   Logs: {}/.tt/logs/{}.log", town_path.display(), name);

                std::fs::create_dir_all(&log_dir)?;
                let log_path = log_dir.join(format!("{}.log", name));
                spawn_agent_loop_background(
                    &exe, &town_path, &name, &agent_id, max_rounds, &log_path,
                )?;

                info!("   Agent running in background. Check status with 'tt status'");
            }
        }

        Commands::List => {
            let town = Town::connect(&cli.town).await?;
            let agents = town.list_agents().await;

            if agents.is_empty() {
                info!("No agents. Run 'tt spawn <name>' to create one.");
            } else {
                info!("Agents:");
                for agent in agents {
                    info!(
                        "  {} ({}) - {:?}",
                        agent.display_label(),
                        agent.id.short_id(),
                        agent.state
                    );
                }
            }
        }

        Commands::Assign { agent, task } => {
            let town = Town::connect(&cli.town).await?;
            let result = tinytown::TaskService::assign(&town, &agent, &task).await?;

            info!("📋 Assigned task {} to agent '{}'", result.task_id, agent);
        }

        Commands::Status {
            deep,
            tasks: show_tasks,
        } => {
            let town = Town::connect(&cli.town).await?;
            let config = town.config();

            info!("🏘️  Town: {}", config.name);
            info!("📂 Root: {}", town.root().display());
            info!("📡 Redis: {}", config.redis_url_redacted());

            let agents = town.list_agents().await;
            info!("🤖 Agents: {}", agents.len());

            // Fetch tasks once before the agent loop to avoid N+1 Redis calls
            let all_tasks = town.channel().list_tasks().await.unwrap_or_default();

            for agent in &agents {
                let inbox_len = town.channel().inbox_len(agent.id).await.unwrap_or(0);
                let peek_count = std::cmp::min(inbox_len, 200) as isize;
                let inbox_messages = if peek_count > 0 {
                    town.channel()
                        .peek_inbox(agent.id, peek_count)
                        .await
                        .unwrap_or_default()
                } else {
                    Vec::new()
                };
                let mut breakdown = MessageBreakdown::default();
                for msg in &inbox_messages {
                    breakdown.count(&msg.msg_type);
                }
                let sampled_note = if inbox_len > inbox_messages.len() {
                    format!(" (sampled first {})", inbox_messages.len())
                } else {
                    String::new()
                };

                // Calculate uptime
                let uptime = chrono::Utc::now() - agent.created_at;
                let uptime_str = if uptime.num_hours() > 0 {
                    format!("{}h {}m", uptime.num_hours(), uptime.num_minutes() % 60)
                } else if uptime.num_minutes() > 0 {
                    format!("{}m {}s", uptime.num_minutes(), uptime.num_seconds() % 60)
                } else {
                    format!("{}s", uptime.num_seconds())
                };

                // Get running tasks assigned to this agent (using pre-fetched all_tasks)
                let running_tasks: Vec<_> = all_tasks
                    .iter()
                    .filter(|t| {
                        t.assigned_to == Some(agent.id) && t.state == tinytown::TaskState::Running
                    })
                    .collect();

                if deep {
                    let parent_tag = agent
                        .parent_agent_id
                        .map_or(String::new(), |_| " (child)".to_string());
                    info!(
                        "   {}{} ({:?}) - {} pending, {} rounds, uptime {}",
                        agent.display_label(),
                        parent_tag,
                        agent.state,
                        inbox_len,
                        agent.rounds_completed,
                        uptime_str
                    );
                    // Build a more readable pending breakdown with labels
                    let task_count = breakdown.tasks + breakdown.other_actionable;
                    let mut pending_parts = Vec::new();
                    if task_count > 0 {
                        pending_parts.push(format!(
                            "{} task{}",
                            task_count,
                            if task_count == 1 { "" } else { "s" }
                        ));
                    }
                    if breakdown.queries > 0 {
                        pending_parts.push(format!(
                            "{} quer{}",
                            breakdown.queries,
                            if breakdown.queries == 1 { "y" } else { "ies" }
                        ));
                    }
                    if breakdown.informational > 0 {
                        pending_parts.push(format!("{} info", breakdown.informational));
                    }
                    if breakdown.confirmations > 0 {
                        pending_parts.push(format!(
                            "{} ack{}",
                            breakdown.confirmations,
                            if breakdown.confirmations == 1 {
                                ""
                            } else {
                                "s"
                            }
                        ));
                    }
                    if pending_parts.is_empty() {
                        pending_parts.push("no pending messages".to_string());
                    }
                    info!("      └─ 📬 {}{}", pending_parts.join(", "), sampled_note);
                    // Show running tasks assigned to this agent
                    if !running_tasks.is_empty() {
                        for task in &running_tasks {
                            let desc = if task.description.len() > 55 {
                                format!(
                                    "{}...",
                                    &task.description.chars().take(52).collect::<String>()
                                )
                            } else {
                                task.description.clone()
                            };
                            let started = task
                                .started_at
                                .map(|t| {
                                    let elapsed = chrono::Utc::now() - t;
                                    if elapsed.num_hours() > 0 {
                                        format!(
                                            "{}h {}m ago",
                                            elapsed.num_hours(),
                                            elapsed.num_minutes() % 60
                                        )
                                    } else if elapsed.num_minutes() > 0 {
                                        format!("{}m ago", elapsed.num_minutes())
                                    } else {
                                        "just now".to_string()
                                    }
                                })
                                .unwrap_or_default();
                            info!(
                                "      └─ 🔄 {}: {} (started {})",
                                task.id.short_id(),
                                desc,
                                started
                            );
                        }
                    }
                    // Get recent activity from Redis
                    if let Ok(Some(activity)) = town.channel().get_agent_activity(agent.id).await {
                        for line in activity.lines().take(5) {
                            info!("      └─ {}", line);
                        }
                    }
                } else {
                    // Show current task indicator for working agents in non-deep mode
                    info!(
                        "   {} ({:?}) - {} pending (T:{} Q:{} I:{} C:{})",
                        agent.display_label(),
                        agent.state,
                        inbox_len,
                        breakdown.tasks + breakdown.other_actionable,
                        breakdown.queries,
                        breakdown.informational,
                        breakdown.confirmations
                    );
                    // Show running tasks for this agent
                    if !running_tasks.is_empty() {
                        let task = &running_tasks[0];
                        let desc = if task.description.len() > 50 {
                            format!(
                                "{}...",
                                &task.description.chars().take(47).collect::<String>()
                            )
                        } else {
                            task.description.clone()
                        };
                        info!("      └─ Working: {}", desc);
                    }
                }
            }

            // Task summary section (reuse pre-fetched all_tasks)
            let tasks = &all_tasks;
            let backlog_count = town.channel().backlog_len().await.unwrap_or(0);

            // Count by state
            let mut pending = 0usize;
            let mut assigned = 0usize;
            let mut running = 0usize;
            let mut completed = 0usize;
            let mut failed = 0usize;
            let mut cancelled = 0usize;

            for task in tasks {
                match task.state {
                    tinytown::TaskState::Pending => pending += 1,
                    tinytown::TaskState::Assigned => assigned += 1,
                    tinytown::TaskState::Running => running += 1,
                    tinytown::TaskState::Completed => completed += 1,
                    tinytown::TaskState::Failed => failed += 1,
                    tinytown::TaskState::Cancelled => cancelled += 1,
                }
            }

            let total = tasks.len();
            let in_flight = assigned + running;
            let done = completed + failed + cancelled;
            // Note: backlog items are already counted in `pending` (they have TaskState::Pending)
            // so we don't add backlog_count again to avoid double-counting
            let pending_total = pending;

            info!(
                "📋 Tasks: {} total ({} pending, {} in-flight, {} done)",
                total, pending_total, in_flight, done
            );

            // Show detailed task breakdown when --tasks flag is passed
            if show_tasks {
                info!("");
                info!("📊 Task Breakdown by State:");
                info!("   ⏳ Pending:   {}", pending);
                info!("   📌 Assigned:  {}", assigned);
                info!("   🔄 Running:   {}", running);
                info!("   ✅ Completed: {}", completed);
                info!("   ❌ Failed:    {}", failed);
                info!("   🚫 Cancelled: {}", cancelled);
                info!("   📋 Backlog:   {}", backlog_count);

                // Group tasks by agent
                let mut tasks_by_agent: std::collections::HashMap<String, Vec<&tinytown::Task>> =
                    std::collections::HashMap::new();
                let mut unassigned_tasks: Vec<&tinytown::Task> = Vec::new();

                for task in tasks {
                    if let Some(agent_id) = task.assigned_to {
                        // Find agent label (reusing pre-fetched agents list)
                        let agent_label = agents
                            .iter()
                            .find(|a| a.id == agent_id)
                            .map(|a| a.display_label())
                            .unwrap_or_else(|| agent_id.short_id());
                        tasks_by_agent.entry(agent_label).or_default().push(task);
                    } else {
                        unassigned_tasks.push(task);
                    }
                }

                // Show tasks by agent
                info!("");
                info!("📋 Tasks by Agent:");
                for (agent_label, agent_tasks) in &tasks_by_agent {
                    let active_count = agent_tasks
                        .iter()
                        .filter(|t| !t.state.is_terminal())
                        .count();
                    let done_count = agent_tasks.iter().filter(|t| t.state.is_terminal()).count();
                    info!(
                        "   {} ({} active, {} done):",
                        agent_label, active_count, done_count
                    );
                    for task in agent_tasks.iter().take(5) {
                        let state_icon = match task.state {
                            tinytown::TaskState::Pending => "",
                            tinytown::TaskState::Assigned => "📌",
                            tinytown::TaskState::Running => "🔄",
                            tinytown::TaskState::Completed => "",
                            tinytown::TaskState::Failed => "",
                            tinytown::TaskState::Cancelled => "🚫",
                        };
                        let desc = task.description.chars().take(50).collect::<String>();
                        let truncated = if task.description.chars().count() > 50 {
                            "..."
                        } else {
                            ""
                        };
                        info!(
                            "      {} {} {}{}",
                            state_icon,
                            task.id.short_id(),
                            desc,
                            truncated
                        );
                    }
                    if agent_tasks.len() > 5 {
                        info!("      ... and {} more task(s)", agent_tasks.len() - 5);
                    }
                }

                if !unassigned_tasks.is_empty() {
                    info!("   (unassigned) ({} tasks):", unassigned_tasks.len());
                    for task in unassigned_tasks.iter().take(5) {
                        let desc = task.description.chars().take(50).collect::<String>();
                        let truncated = if task.description.chars().count() > 50 {
                            "..."
                        } else {
                            ""
                        };
                        info!("      ⏳ {} {}{}", task.id.short_id(), desc, truncated);
                    }
                    if unassigned_tasks.len() > 5 {
                        info!("      ... and {} more task(s)", unassigned_tasks.len() - 5);
                    }
                }
            }

            if deep {
                info!("");
                info!("📊 Stats: rounds completed, uptime since spawn");

                // Show recent logs from each agent
                info!("");
                info!("📜 Recent Agent Activity:");
                let log_dir = cli.town.join(".tt/logs");
                if log_dir.exists() {
                    let mut shown_logs = std::collections::HashSet::new();
                    // Reuse the agents variable from earlier to avoid redundant Redis call
                    for agent in &agents {
                        let log_file = log_dir.join(format!("{}.log", agent.name));
                        if log_file.exists() && !shown_logs.contains(&agent.name) {
                            shown_logs.insert(agent.name.clone());
                            info!("");
                            info!("--- {} ---", agent.display_label());
                            if let Ok(content) = std::fs::read_to_string(&log_file) {
                                let lines: Vec<&str> = content.lines().collect();
                                let start = lines.len().saturating_sub(50);
                                let mut shown = 0;
                                let mut consecutive_rounds: Vec<u32> = Vec::new();
                                let mut last_line: Option<String> = None;

                                for line in &lines[start..] {
                                    if shown >= 15 {
                                        break;
                                    }
                                    // Parse and clean up log lines for better UX
                                    if let Some(cleaned) = clean_log_line(line) {
                                        if cleaned.is_empty() {
                                            continue;
                                        }

                                        // Detect round completion patterns:
                                        // "✅ Round N complete" or "Round N: ✅ completed"
                                        let is_round_complete = (cleaned.contains("Round ")
                                            && cleaned.contains("complete"))
                                            && (cleaned.contains("")
                                                || cleaned.contains("completed"));

                                        if is_round_complete {
                                            // Extract round number - try both formats
                                            if let Some(round_str) = cleaned.split("Round ").nth(1)
                                            {
                                                // Handle both "Round N complete" and "Round N:"
                                                let num_part = round_str
                                                    .split_whitespace()
                                                    .next()
                                                    .or_else(|| round_str.split(':').next())
                                                    .unwrap_or("");
                                                if let Ok(round_num) =
                                                    num_part.trim().parse::<u32>()
                                                {
                                                    consecutive_rounds.push(round_num);
                                                    continue;
                                                }
                                            }
                                        }

                                        // Before showing a non-round line, flush any accumulated rounds
                                        if !consecutive_rounds.is_empty() {
                                            if consecutive_rounds.len() == 1 {
                                                info!(
                                                    "  ✅ Round {} completed",
                                                    consecutive_rounds[0]
                                                );
                                            } else {
                                                let min_round =
                                                    consecutive_rounds.iter().min().unwrap_or(&0);
                                                let max_round =
                                                    consecutive_rounds.iter().max().unwrap_or(&0);
                                                info!(
                                                    "  ✅ Rounds {}-{} completed ({} rounds)",
                                                    min_round,
                                                    max_round,
                                                    consecutive_rounds.len()
                                                );
                                            }
                                            shown += 1;
                                            consecutive_rounds.clear();
                                        }

                                        // Skip duplicate consecutive lines
                                        if Some(&cleaned) == last_line.as_ref() {
                                            continue;
                                        }

                                        info!("  {}", cleaned);
                                        last_line = Some(cleaned);
                                        shown += 1;
                                    }
                                }

                                // Flush any remaining accumulated rounds
                                if !consecutive_rounds.is_empty() {
                                    if consecutive_rounds.len() == 1 {
                                        info!("  ✅ Round {} completed", consecutive_rounds[0]);
                                    } else {
                                        let min_round =
                                            consecutive_rounds.iter().min().unwrap_or(&0);
                                        let max_round =
                                            consecutive_rounds.iter().max().unwrap_or(&0);
                                        info!(
                                            "  ✅ Rounds {}-{} completed ({} rounds)",
                                            min_round,
                                            max_round,
                                            consecutive_rounds.len()
                                        );
                                    }
                                }
                            }

                            // Show last lines from most recent round log file
                            // These files show what the AI is actually doing
                            if let Some((round_num, round_log_path)) =
                                find_latest_round_log(&log_dir, &agent.name)
                            {
                                info!("");
                                info!("  📋 Latest Round {} Activity:", round_num);
                                if let Ok(round_content) = std::fs::read_to_string(&round_log_path)
                                {
                                    let round_lines: Vec<&str> = round_content.lines().collect();
                                    // Show last 8 meaningful lines
                                    let mut meaningful_lines: Vec<&str> = Vec::new();
                                    for line in round_lines.iter().rev() {
                                        let trimmed = line.trim();
                                        // Skip empty lines, ANSI-only lines, and noise
                                        if trimmed.is_empty() {
                                            continue;
                                        }
                                        // Skip lines that are mostly ANSI codes
                                        let stripped = strip_ansi_codes(trimmed);
                                        if stripped.is_empty() {
                                            continue;
                                        }
                                        meaningful_lines.push(trimmed);
                                        if meaningful_lines.len() >= 8 {
                                            break;
                                        }
                                    }
                                    // Display in chronological order
                                    meaningful_lines.reverse();
                                    for line in meaningful_lines {
                                        // Clean up and truncate for display (use chars to avoid UTF-8 panic)
                                        let display_line = strip_ansi_codes(line);
                                        let truncated = if display_line.chars().count() > 80 {
                                            format!(
                                                "{}...",
                                                display_line.chars().take(77).collect::<String>()
                                            )
                                        } else {
                                            display_line
                                        };
                                        info!("     {}", truncated);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Commands::Kill { agent } => {
            let town = Town::connect(&cli.town).await?;
            let handle = town.agent(&agent).await?;
            tinytown::AgentService::kill(town.channel(), handle.id()).await?;

            info!("🛑 Requested stop for agent '{}'", agent);
            info!("   Agent will stop at the start of its next round.");
        }

        Commands::Interrupt { agent } => {
            let town = Town::connect(&cli.town).await?;
            let handle = town.agent(&agent).await?;
            tinytown::AgentService::interrupt(town.channel(), handle.id()).await?;

            info!("⏸️  Interrupted agent '{}'", agent);
            info!(
                "   Agent is now paused. Use 'tt resume {}' to continue.",
                agent
            );
        }

        Commands::Wait { agent, timeout } => {
            let town = Town::connect(&cli.town).await?;
            let handle = town.agent(&agent).await?;
            let timeout_duration = timeout.map(std::time::Duration::from_secs);

            info!("⏳ Waiting for agent '{}' to finish...", agent);
            let final_state =
                tinytown::AgentService::wait(town.channel(), handle.id(), timeout_duration).await?;

            info!(
                "   Agent '{}' reached state: {} {}",
                agent,
                final_state.state.emoji(),
                final_state.state
            );
        }

        Commands::Resume { agent } => {
            let town = Town::connect(&cli.town).await?;
            let handle = town.agent(&agent).await?;
            tinytown::AgentService::resume(town.channel(), handle.id()).await?;

            info!("▶️  Resumed agent '{}'", agent);
        }

        Commands::Close { agent } => {
            let town = Town::connect(&cli.town).await?;
            let handle = town.agent(&agent).await?;
            tinytown::AgentService::close(town.channel(), handle.id()).await?;

            info!(
                "🔻 Closing agent '{}' (draining current work, then stopping)",
                agent
            );
        }

        Commands::Prune { all } => {
            let town = Town::connect(&cli.town).await?;
            let removed = tinytown::AgentService::prune(&town, all).await?;

            for agent in &removed {
                info!(
                    "🗑️  Removed {} ({}) - {:?}",
                    agent.name, agent.id, agent.state
                );
            }

            if removed.is_empty() {
                info!("No agents to prune.");
            } else {
                info!("✨ Pruned {} agent(s)", removed.len());
            }
        }

        Commands::Task { action } => {
            let town = Town::connect(&cli.town).await?;

            match action {
                TaskAction::Complete { task_id, result } => {
                    // Parse task ID
                    let tid: tinytown::TaskId = task_id.parse().map_err(|e| {
                        tinytown::Error::TaskNotFound(format!("Invalid task ID: {}", e))
                    })?;

                    if let Some(completed) =
                        tinytown::TaskService::complete(town.channel(), tid, result).await?
                    {
                        let task = completed.task;
                        let result_msg = completed.result;

                        if let Some(binding) = mission_task_binding(&task.tags) {
                            use tinytown::mission::{MissionScheduler, MissionStorage};

                            let storage = MissionStorage::new(
                                town.channel().conn().clone(),
                                &town.config().name,
                            );
                            let scheduler = MissionScheduler::with_defaults(
                                storage.clone(),
                                town.channel().clone(),
                            );
                            let mut artifacts = vec![format!("task:{}", tid)];
                            if !result_msg.trim().is_empty() {
                                artifacts.push(result_msg.clone());
                            }
                            let completion = match binding.kind {
                                MissionTaskKind::Work | MissionTaskKind::Fix => {
                                    scheduler
                                        .record_submission(
                                            binding.mission_id,
                                            binding.work_item_id,
                                            artifacts,
                                        )
                                        .await?
                                }
                                MissionTaskKind::Review => {
                                    if result_msg.trim().to_lowercase().starts_with("rejected:")
                                        || result_msg
                                            .trim()
                                            .to_lowercase()
                                            .starts_with("changes requested:")
                                    {
                                        scheduler
                                            .request_changes(
                                                binding.mission_id,
                                                binding.work_item_id,
                                                result_msg.trim(),
                                            )
                                            .await?
                                    } else {
                                        scheduler
                                            .approve_submission(
                                                binding.mission_id,
                                                binding.work_item_id,
                                                artifacts,
                                            )
                                            .await?
                                    }
                                }
                            };
                            match completion {
                                tinytown::mission::WorkItemCompletion::Completed => {
                                    let tick_result = scheduler.tick().await?;
                                    info!(
                                        "   Mission sync: work item completed; scheduler promoted {} and assigned {}",
                                        tick_result.total_promoted, tick_result.total_assigned
                                    );
                                }
                                tinytown::mission::WorkItemCompletion::ReviewerApprovalRequired
                                | tinytown::mission::WorkItemCompletion::WaitingForReview => {
                                    info!(
                                        "   Mission sync: work item is waiting on reviewer approval"
                                    );
                                }
                                tinytown::mission::WorkItemCompletion::WaitingForExternal => {
                                    info!(
                                        "   Mission sync: work item is waiting on PR/CI/Bugbot/merge watches"
                                    );
                                }
                                tinytown::mission::WorkItemCompletion::MissionNotFound => {
                                    warn!(
                                        "   Mission sync: mission {} no longer exists; skipping work item completion sync",
                                        binding.mission_id
                                    );
                                }
                                tinytown::mission::WorkItemCompletion::WorkItemNotFound => {
                                    warn!(
                                        "   Mission sync: work item {} was not found in mission {}; skipping completion sync",
                                        binding.work_item_id, binding.mission_id
                                    );
                                }
                            }
                        }

                        info!("✅ Task {} marked as completed", task_id);
                        info!(
                            "   Description: {}",
                            truncate_summary(&task.description, 60)
                        );
                        info!("   Result: {}", truncate_summary(&result_msg, 60));
                        if completed.cleared_current_task {
                            info!("   Cleared current assignment pointer for agent");
                        }
                        if let Some(tasks_completed) = completed.tasks_completed {
                            info!("   Agent tasks completed: {}", tasks_completed);
                        }
                    } else {
                        info!("❌ Task {} not found", task_id);
                    }
                }

                TaskAction::Show { task_id } => {
                    // Parse task ID
                    let tid: tinytown::TaskId = task_id.parse().map_err(|e| {
                        tinytown::Error::TaskNotFound(format!("Invalid task ID: {}", e))
                    })?;

                    // Get agents for name lookup
                    let agents = town.list_agents().await;

                    if let Some(task) = town.channel().get_task(tid).await? {
                        info!("📋 Task: {} ({})", task.id.short_id(), task.id);
                        info!("   Description: {}", task.description);
                        info!("   State: {:?}", task.state);
                        if let Some(agent_id) = task.assigned_to {
                            // Look up agent label
                            let agent_label = agents
                                .iter()
                                .find(|a| a.id == agent_id)
                                .map(|a| a.display_label())
                                .unwrap_or_else(|| agent_id.short_id());
                            info!("   Assigned to: {}", agent_label);
                        }
                        info!("   Created: {}", task.created_at);
                        info!("   Updated: {}", task.updated_at);
                        if let Some(started) = task.started_at {
                            info!("   Started: {}", started);
                        }
                        if let Some(completed) = task.completed_at {
                            info!("   Completed: {}", completed);
                        }
                        if let Some(result) = task.result {
                            info!("   Result: {}", result);
                        }
                        if !task.tags.is_empty() {
                            info!("   Tags: {}", task.tags.join(", "));
                        }
                    } else {
                        info!("❌ Task {} not found", task_id);
                    }
                }

                TaskAction::Current { agent } => {
                    let agent_id =
                        resolve_agent_id_for_current_task(&town, agent.as_deref()).await?;
                    let agents = town.list_agents().await;
                    let agent_label = agents
                        .iter()
                        .find(|candidate| candidate.id == agent_id)
                        .map(|candidate| candidate.display_label())
                        .unwrap_or_else(|| agent_id.short_id());

                    if let Some(task) =
                        tinytown::TaskService::current_for_agent(town.channel(), agent_id).await?
                    {
                        info!(
                            "📋 Current task for '{}': {} ({})",
                            agent_label,
                            task.id.short_id(),
                            task.id
                        );
                        info!("   Description: {}", task.description);
                        info!("   State: {:?}", task.state);
                        info!(
                            "   Complete with: tt task complete {} --result \"what was done\"",
                            task.id
                        );
                        if !task.tags.is_empty() {
                            info!("   Tags: {}", task.tags.join(", "));
                        }
                    } else {
                        info!("📭 No current task tracked for '{}'", agent_label);
                    }
                }

                TaskAction::List { state } => {
                    let tasks = town.channel().list_tasks().await?;
                    // Get agents for name lookup
                    let agents = town.list_agents().await;

                    if tasks.is_empty() {
                        info!("📋 No tasks found");
                    } else {
                        // Filter by state if provided
                        let filtered: Vec<_> = if let Some(ref state_filter) = state {
                            let target_state: tinytown::TaskState = match state_filter
                                .to_lowercase()
                                .as_str()
                            {
                                "pending" => tinytown::TaskState::Pending,
                                "assigned" => tinytown::TaskState::Assigned,
                                "running" => tinytown::TaskState::Running,
                                "completed" => tinytown::TaskState::Completed,
                                "failed" => tinytown::TaskState::Failed,
                                "cancelled" => tinytown::TaskState::Cancelled,
                                _ => {
                                    info!(
                                        "❌ Unknown state filter: {}. Valid: pending, assigned, running, completed, failed, cancelled",
                                        state_filter
                                    );
                                    return Ok(());
                                }
                            };
                            tasks
                                .into_iter()
                                .filter(|t| t.state == target_state)
                                .collect()
                        } else {
                            tasks
                        };

                        if filtered.is_empty() {
                            info!(
                                "📋 No tasks found with state '{}'",
                                state.unwrap_or_default()
                            );
                        } else {
                            info!("📋 Tasks ({}):", filtered.len());
                            for task in &filtered {
                                let status_icon = match task.state {
                                    tinytown::TaskState::Pending => "",
                                    tinytown::TaskState::Assigned => "📌",
                                    tinytown::TaskState::Running => "🔄",
                                    tinytown::TaskState::Completed => "",
                                    tinytown::TaskState::Failed => "",
                                    tinytown::TaskState::Cancelled => "🚫",
                                };
                                // Look up agent label instead of showing UUID
                                let agent_label = task
                                    .assigned_to
                                    .and_then(|agent_id| {
                                        agents
                                            .iter()
                                            .find(|a| a.id == agent_id)
                                            .map(|a| a.display_label())
                                    })
                                    .unwrap_or_else(|| "unassigned".to_string());
                                info!(
                                    "   {} {} - {} [{}]",
                                    status_icon,
                                    task.id.short_id(),
                                    truncate_summary(&task.description, 50),
                                    agent_label
                                );
                            }
                        }
                    }
                }
            }
        }

        Commands::Start => {
            let _town = Town::connect(&cli.town).await?;
            info!("🚀 Town connection open");
            // Keep running until Ctrl+C
            tokio::signal::ctrl_c()
                .await
                .expect("Failed to listen for ctrl-c");
            info!("👋 Closing town connection...");
        }

        Commands::Stop => {
            let town = Town::connect(&cli.town).await?;
            let requested = tinytown::AgentService::stop_all(&town).await?;

            if requested.is_empty() {
                info!(
                    "👋 No active agents to stop in town '{}'",
                    town.config().name
                );
            } else {
                info!(
                    "🛑 Requested graceful stop for {} agent(s) in town '{}'",
                    requested.len(),
                    town.config().name
                );
                info!("   Agents will stop at the start of their next round.");
            }

            info!("   Central Redis remains available to other towns.");
        }

        Commands::Reset { force, agents_only } => {
            let town = Town::connect(&cli.town).await?;
            let config = town.config();

            // Show what will be deleted
            let agents = town.list_agents().await;

            if agents_only {
                info!("🗑️  Resetting agents in town '{}'", config.name);
                info!("   This will delete:");
                info!("   - {} agent(s) and their inboxes", agents.len());
                info!("   Tasks and backlog will be preserved.");

                if !force {
                    info!("");
                    info!("⚠️  This action cannot be undone!");
                    info!("   Run with --force to confirm: tt reset --agents-only --force");
                    return Ok(());
                }

                // Perform agents-only reset
                let deleted = town.channel().reset_agents_only().await?;

                info!("");
                info!(
                    "✅ Reset complete: deleted {} Redis keys (agents only)",
                    deleted
                );
                info!("   Run 'tt spawn <name>' to create new agents");
            } else {
                let tasks = town.channel().list_tasks().await.unwrap_or_default();
                let backlog_len = town.channel().backlog_len().await.unwrap_or(0);

                info!("🗑️  Resetting town '{}'", config.name);
                info!("   This will delete:");
                info!("   - {} agent(s)", agents.len());
                info!("   - {} task(s)", tasks.len());
                info!("   - {} backlog item(s)", backlog_len);

                if !force {
                    info!("");
                    info!("⚠️  This action cannot be undone!");
                    info!("   Run with --force to confirm: tt reset --force");
                    return Ok(());
                }

                // Perform the full reset
                let deleted = town.channel().reset_all().await?;

                info!("");
                info!("✅ Reset complete: deleted {} Redis keys", deleted);
                info!("   Run 'tt spawn <name>' to create new agents");
            }
        }

        Commands::Inbox { agent, all } => {
            let town = Town::connect(&cli.town).await?;

            if all {
                // Show pending messages for all agents (replaces old 'tt tasks' command)
                let agents = town.list_agents().await;
                let supervisor_inbox =
                    sampled_inbox(town.channel(), tinytown::AgentId::supervisor(), 100)
                        .await
                        .unwrap_or((0, Vec::new(), MessageBreakdown::default()));

                if agents.is_empty() && supervisor_inbox.0 == 0 {
                    info!("No agents. Run 'tt spawn <name>' to create one.");
                } else {
                    info!("📋 Pending Messages by Agent:");
                    info!("");

                    let mut total_actionable = 0;
                    let mut printed_any = false;
                    for agent in &agents {
                        let (inbox_len, messages, breakdown) =
                            sampled_inbox(town.channel(), agent.id, 100)
                                .await
                                .unwrap_or((0, Vec::new(), MessageBreakdown::default()));
                        if inbox_len == 0 {
                            continue;
                        }

                        printed_any = true;
                        let heading = format!("{} ({:?})", agent.display_label(), agent.state);
                        print_all_inbox_section(
                            town.channel(),
                            &heading,
                            inbox_len,
                            &messages,
                            breakdown,
                        )
                        .await;
                        total_actionable += breakdown.actionable_count();
                    }

                    if supervisor_inbox.0 > 0 {
                        printed_any = true;
                        let (inbox_len, messages, breakdown) = supervisor_inbox;
                        print_all_inbox_section(
                            town.channel(),
                            "supervisor/conductor (well-known mailbox)",
                            inbox_len,
                            &messages,
                            breakdown,
                        )
                        .await;
                        total_actionable += breakdown.actionable_count();
                    }

                    if !printed_any {
                        info!("  (no pending messages)");
                    } else {
                        info!("Total: {} actionable message(s)", total_actionable);
                    }
                }
            } else if let Some(agent_name) = agent {
                // Show inbox for a specific agent
                let handle = town.agent(&agent_name).await?;
                let agent_id = handle.id();
                let display_name = if is_supervisor_alias(&agent_name) {
                    format!("{} (well-known supervisor/conductor mailbox)", agent_name)
                } else {
                    agent_name.clone()
                };

                let (inbox_len, messages, breakdown) =
                    sampled_inbox(town.channel(), agent_id, 100).await?;
                info!("📬 Inbox for '{}': {} messages", display_name, inbox_len);

                if inbox_len > 0 {
                    info!(
                        "   [T] {} tasks requiring action",
                        breakdown.tasks + breakdown.other_actionable
                    );
                    info!("   [Q] {} queries awaiting response", breakdown.queries);
                    info!("   [I] {} informational", breakdown.informational);
                    info!("   [C] {} confirmations", breakdown.confirmations);
                    info!("");

                    let preview_limit = 10;
                    let shown = std::cmp::min(messages.len(), preview_limit);
                    for msg in messages.iter().take(preview_limit) {
                        let summary = describe_message(town.channel(), &msg.msg_type).await;
                        info!(
                            "   {} {}",
                            inbox_preview_prefix(&msg.msg_type),
                            truncate_summary(&summary, 120)
                        );
                    }

                    if inbox_len > shown {
                        info!("   …plus {} more message(s)", inbox_len - shown);
                    }
                }
            } else {
                info!("Usage: tt inbox <AGENT> or tt inbox --all");
                info!("  tt inbox <agent>  - Show inbox for a specific agent");
                info!("  tt inbox --all    - Show pending messages for all agents");
            }
        }

        Commands::Send {
            to,
            message,
            from,
            query,
            info: informational,
            ack,
            urgent,
        } => {
            use tinytown::{AgentId, Message, MessageType};

            let town = Town::connect(&cli.town).await?;
            let to_handle = town.agent(&to).await?;
            let to_id = to_handle.id();

            let from_id = resolve_sender_id(&town, from.as_deref()).await?;

            let (msg_type, label) = if query {
                (MessageType::Query { question: message }, "query")
            } else if informational {
                (
                    MessageType::Informational { summary: message },
                    "informational",
                )
            } else if ack {
                (
                    MessageType::Confirmation {
                        ack_type: parse_confirmation_type(&message),
                    },
                    "confirmation",
                )
            } else {
                (
                    MessageType::Task {
                        description: message,
                    },
                    "task",
                )
            };

            let msg = Message::new(from_id, to_id, msg_type);
            let from_note = if from_id == AgentId::supervisor() {
                String::new()
            } else {
                format!(" (from {})", from_id)
            };

            if urgent {
                town.channel().send_urgent(&msg).await?;
                info!("🚨 Sent URGENT {} message to '{}'{}", label, to, from_note);
            } else {
                town.channel().send(&msg).await?;
                info!("📤 Sent {} message to '{}'{}", label, to, from_note);
            }
        }

        Commands::AgentLoop {
            name,
            id,
            max_rounds,
        } => {
            // This is the actual agent worker loop.
            // It runs the selected agent CLI repeatedly, checking inbox for tasks.

            use std::time::Duration;
            use tinytown::{AgentId, AgentState};

            let town = Town::connect(&cli.town).await?;
            let config = town.config();
            let channel = town.channel();

            // Parse agent ID
            let agent_id: AgentId = id
                .parse()
                .map_err(|_| tinytown::Error::AgentNotFound(format!("Invalid agent ID: {}", id)))?;

            // Get CLI command
            let agent_state = channel.get_agent_state(agent_id).await?;
            let cli_ref = agent_state
                .as_ref()
                .map(|a| a.cli.clone())
                .unwrap_or_else(|| config.default_cli.clone());
            let cli_name = config.resolve_cli_name(&cli_ref);
            let cli_cmd = config.resolve_cli_command(&cli_ref);
            let idle_timeout_secs = config.agent.idle_timeout_secs;

            info!(
                "🔄 Agent '{}' starting loop (max {} rounds)",
                name, max_rounds
            );
            info!("   CLI: {} ({})", cli_name, cli_cmd);
            info!("   Idle timeout: {}s", idle_timeout_secs);

            // Use manual counter - only increment AFTER CLI execution (fixes round-burning bug)
            let mut round: u32 = 0;

            loop {
                // Check if we've hit max rounds
                if round >= max_rounds {
                    break;
                }

                info!("\n📍 Round {}/{}", round + 1, max_rounds);

                // Check if stop has been requested
                if channel.should_stop(agent_id).await? {
                    info!("   🛑 Stop requested, exiting gracefully...");
                    channel
                        .log_agent_activity(
                            agent_id,
                            &format!("Round {}: 🛑 stopped by request", round + 1),
                        )
                        .await?;
                    channel.clear_stop(agent_id).await?;
                    break;
                }

                // Check if agent has been paused via interrupt
                if let Some(agent_state) = channel.get_agent_state(agent_id).await?
                    && agent_state.state == AgentState::Paused
                {
                    info!("   ⏸️ Agent is paused. Waiting for resume...");
                    tokio::time::sleep(Duration::from_secs(5)).await;
                    continue;
                }

                let display_round = round + 1;
                let urgent_messages = channel.receive_urgent(agent_id).await?;
                let regular_messages = channel.drain_inbox(agent_id).await?;
                let backlog_snapshot = backlog_snapshot_for_agent(channel, &name, 8).await?;

                // If inbox is completely empty, go idle and wait.
                // Backlog prompting is handled below after message classification
                // to avoid duplicate triggers that create orchestration issues.
                if regular_messages.is_empty() && urgent_messages.is_empty() {
                    info!("   📭 Inbox empty, waiting...");
                    if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                        clear_terminal_current_task(channel, &mut agent).await?;
                        let now = chrono::Utc::now();
                        let became_idle =
                            agent.state != AgentState::Paused && agent.state != AgentState::Idle;
                        if agent.state != AgentState::Paused {
                            agent.state = AgentState::Idle;
                        }
                        if became_idle {
                            agent.last_active_at = now;
                        }
                        agent.last_heartbeat = now;

                        if idle_timeout_elapsed(&agent, idle_timeout_secs, now) {
                            info!(
                                "   🔻 Idle timeout reached after {}s, draining and stopping...",
                                idle_timeout_secs
                            );
                            agent.state = AgentState::Draining;
                            channel.set_agent_state(&agent).await?;
                            channel
                                .log_agent_activity(
                                    agent_id,
                                    &format!(
                                        "🔻 Idle timeout reached after {}s; draining and stopping",
                                        idle_timeout_secs
                                    ),
                                )
                                .await?;
                            break;
                        }

                        channel.set_agent_state(&agent).await?;
                    }
                    tokio::time::sleep(idle_poll_interval(idle_timeout_secs)).await;
                    continue;
                }

                let mut breakdown = MessageBreakdown::default();
                let mut actionable_messages: Vec<(tinytown::Message, bool)> = Vec::new();
                let mut informational_summaries: Vec<String> = Vec::new();
                let mut confirmation_counts: std::collections::BTreeMap<String, usize> =
                    std::collections::BTreeMap::new();

                for msg in urgent_messages {
                    breakdown.count(&msg.msg_type);
                    match classify_message(&msg.msg_type) {
                        MessageCategory::Task
                        | MessageCategory::Query
                        | MessageCategory::OtherActionable => {
                            actionable_messages.push((msg, true));
                        }
                        MessageCategory::Informational => {
                            informational_summaries
                                .push(truncate_summary(&summarize_message(&msg.msg_type), 100));
                        }
                        MessageCategory::Confirmation => {
                            let key = truncate_summary(&summarize_message(&msg.msg_type), 60);
                            *confirmation_counts.entry(key).or_insert(0) += 1;
                        }
                    }
                }

                for msg in regular_messages {
                    breakdown.count(&msg.msg_type);
                    match classify_message(&msg.msg_type) {
                        MessageCategory::Task
                        | MessageCategory::Query
                        | MessageCategory::OtherActionable => {
                            actionable_messages.push((msg, false));
                        }
                        MessageCategory::Informational => {
                            informational_summaries
                                .push(truncate_summary(&summarize_message(&msg.msg_type), 100));
                        }
                        MessageCategory::Confirmation => {
                            let key = truncate_summary(&summarize_message(&msg.msg_type), 60);
                            *confirmation_counts.entry(key).or_insert(0) += 1;
                        }
                    }
                }

                info!(
                    "   📬 batched: {} actionable, {} informational, {} confirmations",
                    actionable_messages.len(),
                    informational_summaries.len(),
                    breakdown.confirmations
                );

                if actionable_messages.is_empty() {
                    if backlog_snapshot.total_matching > 0 {
                        info!(
                            "   📋 No direct actionable messages; {} backlog task(s) match this role, prompting claim review",
                            backlog_snapshot.total_matching
                        );
                        actionable_messages.push((
                            tinytown::Message::new(
                                AgentId::supervisor(),
                                agent_id,
                                tinytown::MessageType::Query {
                                    question: format!(
                                        "No direct assignments right now. Backlog has {} role-matching task(s): review and claim one with `tt backlog claim <task-id> {}`.",
                                        backlog_snapshot.total_matching, name
                                    ),
                                },
                            ),
                            false,
                        ));
                    } else if backlog_snapshot.total_backlog > 0 {
                        let summary = format!(
                            "Round {}: ⏭️ no direct work and {} backlog task(s) did not match role hint",
                            display_round, backlog_snapshot.total_backlog
                        );
                        info!("   {}", summary);
                        channel.log_agent_activity(agent_id, &summary).await?;

                        if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                            let now = chrono::Utc::now();
                            if agent.state != AgentState::Paused {
                                agent.state = AgentState::Idle;
                                agent.last_active_at = now;
                            }
                            agent.last_heartbeat = now;
                            channel.set_agent_state(&agent).await?;
                        }

                        tokio::time::sleep(Duration::from_secs(1)).await;
                        continue;
                    } else {
                        let summary = format!(
                            "Round {}: ⏭️ auto-handled {} informational, {} confirmations",
                            display_round,
                            informational_summaries.len(),
                            breakdown.confirmations
                        );
                        info!("   {}", summary);
                        channel.log_agent_activity(agent_id, &summary).await?;

                        if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                            let now = chrono::Utc::now();
                            if agent.state != AgentState::Paused {
                                agent.state = AgentState::Idle;
                                agent.last_active_at = now;
                            }
                            agent.last_heartbeat = now;
                            channel.set_agent_state(&agent).await?;
                        }

                        tokio::time::sleep(Duration::from_secs(1)).await;
                        continue;
                    }
                }

                let urgent_actionable = actionable_messages
                    .iter()
                    .filter(|(_, urgent)| *urgent)
                    .count();
                track_current_task_for_round(channel, agent_id, &actionable_messages).await?;
                let actionable_section =
                    format_actionable_section(channel, &actionable_messages).await;

                let informational_section = if informational_summaries.is_empty() {
                    String::new()
                } else {
                    let mut section = String::from("\n## Informational (batched summary)\n\n");
                    for summary in informational_summaries.iter().take(8) {
                        section.push_str(&format!("- {}\n", summary));
                    }
                    if informational_summaries.len() > 8 {
                        section.push_str(&format!(
                            "- ...and {} more informational message(s)\n",
                            informational_summaries.len() - 8
                        ));
                    }
                    section
                };

                let confirmation_section = if confirmation_counts.is_empty() {
                    String::new()
                } else {
                    let mut section = String::from("\n## Confirmations (auto-dismissed)\n\n");
                    for (kind, count) in &confirmation_counts {
                        section.push_str(&format!("- {} x{}\n", kind, count));
                    }
                    section
                };

                let role_hint = backlog_role_hint(&name);
                let backlog_section = {
                    let mut section = format!(
                        "\n## Backlog Snapshot\n\n- Total backlog tasks: {}\n- Role-matching backlog tasks: {}\n- Role match hint: {}\n",
                        backlog_snapshot.total_backlog, backlog_snapshot.total_matching, role_hint
                    );
                    if backlog_snapshot.total_matching > 0 {
                        section.push_str("\nReview and claim role-matching items:\n");
                        for (task_id, task) in &backlog_snapshot.tasks {
                            let tags = if task.tags.is_empty() {
                                String::new()
                            } else {
                                format!(" [{}]", task.tags.join(", "))
                            };
                            section.push_str(&format!(
                                "- {} - {}{}\n",
                                task_id,
                                truncate_summary(&task.description, 90),
                                tags
                            ));
                        }
                        if backlog_snapshot.total_matching > backlog_snapshot.tasks.len() {
                            section.push_str(&format!(
                                "- ...and {} more role-matching backlog task(s)\n",
                                backlog_snapshot.total_matching - backlog_snapshot.tasks.len()
                            ));
                        }
                    } else if backlog_snapshot.total_backlog > 0 {
                        section.push_str(
                            "\nNo backlog tasks currently match your role hint. Do not claim unrelated work by default.\n",
                        );
                    }
                    section
                };

                let prompt = format!(
                    r#"# Agent: {name}

You are agent "{name}" in Tinytown "{town_name}".

{actionable_section}{informational_section}{confirmation_section}
## Available Commands

```bash
tt status                              # Check town status and all agents
tt assign <agent> "task"               # Assign actionable work
tt backlog list                        # Review unassigned backlog tasks
tt backlog claim <task_id> {agent_name}   # Claim a backlog task for yourself
tt send <agent> --query "question"     # Ask for a response
tt send <agent> --info "update"        # Send FYI update
tt send <agent> --ack "received"       # Send acknowledgment
tt send <agent> --urgent --query "..." # Priority message for next round
tt task current                        # Show your tracked current assignment
tt task complete <task_id> --result "summary"  # Mark a task as done
```

{backlog_section}
## Current State
- Round: {display_round}/{max_rounds}
- Actionable messages: {actionable_count}
- Urgent actionable: {urgent_actionable}
- Batched informational: {info_count}
- Auto-dismissed confirmations: {confirmation_count}

## Your Workflow

1. Handle all actionable messages listed above.
2. If you have no direct assignment or extra capacity, review backlog and claim one role-matching task.
3. Claim only work that matches your role hint; do not claim unrelated tasks.
4. Prefer direct agent-to-agent messages for concrete execution handoffs, review requests, and unblock checks.
5. Use `supervisor` / `conductor` when you need human guidance, priority changes, broader sequencing, escalation, or town-wide visibility.
6. If blocked, send a query with specific unblock needs.
7. Use `tt task current` to confirm the real Tinytown task id before completing work; never use mission/work-item UUIDs from the description as the task id.
8. When finished with a task, mark it complete: `tt task complete <task_id> --result "what was done"`
9. Send informational updates or confirmations as appropriate, including FYI summaries to supervisor/conductor when the conductor should stay informed.

Only run commands needed to complete listed work; inbox messages for this round are already provided above.
"#,
                    name = name,
                    agent_name = name,
                    town_name = config.name,
                    actionable_section = actionable_section,
                    informational_section = informational_section,
                    confirmation_section = confirmation_section,
                    backlog_section = backlog_section,
                    display_round = display_round,
                    max_rounds = max_rounds,
                    actionable_count = actionable_messages.len(),
                    urgent_actionable = urgent_actionable,
                    info_count = informational_summaries.len(),
                    confirmation_count = breakdown.confirmations,
                );

                // Write prompt to temp file (under .tt/)
                let prompt_file = cli.town.join(format!(".tt/agent_{}_prompt.md", name));
                std::fs::write(&prompt_file, &prompt)?;

                // Update agent state to working
                if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                    agent.state = AgentState::Working;
                    agent.last_active_at = chrono::Utc::now();
                    agent.last_heartbeat = chrono::Utc::now();
                    channel.set_agent_state(&agent).await?;
                }
                if let Some(mut task) =
                    tinytown::TaskService::current_for_agent(channel, agent_id).await?
                    && !task.state.is_terminal()
                    && task.state != tinytown::TaskState::Running
                {
                    task.start();
                    channel.set_task(&task).await?;
                }

                // Run the agent CLI
                info!("   🤖 Running {}...", cli_name);
                let output_file = cli
                    .town
                    .join(format!(".tt/logs/{}_round_{}.log", name, display_round));
                let output = std::fs::File::create(&output_file)?;

                let shell_cmd = build_cli_command(&cli_name, &cli_cmd, &prompt_file);
                let status = std::process::Command::new("sh")
                    .arg("-c")
                    .arg(&shell_cmd)
                    .current_dir(&cli.town)
                    .env(TT_AGENT_ID_ENV, agent_id.to_string())
                    .env(TT_AGENT_NAME_ENV, &name)
                    .stdin(std::process::Stdio::null())
                    .stdout(output.try_clone()?)
                    .stderr(output)
                    .status();

                // Clean up prompt file
                let _ = std::fs::remove_file(&prompt_file);

                // Log activity and result
                let activity_msg = match &status {
                    Ok(s) if s.success() => {
                        info!("   ✅ Round {} complete", display_round);
                        format!("Round {}: ✅ completed", display_round)
                    }
                    Ok(_) => {
                        info!("   ⚠️ CLI exited with error");
                        format!("Round {}: ⚠️ CLI error", display_round)
                    }
                    Err(e) => {
                        info!("   ❌ Failed to run CLI: {}", e);
                        format!("Round {}: ❌ failed: {}", display_round, e)
                    }
                };

                // Store activity in Redis (bounded, TTL'd)
                channel.log_agent_activity(agent_id, &activity_msg).await?;

                let should_requeue = match &status {
                    Ok(s) => !s.success(),
                    Err(_) => true,
                };
                if should_requeue {
                    info!(
                        "   ↩️ Re-queueing {} actionable message(s)",
                        actionable_messages.len()
                    );
                    for (msg, was_urgent) in &actionable_messages {
                        if *was_urgent {
                            channel.send_urgent(msg).await?;
                        } else {
                            channel.send(msg).await?;
                        }
                    }
                    if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                        if let Some(task_id) = agent.current_task
                            && let Some(mut task) = channel.get_task(task_id).await?
                            && task.state == tinytown::TaskState::Running
                        {
                            task.assign(agent_id);
                            channel.set_task(&task).await?;
                        }
                        agent.current_task = None;
                        channel.set_agent_state(&agent).await?;
                    }
                }

                if status.is_err() {
                    break;
                }

                // Increment round counter AFTER successful CLI execution (fixes round-burning bug)
                round += 1;

                // Update agent state back to idle and increment stats
                if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                    clear_terminal_current_task(channel, &mut agent).await?;
                    let now = chrono::Utc::now();
                    if agent.state != AgentState::Paused {
                        agent.state = AgentState::Idle;
                        agent.last_active_at = now;
                    }
                    agent.rounds_completed += 1;
                    agent.last_heartbeat = now;
                    channel.set_agent_state(&agent).await?;
                    info!("   📊 Rounds completed: {}", agent.rounds_completed);
                } else {
                    warn!("   ⚠️ Could not update agent state - agent not found in Redis");
                }

                // Small delay between rounds
                tokio::time::sleep(Duration::from_secs(1)).await;
            }

            // Mark agent as stopped with final stats
            if let Some(mut agent) = channel.get_agent_state(agent_id).await? {
                agent.state = AgentState::Stopped;
                agent.last_heartbeat = chrono::Utc::now();
                channel.set_agent_state(&agent).await?;
                info!(
                    "🏁 Agent '{}' finished: {} rounds, {} tasks",
                    name, agent.rounds_completed, agent.tasks_completed
                );
            } else {
                info!("🏁 Agent '{}' finished after {} rounds", name, max_rounds);
            }
        }

        Commands::Conductor => {
            let town = Town::connect(&cli.town).await?;
            let config = town.config();
            let backlog_count = town.channel().backlog_len().await.unwrap_or(0);

            // Build conductor context with current state
            let agents = town.list_agents().await;
            let mut agent_status = String::new();
            for agent in &agents {
                let inbox = town.channel().inbox_len(agent.id).await.unwrap_or(0);
                agent_status.push_str(&format!(
                    "  - {} ({:?}) - {} messages pending\n",
                    agent.display_label(),
                    agent.state,
                    inbox
                ));
            }

            // Detect if this is a fresh start or resuming
            let is_fresh_start = agents.is_empty();
            let startup_mode = if is_fresh_start {
                format!(
                    r#"## 🆕 Fresh Start

This is a new town with no agents yet. Your first job is to help the user:

1. **Understand their goal**: What do they want to build or accomplish?
2. **Analyze the project**: Look at the codebase, README, or any design docs
3. **Suggest team roles**: Based on the project, recommend which agents would help:

### Common Team Roles

| Role | When to Use |
|------|-------------|
| `backend` | API development, server-side logic |
| `frontend` | UI/UX implementation |
| `tester` | Writing and running tests |
| `reviewer` | **Always include** - quality gate for all work |
| `devops` | CI/CD, deployment, infrastructure |
| `security` | Security review, vulnerability analysis |
| `docs` | Documentation, API specs, README updates |
| `architect` | System design, code structure decisions |

4. **Break down the work**: Help decompose their idea into specific, assignable tasks
5. **Use backlog for unassigned work**: If ownership is unclear, park tasks in backlog and let role-matched agents claim them

### First Interaction Template

Ask the user:
> "I'm ready to help orchestrate your project! To get started:
> 1. What are you trying to build or accomplish?
> 2. Is there a design doc, README, or existing code I should analyze?
> 3. Based on that, I'll suggest which agents to spawn and how to break down the work."

If they provide a design or task, analyze it and propose:
- Which agents to spawn (always include reviewer!)
- Task breakdown with assignments
- Suggested order of execution

Backlog currently has **{backlog_count}** task(s)."#,
                    backlog_count = backlog_count
                )
            } else {
                format!(
                    r#"## 🔄 Resuming Session

You have existing agents running:
{agent_status}
Check their status with `tt status --deep` to see progress, then continue coordinating.
Backlog currently has **{backlog_count}** task(s).

If work is stalled or you need to pivot, you can:
- `tt kill <agent>` to stop agents
- Spawn new agents for different roles
- Reassign tasks as needed
- Use `tt backlog list` and `tt backlog claim <task-id> <agent>` for unassigned tasks"#,
                    agent_status = agent_status,
                    backlog_count = backlog_count
                )
            };

            if agent_status.is_empty() {
                agent_status = "  (no agents spawned yet)\n".to_string();
            }

            let context = format!(
                r#"# Tinytown Conductor

You are the **conductor** of Tinytown "{name}" - like the train conductor guiding the miniature train through Tiny Town, Colorado, you coordinate AI agents working on this project.

## Current Town State

**Town:** {name}
**Location:** {root}
**Agents ({agent_count}):**
{agent_status}
**Backlog tasks:** {backlog_count}

{startup_mode}

## Your Capabilities

You have access to the `tt` CLI tool. Run these commands in your shell to orchestrate:

### Spawn agents (starts actual AI process!)
```bash
tt spawn <name>                    # Spawn agent with default CLI (backgrounds)
tt spawn <name> --foreground       # Run in foreground (see output)
tt spawn <name> --max-rounds 5     # Limit iterations (default: 10)
```

### Assign tasks
```bash
tt assign <agent> "<task description>"
```

### Manage backlog (unassigned tasks)
```bash
tt backlog add "<task description>" --tags backend,api
tt backlog list
tt backlog claim <task_id> <agent>
tt backlog assign-all <agent>
```

### Send messages between agents
```bash
tt send <agent> "task"             # Send actionable task message
tt send <agent> --query "question" # Ask for a response
tt send <agent> --info "update"    # Send FYI update
tt send <agent> --ack "received"   # Send acknowledgment
tt send <agent> --urgent --query "msg" # URGENT: processed first next round
tt inbox <agent>                   # Check agent's inbox
```

### Worker Report-Back Loop

- `conductor` is the user-facing role name; `supervisor` is the same well-known mailbox/id.
- Workers should report back to the conductor with:
  - `tt send supervisor --info "implementation complete; reviewer should look at src/auth.rs"`
  - `tt send conductor --query "Need product decision on password reset behavior"`
  - `tt send supervisor --ack "Received. I will start after current task."`
- Conductor should monitor those report-backs with:
  - `tt inbox conductor`
  - `tt inbox --all`
  - `tt status --deep`
- When work tied to a real Tinytown task is done, workers should still run `tt task complete <task_id> --result "what changed"` instead of only sending an informational message.

### Mission Mode Supervision

- `tt mission start ...` bootstraps a mission, but `tt mission dispatch` is the persistent runtime that keeps it moving.
- If you are supervising a mission, make sure the dispatcher is running before you start manually prodding agents.
- Treat the dispatcher as the default orchestrator for mission-owned work. Do not manually reassign mission tasks unless you are intentionally intervening.
- Watch the conductor inbox for dispatcher escalations such as `[Mission Help Needed] ...`.
- When the dispatcher asks for help:
  - inspect status with `tt mission status --run <mission-id> --dispatcher`
  - review detailed work/watch state with `tt mission status --run <mission-id> --work --watch`
  - if staffing is the problem, spawn or free the needed agent(s)
  - reply to the dispatcher with `tt mission note <mission-id> "resume ..."` or `tt mission note <mission-id> "pause ..."`
- Use `tt mission note` for operator directives to the dispatcher; do not rely on free-form inbox messages for dispatcher control.
- Your role in mission mode is to supervise exceptions, staffing, and scope decisions, while the dispatcher owns routine progression.

### Check status and stats
```bash
tt status         # Overview of town and agents
tt status --deep  # Stats: rounds completed, uptime, recent activity
tt list           # List all agents
```

### Stop agents
```bash
tt kill <agent>   # Request agent to stop gracefully (at start of next round)
```

### Plan and persist tasks
```bash
tt plan --init              # Create tasks.toml for planning
tt plan                     # View planned tasks
tt sync push                # Send tasks.toml to Redis
tt sync pull                # Save Redis state to tasks.toml (for git)
tt save                     # Save Redis AOF snapshot (for version control)
```

### Mission mode
```bash
tt mission start --issue <N> [--issue <N> ...]
tt mission dispatch [--run <mission-id>] [--once]
tt mission status [--run <mission-id>] [--work] [--watch] [--dispatcher]
tt mission note <mission-id> "<directive>"
```

## Your Role

1. **Understand** what the user wants to accomplish
2. **Break down** complex requests into discrete tasks
3. **Spawn** appropriate agents including a **reviewer** for quality control
4. **Assign** tasks to agents with clear, actionable descriptions
5. **Use backlog** for unassigned work and role-based claiming
6. **Monitor** progress with `tt status --deep` (shows rounds, uptime, activity)
7. **Coordinate** handoffs between agents without becoming the bottleneck
8. **Use reviewer outcomes** to decide when work is complete
9. **Supervise mission mode** by keeping the dispatcher running, responding to dispatcher help requests, and using `tt mission note` / `tt mission status --dispatcher` when missions escalate
10. **Cleanup**: When done, stop agents with `tt kill <agent>`

## The Reviewer Pattern

Always spawn a **reviewer** agent. This agent decides when work is satisfactorily done, but the next execution step should usually flow directly to the owning worker:

1. Worker completes task → worker or conductor routes review to reviewer
2. Reviewer checks the work → approves or sends concrete fixes directly to the owning worker
3. Reviewer or worker sends `--info` to supervisor/conductor when visibility matters
4. You step in for human decisions, priority changes, cross-team sequencing, or escalation

This keeps execution flowing: agents hand off obvious next steps directly, reviewer remains the quality gate, and you stay focused on higher-level orchestration.

## Agent Naming Convention

Agents are displayed as **Nickname [role]** (e.g., "Fred [backend]", "Martha [reviewer]").
When referring to agents in plans, messages, or status updates, always use this format.
Agents also have short IDs (first 4 hex characters of their UUID) shown in status output;
you can reference them by their name or short ID.

## Guidelines

- **Always spawn a reviewer** - they're your quality gate
- Be proactive: spawn agents and assign tasks without waiting to be told exactly how
- Be specific: task descriptions should be clear and actionable
- Be efficient: parallelize independent work across multiple agents
- Prefer direct worker/reviewer/worker coordination when the next handoff is obvious
- Keep the conductor in the loop with `tt send supervisor --info ...` when humans need visibility without blocking execution
- Check `tt status` frequently to monitor progress
- Check `tt inbox conductor` for blocker queries and mission dispatcher help requests
- Keep backlog flowing: if an agent goes idle, have it review backlog and claim role-matching work
- In mission mode, prefer `tt mission status --dispatcher` and `tt mission note` over ad hoc manual nudges when the dispatcher is already managing the run
- **Save state to git**: Run `tt sync pull` periodically to save task state to tasks.toml, then suggest committing it

## Example Workflow

User: "Build a user authentication system"

You:
1. `tt spawn backend` - for implementation
2. `tt spawn tester` - for tests
3. `tt spawn reviewer` - for quality control (ALWAYS include this)
4. `tt assign backend "Implement REST API for user auth: POST /signup, POST /login, POST /logout, POST /reset-password. Use bcrypt for passwords."`
5. `tt assign tester "Write integration tests for auth API: test signup, login, logout, password reset. Cover success and error cases."`
6. Monitor with `tt status`
7. When backend is ready: backend or conductor notifies reviewer directly with `tt send reviewer "Auth API implementation complete. Review src/auth.rs and route fixes back to backend if needed."`
8. If reviewer finds concrete issues → reviewer sends them directly to backend and copies supervisor/conductor with `--info`
9. If reviewer approves → done! If broader coordination is needed → you step in and reassign or reprioritize.
10. Save state: `tt sync pull` to save tasks to tasks.toml
11. Suggest: "Run `git add tasks.toml && git commit -m 'Update task state'` to persist"

Now, help the user orchestrate their project!
"#,
                name = config.name,
                root = cli.town.display(),
                agent_count = agents.len(),
                agent_status = agent_status,
                backlog_count = backlog_count,
                startup_mode = startup_mode,
            );

            // Write context to a temp file for the CLI (under .tt/)
            let context_file = cli.town.join(".tt/conductor_context.md");
            std::fs::write(&context_file, &context)?;

            // Get the CLI name (conductor runs interactively, not in --print mode)
            let cli_name = config.conductor_cli_name();

            info!("🚂 Starting conductor with {} CLI...", cli_name);
            info!("   Context: {}", context_file.display());
            info!("");

            // Build the interactive command (no --print flag)
            // For conductor, we want full interactive mode
            let exec_cmd = match cli_name {
                "auggie" => format!(
                    "exec auggie --instruction-file '{}'",
                    context_file.display()
                ),
                "claude" => format!("exec claude --resume '{}'", context_file.display()),
                "aider" => format!("exec aider --message-file '{}'", context_file.display()),
                "codex" => format!(
                    "exec codex --dangerously-bypass-approvals-and-sandbox \"$(cat '{}')\"",
                    context_file.display()
                ),
                "codex-mini" => format!(
                    "exec codex --dangerously-bypass-approvals-and-sandbox -m gpt-5.4-mini -c model_reasoning_effort=\"medium\" \"$(cat '{}')\"",
                    context_file.display()
                ),
                _ => {
                    if cli_name.starts_with("codex ") {
                        format!("exec {} \"$(cat '{}')\"", cli_name, context_file.display())
                    } else {
                        // For unknown CLIs, try piping the context
                        format!("cat '{}' | exec {}", context_file.display(), cli_name)
                    }
                }
            };

            info!("   Running: {}", exec_cmd);
            info!("");

            // Use exec to replace this process with the CLI
            // This gives full interactive control (stdin/stdout/stderr)
            use std::os::unix::process::CommandExt;
            let err = std::process::Command::new("sh")
                .arg("-c")
                .arg(&exec_cmd)
                .current_dir(&cli.town)
                .exec();

            // If we get here, exec failed
            eprintln!("❌ Failed to exec conductor: {}", err);
            std::process::exit(1);
        }

        Commands::Plan { init } => {
            if init {
                plan::init_tasks_file(&cli.town)?;
                info!("📝 Created tasks.toml - edit it to plan your work!");
            } else {
                // Open tasks.toml in editor
                let tasks_file = cli.town.join("tasks.toml");
                if !tasks_file.exists() {
                    info!("No tasks.toml found. Run 'tt plan --init' first.");
                } else {
                    let tasks = plan::load_tasks_file(&cli.town)?;
                    info!("📋 Tasks in plan ({}):", tasks_file.display());
                    for task in &tasks.tasks {
                        let status_icon = match task.status.as_str() {
                            "pending" => "",
                            "assigned" => "📌",
                            "running" => "🔄",
                            "completed" => "",
                            "failed" => "",
                            _ => "",
                        };
                        let agent = task.agent.as_deref().unwrap_or("unassigned");
                        info!(
                            "  {} [{}] {} - {}",
                            status_icon, agent, task.id, task.description
                        );
                    }
                }
            }
        }

        Commands::Sync { direction } => {
            let town = Town::connect(&cli.town).await?;
            match direction.as_str() {
                "push" => {
                    let count = plan::push_tasks_to_redis(&cli.town, town.channel()).await?;
                    info!("⬆️  Pushed {} tasks from tasks.toml to Redis", count);
                }
                "pull" => {
                    let count = plan::pull_tasks_from_redis(&cli.town, town.channel()).await?;
                    info!("⬇️  Pulled {} tasks from Redis to tasks.toml", count);
                }
                _ => {
                    info!("Usage: tt sync [push|pull]");
                    info!("  push - Send tasks.toml to Redis");
                    info!("  pull - Save Redis tasks to tasks.toml");
                }
            }
        }

        Commands::Save => {
            let town = Town::connect(&cli.town).await?;
            let config = town.config();
            let aof_path = cli.town.join(&config.redis.aof_path);

            // Trigger Redis BGREWRITEAOF to compact and save
            info!("💾 Saving Redis state...");

            let redis_url = config.redis_url();
            let client = redis::Client::open(redis_url)?;
            let mut conn = client.get_multiplexed_async_connection().await?;

            // Trigger background rewrite
            let _: () = redis::cmd("BGREWRITEAOF").query_async(&mut conn).await?;

            info!("   AOF rewrite triggered. File: {}", aof_path.display());
            info!("");
            info!("   To version control Redis state:");
            info!("   git add {}", config.redis.aof_path);
            info!("   git commit -m 'Save town state'");
        }

        Commands::Restore => {
            let config = tinytown::Config::load(&cli.town)?;
            let aof_path = cli.town.join(&config.redis.aof_path);

            if !aof_path.exists() {
                info!("❌ No AOF file found at: {}", aof_path.display());
                info!("   Run 'tt save' first to create one.");
            } else {
                info!("📂 AOF file found: {}", aof_path.display());
                info!("");
                info!("   To restore from AOF:");
                info!("   1. Stop Redis if running");
                info!(
                    "   2. Start Redis with: redis-server --appendonly yes --appendfilename {}",
                    config.redis.aof_path
                );
                info!("   3. Redis will replay the AOF and restore state");
                info!("");
                info!("   Or just run 'tt init' - it will use existing AOF if present.");
            }
        }

        Commands::Config { key, value } => {
            let config_path = GlobalConfig::config_path()?;

            match (key, value) {
                // No args: show all config
                (None, None) => {
                    let config = GlobalConfig::load()?;
                    info!("⚙️  Global config: {}", config_path.display());
                    info!("");
                    info!("default_cli = \"{}\"", config.default_cli);
                    if let Some(conductor_cli) = &config.conductor_cli {
                        info!("conductor_cli = \"{}\"", conductor_cli);
                    }
                    if !config.agent_clis.is_empty() {
                        info!("");
                        info!("[agent_clis]");
                        for (name, cmd) in &config.agent_clis {
                            info!("{} = \"{}\"", name, cmd);
                        }
                    }
                    info!("");
                    info!(
                        "Available CLIs: claude, auggie, codex, codex-mini, aider, gemini, copilot, cursor"
                    );
                }
                // Key only: show that value
                (Some(key), None) => {
                    let config = GlobalConfig::load()?;
                    if let Some(val) = config.get(&key) {
                        println!("{}", val);
                    } else {
                        info!("❌ Unknown config key: {}", key);
                        info!("   Available keys: default_cli, conductor_cli, agent_clis.<name>");
                    }
                }
                // Key and value: set it
                (Some(key), Some(value)) => {
                    let mut config = GlobalConfig::load()?;
                    config.set(&key, &value)?;
                    config.save()?;
                    info!("✅ Set {} = \"{}\"", key, value);
                    info!("   Saved to: {}", config_path.display());
                }
                // Value without key (shouldn't happen due to clap)
                (None, Some(_)) => {
                    info!("❌ Please specify a key");
                }
            }
        }

        Commands::History { limit, agent } => {
            let town = Town::connect(&cli.town).await?;
            let agents = town.list_agents().await;
            let events = town
                .channel()
                .event_stream()
                .read_recent_town_events(limit)
                .await?;

            if events.is_empty() {
                info!("📜 No events recorded yet.");
            } else {
                // Build agent ID → display_label map
                let agent_labels: std::collections::HashMap<tinytown::AgentId, String> =
                    agents.iter().map(|a| (a.id, a.display_label())).collect();

                let resolve = |aid: tinytown::AgentId| -> String {
                    agent_labels
                        .get(&aid)
                        .cloned()
                        .unwrap_or_else(|| aid.short_id())
                };

                info!("📜 Recent History ({} events):", events.len());
                info!("");
                for (_stream_id, event) in &events {
                    let ts = event.timestamp.format("%H:%M:%S");

                    // Filter by agent if requested
                    if let Some(ref agent_name) = agent {
                        let matches = event.agent_id.is_some_and(|aid| {
                            agents.iter().any(|a| a.id == aid && a.name == *agent_name)
                        });
                        if !matches {
                            continue;
                        }
                    }

                    let who = event
                        .agent_id
                        .map(&resolve)
                        .unwrap_or_else(|| "system".to_string());

                    let event_icon = match event.event_type {
                        tinytown::events::EventType::AgentSpawned => "🐣",
                        tinytown::events::EventType::AgentStopped
                        | tinytown::events::EventType::AgentCompleted => "🏁",
                        tinytown::events::EventType::AgentStateChanged => "🔄",
                        tinytown::events::EventType::TaskAssigned => "📌",
                        tinytown::events::EventType::TaskCompleted => "",
                        tinytown::events::EventType::TaskFailed => "",
                        tinytown::events::EventType::TaskDelegated => "🤝",
                        tinytown::events::EventType::ReviewerHandoff => "👀",
                        tinytown::events::EventType::ReviewerApproval => "",
                        tinytown::events::EventType::ConductorEscalation => "🚨",
                        tinytown::events::EventType::AgentInterrupted => "⏸️",
                        tinytown::events::EventType::AgentResumed => "▶️",
                        tinytown::events::EventType::AgentFailed => "💥",
                        tinytown::events::EventType::MissionStateChanged
                        | tinytown::events::EventType::MissionEvent => "🎯",
                        tinytown::events::EventType::MissionWorkPromoted
                        | tinytown::events::EventType::MissionWorkAssigned
                        | tinytown::events::EventType::MissionWorkCompleted
                        | tinytown::events::EventType::MissionWorkBlocked => "📋",
                        tinytown::events::EventType::MissionHelpNeeded => "🆘",
                        tinytown::events::EventType::MissionWatchTriggered => "👁️",
                    };

                    let msg_short: String = event.message.chars().take(80).collect();
                    let truncated = if event.message.chars().count() > 80 {
                        "..."
                    } else {
                        ""
                    };
                    info!(
                        "  {} {} *{}* {}{}",
                        ts, event_icon, who, msg_short, truncated
                    );
                }
            }
        }

        Commands::Recover => {
            use tinytown::AgentState;

            let town = Town::connect(&cli.town).await?;
            let agents = town.list_agents().await;

            let mut recovered = 0;
            let mut checked = 0;

            info!("🔍 Scanning for orphaned agents...");

            for agent in agents {
                checked += 1;

                // Check if agent is in an active state (should have a running process)
                // Include Idle — a dead Idle agent should also be recoverable (Issue #48)
                let is_active_state = matches!(
                    agent.state,
                    AgentState::Working
                        | AgentState::Starting
                        | AgentState::Idle
                        | AgentState::Draining
                );

                if !is_active_state {
                    continue;
                }

                // Check if the agent's process is still running by looking for its log file
                // and checking if it was recently modified (within last 2 minutes)
                let log_file = cli.town.join(format!(".tt/logs/{}.log", agent.name));
                let is_stale = if log_file.exists() {
                    if let Ok(metadata) = std::fs::metadata(&log_file) {
                        if let Ok(modified) = metadata.modified() {
                            let elapsed = std::time::SystemTime::now()
                                .duration_since(modified)
                                .unwrap_or_default();
                            // If log hasn't been modified in 2 minutes, consider stale
                            elapsed.as_secs() > 120
                        } else {
                            // Can't get modified time, assume stale if old heartbeat
                            let heartbeat_age = chrono::Utc::now() - agent.last_heartbeat;
                            heartbeat_age.num_seconds() > 120
                        }
                    } else {
                        true
                    }
                } else {
                    // No log file and agent claims to be working - likely orphaned
                    let heartbeat_age = chrono::Utc::now() - agent.last_heartbeat;
                    heartbeat_age.num_seconds() > 120
                };

                if is_stale {
                    // Update agent state to stopped
                    if let Some(mut agent_state) = town.channel().get_agent_state(agent.id).await? {
                        agent_state.state = AgentState::Stopped;
                        town.channel().set_agent_state(&agent_state).await?;
                    }

                    // Log activity
                    town.channel()
                        .log_agent_activity(agent.id, "🔄 Recovered by tt recover (orphaned)")
                        .await?;

                    info!(
                        "   🔄 Recovered '{}' ({:?}) - last heartbeat {:?} ago",
                        agent.name,
                        agent.state,
                        chrono::Utc::now() - agent.last_heartbeat
                    );
                    recovered += 1;
                }
            }

            info!("");
            if recovered == 0 {
                info!("✨ No orphaned agents found ({} agents checked)", checked);
            } else {
                info!(
                    "✨ Recovered {} orphaned agent(s) ({} total checked)",
                    recovered, checked
                );
                info!("   Run 'tt prune' to remove them from Redis");
            }
        }

        Commands::Towns => {
            use tinytown::global_config::GLOBAL_CONFIG_DIR;

            let towns_path = dirs::home_dir()
                .map(|h| h.join(GLOBAL_CONFIG_DIR).join("towns.toml"))
                .ok_or_else(|| {
                    tinytown::Error::Io(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "Could not find home directory",
                    ))
                })?;

            if !towns_path.exists() {
                info!("📍 No towns registered yet.");
                info!("   Run 'tt init' in a directory to register a town.");
                return Ok(());
            }

            // Parse towns.toml
            let content = std::fs::read_to_string(&towns_path)?;
            let towns_file: TownsFile = toml::from_str(&content).map_err(|e| {
                tinytown::Error::Io(std::io::Error::other(format!("Invalid towns.toml: {}", e)))
            })?;

            info!("🏘️  Registered Towns ({}):", towns_file.towns.len());
            info!("");

            for town_entry in &towns_file.towns {
                let path = std::path::Path::new(&town_entry.path);

                // Try to connect to the town's Redis
                let status = if path.exists() {
                    // Check if tinytown.toml exists
                    let config_file = path.join("tinytown.toml");
                    if !config_file.exists() {
                        "⚠️  (no config)".to_string()
                    } else {
                        // Try to connect
                        match Town::connect(path).await {
                            Ok(t) => {
                                let agents = t.list_agents().await;
                                let active = agents.iter().filter(|a| a.state.is_active()).count();
                                format!("[OK] {} agents ({} active)", agents.len(), active)
                            }
                            Err(_) => "[OFFLINE]".to_string(),
                        }
                    }
                } else {
                    "❌ (path not found)".to_string()
                };

                info!("   {} - {}", town_entry.name, status);
                info!("      📂 {}", town_entry.path);
            }
        }

        Commands::Backlog { action } => {
            let town = Town::connect(&cli.town).await?;

            match action {
                BacklogAction::Add { description, tags } => {
                    let mut task = Task::new(&description);
                    if let Some(tag_str) = tags {
                        let tag_list: Vec<String> =
                            tag_str.split(',').map(|s| s.trim().to_string()).collect();
                        task = task.with_tags(tag_list);
                    }

                    // Store task and add to backlog
                    town.channel().set_task(&task).await?;
                    town.channel().backlog_push(task.id).await?;

                    info!("📋 Added task to backlog: {}", task.id);
                    info!("   Description: {}", description);
                }

                BacklogAction::List => {
                    let task_ids = town.channel().backlog_list().await?;

                    if task_ids.is_empty() {
                        info!("📋 Backlog is empty");
                    } else {
                        info!("📋 Backlog ({} tasks):", task_ids.len());
                        info!("");
                        for task_id in task_ids {
                            if let Ok(Some(task)) = town.channel().get_task(task_id).await {
                                let tags = if task.tags.is_empty() {
                                    String::new()
                                } else {
                                    format!(" [{}]", task.tags.join(", "))
                                };
                                info!(
                                    "   {} ({}) - {}{}",
                                    task_id.short_id(),
                                    task_id,
                                    task.description.chars().take(60).collect::<String>(),
                                    tags
                                );
                            } else {
                                info!("   {} ({}) - (task not found)", task_id.short_id(), task_id);
                            }
                        }
                    }
                }

                BacklogAction::Claim { task_id, agent } => {
                    // Parse task ID
                    let tid: tinytown::TaskId = task_id.parse().map_err(|e| {
                        tinytown::Error::TaskNotFound(format!("Invalid task ID: {}", e))
                    })?;

                    // Check task exists in backlog
                    let removed = town.channel().backlog_remove(tid).await?;
                    if !removed {
                        info!("❌ Task {} not found in backlog", task_id);
                        return Ok(());
                    }

                    // Get agent
                    let agent_handle = town.agent(&agent).await?;

                    // Assign the task (consistent with tt assign - agent will start() when working)
                    if let Some(mut task) = town.channel().get_task(tid).await? {
                        task.assign(agent_handle.id());
                        town.channel().set_task(&task).await?;

                        // Send assignment message
                        use tinytown::agent::AgentId;
                        use tinytown::message::{Message, MessageType};
                        let msg = Message::new(
                            AgentId::supervisor(),
                            agent_handle.id(),
                            MessageType::TaskAssign {
                                task_id: tid.to_string(),
                            },
                        );
                        town.channel().send(&msg).await?;

                        info!("✅ Claimed task {} and assigned to '{}'", task_id, agent);
                    } else {
                        info!("❌ Task {} not found", task_id);
                    }
                }

                BacklogAction::AssignAll { agent } => {
                    let agent_handle = town.agent(&agent).await?;
                    let mut count = 0;

                    while let Some(tid) = town.channel().backlog_pop().await? {
                        if let Some(mut task) = town.channel().get_task(tid).await? {
                            // Consistent with tt assign - agent will call start() when working
                            task.assign(agent_handle.id());
                            town.channel().set_task(&task).await?;

                            use tinytown::agent::AgentId;
                            use tinytown::message::{Message, MessageType};
                            let msg = Message::new(
                                AgentId::supervisor(),
                                agent_handle.id(),
                                MessageType::TaskAssign {
                                    task_id: tid.to_string(),
                                },
                            );
                            town.channel().send(&msg).await?;
                            count += 1;
                        }
                    }

                    if count == 0 {
                        info!("📋 Backlog is empty, no tasks to assign");
                    } else {
                        info!("✅ Assigned {} task(s) from backlog to '{}'", count, agent);
                    }
                }

                BacklogAction::Remove { task_id } => {
                    // Parse task ID
                    let tid: tinytown::TaskId = task_id.parse().map_err(|e| {
                        tinytown::Error::TaskNotFound(format!("Invalid task ID: {}", e))
                    })?;

                    // Remove from backlog
                    let removed = tinytown::BacklogService::remove(town.channel(), tid).await?;
                    if removed {
                        info!("✅ Removed task {} from backlog", task_id);
                    } else {
                        info!("❌ Task {} not found in backlog", task_id);
                    }
                }
            }
        }

        Commands::Reclaim {
            to_backlog,
            to,
            from,
        } => {
            let town = Town::connect(&cli.town).await?;
            let agents = town.list_agents().await;

            // Find dead agents (stopped or error state)
            let dead_agents: Vec<_> = agents
                .iter()
                .filter(|a| a.state.is_terminal())
                .filter(|a| from.as_ref().is_none_or(|f| &a.name == f))
                .collect();

            if dead_agents.is_empty() {
                if let Some(f) = &from {
                    info!("❌ Agent '{}' not found or not in terminal state", f);
                } else {
                    info!("✨ No dead agents found with tasks to reclaim");
                }
                return Ok(());
            }

            let mut total_reclaimed = 0;

            // Get target agent if specified
            let target_agent = if let Some(target_name) = &to {
                Some(town.agent(target_name).await?)
            } else {
                None
            };

            info!("🔄 Reclaiming orphaned tasks...");

            for agent in dead_agents {
                let messages = town.channel().drain_inbox(agent.id).await?;

                if messages.is_empty() {
                    continue;
                }

                info!(
                    "   {} ({:?}): {} message(s)",
                    agent.name,
                    agent.state,
                    messages.len()
                );

                for msg in messages {
                    // Check if it's a task assignment message
                    if let tinytown::message::MessageType::TaskAssign { task_id } = &msg.msg_type {
                        if let Ok(tid) = task_id.parse::<tinytown::TaskId>() {
                            if to_backlog {
                                // Move to backlog
                                town.channel().backlog_push(tid).await?;
                                info!("      → backlog: {}", task_id);
                            } else if let Some(ref target) = target_agent {
                                // Move to target agent
                                town.channel()
                                    .move_message_to_inbox(&msg, target.id())
                                    .await?;
                                info!("      → {}: {}", to.as_ref().unwrap(), task_id);
                            } else {
                                // Just list what we found (no destination specified)
                                info!("      task: {}", task_id);
                            }
                            total_reclaimed += 1;
                        }
                    } else if let tinytown::message::MessageType::Task { description } =
                        &msg.msg_type
                    {
                        if to_backlog {
                            let task = tinytown::Task::new(description.clone());
                            let task_id = task.id;
                            town.channel().set_task(&task).await?;
                            town.channel().backlog_push(task_id).await?;
                            info!("      → backlog: {}", task_id);
                        } else if let Some(ref target) = target_agent {
                            town.channel()
                                .move_message_to_inbox(&msg, target.id())
                                .await?;
                            info!(
                                "      → {}: {}",
                                to.as_ref().unwrap(),
                                truncate_summary(description, 60)
                            );
                        } else {
                            info!("      task: {}", truncate_summary(description, 60));
                        }
                        total_reclaimed += 1;
                    } else {
                        // Non-task message - move to target or discard
                        if let Some(ref target) = target_agent {
                            town.channel()
                                .move_message_to_inbox(&msg, target.id())
                                .await?;
                        }
                    }
                }
            }

            info!("");
            if total_reclaimed == 0 {
                info!("📋 No tasks found in dead agent inboxes");
            } else if to_backlog {
                info!("✅ Moved {} task(s) to backlog", total_reclaimed);
            } else if let Some(target_name) = &to {
                info!("✅ Moved {} task(s) to '{}'", total_reclaimed, target_name);
            } else {
                info!("📋 Found {} orphaned task(s)", total_reclaimed);
                info!("   Use --to-backlog or --to <agent> to reclaim them");
            }
        }

        Commands::Restart {
            agent,
            rounds,
            foreground,
        } => {
            use tinytown::AgentState;

            let town = Town::connect(&cli.town).await?;

            // Get the agent
            let Some(mut agent_state) = town.channel().get_agent_by_name(&agent).await? else {
                info!("❌ Agent '{}' not found", agent);
                return Ok(());
            };

            // Check if agent is in terminal state
            if !agent_state.state.is_terminal() {
                info!(
                    "❌ Agent '{}' is still active ({:?})",
                    agent, agent_state.state
                );
                info!("   Use 'tt kill {}' to stop it first", agent);
                return Ok(());
            }

            // Reset agent state
            agent_state.state = AgentState::Idle;
            agent_state.rounds_completed = 0;
            agent_state.last_heartbeat = chrono::Utc::now();
            town.channel().set_agent_state(&agent_state).await?;

            // Clear any stop flags
            town.channel().clear_stop(agent_state.id).await?;

            // Log activity
            town.channel()
                .log_agent_activity(
                    agent_state.id,
                    &format!("🔄 Restarted with {} rounds", rounds),
                )
                .await?;

            info!("🔄 Restarting agent '{}'...", agent);
            info!("   Rounds: {}", rounds);

            // Spawn the agent loop process
            let logs_dir = cli.town.join(".tt/logs");
            std::fs::create_dir_all(&logs_dir)?;

            // Clean up old round log files to prevent stale data in 'tt status --deep'
            let cleaned = clean_agent_round_logs(&logs_dir, &agent);
            if cleaned > 0 {
                info!("   Cleaned {} old round log file(s)", cleaned);
            }

            let log_file = logs_dir.join(format!("{}.log", agent));
            let exe = std::env::current_exe()?;
            let town_path = cli.town.canonicalize().unwrap_or(cli.town.clone());
            let agent_id = agent_state.id.to_string();

            if foreground {
                // Run in foreground
                std::process::Command::new(&exe)
                    .arg("--town")
                    .arg(&town_path)
                    .arg("agent-loop")
                    .arg(&agent)
                    .arg(&agent_id)
                    .arg(rounds.to_string())
                    .status()?;
            } else {
                spawn_agent_loop_background(
                    &exe, &town_path, &agent, &agent_id, rounds, &log_file,
                )?;

                info!("   Log: {}", log_file.display());
                info!("");
                info!("✅ Agent '{}' restarted", agent);
            }
        }

        Commands::Auth { action } => match action {
            AuthAction::GenKey => {
                use tinytown::generate_api_key;

                let (raw_key, hash) = generate_api_key();

                info!("🔐 Generated new API key");
                info!("");
                info!("API Key (store securely, shown only once):");
                println!("{}", raw_key);
                info!("");
                info!("API Key Hash (add to tinytown.toml):");
                println!("{}", hash);
                info!("");
                info!("Add to your tinytown.toml:");
                info!("");
                info!("  [townhall.auth]");
                info!("  mode = \"api_key\"");
                info!("  api_key_hash = \"{}\"", hash);
                info!("");
                info!("Then use the API key with townhall:");
                info!(
                    "  curl -H 'Authorization: Bearer {}' http://localhost:8080/v1/status",
                    &raw_key[..8]
                );
            }
        },

        Commands::Migrate {
            dry_run,
            force,
            hash,
        } => {
            use tinytown::{
                migrate_json_to_hash, migrate_to_town_isolation, needs_hash_migration,
                needs_migration, preview_hash_migration, preview_migration,
            };

            let town = Town::connect(&cli.town).await?;
            let config = town.config();
            let town_name = &config.name;

            // Get a connection for migration
            let redis_url = config.redis_url();
            let client = redis::Client::open(redis_url)?;
            let mut conn = redis::aio::ConnectionManager::new(client).await?;

            if hash {
                // JSON-to-Hash migration
                let needs_mig = needs_hash_migration(&mut conn, town_name).await?;
                if !needs_mig {
                    info!(
                        "✅ No JSON-to-Hash migration needed - all keys already use Hash storage"
                    );
                    info!("   Town: {}", town_name);
                    return Ok(());
                }

                if dry_run {
                    info!("🔍 JSON-to-Hash Migration Preview (dry run)");
                    info!("   Town: {}", town_name);
                    info!("");

                    let preview = preview_hash_migration(&mut conn, town_name).await?;
                    if preview.is_empty() {
                        info!("   No JSON string keys found.");
                    } else {
                        info!("   Keys to convert to Hash:");
                        for key in &preview {
                            info!("   {} (string → hash)", key);
                        }
                        info!("");
                        info!("   Total: {} key(s) would be migrated", preview.len());
                        info!("");
                        info!(
                            "   Run 'tt migrate --hash' (without --dry-run) to perform migration."
                        );
                    }
                } else {
                    if !force {
                        info!("⚠️  JSON-to-Hash Migration Warning");
                        info!("");
                        info!("   This will convert JSON string storage to Redis Hash format.");
                        info!(
                            "   Benefits: atomic field updates, memory efficiency, partial reads."
                        );
                        info!("");
                        info!("   This operation cannot be undone.");
                        info!("");
                        info!("   Run with --force to skip this prompt, or --dry-run to preview.");
                        info!("");

                        eprint!("   Continue? [y/N]: ");
                        let mut input = String::new();
                        std::io::stdin().read_line(&mut input)?;
                        if !input.trim().eq_ignore_ascii_case("y") {
                            info!("   Migration cancelled.");
                            return Ok(());
                        }
                    }

                    info!("🔄 Migrating JSON strings to Redis Hashes...");
                    info!("   Town: {}", town_name);

                    let stats = migrate_json_to_hash(&mut conn, town_name).await?;

                    info!("");
                    info!("✅ JSON-to-Hash migration complete!");
                    info!("   Agents migrated: {}", stats.agents_migrated);
                    info!("   Tasks migrated:  {}", stats.tasks_migrated);
                    info!("   Already hash:    {}", stats.already_hash);

                    if !stats.errors.is_empty() {
                        warn!("");
                        warn!("   ⚠️  {} key(s) failed to migrate:", stats.errors.len());
                        for key in &stats.errors {
                            warn!("      - {}", key);
                        }
                    }
                }
            } else {
                // Town isolation migration (existing behavior)
                let needs_mig = needs_migration(&mut conn).await?;
                if !needs_mig {
                    info!("✅ No migration needed - all keys already use town isolation format");
                    info!("   Town: {}", town_name);
                    return Ok(());
                }

                if dry_run {
                    info!("🔍 Migration Preview (dry run)");
                    info!("   Town: {}", town_name);
                    info!("");

                    let preview = preview_migration(&mut conn).await?;
                    if preview.is_empty() {
                        info!("   No old-format keys found.");
                    } else {
                        info!("   Keys to migrate:");
                        for (old_key, new_pattern) in &preview {
                            let new_key = new_pattern.replace("<town>", town_name);
                            info!("   {} → {}", old_key, new_key);
                        }
                        info!("");
                        info!("   Total: {} key(s) would be migrated", preview.len());
                        info!("");
                        info!("   Run 'tt migrate' (without --dry-run) to perform migration.");
                    }
                } else {
                    if !force {
                        info!("⚠️  Migration Warning");
                        info!("");
                        info!(
                            "   This will migrate old Redis keys to the new town-isolated format:"
                        );
                        info!("   tt:type:id → tt:{}:type:id", town_name);
                        info!("");
                        info!("   This operation cannot be undone.");
                        info!("");
                        info!("   Run with --force to skip this prompt, or --dry-run to preview.");
                        info!("");

                        eprint!("   Continue? [y/N]: ");
                        let mut input = String::new();
                        std::io::stdin().read_line(&mut input)?;
                        if !input.trim().eq_ignore_ascii_case("y") {
                            info!("   Migration cancelled.");
                            return Ok(());
                        }
                    }

                    info!("🔄 Migrating to town isolation...");
                    info!("   Town: {}", town_name);

                    let stats = migrate_to_town_isolation(&mut conn, town_name).await?;

                    info!("");
                    info!("✅ Migration complete!");
                    info!("   Agents migrated:  {}", stats.agents_migrated);
                    info!("   Inboxes migrated: {}", stats.inboxes_migrated);
                    info!("   Tasks migrated:   {}", stats.tasks_migrated);
                    info!(
                        "   Other keys:       {}",
                        stats.urgent_migrated
                            + stats.activity_migrated
                            + stats.stop_migrated
                            + stats.backlog_migrated
                    );

                    if !stats.errors.is_empty() {
                        warn!("");
                        warn!("   ⚠️  {} key(s) failed to migrate:", stats.errors.len());
                        for key in &stats.errors {
                            warn!("      - {}", key);
                        }
                    }
                }
            }
        }

        Commands::Mission { action } => {
            use tinytown::mission::{
                DispatcherConfig, GhCliGitHubClient, MissionDispatcher, MissionId, MissionPolicy,
                MissionRun, MissionScheduler, MissionState, MissionStorage, ObjectiveRef,
                build_mission_work_items, parse_issue_ref,
            };

            let town = Town::connect(&cli.town).await?;
            let config = town.config();
            let storage = MissionStorage::new(town.channel().conn().clone(), &config.name);

            match action {
                MissionAction::Start {
                    issues,
                    docs,
                    max_parallel,
                    no_reviewer,
                } => {
                    if issues.is_empty() && docs.is_empty() {
                        info!("❌ At least one --issue or --doc is required");
                        return Ok(());
                    }

                    // Parse objectives
                    let mut objectives = Vec::new();

                    for issue in &issues {
                        if let Some(obj) = parse_issue_ref(issue, &config.name, town.root()) {
                            objectives.push(obj);
                        } else {
                            warn!("⚠️  Could not parse issue: {}", issue);
                        }
                    }

                    for doc in &docs {
                        objectives.push(ObjectiveRef::Doc { path: doc.clone() });
                    }

                    if objectives.is_empty() {
                        info!("❌ No valid objectives found");
                        return Ok(());
                    }

                    // Create mission with policy
                    let policy = MissionPolicy {
                        max_parallel_items: max_parallel,
                        reviewer_required: !no_reviewer,
                        ..Default::default()
                    };

                    let mut mission = MissionRun::new(objectives.clone()).with_policy(policy);
                    mission.start();

                    // Save to Redis
                    storage.save_mission(&mission).await?;
                    storage.add_active(mission.id).await?;
                    storage
                        .log_event(mission.id, "Mission started via CLI")
                        .await?;

                    let work_items =
                        build_mission_work_items(town.root(), mission.id, &objectives)?;
                    let work_item_count = work_items.len();
                    for item in &work_items {
                        storage.save_work_item(item).await?;
                    }
                    storage
                        .log_event(
                            mission.id,
                            &format!(
                                "Bootstrapped {} work item(s) from mission objectives",
                                work_item_count
                            ),
                        )
                        .await?;

                    let scheduler =
                        MissionScheduler::with_defaults(storage.clone(), town.channel().clone());
                    let tick_result = scheduler.tick().await?;

                    info!("🚀 Mission started!");
                    info!("   ID: {}", mission.id);
                    info!("   Objectives: {}", objectives.len());
                    info!("   Work items: {}", work_item_count);
                    for obj in &objectives {
                        info!("      - {}", obj);
                    }
                    info!("   Max parallel: {}", max_parallel);
                    info!("   Reviewer required: {}", !no_reviewer);
                    info!(
                        "   Scheduler bootstrap: {} promoted, {} assigned",
                        tick_result.total_promoted, tick_result.total_assigned
                    );
                    info!("");
                    info!(
                        "   Check status with: tt mission status --run {}",
                        mission.id
                    );
                }

                MissionAction::Status {
                    run,
                    work,
                    watch,
                    dispatcher,
                } => {
                    if let Some(run_id) = run {
                        // Show specific mission
                        let mission_id: MissionId = run_id
                            .parse()
                            .map_err(|_| tinytown::Error::Config("Invalid mission ID".into()))?;

                        let Some(mission) = storage.get_mission(mission_id).await? else {
                            info!("❌ Mission {} not found", run_id);
                            return Ok(());
                        };

                        print_mission_status(&storage, &mission, work, watch, dispatcher).await?;
                    } else {
                        // Show all active missions
                        let active_ids = storage.list_active().await?;

                        if active_ids.is_empty() {
                            info!("📋 No active missions");
                            info!("   Start one with: tt mission start --issue <N>");
                            return Ok(());
                        }

                        info!("📋 Active Missions: {}", active_ids.len());
                        info!("");

                        for mission_id in active_ids {
                            if let Some(mission) = storage.get_mission(mission_id).await? {
                                if work || watch || dispatcher {
                                    print_mission_status(
                                        &storage, &mission, work, watch, dispatcher,
                                    )
                                    .await?;
                                } else {
                                    print_mission_summary(&mission);
                                }
                            }
                        }
                    }
                }

                MissionAction::Resume { run_id } => {
                    let mission_id: MissionId = run_id
                        .parse()
                        .map_err(|_| tinytown::Error::Config("Invalid mission ID".into()))?;

                    let Some(mut mission) = storage.get_mission(mission_id).await? else {
                        info!("❌ Mission {} not found", run_id);
                        return Ok(());
                    };

                    if mission.state == MissionState::Running {
                        info!("ℹ️  Mission {} is already running", run_id);
                        return Ok(());
                    }

                    if mission.state == MissionState::Completed {
                        info!("ℹ️  Mission {} is already completed", run_id);
                        return Ok(());
                    }

                    if mission.state == MissionState::Failed {
                        info!("ℹ️  Mission {} has failed and cannot be resumed", run_id);
                        return Ok(());
                    }

                    if !mission.state.can_resume() {
                        info!(
                            "ℹ️  Mission {} is not blocked and cannot be resumed",
                            run_id
                        );
                        return Ok(());
                    }

                    mission.start();
                    storage.save_mission(&mission).await?;
                    storage.add_active(mission_id).await?;
                    storage
                        .log_event(mission_id, "Mission resumed via CLI")
                        .await?;

                    info!("▶️  Mission {} resumed", run_id);
                }

                MissionAction::Dispatch { run, once } => {
                    let run_id =
                        if let Some(run_id) = run {
                            Some(run_id.parse().map_err(|_| {
                                tinytown::Error::Config("Invalid mission ID".into())
                            })?)
                        } else {
                            None
                        };

                    let dispatcher = MissionDispatcher::new(
                        storage.clone(),
                        town.channel().clone(),
                        GhCliGitHubClient,
                        DispatcherConfig::default(),
                    );

                    if once {
                        let result = dispatcher.tick(run_id).await?;
                        info!(
                            "🛰️  Dispatcher tick: claimed {} mission(s), processed {} watch(es), promoted {}, assigned {}",
                            result.claimed_missions.len(),
                            result.watch_result.watches_processed,
                            result.scheduler_result.total_promoted,
                            result.scheduler_result.total_assigned
                        );
                    } else {
                        info!("🛰️  Mission dispatcher running");
                        if let Some(run_id) = run_id {
                            info!("   Run filter: {}", run_id);
                        } else {
                            info!("   Scope: all active missions");
                        }
                        dispatcher.run(run_id).await?;
                    }
                }

                MissionAction::Note { run_id, message } => {
                    use tinytown::mission::MissionControlMessage;

                    let mission_id: MissionId = run_id
                        .parse()
                        .map_err(|_| tinytown::Error::Config("Invalid mission ID".into()))?;
                    let Some(_mission) = storage.get_mission(mission_id).await? else {
                        info!("❌ Mission {} not found", run_id);
                        return Ok(());
                    };

                    let note = MissionControlMessage::new(mission_id, "conductor", message.clone());
                    storage.save_control_message(&note).await?;
                    storage
                        .log_event(
                            mission_id,
                            &format!("Conductor note queued for dispatcher: {}", message),
                        )
                        .await?;
                    info!("📝 Queued dispatcher note for mission {}", run_id);
                }

                MissionAction::Stop { run_id, force } => {
                    let mission_id: MissionId = run_id
                        .parse()
                        .map_err(|_| tinytown::Error::Config("Invalid mission ID".into()))?;

                    let Some(mut mission) = storage.get_mission(mission_id).await? else {
                        info!("❌ Mission {} not found", run_id);
                        return Ok(());
                    };

                    if force {
                        mission.fail("Stopped by user (forced)");
                    } else {
                        mission.block("Stopped by user");
                    }

                    storage.save_mission(&mission).await?;
                    storage.remove_active(mission_id).await?;
                    storage
                        .log_event(mission_id, &format!("Mission stopped (force={})", force))
                        .await?;

                    info!("⏹️  Mission {} stopped", run_id);
                }

                MissionAction::List { all } => {
                    let missions = if all {
                        storage.list_all_missions().await?
                    } else {
                        let active_ids = storage.list_active().await?;
                        let mut missions = Vec::new();
                        for id in active_ids {
                            if let Some(m) = storage.get_mission(id).await? {
                                missions.push(m);
                            }
                        }
                        missions
                    };

                    if missions.is_empty() {
                        info!("📋 No missions found");
                        return Ok(());
                    }

                    info!("📋 Missions: {}", missions.len());
                    info!("");

                    for mission in missions {
                        print_mission_summary(&mission);
                    }
                }
            }
        }

        Commands::Events {
            count,
            agent,
            mission,
            follow,
        } => {
            let town = Town::connect(&cli.town).await?;
            let es = town.event_stream();

            let mut last_id = "0-0".to_string();

            loop {
                let events = if let Some(ref mid_str) = mission {
                    use tinytown::mission::MissionId;
                    let mid: MissionId = mid_str
                        .parse()
                        .map_err(|_| tinytown::Error::Config("Invalid mission ID".into()))?;
                    es.read_mission_events(mid, &last_id, count).await?
                } else if let Some(ref agent_name) = agent {
                    let agent_obj = town
                        .channel()
                        .get_agent_by_name(agent_name)
                        .await?
                        .ok_or_else(|| tinytown::Error::AgentNotFound(agent_name.clone()))?;
                    es.read_agent_events(agent_obj.id, &last_id, count).await?
                } else {
                    es.read_town_events(&last_id, count).await?
                };

                for (id, event) in &events {
                    let scope = if let Some(mid) = event.mission_id {
                        format!("mission:{}", mid)
                    } else if let Some(aid) = event.agent_id {
                        format!("agent:{}", aid)
                    } else {
                        "town".to_string()
                    };
                    println!(
                        "{} [{}] {}{}",
                        event.timestamp.format("%H:%M:%S"),
                        event.event_type,
                        scope,
                        event.message
                    );
                    last_id = id.clone();
                }

                if !follow {
                    if events.is_empty() {
                        info!("No events found. Events are emitted on state transitions.");
                    }
                    break;
                }

                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            }
        }
    }

    Ok(())
}

// ==================== Mission Helper Functions ====================

/// Print a summary of a mission.
fn print_mission_summary(mission: &tinytown::mission::MissionRun) {
    let state_emoji = match mission.state {
        tinytown::mission::MissionState::Planning => "📝",
        tinytown::mission::MissionState::Running => "🚀",
        tinytown::mission::MissionState::Blocked => "🚧",
        tinytown::mission::MissionState::Completed => "",
        tinytown::mission::MissionState::Failed => "",
    };

    let objectives_str: Vec<String> = mission
        .objective_refs
        .iter()
        .map(|o| o.to_string())
        .collect();
    let objectives_short = if objectives_str.len() > 2 {
        format!(
            "{}, {} +{} more",
            objectives_str[0],
            objectives_str[1],
            objectives_str.len() - 2
        )
    } else {
        objectives_str.join(", ")
    };

    let age = chrono::Utc::now() - mission.created_at;
    let age_str = if age.num_hours() > 24 {
        format!("{}d ago", age.num_days())
    } else if age.num_hours() > 0 {
        format!("{}h ago", age.num_hours())
    } else {
        format!("{}m ago", age.num_minutes())
    };

    info!(
        "   {} {} ({:?}) - {} - {}",
        state_emoji,
        mission.id.short_id(),
        mission.state,
        objectives_short,
        age_str
    );

    if let Some(reason) = &mission.blocked_reason {
        info!("      └─ Blocked: {}", reason);
    }
}

/// Print detailed mission status.
async fn print_mission_status(
    storage: &tinytown::mission::MissionStorage,
    mission: &tinytown::mission::MissionRun,
    show_work: bool,
    show_watch: bool,
    show_dispatcher: bool,
) -> tinytown::Result<()> {
    let state_emoji = match mission.state {
        tinytown::mission::MissionState::Planning => "📝",
        tinytown::mission::MissionState::Running => "🚀",
        tinytown::mission::MissionState::Blocked => "🚧",
        tinytown::mission::MissionState::Completed => "",
        tinytown::mission::MissionState::Failed => "",
    };

    info!("🎯 Mission Status");
    info!("   ID: {} ({})", mission.id.short_id(), mission.id);
    info!("   State: {} {:?}", state_emoji, mission.state);
    info!(
        "   Created: {}",
        mission.created_at.format("%Y-%m-%d %H:%M:%S UTC")
    );
    info!(
        "   Updated: {}",
        mission.updated_at.format("%Y-%m-%d %H:%M:%S UTC")
    );
    info!("");

    info!("📋 Objectives: {}", mission.objective_refs.len());
    for obj in &mission.objective_refs {
        info!("   - {}", obj);
    }
    info!("");

    info!("⚙️  Policy:");
    info!("   Max parallel: {}", mission.policy.max_parallel_items);
    info!("   Reviewer required: {}", mission.policy.reviewer_required);
    info!("   Auto-merge: {}", mission.policy.auto_merge);
    info!("   Watch interval: {}s", mission.policy.watch_interval_secs);
    info!("");

    if let Some(reason) = &mission.blocked_reason {
        info!("🚧 Blocked Reason: {}", reason);
        info!("");
    }
    if let Some(next_wake_at) = mission.next_wake_at {
        info!(
            "⏰ Next Wake: {}",
            next_wake_at.format("%Y-%m-%d %H:%M:%S UTC")
        );
        info!("");
    }

    if show_dispatcher {
        info!("🛰️  Dispatcher:");
        match mission.dispatcher_last_tick_at {
            Some(ts) => info!("   Last tick: {}", ts.format("%Y-%m-%d %H:%M:%S UTC")),
            None => info!("   Last tick: never"),
        }
        match mission.dispatcher_last_progress_at {
            Some(ts) => info!("   Last progress: {}", ts.format("%Y-%m-%d %H:%M:%S UTC")),
            None => info!("   Last progress: none recorded"),
        }
        if let Some(ts) = mission.dispatcher_last_help_request_at {
            info!(
                "   Last help request: {}",
                ts.format("%Y-%m-%d %H:%M:%S UTC")
            );
        }
        if let Some(reason) = &mission.dispatcher_last_help_request_reason {
            info!("   Help reason: {}", reason);
        }

        let control_messages = storage.list_control_messages(mission.id).await?;
        let pending_controls: Vec<_> = control_messages
            .iter()
            .filter(|message| message.is_pending())
            .collect();
        info!("   Control messages: {} total", control_messages.len());
        info!("   Pending control messages: {}", pending_controls.len());
        for message in pending_controls.iter().take(3) {
            info!(
                "      - {}: {}",
                message.sender,
                truncate_summary(&message.body, 100)
            );
        }
        info!("");
    }

    // Work items
    let work_items = storage.list_work_items(mission.id).await?;
    info!("📦 Work Items: {}", work_items.len());

    if show_work || work_items.len() <= 5 {
        for item in &work_items {
            let status_emoji = match item.status {
                tinytown::mission::WorkStatus::Pending => "",
                tinytown::mission::WorkStatus::Ready => "🔵",
                tinytown::mission::WorkStatus::Assigned => "📌",
                tinytown::mission::WorkStatus::Running => "🔄",
                tinytown::mission::WorkStatus::Blocked => "🚧",
                tinytown::mission::WorkStatus::Done => "",
            };
            info!(
                "   {} {} ({:?}) - {:?}",
                status_emoji, item.title, item.kind, item.status
            );
            if let Some(agent) = item.assigned_to {
                info!("      └─ Assigned to: {}", agent);
            }
            if item.reviewer_approved {
                info!("      └─ Reviewer approved");
            }
        }
    } else {
        // Count by status
        let pending = work_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WorkStatus::Pending)
            .count();
        let ready = work_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WorkStatus::Ready)
            .count();
        let running = work_items
            .iter()
            .filter(|w| {
                w.status == tinytown::mission::WorkStatus::Running
                    || w.status == tinytown::mission::WorkStatus::Assigned
            })
            .count();
        let done = work_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WorkStatus::Done)
            .count();
        let blocked = work_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WorkStatus::Blocked)
            .count();

        info!("   ⏳ Pending: {}", pending);
        info!("   🔵 Ready: {}", ready);
        info!("   🔄 Running: {}", running);
        info!("   ✅ Done: {}", done);
        info!("   🚧 Blocked: {}", blocked);
        info!("   (use --work for full list)");
    }
    info!("");

    // Watch items
    let watch_items = storage.list_watch_items(mission.id).await?;
    info!("👁️  Watch Items: {}", watch_items.len());

    if show_watch {
        for item in &watch_items {
            let status_emoji = match item.status {
                tinytown::mission::WatchStatus::Active => "🟢",
                tinytown::mission::WatchStatus::Snoozed => "😴",
                tinytown::mission::WatchStatus::Done => "",
            };
            info!(
                "   {} {:?} - {} ({:?})",
                status_emoji, item.kind, item.target_ref, item.status
            );
            info!(
                "      └─ Next check: {}",
                item.next_due_at.format("%H:%M:%S")
            );
        }
    } else if !watch_items.is_empty() {
        let active = watch_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WatchStatus::Active)
            .count();
        let done = watch_items
            .iter()
            .filter(|w| w.status == tinytown::mission::WatchStatus::Done)
            .count();
        info!("   🟢 Active: {}", active);
        info!("   ✅ Done: {}", done);
        info!("   (use --watch for full list)");
    }
    info!("");

    // Recent events
    let events = storage.get_events(mission.id, 5).await?;
    if !events.is_empty() {
        info!("📜 Recent Events:");
        for event in events {
            info!("   {}", event);
        }
    }

    Ok(())
}

/// Town registry entry for ~/.tt/towns.toml
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct TownEntry {
    path: String,
    name: String,
}

/// Towns file format
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
struct TownsFile {
    #[serde(default)]
    towns: Vec<TownEntry>,
}

#[cfg(test)]
mod tests {
    use super::{backlog_task_matches_role, is_supervisor_alias, validate_spawn_agent_name};
    use tinytown::Task;

    #[test]
    fn reviewer_does_not_match_implementation_backlog_tags() {
        let task = Task::new("Add demo data mode").with_tags(["backend", "frontend", "data"]);
        assert!(!backlog_task_matches_role(&task, "reviewer"));
    }

    #[test]
    fn reviewer_matches_review_or_security_tags() {
        let review_task = Task::new("Review auth flow").with_tags(["review", "security"]);
        assert!(backlog_task_matches_role(&review_task, "reviewer"));
    }

    #[test]
    fn backend_matches_backend_and_data_tags() {
        let task = Task::new("Implement importer").with_tags(["backend", "data"]);
        assert!(backlog_task_matches_role(&task, "backend"));
    }

    #[test]
    fn generalist_roles_can_match_generic_backlog() {
        let task = Task::new("Pick up the next general task");
        assert!(backlog_task_matches_role(&task, "worker"));
        assert!(backlog_task_matches_role(&task, "agent"));
    }

    #[test]
    fn supervisor_aliases_are_reserved_spawn_names() {
        assert!(is_supervisor_alias("supervisor"));
        assert!(is_supervisor_alias("Conductor"));
        assert!(validate_spawn_agent_name("supervisor").is_err());
        assert!(validate_spawn_agent_name("conductor").is_err());
        assert!(validate_spawn_agent_name("supervisor-2").is_ok());
        assert!(validate_spawn_agent_name("backend").is_ok());
    }
}