attini 0.0.1

CLI coding agent that aims to be as autonomous as it can be, without ever leaving your control
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
//! Sync single-turn agent loop for `attini tell`.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::{Duration, Instant};

use nojson::{DisplayJson, RawJson};

use crate::curl::{self, ProgressSinks};
use crate::permissions;
use crate::sansio::agent::{
    CommandError, CommandInvocation, PatchError, PatchInvocation, PatchPreview, PatchTool,
    ReadOnlyTool, ToolExecutionError, ToolOutcome,
};
use crate::sansio::deepseek::{ChatMessage, ChatRequest, ToolCall, ToolDef};
use crate::sansio::permissions::{
    Authorization, AutoDecision, Judgment, Rule, RuleScope, evaluate, evaluate_write,
};
use crate::session::{
    ApprovalDecision, AutoDecidedBy, AutoDecidedMatch, ChatMessageWithTs, InvocationEndReason,
    MetricsSnapshotBody, Pending, PendingToolKind, Session, SessionRecord, TokenUsageBody,
    now_unix_millis,
};
use crate::tools::ToolExecutor;

pub const EXIT_OK: u8 = 0;
pub const EXIT_ERROR: u8 = 1;
pub const EXIT_AWAITING_APPROVAL: u8 = 10;

pub const DEFAULT_MAX_TURNS: usize = 20;

/// Counters collected during one invocation of `tell_cli::run` for
/// later persistence into `MetricsSnapshotBody::entries`. Shared by
/// mutable reference between `run()` and `drive()` so both the Ok
/// and Err outcomes flush the same accumulated values.
#[derive(Debug, Default)]
pub struct Counters {
    pub turns: u64,
    pub tool_calls_by_kind: ToolCallsByKind,
    pub tool_errors: u64,
    pub prompt_tokens_billed_total: u64,
    /// Latest per-call `prompt_tokens` from the most recent successful
    /// model call. Unlike [`Counters::prompt_tokens_billed_total`]
    /// (a cumulative sum over the invocation), this reflects the *current*
    /// conversation size and is what the status line's `ctx=` shows.
    pub prompt_tokens_last: u64,
    pub completion_tokens_total: u64,
    pub prompt_cache_hit_tokens_total: u64,
    pub prompt_cache_miss_tokens_total: u64,
    /// Number of times `try_auto_compact` invoked `compact_conversation`.
    /// (Total number of times it fired past the threshold; counted as 1
    /// whether it ends in an internal skip, a summariser success, or any
    /// of the various `Err` outcomes.)
    pub compaction_attempts: u64,
    /// Number of times `compact_conversation` returned `Err`.
    /// (Aggregates `Err` arising from `load_records_since_last_summary`,
    /// `run_summariser`, or the `?` in `session.append`.)
    pub compaction_failures: u64,
}

/// Per-tool-name buckets for `Counters::tool_calls_by_kind`. Names are
/// matched directly against `ToolCall::function_name`; anything not
/// in the fixed set falls into `unknown` (mirrors the `Unknown`
/// branch of the dispatch loop's `classify()` helper).
#[derive(Debug, Default)]
pub struct ToolCallsByKind {
    pub list: u64,
    pub read: u64,
    pub search: u64,
    pub patch: u64,
    pub command: u64,
    pub unknown: u64,
}

impl Counters {
    /// Flatten into the `Vec<(String, u64)>` shape expected by
    /// `MetricsSnapshotBody::entries`. Also takes `duration_ms`
    /// separately because that value is known only in `run()`, not
    /// during `drive()`.
    pub fn to_metrics_entries(&self, duration_ms: u64) -> Vec<(String, u64)> {
        vec![
            ("turns".to_string(), self.turns),
            ("tool_calls.list".to_string(), self.tool_calls_by_kind.list),
            ("tool_calls.read".to_string(), self.tool_calls_by_kind.read),
            (
                "tool_calls.search".to_string(),
                self.tool_calls_by_kind.search,
            ),
            (
                "tool_calls.patch".to_string(),
                self.tool_calls_by_kind.patch,
            ),
            (
                "tool_calls.command".to_string(),
                self.tool_calls_by_kind.command,
            ),
            (
                "tool_calls.unknown".to_string(),
                self.tool_calls_by_kind.unknown,
            ),
            ("tool_errors".to_string(), self.tool_errors),
            ("duration_ms".to_string(), duration_ms),
            (
                "prompt_tokens_billed_total".to_string(),
                self.prompt_tokens_billed_total,
            ),
            (
                "completion_tokens_total".to_string(),
                self.completion_tokens_total,
            ),
            (
                "prompt_cache_hit_tokens_total".to_string(),
                self.prompt_cache_hit_tokens_total,
            ),
            (
                "prompt_cache_miss_tokens_total".to_string(),
                self.prompt_cache_miss_tokens_total,
            ),
            ("compaction_attempts".to_string(), self.compaction_attempts),
            ("compaction_failures".to_string(), self.compaction_failures),
        ]
    }
}

/// `prompt_tokens` threshold above which the next `Continuation::Prompt`
/// invocation summarises before making the model call. Set to 1/4 of
/// the DeepSeek 64 K context (`64 × 1024 / 4 = 16384`) so compaction
/// leaves room for the next turn's growth plus the memory tier, tool
/// definitions, and the summarizer's own input.
pub const COMPACTION_TRIGGER_TOKENS: u64 = 16_384;

/// Upper bound on the number of diff lines printed for a patch
/// preview / auto-approved patch. Beyond this the rest is collapsed
/// into a `... (N more lines omitted)` marker. Keeps a pathological
/// patch from flooding the terminal while still showing what changed
/// for the common case.
pub const PATCH_PREVIEW_MAX_LINES: usize = 200;

/// Upper bound on the number of content lines printed for a `read`
/// tool result on stderr. Beyond this the rest is collapsed into a
/// `... (N more lines omitted)` marker, so a large read cannot flood
/// the terminal while still showing the head of what was read. The
/// JSON payload sent to the model is unaffected; this is display
/// only.
pub const READ_PREVIEW_MAX_LINES: usize = 20;

/// Target number of real records to retain past the summary cutoff
/// when compacting. Actual retention may be a little higher: the
/// cutoff snaps toward the tail until it lands on a User record or
/// an Assistant record without pending `tool_calls`, so any pair
/// of `assistant -> tool` records stays together.
pub const KEEP_RECENT_RECORDS_TARGET: usize = 10;

/// Maximum prose characters sent to the summariser in a single
/// compaction pass. Roughly tokens ≈ chars/4 for ASCII-heavy tool
/// output, so 200 000 chars ≈ 50 000 tokens — inside even a 64 K
/// context with room for the ~500-word response. When the rendered
/// transcript exceeds this the newest portion is kept and the
/// oldest records are dropped.
pub const SUMMARY_MAX_CHARS: usize = 200_000;

/// Maximum prose characters kept from a single assistant/user record
/// before it is truncated in a summary transcript.
pub const SUMMARY_RECORD_MAX_CHARS: usize = 16_000;

/// Maximum prose characters kept from a single tool result in a
/// summary transcript.
pub const SUMMARY_TOOL_RESULT_MAX_CHARS: usize = 200;

/// Maximum raw character size of the retained record tail after a
/// compaction pass. If the newest records themselves are enormous
/// (a giant tool result), the cutoff walks further back so they are
/// folded into the summary rather than left to blow up the main
/// model call. 250 000 chars ≈ 62 000 tokens, inside even a 64 K
/// context; normal recent tails are far smaller and unaffected.
pub const RETAINED_TAIL_MAX_CHARS: usize = 250_000;

/// Maximum raw character size of the real records between the last
/// summary and now, used as a second auto-compaction trigger. When
/// the previous turn suspended before recording its `token_usage`,
/// `latest_prompt_tokens()` is stale/small even though the actual
/// records (which include a huge tool result) are enormous; this
/// bound catches that case so compaction still fires. Mirrors
/// [`RETAINED_TAIL_MAX_CHARS`] for consistency.
pub const RECORDS_TOTAL_MAX_CHARS: usize = 250_000;

/// Byte size of `conversation.jsonl` at which an automatic physical
/// prune pass runs. Compaction appends a summary but never deletes the
/// records it summarised, so the append-only log grows without bound;
/// once it crosses this size the records before the midpoint are
/// dropped at a safe boundary. 100 MB is far larger than any session
/// that still benefits from full history, so this fires rarely.
pub const CONVERSATION_PRUNE_TRIGGER_BYTES: u64 = 100 * 1024 * 1024;

pub struct TellConfig {
    pub session_name: String,
    pub model: String,
    /// Maximum completion tokens per model call. `None` uses the
    /// model's own default; `Some(n)` caps response size / cost.
    pub max_tokens: Option<u64>,
    pub workspace_root: PathBuf,
    pub system_prompt: Option<String>,
    pub max_turns: usize,
    /// Maximum tool calls admitted in a single model turn. Extras in
    /// the same response get a synthetic error result and the loop
    /// advances to the next turn.
    pub turn_tool_call_limit: usize,
    /// Sliding-window rate cap on admitted tool calls. `None`
    /// disables the check.
    pub tool_call_rate: Option<RateLimit>,
    /// Invocation-scope backstop on admitted tool calls. Hitting it
    /// stops the loop with [`InvocationEndReason::SessionToolCallExhausted`].
    /// `None` disables the check.
    pub session_tool_call_max: Option<usize>,
    /// How side-effecting tool calls are authorized in this
    /// invocation. `plan run` supplies
    /// [`Authorization::ApprovedPlan`]; every other entry point uses
    /// the default `PerTool`.
    pub authorization: Authorization,
    /// Sampling temperature for model calls. `None` uses the request
    /// default (`Some(0.0)`, deterministic code editing); `Some(t)`
    /// overrides it.
    pub temperature: Option<f64>,
    /// Requested one-shot grant to run alongside a `Continuation::Approve`:
    /// `attini approve --grant <SCOPE>`. Persists an auto-approve rule for
    /// the approved command's argv-prefix after the approval succeeds.
    /// `None` for every other entry point.
    pub grant_request: GrantRequest,
    /// Wall-clock cap on a single `command` tool call, in seconds. The
    /// child runs in its own process group and is killed (SIGTERM, then
    /// SIGKILL) when the cap elapses; the result sets `termination_reason`
    /// to `timeout`. `None` disables the cap. `Some(0)` is treated as
    /// disabled too, so `--command-timeout 0` opts out.
    pub command_timeout_seconds: Option<u64>,
}

/// Default `command` tool timeout in seconds, used when neither
/// `--command-timeout` nor `ATTINI_COMMAND_TIMEOUT_SECONDS` is set.
pub const DEFAULT_COMMAND_TIMEOUT_SECONDS: u64 = 180;

/// The `--grant SCOPE` value accepted by `attini approve`.
///
/// `Oneshot` is the default: approve the pending call and persist
/// nothing. `Session` / `Workspace` additionally append the approved
/// command's argv-prefix as an auto-approve rule to the corresponding
/// `permissions.jsonl`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GrantRequest {
    /// No grant was requested (`--grant` omitted, or not an approve run).
    None,
    /// `--grant oneshot`: persist nothing (the default approve behavior).
    Oneshot,
    /// `--grant session`: append to the session-local `permissions.jsonl`.
    Session,
    /// `--grant workspace`: append to the workspace-wide `permissions.jsonl`.
    Workspace,
}

pub const DEFAULT_TURN_TOOL_CALL_LIMIT: usize = 20;
pub const DEFAULT_TOOL_CALL_RATE_CALLS: usize = 60;
pub const DEFAULT_TOOL_CALL_RATE_WINDOW_SECS: u64 = 60;
pub const DEFAULT_SESSION_TOOL_CALL_MAX: usize = 5000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimit {
    pub calls: usize,
    pub window: Duration,
}

pub enum Continuation {
    /// A fresh user prompt for this invocation.
    Prompt(String),
    /// Resume a stopped session: approve the pending tool call in the
    /// session's `pending.json` if there is one; otherwise re-issue the
    /// identical request when the previous invocation ended in a
    /// retryable transport failure ([`Continuation::Retry`]); otherwise
    /// continue with a fixed continuation message ([`RESUME_PROMPT`]).
    Approve,
    /// Internal only: re-run the loop against the conversation exactly
    /// as it stands, without appending any new user record. Produced by
    /// normalising [`Continuation::Approve`] when the previous
    /// invocation ended in [`InvocationEndReason::TransportError`] before
    /// any assistant output was recorded, so the same request can safely
    /// be sent again.
    Retry,
}

/// Fixed user message appended when `attini approve` is run on a session
/// that has no pending tool call (i.e. it stopped at `max_turns`). It
/// deliberately carries no new instruction: approving a stop means "keep
/// going", while a new instruction goes through `attini tell`. The model
/// already has its own last turn in context, so a bare continuation is
/// enough to pick the work back up.
pub const RESUME_PROMPT: &str = "Continue from where you left off.";

/// Terminal outcome of one `tell_cli::run` invocation.
#[derive(Debug)]
pub enum TellOutcome {
    /// Normal exit with the process exit code.
    Exit(ExitCode),
}

pub fn run(cfg: TellConfig, cont: Continuation) -> io::Result<TellOutcome> {
    let mut session = Session::open(&cfg.session_name)?;
    // Canonicalise the persistent extra_read_paths (from
    // permissions.jsonl) and hand the resulting Vec to the
    // ToolExecutor. Any path that fails
    // to canonicalise is warned + skipped so a single bad entry does
    // not disable the whole read-path list.
    let loaded = permissions::load(&cfg.session_name)?;
    let candidates: Vec<PathBuf> = loaded.extra_read_paths.iter().map(PathBuf::from).collect();
    let extra_read_roots = canonicalise_extra_read_roots(&cfg.workspace_root, candidates);
    let mut executor = ToolExecutor::new(
        &cfg.workspace_root,
        extra_read_roots,
        cfg.session_name.clone(),
    )?;
    // Hand the executor the flattened `write` rules (workspace layer
    // first, then session layer) so `patch` writes can be authorised by
    // an explicit rule before falling back to the git-tracking
    // heuristic. Rules from both layers are concatenated; last-match-wins
    // is preserved because `evaluate_write` walks the slice in order.
    let mut write_rules: Vec<Rule> = Vec::new();
    write_rules.extend(loaded.workspace.iter().cloned());
    write_rules.extend(loaded.session.iter().cloned());
    executor.set_write_rules(write_rules);

    let start_ts = now_unix_millis();
    session.append(&SessionRecord::InvocationStart {
        ts: start_ts,
        attini_version: env!("CARGO_PKG_VERSION").to_string(),
        model: cfg.model.clone(),
    })?;

    // One-line start-of-invocation breadcrumb to stderr (a diagnostic, not
    // machine-consumed output). Printed BEFORE the model runs: it tells the
    // human which session/model is about to advance and how big the current
    // conversation already is (the last recorded `prompt_tokens`). `ctx=`
    // comes from the last recorded `prompt_tokens` (the conversation size
    // so far), not the cumulative billed total. Disabled with
    // ATTINI_STATUS_LINE=0.
    if std::env::var("ATTINI_STATUS_LINE").as_deref() != Ok("0") {
        let ctx_tokens = session.latest_prompt_tokens().ok().flatten().unwrap_or(0);
        eprintln!(
            "{}",
            render_tell_status_line(&cfg.model, &cfg.session_name, ctx_tokens)
        );
    }

    let mut counters = Counters::default();
    let outcome = drive(&mut session, &executor, &cfg, cont, &mut counters);

    let (reason, exit_code) = match &outcome {
        Ok(Driven::Completed) => (InvocationEndReason::Completed, EXIT_OK),
        Ok(Driven::AwaitingApproval) => (
            InvocationEndReason::AwaitingApproval,
            EXIT_AWAITING_APPROVAL,
        ),
        Ok(Driven::SessionToolCallExhausted) => {
            (InvocationEndReason::SessionToolCallExhausted, EXIT_ERROR)
        }
        Ok(Driven::TransportFailed(_)) => (InvocationEndReason::TransportError, EXIT_ERROR),
        Err(_) => (InvocationEndReason::Error, EXIT_ERROR),
    };

    let end_ts = now_unix_millis();
    let duration_ms = end_ts.saturating_sub(start_ts);
    let _ = session.append(&SessionRecord::MetricsSnapshot {
        ts: end_ts,
        counters: MetricsSnapshotBody {
            entries: counters.to_metrics_entries(duration_ms),
        },
    });
    let _ = session.append(&SessionRecord::InvocationEnd { ts: end_ts, reason });

    match outcome {
        Ok(Driven::TransportFailed(message)) => {
            eprintln!("attini: {message}");
            eprintln!(
                "attini: this looks like a transient transport failure; run \
                 `attini approve -s {}` to re-issue the same request",
                cfg.session_name
            );
            Ok(TellOutcome::Exit(ExitCode::from(EXIT_ERROR)))
        }
        Ok(_) => Ok(TellOutcome::Exit(ExitCode::from(exit_code))),
        Err(e) => {
            eprintln!("attini: {e}");
            Ok(TellOutcome::Exit(ExitCode::from(EXIT_ERROR)))
        }
    }
}

/// Render the single-line start-of-invocation breadcrumb written to stderr
/// by [`run`]. Pure function so the format can be unit-tested without
/// touching stdout. `ctx=` is the current conversation size (the last
/// recorded `prompt_tokens`) handed in by the caller; it is not the
/// cumulative billed total.
fn render_tell_status_line(model: &str, session_name: &str, ctx_tokens: u64) -> String {
    format!(
        "[tell] model={} session={} ctx={}",
        model, session_name, ctx_tokens,
    )
}

enum Driven {
    Completed,
    AwaitingApproval,
    /// Invocation-scope tool-call backstop tripped
    /// ([`TellConfig::session_tool_call_max`]).
    SessionToolCallExhausted,
    /// A model call failed at the transport layer before any assistant
    /// output for the turn was recorded. Recorded as
    /// [`InvocationEndReason::TransportError`] so a later `attini
    /// approve` can re-issue the request. Carries the human-readable
    /// failure message for the stderr diagnostic.
    TransportFailed(String),
}

/// Enforces the three tool-call caps (per-turn, sliding rate window,
/// invocation-scope backstop) in `drive`'s tool_calls dispatch loop.
/// Counters increment only on admitted calls: rate-window and
/// session-cumulative do not consume budget when a cap already
/// rejected the call.
struct ToolCallGate {
    turn_limit: usize,
    rate: Option<RateLimit>,
    session_max: Option<usize>,
    turn_count: usize,
    rate_deque: VecDeque<Instant>,
    session_count: usize,
}

#[derive(Debug, PartialEq, Eq)]
enum GateDecision {
    Proceed,
    TurnLimitExceeded,
    RateLimitExceeded,
    SessionExhausted,
}

impl ToolCallGate {
    fn new(cfg: &TellConfig) -> Self {
        Self {
            turn_limit: cfg.turn_tool_call_limit,
            rate: cfg.tool_call_rate,
            session_max: cfg.session_tool_call_max,
            turn_count: 0,
            rate_deque: VecDeque::new(),
            session_count: 0,
        }
    }

    fn begin_turn(&mut self) {
        self.turn_count = 0;
    }

    /// Check whether one more tool call may proceed. On `Proceed`,
    /// admit the call and record it (turn counter, session counter,
    /// and rate window). On any rejection, do not consume budget.
    fn admit(&mut self, now: Instant) -> GateDecision {
        if self.turn_count >= self.turn_limit {
            return GateDecision::TurnLimitExceeded;
        }
        if let Some(rate) = self.rate {
            let cutoff = now.checked_sub(rate.window).unwrap_or(now);
            while self.rate_deque.front().is_some_and(|t| *t < cutoff) {
                self.rate_deque.pop_front();
            }
            if self.rate_deque.len() >= rate.calls {
                return GateDecision::RateLimitExceeded;
            }
        }
        if let Some(max) = self.session_max
            && self.session_count >= max
        {
            return GateDecision::SessionExhausted;
        }
        self.turn_count += 1;
        self.session_count += 1;
        if self.rate.is_some() {
            self.rate_deque.push_back(now);
        }
        GateDecision::Proceed
    }
}

/// Map a pending-free `attini approve` to the continuation it should
/// actually run, given the reason the previous invocation ended.
///
/// A retryable transport failure re-issues the identical request
/// ([`Continuation::Retry`]); anything else falls back to the fixed
/// continuation message. Pure so the decision can be unit-tested
/// without a session.
fn normalise_pending_free_approve(last: Option<InvocationEndReason>) -> Continuation {
    if last == Some(InvocationEndReason::TransportError) {
        Continuation::Retry
    } else {
        Continuation::Prompt(RESUME_PROMPT.to_string())
    }
}

fn drive(
    session: &mut Session,
    executor: &ToolExecutor,
    cfg: &TellConfig,
    cont: Continuation,
    counters: &mut Counters,
) -> io::Result<Driven> {
    // `Approve` resumes a stopped session. Normalise the no-pending
    // cases here so the rest of `drive` stays single-path:
    //   1. pending tool call present  -> approve + execute (unchanged).
    //   2. else, previous invocation ended in a retryable transport
    //      failure -> re-issue the identical request
    //      ([`Continuation::Retry`]); nothing new is appended.
    //   3. else (stopped at `max_turns`) -> fixed continuation message.
    let cont = match cont {
        Continuation::Approve if session.load_pending()?.is_some() => Continuation::Approve,
        Continuation::Approve => {
            let last = session.last_invocation_end_reason()?;
            if last == Some(InvocationEndReason::TransportError) {
                eprintln!(
                    "[approve] previous invocation ended in a transport error; re-issuing the same request"
                );
            }
            normalise_pending_free_approve(last)
        }
        other => other,
    };

    if matches!(cont, Continuation::Prompt(_)) {
        try_auto_compact(session, &cfg.model, counters, cfg.max_tokens)?;
    }

    let is_prompt = matches!(cont, Continuation::Prompt(_));
    let is_retry = matches!(cont, Continuation::Retry);
    let is_approve = matches!(cont, Continuation::Approve);

    let mut messages = build_initial_messages(session, cfg)?;

    // The `Prompt` path appends a fresh user record before the model
    // call; `Retry` re-issues the existing conversation as-is. Any
    // assistant `tool_call` left unanswered when the loop previously
    // suspended must be answered *before* that user record is appended
    // (or before the identical request is re-sent), otherwise a
    // synthetic tool result would be persisted after the user and break
    // the assistant -> tool continuity the API requires. A transport
    // error leaves no assistant record, so `Retry` normally repairs
    // nothing, but the pass is harmless and keeps the invariant.
    if is_prompt || is_retry {
        let repaired = repair_orphaned_tool_calls(session, &mut messages)?;
        if repaired > 0 {
            eprintln!(
                "[repair] inserted {repaired} synthetic tool result(s) for unanswered tool_call(s)"
            );
        }
    }

    match cont {
        Continuation::Prompt(text) => {
            session.append(&SessionRecord::User {
                ts: now_unix_millis(),
                text: text.clone(),
            })?;
            messages.push(ChatMessage::User(text));
        }
        Continuation::Approve => {
            let pendings = load_pending_or_err(session)?;
            // `--grant` is validated here (after the pending set is known)
            // but applied only after every approval has succeeded, so a
            // rejected/broken pending set never leaves a grant behind. See
            // [`plan_grant`] for the up-front checks.
            let grant = plan_grant(cfg.grant_request, &pendings, executor.root())?;
            for pending in &pendings {
                session.append(&SessionRecord::ToolApproval {
                    ts: now_unix_millis(),
                    call_id: pending.call_id.clone(),
                    decision: ApprovalDecision::Approve,
                    auto_decided_by: None,
                })?;
                let content = execute_pending(pending, executor, command_timeout(cfg))?;
                append_tool(session, &mut messages, &pending.call_id, content)?;
            }
            session.clear_pending()?;
            // Best-effort: the approval already stands, so a grant failure
            // is a warning, not a rollback.
            if let Some(intent) = grant {
                apply_grant(cfg, &intent);
            }
        }
        // Re-issue the identical request: append no new user record, just
        // fall through to the model-call loop with the conversation as-is.
        Continuation::Retry => {}
    }

    // `Approve` consumes the parked pending inside the match above
    // (appending a Tool record for the answered call), so it runs the
    // orphan repair *after* the match; otherwise the pending is still
    // parked and the freshly-appended Tool record could be re-surfaced
    // as an orphan.
    if is_approve {
        let repaired = repair_orphaned_tool_calls(session, &mut messages)?;
        if repaired > 0 {
            eprintln!(
                "[repair] inserted {repaired} synthetic tool result(s) for unanswered tool_call(s)"
            );
        }
    }

    let tools = build_tool_defs();
    let rules = permissions::load(&cfg.session_name)?;
    // Rule chain in increasing precedence: workspace, then session.
    let permission_layers: Vec<(RuleScope, &[Rule])> = vec![
        (RuleScope::Workspace, rules.workspace.as_slice()),
        (RuleScope::Session, rules.session.as_slice()),
    ];
    let mut gate = ToolCallGate::new(cfg);

    for _ in 0..cfg.max_turns {
        gate.begin_turn();
        let request = ChatRequest::new(cfg.model.clone(), messages.clone())
            .with_tools(tools.clone())
            .with_max_tokens(cfg.max_tokens)
            .with_temperature(cfg.temperature);
        let mut stdout = io::stdout();
        let call_result = {
            let mut sinks = ProgressSinks {
                content: &mut stdout,
            };
            match curl::call(&request, &mut sinks) {
                Ok(r) => r,
                Err(e) if e.is_retryable() => {
                    // Transport fault: the turn produced no assistant
                    // output, so the identical request can be re-issued
                    // by `attini approve`. Record it as a distinct end
                    // reason and stop cleanly (exit 1) rather than
                    // surfacing a raw error.
                    return Ok(Driven::TransportFailed(format!("model call failed: {e}")));
                }
                Err(e) => {
                    return Err(io::Error::other(format!("model call failed: {e}")));
                }
            }
        };
        let _ = writeln!(io::stdout());

        let assistant = call_result.clone().into_assistant();
        session.append(&SessionRecord::Assistant {
            ts: now_unix_millis(),
            content: call_result.content.clone(),
            tool_calls: call_result.tool_calls.clone(),
        })?;
        counters.turns += 1;
        if let Some(usage) = call_result.usage {
            session.append(&SessionRecord::TokenUsage {
                ts: now_unix_millis(),
                body: TokenUsageBody {
                    prompt_tokens: usage.prompt_tokens,
                    completion_tokens: usage.completion_tokens,
                    total_tokens: usage.total_tokens,
                    prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens,
                    prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens,
                },
            })?;
            counters.prompt_tokens_last = usage.prompt_tokens.unwrap_or(0);
            counters.prompt_tokens_billed_total = counters
                .prompt_tokens_billed_total
                .saturating_add(usage.prompt_tokens.unwrap_or(0));
            counters.completion_tokens_total = counters
                .completion_tokens_total
                .saturating_add(usage.completion_tokens.unwrap_or(0));
            counters.prompt_cache_hit_tokens_total = counters
                .prompt_cache_hit_tokens_total
                .saturating_add(usage.prompt_cache_hit_tokens.unwrap_or(0));
            counters.prompt_cache_miss_tokens_total = counters
                .prompt_cache_miss_tokens_total
                .saturating_add(usage.prompt_cache_miss_tokens.unwrap_or(0));
        }
        messages.push(assistant);

        if call_result.tool_calls.is_empty() {
            return Ok(Driven::Completed);
        }

        // Batch-approval state: every tool call in this turn that needs
        // human approval is parked here. Once the first one is seen we
        // stop executing side-effecting siblings (auto-approved patches
        // / commands) so the assistant `tool_calls` list and the answer
        // `tool` messages stay in the same order; the pending ones are
        // parked and the rest are left for the orphan-repair pass to
        // cancel, after which the model re-issues them.
        let mut parked: Vec<Pending> = Vec::new();
        let mut suspending = false;

        for tc in &call_result.tool_calls {
            // Fine-grained tool_calls_by_kind counting is done here
            // (not via classify()) because classify() collapses
            // list/read/search into ToolKind::ReadOnly for dispatch.
            match tc.function_name.as_str() {
                "list" => counters.tool_calls_by_kind.list += 1,
                "read" => counters.tool_calls_by_kind.read += 1,
                "search" => counters.tool_calls_by_kind.search += 1,
                "patch" => counters.tool_calls_by_kind.patch += 1,
                "command" => counters.tool_calls_by_kind.command += 1,
                _ => counters.tool_calls_by_kind.unknown += 1,
            }
            match gate.admit(Instant::now()) {
                GateDecision::Proceed => {}
                GateDecision::TurnLimitExceeded => {
                    let content = tool_error_json(
                        "turn_tool_call_limit_exceeded",
                        &format!(
                            "turn_tool_call_limit={} exceeded in this turn",
                            cfg.turn_tool_call_limit
                        ),
                    );
                    eprintln!(
                        "[cap] turn_tool_call_limit={} exceeded",
                        cfg.turn_tool_call_limit
                    );
                    counters.tool_errors += 1;
                    append_tool(session, &mut messages, &tc.id, content)?;
                    continue;
                }
                GateDecision::RateLimitExceeded => {
                    let rate = cfg
                        .tool_call_rate
                        .expect("rate cap must be Some to hit RateLimitExceeded");
                    let content = tool_error_json(
                        "tool_call_rate_exceeded",
                        &format!(
                            "tool_call_rate={}/{}s exceeded",
                            rate.calls,
                            rate.window.as_secs()
                        ),
                    );
                    eprintln!(
                        "[cap] tool_call_rate={}/{}s exceeded",
                        rate.calls,
                        rate.window.as_secs()
                    );
                    counters.tool_errors += 1;
                    append_tool(session, &mut messages, &tc.id, content)?;
                    continue;
                }
                GateDecision::SessionExhausted => {
                    let max = cfg
                        .session_tool_call_max
                        .expect("session cap must be Some to hit SessionExhausted");
                    eprintln!("[cap] session_tool_call_max={max} exhausted; ending invocation");
                    return Ok(Driven::SessionToolCallExhausted);
                }
            }
            match classify(&tc.function_name) {
                ToolKind::ReadOnly => {
                    if suspending {
                        // Left unanswered so the orphan-repair pass can
                        // cancel it in tool-call order on resume.
                    } else {
                        match run_read_only(tc, executor) {
                            ReadOnlyDispatch::Done {
                                summary,
                                content,
                                errored,
                            } => {
                                eprintln!("{summary}");
                                if errored {
                                    counters.tool_errors += 1;
                                }
                                append_tool(session, &mut messages, &tc.id, content)?;
                            }
                            ReadOnlyDispatch::NeedsApproval { summary, preview } => {
                                eprintln!("{summary}");
                                parked.push(build_pending(tc, PendingToolKind::Read, preview));
                                suspending = true;
                            }
                        }
                    }
                }
                ToolKind::Patch => {
                    if let PatchDispatch::Awaiting(pending) = dispatch_patch_unapproved(
                        tc,
                        executor,
                        &permission_layers,
                        &cfg.authorization,
                        session,
                        &mut messages,
                        counters,
                        suspending,
                    )? {
                        parked.push(pending);
                        suspending = true;
                    }
                }
                ToolKind::Command => {
                    if let CommandDispatch::Awaiting(pending) = dispatch_command(
                        tc,
                        executor,
                        &permission_layers,
                        &cfg.authorization,
                        session,
                        &mut messages,
                        counters,
                        suspending,
                        command_timeout(cfg),
                    )? {
                        parked.push(pending);
                        suspending = true;
                    }
                }
                ToolKind::Unknown => {
                    if suspending {
                        // Left unanswered; cancelled on resume.
                    } else {
                        let content = tool_error_json(
                            "unknown_tool",
                            &format!("no such tool: {}", tc.function_name),
                        );
                        eprintln!("[unknown tool] {}", tc.function_name);
                        counters.tool_errors += 1;
                        append_tool(session, &mut messages, &tc.id, content)?;
                    }
                }
            }
        }

        if !parked.is_empty() {
            session.save_pending(&parked)?;
            return Ok(Driven::AwaitingApproval);
        }
    }

    Err(io::Error::other(max_turns_error(cfg.max_turns)))
}

/// Build the error message shown when `tell` runs out of turns. The
/// continuation command is placed on its own line so it can be copied
/// verbatim; the session is taken from `-s` / `ATTINI_SESSION_NAME`
/// (defaulting to `main`), so it is omitted here rather than restating
/// a name that is already implicit in context. Exit code stays the
/// generic 1 (a `tell` loop that used all its turns is a runtime
/// failure, not a success).
fn max_turns_error(max_turns: usize) -> String {
    format!(
        "tell loop exceeded max_turns={max_turns}; continue this session? \
         run the following command:\n\
         attini approve  # or give a new instruction with: attini tell '...'"
    )
}

fn canonicalise_extra_read_roots(
    workspace_root: &std::path::Path,
    candidates: Vec<PathBuf>,
) -> Vec<PathBuf> {
    let mut seen = std::collections::BTreeSet::<PathBuf>::new();
    let mut out = Vec::new();
    for p in candidates {
        let absolute = if p.is_absolute() {
            p.clone()
        } else {
            workspace_root.join(&p)
        };
        match absolute.canonicalize() {
            Ok(canon) => {
                if seen.insert(canon.clone()) {
                    out.push(canon);
                }
            }
            Err(e) => eprintln!("attini: extra_read_paths: skipping {}: {e}", p.display()),
        }
    }
    out
}

fn build_initial_messages(session: &Session, cfg: &TellConfig) -> io::Result<Vec<ChatMessage>> {
    let mut messages = Vec::new();
    let summaries = session.load_summaries()?;
    let total = summaries.len();
    for (i, summary) in summaries.into_iter().enumerate() {
        let header = if total > 1 {
            format!(
                "# Prior conversation summary (part {} of {})\n\n",
                i + 1,
                total
            )
        } else {
            "# Prior conversation summary\n\n".to_string()
        };
        messages.push(ChatMessage::System(format!("{header}{}", summary.text)));
    }
    if let Some(sys) = &cfg.system_prompt {
        messages.push(ChatMessage::System(sys.clone()));
    }
    messages.push(ChatMessage::System(render_scratchpad_note(
        &cfg.session_name,
    )));
    messages.push(ChatMessage::System(render_tool_batching_note()));
    for record in session.load_records_since_last_summary()? {
        messages.push(record.message);
    }
    Ok(messages)
}

/// Tell the model it may keep working notes under the session's
/// scratchpad directory. The patch tool permits writes there (it is
/// not rejected by the Layer-1 `.attini/` guard), but because the
/// files are not git-tracked those edits still go through the
/// approval prompt, so the note is honest about that rather than
/// promising an auto-approve free zone.
fn render_scratchpad_note(session_name: &str) -> String {
    format!(
        "# Working notes\n\n\
         You may keep working notes / scratchpad files under \
         `.attini/{session_name}/scratchpad/` (relative to the workspace root). \
         This per-session directory is not tracked by git and never appears in \
         `git diff`. Use it for checklists, intermediate findings, or step lists \
         that would otherwise clutter the conversation. Because files there are \
         not tracked, `patch` writes are permitted but are shown for approval, \
         like any other non-tracked write.\n"
    )
}

/// Tell the model how to batch tool calls within a single turn so a
/// read-only call is not stranded behind an approval-gated one. When
/// a turn emits a call that needs approval (a `command`, or a `patch`
/// on a non-tracked path), any tool call ordered after it in the same
/// turn is left unanswered and later cancelled by the orphan-repair
/// pass — the model receives no result for it and must reissue it.
/// Emitting approval-gated calls last (or alone) avoids the wasted
/// round trip.
fn render_tool_batching_note() -> String {
    "# Tool call batching\n\n\
     You may emit several tool calls in one turn. However, if any of them \
     requires human approval — a `command`, or a `patch` on a non-tracked \
     path — place it **last** in the turn, or emit it alone. Any tool call \
     ordered after an approval-gated one (including a read-only `read`, \
     `search`, or `list`) is left unanswered and cancelled on resume, so \
     you would have to reissue it. Read-only calls may be freely batched \
     together, and may precede an approval-gated call; just do not put \
     them after one.\n"
        .to_string()
}

// -------------------------------------------------------------------
// Compaction: summarise older records and append a `summary` record
// -------------------------------------------------------------------

const SUMMARIZER_SYSTEM_PROMPT: &str = "You are summarizing a conversation between a user and a coding agent \
so the agent can continue with a shorter context. Preserve:\n\
\n\
- Unfinished tasks and any next steps the user or agent laid out\n\
- Decisions reached (chosen approaches; rejected alternatives with the reason)\n\
- File paths and key symbols (functions, types) that were read, modified,\n\
  or discussed\n\
- Recent errors and their root cause, if any\n\
\n\
Aim for ~500 words of plain prose. Do not include markdown code fences \
unless quoting a short critical excerpt. Do not comment on the \
summarization itself; produce only the summary.";

/// Decide whether to auto-compact before a `Prompt` invocation.
///
/// Returns `true` when at least one of two independent signals says
/// the real history is too large:
///   * the last successful turn recorded `>= COMPACTION_TRIGGER_TOKENS`
///     prompt tokens (`latest`);
///   * the raw character size of the real records since the last
///     summary (`total_chars`) exceeds `RECORDS_TOTAL_MAX_CHARS`.
///
/// The second signal matters when the previous turn suspended before
/// recording its `token_usage`: `latest` is then stale/small, but the
/// actual records (e.g. a huge tool result) are still enormous and
/// would overflow the next main call.
fn should_auto_compact(latest: u64, total_chars: usize) -> bool {
    latest >= COMPACTION_TRIGGER_TOKENS || total_chars > RECORDS_TOTAL_MAX_CHARS
}

fn try_auto_compact(
    session: &mut Session,
    model: &str,
    counters: &mut Counters,
    max_tokens: Option<u64>,
) -> io::Result<()> {
    if session.load_pending()?.is_some() {
        return Ok(());
    }
    // Physical pruning is independent of summarisation: it fires purely
    // on file size, so it must be checked even when the records since
    // the last summary are already small. It runs while the session
    // LOCK is held, so the log is only rewritten by its owner.
    if let Err(e) = maybe_prune_conversation(session) {
        eprintln!("[prune] skipped: {e}");
    }
    // Judge the need to compact from two independent signals:
    //   * the token threshold, which reflects the *last successful* turn;
    //   * the raw size of the real records since the last summary, which
    //     stays accurate even when that turn suspended before recording
    //     `token_usage` (leaving a huge tool result behind but a stale,
    //     small `latest`).
    let latest = session.latest_prompt_tokens()?.unwrap_or(0);
    let total_chars = if latest < COMPACTION_TRIGGER_TOKENS {
        let records = session.load_records_since_last_summary()?;
        records
            .iter()
            .map(|r| message_raw_char_len(&r.message) + 1)
            .sum::<usize>()
    } else {
        0
    };
    if !should_auto_compact(latest, total_chars) {
        return Ok(());
    }
    if latest < COMPACTION_TRIGGER_TOKENS {
        eprintln!(
            "[compaction] previous prompt was {latest} tokens (below threshold) but records are \
             {total_chars} chars, summarising..."
        );
    } else {
        eprintln!(
            "[compaction] previous prompt was {latest} tokens (threshold {COMPACTION_TRIGGER_TOKENS}), summarising..."
        );
    }
    counters.compaction_attempts += 1;
    if let Err(e) = compact_conversation(session, model, max_tokens) {
        counters.compaction_failures += 1;
        eprintln!("[compaction] failed, continuing with full history: {e}");
    }
    Ok(())
}

/// Run one compaction pass against `session`. Reads real records
/// since the last summary, picks a safe cutoff so no
/// `assistant -> tool` pair is split, sends the older records to
/// the summarizer, and appends a `SessionRecord::Summary`.
///
/// Called by the auto-compaction path (`try_auto_compact`). Callers are
/// expected to have already checked that the session is idle (no LOCK
/// holder, no `pending.json`).
pub fn compact_conversation(
    session: &mut Session,
    model: &str,
    max_tokens: Option<u64>,
) -> io::Result<()> {
    let records = session.load_records_since_last_summary()?;
    let Some(keep_start) = compaction_cutoff(
        &records,
        KEEP_RECENT_RECORDS_TARGET,
        RETAINED_TAIL_MAX_CHARS,
    ) else {
        eprintln!("[compaction] no records eligible for summarisation. skipping.");
        return Ok(());
    };
    let to_summarise: Vec<ChatMessageWithTs> = if keep_start == records.len() {
        // Folding every record; the retained tail is empty so the
        // summary alone becomes the history for the next call.
        records.clone()
    } else {
        records[..keep_start].to_vec()
    };
    let record_count = to_summarise.len();
    let since_ts = to_summarise
        .first()
        .map(|r| r.ts)
        .expect("to_summarise is non-empty");
    let cutoff_ts = to_summarise
        .last()
        .map(|r| r.ts)
        .expect("to_summarise is non-empty");

    let text = run_summariser(model, to_summarise, max_tokens)?;
    let words = text.split_whitespace().count();

    session.append(&SessionRecord::Summary {
        ts: now_unix_millis(),
        since_ts,
        cutoff_ts,
        text,
    })?;
    eprintln!("[compaction] applied. summarised {record_count} records into ~{words} words.");
    Ok(())
}

/// Automatic physical pruning: when `conversation.jsonl` has grown past
/// [`CONVERSATION_PRUNE_TRIGGER_BYTES`], drop every record before the
/// first safe boundary at or after the byte midpoint, roughly halving
/// the file. There is no manual `prune` command; this is the only path.
///
/// Called from `try_auto_compact` while the session `LOCK` is held, so
/// the log is only ever rewritten by the process that owns the session.
/// Returns `Ok(None)` when the file is under the threshold or no safe
/// boundary exists past the midpoint (in which case the file is left
/// untouched rather than split a pair).
fn maybe_prune_conversation(session: &Session) -> io::Result<Option<PruneStats>> {
    let path = session.conversation_path();
    let orig_size = match std::fs::metadata(path) {
        Ok(m) => m.len(),
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    if orig_size <= CONVERSATION_PRUNE_TRIGGER_BYTES {
        return Ok(None);
    }
    let Some((offset, dropped)) = prune_offset_past_midpoint(path, orig_size)? else {
        return Ok(None);
    };
    if offset == 0 {
        return Ok(None);
    }
    rewrite_file_from_offset(path, offset)?;
    let new_size = std::fs::metadata(path)?.len();
    eprintln!(
        "[prune] dropped {dropped} records, {orig_size} -> {new_size} bytes (file crossed \
         {CONVERSATION_PRUNE_TRIGGER_BYTES} bytes)"
    );
    Ok(Some(PruneStats {
        dropped_records: dropped,
        orig_size,
        new_size,
    }))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PruneStats {
    dropped_records: u64,
    orig_size: u64,
    new_size: u64,
}

/// Scan `conversation.jsonl` and return the byte offset of the first
/// *safe* record boundary at or after `orig_size / 2`, together with
/// the number of records strictly before it.
///
/// A safe boundary is a line whose message is a User record or an
/// Assistant record without pending `tool_calls` (see
/// [`is_safe_boundary`]); cutting there never separates an
/// `assistant -> tool` pair. Returns `Ok(None)` when no such boundary
/// exists at or after the midpoint (the whole tail is one unresolved
/// pair), so the caller leaves the file alone.
fn prune_offset_past_midpoint(
    path: &std::path::Path,
    orig_size: u64,
) -> io::Result<Option<(u64, u64)>> {
    use std::io::BufRead;
    let file = std::fs::File::open(path)?;
    let mut reader = std::io::BufReader::new(file);
    let midpoint = orig_size / 2;
    let mut offset: u64 = 0;
    let mut line_index: u64 = 0;
    let mut line = String::new();
    loop {
        line.clear();
        let start = offset;
        let read_bytes = reader.read_line(&mut line)?;
        if read_bytes == 0 {
            break;
        }
        offset += read_bytes as u64;
        if !line.trim().is_empty() {
            if start >= midpoint && line_is_safe_boundary(&line) {
                return Ok(Some((start, line_index)));
            }
            line_index += 1;
        }
    }
    Ok(None)
}

/// Whether a raw conversation line is a safe prune boundary: it parses
/// as a `user` record, or as an `assistant` record whose `tool_calls`
/// are empty. Anything else (`tool`, an assistant turn awaiting tools,
/// a non-message record) is unsafe to cut at.
fn line_is_safe_boundary(line: &str) -> bool {
    let json = match RawJson::parse(line) {
        Ok(j) => j,
        Err(_) => return false,
    };
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str());
    match kind {
        Ok(ref k) if k.as_ref() == "user" => true,
        Ok(ref k) if k.as_ref() == "assistant" => {
            // Safe when it carries non-empty `text` (a final answer).
            let has_text = value
                .to_member("text")
                .and_then(|m| m.required())
                .ok()
                .and_then(|t| t.to_unquoted_string_str().ok())
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false);
            if has_text {
                return true;
            }
            // Otherwise safe only when it carries no pending tool calls.
            let has_calls = value
                .to_member("tool_calls")
                .and_then(|m| m.required())
                .ok()
                .and_then(|tc| tc.to_array().ok())
                .map(|mut a| a.next().is_some())
                .unwrap_or(false);
            !has_calls
        }
        _ => false,
    }
}

/// Copy the suffix of `path` starting at `offset` over the whole file,
/// via a tmp file + rename so a crash mid-write cannot truncate the
/// conversation.
fn rewrite_file_from_offset(path: &std::path::Path, offset: u64) -> io::Result<()> {
    use std::io::{Read, Seek, SeekFrom};
    let mut file = std::fs::File::open(path)?;
    file.seek(SeekFrom::Start(offset))?;
    let mut buf = Vec::new();
    file.read_to_end(&mut buf)?;
    drop(file);

    let tmp = path.with_extension("jsonl.prune-tmp");
    let _ = std::fs::remove_file(&tmp);
    {
        let mut out = std::fs::File::create(&tmp)?;
        out.write_all(&buf)?;
        out.sync_all()?;
    }
    std::fs::rename(&tmp, path)
}

const ASK_SYSTEM_PROMPT: &str = "You are an OUTSIDE observer reading a recording of a \
coding-agent session. You are NOT the coding assistant and you are NOT continuing \
its work: do not emit tool calls, do not write plan steps, do not pick up an \
unfinished action, do not reproduce the session's agentic wording. Read the session \
transcript below (rendered as plain prose; tool calls and results are abbreviated) \
and answer directly and concisely about what is happening now: unfinished work, \
decisions, files/symbols in play, and any tool call awaiting approval. If a question \
is appended, answer that question specifically. Otherwise produce a short status \
summary (~300 words) of the current state, in third person. Never begin with an \
action verb such as 'I will / I am going to / let's'. Do not comment on the \
instruction itself; produce only the answer. Answer in the same language the session \
transcript is written in (if the transcript mixes languages, use its dominant \
language), even when no question is appended. A prior observer answer may be included \
    below as context: treat it as a hint only and always let the transcript below \
    override it.";

/// Abbreviate JSON tool arguments to a short single-line prefix so the
/// prose transcript stays readable and does not invite the model to
/// reproduce the raw agentic tool-call format.
fn abbreviate_args(args_json: &str) -> String {
    let t = args_json.trim();
    if t.is_empty() {
        return String::new();
    }
    let mut cleaned = String::new();
    for c in t.chars().take(90) {
        cleaned.push(if c == '\n' { ' ' } else { c });
    }
    if t.chars().count() > 90 {
        cleaned.push('…');
    }
    cleaned
}

/// Render conversation records as a plain third-person prose transcript
/// with tool calls and results abbreviated. This deliberately strips the
/// raw `tool_calls`/`tool` JSON and any `<invoke>`-style XML so a
/// summariser model does not imitate the coding-agent's tool-calling
/// format and instead behaves as an outside observer.
fn render_records_prose(records: &[ChatMessageWithTs]) -> String {
    let mut out = String::new();
    for rec in records {
        match &rec.message {
            ChatMessage::System(s) => out.push_str(&format!("[system] {}\n", s.trim())),
            ChatMessage::User(s) => out.push_str(&format!("user: {}\n", s.trim())),
            ChatMessage::Assistant {
                content,
                tool_calls,
                ..
            } => {
                let c = content.trim();
                let mut lines = Vec::new();
                if !c.is_empty() {
                    lines.push(c.to_string());
                }
                for tc in tool_calls {
                    let a = abbreviate_args(&tc.arguments_json);
                    if a.is_empty() {
                        lines.push(format!("  [tool call: {}]", tc.function_name));
                    } else {
                        lines.push(format!("  [tool call: {} ({})]", tc.function_name, a));
                    }
                }
                if !lines.is_empty() {
                    out.push_str(&format!("assistant: {}\n", lines.join("\n")));
                }
            }
            ChatMessage::Tool { content, .. } => {
                let t = content.trim();
                let brief = if t.is_empty() {
                    String::new()
                } else {
                    let mut s = String::new();
                    for c in t.chars().take(200) {
                        s.push(c);
                    }
                    if t.chars().count() > 200 {
                        s.push('…');
                    }
                    s
                };
                out.push_str(&format!("  [tool result: {}]\n", brief));
            }
        }
        out.push('\n');
    }
    out
}

/// Truncate a prose segment to `max_chars` characters, keeping the
/// head and appending a marker that notes how many were dropped.
fn truncate_prose(s: &str, max_chars: usize) -> String {
    let count = s.chars().count();
    if count <= max_chars {
        return s.to_string();
    }
    let head: String = s.chars().take(max_chars).collect();
    format!("{head}…[truncated {} chars]", count - max_chars)
}

/// Render a single record into a bounded prose block for the
/// summariser. Assistant/user content is capped, tool-call arguments
/// are abbreviated, and tool results are truncated to a short line, so
/// an enormous conversation (huge tool results) never blows up the
/// summariser request.
fn render_summary_block(rec: &ChatMessageWithTs) -> String {
    match &rec.message {
        ChatMessage::System(s) => format!(
            "[system] {}\n",
            truncate_prose(s.trim(), SUMMARY_RECORD_MAX_CHARS)
        ),
        ChatMessage::User(s) => format!(
            "user: {}\n",
            truncate_prose(s.trim(), SUMMARY_RECORD_MAX_CHARS)
        ),
        ChatMessage::Assistant {
            content,
            tool_calls,
            ..
        } => {
            let mut lines = Vec::new();
            let c = content.trim();
            if !c.is_empty() {
                lines.push(truncate_prose(c, SUMMARY_RECORD_MAX_CHARS));
            }
            for tc in tool_calls {
                let a = abbreviate_args(&tc.arguments_json);
                if a.is_empty() {
                    lines.push(format!("  [tool call: {}]", tc.function_name));
                } else {
                    lines.push(format!("  [tool call: {} ({})]", tc.function_name, a));
                }
            }
            if lines.is_empty() {
                String::new()
            } else {
                format!("assistant: {}\n", lines.join("\n"))
            }
        }
        ChatMessage::Tool { content, .. } => {
            let t = content.trim();
            let brief = truncate_prose(t, SUMMARY_TOOL_RESULT_MAX_CHARS);
            format!("  [tool result: {}]\n", brief)
        }
    }
}

/// Render conversation records into a bounded prose transcript for the
/// summariser. Each record is rendered into a small bounded block, and
/// the blocks are kept newest-first until the total reaches
/// [`SUMMARY_MAX_CHARS`]; older blocks are dropped. When anything is
/// dropped a note is prepended so the resulting summary reflects the
/// most recent state.
fn render_summary_transcript(records: &[ChatMessageWithTs]) -> String {
    let blocks: Vec<String> = records.iter().map(render_summary_block).collect();
    let mut kept: Vec<String> = Vec::new();
    let mut total = 0usize;
    let mut dropped_oldest = false;
    for block in blocks.iter().rev() {
        let len = block.chars().count();
        if total + len > SUMMARY_MAX_CHARS {
            dropped_oldest = true;
            break;
        }
        kept.push(block.clone());
        total += len;
    }
    let mut out = String::new();
    if dropped_oldest {
        out.push_str(
            "[Note: the earliest records of this segment were dropped to fit the \
             summariser's context window; the transcript below is the most recent \
             portion, so the summary should reflect the current state.]\n\n",
        );
    }
    for block in kept.into_iter().rev() {
        out.push_str(&block);
        out.push('\n');
    }
    out
}

fn call_summariser_messages(
    model: &str,
    messages: Vec<ChatMessage>,
    max_tokens: Option<u64>,
) -> io::Result<String> {
    let request = ChatRequest::new(model.to_string(), messages).with_max_tokens(max_tokens);
    let mut sink = io::sink();
    let mut sinks = ProgressSinks { content: &mut sink };
    let result = curl::call(&request, &mut sinks)
        .map_err(|e| io::Error::other(format!("summariser call failed: {e}")))?;
    pick_summary_text(&result).ok_or_else(|| io::Error::other("summariser returned empty content"))
}

fn run_summariser(
    model: &str,
    records: Vec<ChatMessageWithTs>,
    max_tokens: Option<u64>,
) -> io::Result<String> {
    // Render the records as a bounded prose transcript rather than
    // sending the raw ChatMessages. Raw messages include the full
    // tool-result JSON, which can be enormous and push the request
    // past the model context window so compaction fails and the
    // invocation later fails too. The prose form preserves the
    // semantic thread (assistant conclusions, decisions, file/symbol
    // mentions) while keeping each tool result to a short line.
    let transcript = render_summary_transcript(&records);
    let messages = vec![
        ChatMessage::System(SUMMARIZER_SYSTEM_PROMPT.to_string()),
        ChatMessage::User(transcript),
    ];
    call_summariser_messages(model, messages, max_tokens)
}

/// Read-only model summarisation used by `attini ask`. Unlike
/// `run_summariser` this never persists anything; it just answers a
/// (optional) question about the current session state.
pub(crate) fn run_ask_summary(
    records: Vec<ChatMessageWithTs>,
    model: &str,
    question: Option<&str>,
    prior: Option<&str>,
    max_tokens: Option<u64>,
) -> io::Result<String> {
    let mut system = ASK_SYSTEM_PROMPT.to_string();
    if let Some(p) = prior {
        system.push_str(
            "\n\n--- PREVIOUS ask context (an EARLIER observer answer; it is a HINT, not \
             ground truth \u{2014} the transcript below is authoritative) ---\n\n",
        );
        system.push_str(p);
        system.push_str("\n\n--- END PREVIOUS ask context ---\n");
    }
    if let Some(q) = question {
        system.push_str("\n\nThe user's question is: ");
        system.push_str(q);
        system.push('\n');
    }
    system.push_str("\n\n--- BEGIN SESSION TRANSCRIPT (prose) ---\n\n");
    system.push_str(&render_records_prose(&records));
    system.push_str("\n--- END SESSION TRANSCRIPT ---\n");
    call_summariser_messages(model, vec![ChatMessage::System(system)], max_tokens)
}

/// Pick a usable summary from a [`CallResult`]: the assistant text.
/// Returns `None` for an empty (or whitespace-only) response so the
/// caller can surface a clear error rather than persisting a blank
/// summary.
fn pick_summary_text(result: &curl::CallResult) -> Option<String> {
    let content = result.content.trim();
    if content.is_empty() {
        return None;
    }
    Some(content.to_string())
}

/// Given the real records that follow the last summary, return
/// the index from which the tail is kept intact. Records at
/// smaller indices are candidates for the new summary.
///
/// The cutoff never falls inside an `assistant -> tool` pair: it
/// snaps toward the tail until it lands on a User record or an
/// Assistant record without `tool_calls`. Returns `records.len()`
/// (kept = nothing) if no safe boundary exists past the initial
/// target — which happens when the tail is a single unresolved
/// `assistant -> tool` pair, in which case leaving everything as
/// candidates would still be wrong, so we bail and keep the whole
/// tail by returning 0 as well.
fn safe_tail_start(records: &[ChatMessageWithTs], target_keep: usize) -> usize {
    let n = records.len();
    if n <= target_keep {
        return 0;
    }
    let mut i = n - target_keep;
    while i < n {
        if is_safe_boundary(&records[i].message) {
            return i;
        }
        i += 1;
    }
    // No safe boundary in the tail — refuse to summarise anything
    // this round rather than emit an orphan tool message.
    0
}

fn is_safe_boundary(msg: &ChatMessage) -> bool {
    match msg {
        ChatMessage::User(_) => true,
        ChatMessage::Assistant { tool_calls, .. } => tool_calls.is_empty(),
        _ => false,
    }
}

/// Rough byte length of a message's payload. Used purely as an
/// order-of-magnitude heuristic for the retained-tail budget; an
/// ASCII-heavy tool result's bytes closely track its token count.
fn message_raw_char_len(msg: &ChatMessage) -> usize {
    match msg {
        ChatMessage::System(s) => s.len(),
        ChatMessage::User(s) => s.len(),
        ChatMessage::Assistant {
            content,
            tool_calls,
        } => {
            content.len()
                + tool_calls
                    .iter()
                    .map(|tc| tc.function_name.len() + tc.arguments_json.len())
                    .sum::<usize>()
        }
        ChatMessage::Tool { content, .. } => content.len(),
    }
}

/// Choose the compaction cutoff, returning `None` when there is
/// nothing to compact (too few records) and `Some(keep_start)`
/// otherwise. `keep_start` is the index where the retained tail
/// begins; `Some(n)` (the record count) means fold every record into
/// the summary, leaving an empty retained tail.
///
/// Beyond the record-count target in [`safe_tail_start`], the cutoff
/// is walked **forward** while the retained tail's raw size exceeds
/// `max_tail_chars`. A retained tail that is oversized because of a
/// huge record at the very end (a session suspended right after a
/// giant tool result) cannot be shrunk by folding older records, so
/// the walk folds toward the end and finally folds everything.
fn compaction_cutoff(
    records: &[ChatMessageWithTs],
    target_keep: usize,
    max_tail_chars: usize,
) -> Option<usize> {
    let n = records.len();
    // `safe_tail_start` returns 0 when the history is short (<= target)
    // or when no safe boundary exists in the initial tail. Starting at
    // 0 here means: if the *whole* history already fits the budget, we
    // skip (return None); if it is too large because of one huge record
    // even though there are few records, the loop below walks forward
    // to a safe boundary and folds it -- exactly the trigger hole this
    // guard closes.
    let mut keep_start = safe_tail_start(records, target_keep);
    // If the retained tail cannot fit, fold its oldest part by moving
    // the cutoff toward the end, stopping at a safe boundary so an
    // `assistant -> tool` pair is never split.
    while keep_start < n {
        let tail_chars: usize = records[keep_start..]
            .iter()
            .map(|r| message_raw_char_len(&r.message))
            .sum();
        if tail_chars <= max_tail_chars {
            break;
        }
        let mut next = keep_start + 1;
        while next < n && !is_safe_boundary(&records[next].message) {
            next += 1;
        }
        // `next` may reach `n`, which folds everything.
        keep_start = next;
    }
    if keep_start == 0 {
        // The whole history fits the budget but no safe boundary exists
        // in the initial retained window: nothing to safely fold, so
        // skip compaction rather than summarise the entire conversation.
        return None;
    }
    Some(keep_start)
}

fn build_tool_defs() -> Vec<ToolDef> {
    let mut defs = ReadOnlyTool::definitions();
    defs.push(PatchInvocation::definition());
    defs.push(CommandInvocation::definition());
    defs
}

enum CommandDispatch {
    /// The call needs human approval; carries the parked pending.
    Awaiting(Pending),
    /// The call was handled (or, in `dry_run`, can be skipped).
    Continue,
}

#[expect(
    clippy::too_many_arguments,
    reason = "the dispatcher threads the shared tool-call context (session, messages, counters, \
              rules, executor) through in one call to keep dispatch borrows in one place"
)]
fn dispatch_command(
    tc: &ToolCall,
    executor: &ToolExecutor,
    layers: &[(RuleScope, &[Rule])],
    authorization: &Authorization,
    session: &mut Session,
    messages: &mut Vec<ChatMessage>,
    counters: &mut Counters,
    dry_run: bool,
    timeout: Option<Duration>,
) -> io::Result<CommandDispatch> {
    let inv = match CommandInvocation::parse(&tc.arguments_json) {
        Ok(inv) => inv,
        Err(err) => {
            if !dry_run {
                let msg = err.message();
                let content = tool_error_json("command_args", &msg);
                eprintln!("[command] parse err: {msg}");
                counters.tool_errors += 1;
                append_tool(session, messages, &tc.id, content)?;
            }
            return Ok(CommandDispatch::Continue);
        }
    };
    let judgment = evaluate(layers, &inv.argv, authorization);
    let display = shell_escape_argv(&inv.argv);
    match judgment {
        Judgment::AutoApprove(dec) => {
            if !dry_run {
                let dec_display = shell_escape_argv(&dec.args_prefix);
                eprintln!(
                    "[command] auto-approve via {} rule '{}': {}",
                    dec.scope.as_str(),
                    dec_display,
                    display
                );
                append_auto_approval(session, &tc.id, ApprovalDecision::Approve, &dec)?;
                let content = match run_command_sync(&inv, executor, timeout) {
                    Ok(s) => s,
                    Err(err) => {
                        let (code, msg) = err.to_code_and_message();
                        counters.tool_errors += 1;
                        let payload = tool_error_json(code, &msg);
                        append_tool(session, messages, &tc.id, payload)?;
                        return Ok(CommandDispatch::Continue);
                    }
                };
                append_tool(session, messages, &tc.id, content)?;
            }
            Ok(CommandDispatch::Continue)
        }
        Judgment::AutoDeny(dec) => {
            if !dry_run {
                let dec_display = shell_escape_argv(&dec.args_prefix);
                eprintln!(
                    "[command] auto-deny via {} rule '{}': {}",
                    dec.scope.as_str(),
                    dec_display,
                    display
                );
                append_auto_approval(session, &tc.id, ApprovalDecision::Reject, &dec)?;
                let content = tool_error_json(
                    "denied_by_rule",
                    &format!(
                        "auto-denied by {} rule args_prefix {:?}",
                        dec.scope.as_str(),
                        dec.args_prefix
                    ),
                );
                counters.tool_errors += 1;
                append_tool(session, messages, &tc.id, content)?;
            }
            Ok(CommandDispatch::Continue)
        }
        Judgment::Pending => {
            let preview_text = render_command_preview_from(&inv);
            eprintln!("[command] approval required");
            eprintln!("{preview_text}");
            emit_suggested_rule(&inv.argv);
            Ok(CommandDispatch::Awaiting(build_pending(
                tc,
                PendingToolKind::Command,
                preview_text,
            )))
        }
    }
}

fn append_auto_approval(
    session: &mut Session,
    call_id: &str,
    decision: ApprovalDecision,
    dec: &AutoDecision,
) -> io::Result<()> {
    let sidecar = AutoDecidedBy {
        scope: dec.scope.as_str().to_string(),
        args_prefix: dec.args_prefix.clone(),
        allow: dec.allowed,
        matches: dec
            .matches
            .iter()
            .map(|m| AutoDecidedMatch {
                scope: m.scope.as_str().to_string(),
                kind: m.kind.as_str().to_string(),
                allow: m.allow,
                args_prefix: m.args_prefix.clone(),
                path: m.path.clone(),
                adopted: m.adopted,
            })
            .collect(),
    };
    session.append(&SessionRecord::ToolApproval {
        ts: now_unix_millis(),
        call_id: call_id.to_string(),
        decision,
        auto_decided_by: Some(sidecar),
    })
}

/// Suggest the `attini approve --grant` invocation that would
/// pre-approve the argv-prefix of the pending command. `argv` is
/// truncated to at most two elements (typical pattern: `program
/// subcommand`) so the rule stays a general prefix rather than
/// baking every flag in.
fn emit_suggested_rule(argv: &[String]) {
    let Some(prefix) = grant_prefix(argv) else {
        return;
    };
    let prefix_display = shell_escape_argv(&prefix);
    eprintln!("suggested rule (fold into the next approve):");
    eprintln!("  attini approve --grant session      # allow {prefix_display} (session-local)");
    eprintln!("  attini approve --grant workspace    # allow {prefix_display} (workspace-wide)");
}

/// Truncate an argv to the prefix an auto-approve rule should use: at most
/// two elements (typical pattern: `program subcommand`) so the rule stays a
/// general prefix rather than baking every flag in. Shared by
/// [`emit_suggested_rule`] and `attini approve --grant` so the two can never
/// disagree about what prefix would be written.
fn grant_prefix(argv: &[String]) -> Option<Vec<String>> {
    if argv.is_empty() {
        return None;
    }
    let take = argv.len().min(2);
    Some(argv[..take].to_vec())
}

/// Resolved, not-yet-persisted grant for a single pending call. The
/// variant mirrors the pending tool kind: a command grant persists an
/// argv prefix, a read grant persists a canonical path.
#[derive(Debug)]
enum GrantIntent {
    Command(Vec<String>),
    Read(String),
    Write(String),
}

/// Validate and resolve the `attini approve --grant` request against the
/// pending set, returning the grant to persist (if any).
///
/// A grant that cannot be formed is an error, not a silent no-op: if the
/// pending call(s) are not exactly one grantable call, or the prefix/path
/// cannot be derived, `--grant` is rejected before any approval is
/// recorded. `--grant oneshot` (and no grant at all) never persist
/// anything and therefore never depend on the pending set.
///
/// `attini approve` on a session with no pending call (it stopped at
/// `max_turns`) falls back to a plain continuation, in which case there is
/// nothing to grant: `--grant` is silently ignored there rather than
/// errored, since the human's intent was simply "keep going".
fn plan_grant(
    request: GrantRequest,
    pendings: &[Pending],
    workspace_root: &std::path::Path,
) -> io::Result<Option<GrantIntent>> {
    match request {
        GrantRequest::None | GrantRequest::Oneshot => return Ok(None),
        GrantRequest::Session | GrantRequest::Workspace => {}
    }
    let [pending] = pendings else {
        return Err(io::Error::other(
            "--grant is ambiguous with multiple pending calls; approve one at a time".to_string(),
        ));
    };
    match pending.tool_kind {
        PendingToolKind::Command => {
            let inv = CommandInvocation::parse(&pending.arguments_json).map_err(|e| {
                io::Error::other(format!(
                    "--grant: could not read the pending command: {e:?}"
                ))
            })?;
            match grant_prefix(&inv.argv) {
                Some(prefix) => Ok(Some(GrantIntent::Command(prefix))),
                None => Err(io::Error::other(
                    "--grant: the pending command has no argv to persist".to_string(),
                )),
            }
        }
        PendingToolKind::Read => {
            // Persist the canonical target path, matching the one-shot
            // root the read is executed with, so a later grant-based load
            // resolves the same directory.
            let inv = ReadOnlyTool::parse(&pending.function_name, &pending.arguments_json)
                .map_err(|e| {
                    io::Error::other(format!("--grant: could not read the pending read: {e:?}"))
                })?;
            match read_extra_root(&inv, workspace_root) {
                // Persist an in-workspace target as a workspace-relative
                // path (the shape a human writes by hand). Out-of-workspace
                // targets keep the absolute canonical path, which the
                // executor accepts as a root.
                Some(path) => Ok(Some(GrantIntent::Read(grant_read_path(
                    &path,
                    workspace_root,
                )))),
                None => Err(io::Error::other(
                    "--grant: the pending read has no resolvable path to persist".to_string(),
                )),
            }
        }
        PendingToolKind::Patch => {
            let inv = PatchInvocation::parse(&pending.arguments_json).map_err(|e| {
                io::Error::other(format!("--grant: could not read the pending patch: {e:?}"))
            })?;
            // A patch may target several paths; a single `--grant`
            // can only persist one `write` rule, so require exactly one
            // target path (the common case). `PatchInvocation::parse`
            // already guarantees the paths are distinct.
            let [edit] = inv.edits.as_slice() else {
                return Err(io::Error::other(
                    "--grant is ambiguous for a patch touching multiple paths; approve one at a time"
                        .to_string(),
                ));
            };
            let target = edit.path();
            // Persist an in-workspace target as a workspace-relative
            // path, the same shape the `write` rules are evaluated
            // against (`workspace_relative_write_target`), so a grant
            // and a deny rule compare like-for-like under
            // last-match-wins. Out-of-workspace or non-existent targets
            // fall back to the raw path, which the executor rejects
            // anyway.
            match workspace_relative_write_target(target, workspace_root) {
                Some(rel) => Ok(Some(GrantIntent::Write(rel))),
                None => Ok(Some(GrantIntent::Write((*target).to_string()))),
            }
        }
    }
}

/// Best-effort persistence of the resolved grant, run after every pending
/// call has been approved. The approval already stands, so any failure is
/// reported as a one-line warning rather than rolling the approval back.
fn apply_grant(cfg: &TellConfig, intent: &GrantIntent) {
    let scope = match cfg.grant_request {
        GrantRequest::Session => permissions::GrantScope::Session(&cfg.session_name),
        GrantRequest::Workspace => permissions::GrantScope::Workspace,
        GrantRequest::None | GrantRequest::Oneshot => return,
    };
    let outcome = match intent {
        GrantIntent::Command(argv_prefix) => permissions::grant(scope, argv_prefix),
        GrantIntent::Read(path) => permissions::grant_read(scope, path),
        GrantIntent::Write(path) => permissions::grant_write(scope, path),
    };
    let display = match intent {
        GrantIntent::Command(argv_prefix) => shell_escape_argv(argv_prefix),
        GrantIntent::Read(path) => path.clone(),
        GrantIntent::Write(path) => path.clone(),
    };
    match outcome {
        Ok(permissions::GrantOutcome::Appended(path)) => {
            eprintln!(
                "[approve] granted: appended '{display}' to {}",
                path.display()
            );
        }
        Ok(permissions::GrantOutcome::AlreadyGranted(path)) => {
            eprintln!("[approve] already granted (no-op): {}", path.display());
        }
        Err(e) => {
            eprintln!("[approve] warning: grant of '{display}' failed: {e}; approval still stands");
        }
    }
}

/// Unconditionally wrap `s` in POSIX single-quotes, escaping any
/// interior single-quotes with the `'\\''` sequence. Used by
/// [`shell_escape_argv`] as the quoting primitive.
pub(crate) fn shell_single_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        if c == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(c);
        }
    }
    out.push('\'');
    out
}

/// Format an argv slice as a shell-escaped single-line command for
/// human display (preview text, suggested-rule hint, log lines).
/// Simple tokens are emitted raw; empty strings and tokens
/// containing whitespace or POSIX shell metacharacters are
/// single-quoted. The output is not eval-safe in every corner but is
/// unambiguous for the argv patterns coding agents typically
/// produce.
fn shell_escape_argv(argv: &[String]) -> String {
    argv.iter()
        .map(|s| {
            if s.is_empty() || s.chars().any(needs_shell_quote) {
                shell_single_quote(s)
            } else {
                s.clone()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn needs_shell_quote(c: char) -> bool {
    matches!(
        c,
        ' ' | '\t'
            | '\n'
            | '|'
            | '&'
            | ';'
            | '('
            | ')'
            | '$'
            | '`'
            | '>'
            | '<'
            | '\\'
            | '"'
            | '\''
            | '*'
            | '?'
            | '['
            | ']'
            | '{'
            | '}'
            | '!'
            | '#'
            | '~'
            | '='
    )
}

fn render_command_preview_from(inv: &CommandInvocation) -> String {
    format!("command preview: {}", shell_escape_argv(&inv.argv))
}

enum ToolKind {
    ReadOnly,
    Patch,
    Command,
    Unknown,
}

fn classify(name: &str) -> ToolKind {
    match name {
        "list" | "read" | "search" => ToolKind::ReadOnly,
        "patch" => ToolKind::Patch,
        "command" => ToolKind::Command,
        _ => ToolKind::Unknown,
    }
}

/// Outcome of handling one read-only tool call.
enum ReadOnlyDispatch {
    /// Answered inline; `errored` is `true` iff `content` is a
    /// `tool_error_json` payload (parse failure or executor error) so the
    /// caller can update `Counters::tool_errors` without re-parsing.
    Done {
        summary: String,
        content: String,
        errored: bool,
    },
    /// The call targeted a path outside the workspace; park it for human
    /// approval instead of answering with an error. Carries the display
    /// line shown to the human and the preview stored in `pending.json`.
    NeedsApproval { summary: String, preview: String },
}

/// Returns the dispatch result for one read-only tool call. `errored`
/// in the `Done` case is `true` iff the returned content is a
/// `tool_error_json` payload.
///
/// `read` rules only widen the executor's roots (they are allow-only),
/// so there is no permission gate here: a read either lands inside a
/// known root or falls out of the workspace and is parked for one-shot
/// approval.
fn run_read_only(tc: &ToolCall, executor: &ToolExecutor) -> ReadOnlyDispatch {
    match ReadOnlyTool::parse(&tc.function_name, &tc.arguments_json) {
        Ok(inv) => {
            let args_summary = summarize_read_only(&inv);
            match executor.execute(inv.clone()) {
                ToolOutcome::Ok(payload) => {
                    let mut summary = format!("[{args_summary}] ok");
                    // Echo the head of a `read` result to stderr so a
                    // human can see what was read without opening the
                    // file. Display only: the payload sent to the model
                    // is unchanged.
                    if let Some(preview) = read_content_preview(&payload) {
                        summary.push('\n');
                        summary.push_str(&preview);
                    }
                    ReadOnlyDispatch::Done {
                        summary,
                        content: payload,
                        errored: false,
                    }
                }
                // Outside the workspace: this is the one read error we can
                // turn into an approval request. Both the workspace and any
                // granted roots were tried; offer the human the chance to
                // widen the boundary for this single call. `inv` is reused
                // (cloned) by `execute_pending` on approval.
                ToolOutcome::Err(ToolExecutionError::OutsideWorkspace) => {
                    let preview = format!(r#"{args_summary} (outside workspace)"#);
                    ReadOnlyDispatch::NeedsApproval {
                        summary: format!("[{args_summary}] approval required"),
                        preview,
                    }
                }
                ToolOutcome::Err(err) => ReadOnlyDispatch::Done {
                    summary: format!("[{args_summary}] err: {}", err.message()),
                    content: tool_error_json_from(&err),
                    errored: true,
                },
            }
        }
        Err(err) => ReadOnlyDispatch::Done {
            summary: format!("[{}] parse err: {}", tc.function_name, err.message()),
            content: tool_error_json_from(&err),
            errored: true,
        },
    }
}

/// Path a read-only invocation targets, for the purpose of deriving a
/// one-shot extra read root after approval. `read`/`list` use their
/// `path`; `search` uses its `path_prefix` when present (`None` means
/// the workspace root, which never needs approval).
fn read_only_target(inv: &ReadOnlyTool) -> Option<&str> {
    match inv {
        ReadOnlyTool::List { path, .. } => Some(path),
        ReadOnlyTool::Read { path, .. } => Some(path),
        ReadOnlyTool::Search { path_prefix, .. } => path_prefix.as_deref(),
    }
}

/// The path to persist in a `read` rule for a granted read.
///
/// Inside the workspace, the rule is stored workspace-relative (e.g.
/// `secret_dir/secret.txt`) because that is the shape a human writes by
/// hand. Outside the workspace, the absolute canonical path is kept,
/// since the executor accepts it as a root and there is no
/// workspace-relative form.
fn grant_read_path(canonical: &Path, workspace_root: &Path) -> String {
    let root = workspace_root
        .canonicalize()
        .unwrap_or_else(|_| workspace_root.to_path_buf());
    match canonical.strip_prefix(&root) {
        Ok(rel) => rel.to_string_lossy().into_owned(),
        Err(_) => canonical.display().to_string(),
    }
}

/// Resolve the approved read target to an absolute canonical path to be
/// used as a one-shot extra read root. Relative targets resolve against
/// `workspace_root`, matching [`resolve_within_any`]'s semantics. Returns
/// `None` when there is no target or it does not exist on disk.
fn read_extra_root(inv: &ReadOnlyTool, workspace_root: &Path) -> Option<PathBuf> {
    let target = read_only_target(inv)?;
    let candidate = if std::path::Path::new(target).is_absolute() {
        PathBuf::from(target)
    } else {
        workspace_root.join(target)
    };
    candidate.canonicalize().ok()
}

/// Aggregate verdict of the `write` rules over every edit in a patch.
#[derive(Clone, Copy, PartialEq, Eq)]
enum WriteVerdict {
    /// Every edit is allowed by a winning `write` `allow:true` rule.
    Allowed,
    /// At least one edit is denied by a winning `write` `allow:false`
    /// rule. Denial wins over anything else.
    Denied,
    /// No edit is denied, but at least one is not covered by an
    /// allow rule, so fall back to the git-tracking heuristic.
    Undecided,
}

/// Evaluate every edit in `inv` against the `write` rules. A single
/// denied edit denies the whole patch; otherwise the patch is allowed
/// only when every edit is covered by a winning `allow:true` rule.
fn patch_write_verdict(
    inv: &PatchInvocation,
    permission_layers: &[(RuleScope, &[Rule])],
    authorization: &Authorization,
    workspace_root: &Path,
) -> WriteVerdict {
    let mut all_allowed = true;
    for edit in &inv.edits {
        // In-workspace targets are compared as workspace-relative
        // paths; outside-workspace targets as absolute canonical
        // paths, mirroring how the executor's Layer 3 evaluates them
        // and how `--grant` persists an outside rule.
        let target = match workspace_relative_write_target(edit.path(), workspace_root) {
            Some(rel) => PathBuf::from(rel),
            None => match canonical_write_target(edit.path(), workspace_root) {
                Some(abs) => abs,
                // A path that does not canonicalise cannot be covered
                // by any rule; fall back to the git-tracking heuristic.
                None => {
                    all_allowed = false;
                    continue;
                }
            },
        };
        match evaluate_write(permission_layers, &target, authorization) {
            Judgment::AutoDeny(_) => return WriteVerdict::Denied,
            Judgment::AutoApprove(_) => {}
            Judgment::Pending => all_allowed = false,
        }
    }
    if all_allowed {
        WriteVerdict::Allowed
    } else {
        WriteVerdict::Undecided
    }
}

/// Reduce a patch edit's target path to the workspace-relative form a
/// `write` rule is compared against. Returns `None` when the path
/// escapes the workspace or cannot be canonicalised.
fn workspace_relative_write_target(target: &str, workspace_root: &Path) -> Option<String> {
    let candidate = if Path::new(target).is_absolute() {
        PathBuf::from(target)
    } else {
        workspace_root.join(target)
    };
    let canon = candidate.canonicalize().ok()?;
    let root = workspace_root.canonicalize().ok()?;
    let rel = canon.strip_prefix(&root).ok()?;
    Some(rel.to_string_lossy().into_owned())
}

/// Canonical absolute form of a patch edit's target, used to compare an
/// outside-workspace target against `write` rules (which are written as
/// absolute paths for outside targets, mirroring `read` rules). Returns
/// `None` when the path does not exist on disk and cannot be
/// canonicalised.
fn canonical_write_target(target: &str, workspace_root: &Path) -> Option<PathBuf> {
    let candidate = if Path::new(target).is_absolute() {
        PathBuf::from(target)
    } else {
        workspace_root.join(target)
    };
    candidate.canonicalize().ok()
}

fn summarize_read_only(inv: &ReadOnlyTool) -> String {
    match inv {
        ReadOnlyTool::List {
            path, recursive, ..
        } => {
            if *recursive {
                format!(r#"list "{path}" recursive"#)
            } else {
                format!(r#"list "{path}""#)
            }
        }
        ReadOnlyTool::Read { path, line_range } => match line_range {
            Some((start, end)) => format!(r#"read "{path}" lines {start}..{end}"#),
            None => format!(r#"read "{path}""#),
        },
        ReadOnlyTool::Search {
            pattern,
            path_prefix,
            ..
        } => match path_prefix {
            Some(prefix) => format!(r#"search "{pattern}" in "{prefix}""#),
            None => format!(r#"search "{pattern}""#),
        },
    }
}

/// Render the head of a `read` result's `content` for stderr,
/// capped at [`READ_PREVIEW_MAX_LINES`] lines with a
/// `... (N more lines omitted)` marker. Returns `None` when the
/// payload is not a readable object with a string `content` member
/// (e.g. a `list` or `search` result), so callers can append it
/// unconditionally. Never fails: display is best-effort.
fn read_content_preview(payload: &str) -> Option<String> {
    let json = RawJson::parse(payload).ok()?;
    let content = json
        .value()
        .to_member("content")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .ok()?;
    let mut out = String::new();
    let mut shown: usize = 0;
    let mut omitted: usize = 0;
    for line in content.lines() {
        if shown < READ_PREVIEW_MAX_LINES {
            out.push_str("  | ");
            out.push_str(line);
            out.push('\n');
            shown += 1;
        } else {
            omitted += 1;
        }
    }
    if omitted > 0 {
        out.push_str(&format!("  | ... ({omitted} more lines omitted)\n"));
    }
    // Trim the trailing newline so the caller controls spacing.
    while out.ends_with('\n') {
        out.pop();
    }
    if out.is_empty() { None } else { Some(out) }
}

enum PatchDispatch {
    /// The call needs human approval; carries the parked pending.
    Awaiting(Pending),
    /// The call was handled (or, in `dry_run`, can be skipped).
    Continue,
}

/// Dispatch a patch tool call outside an approved-plan run.
///
/// Edits on git-tracked files are auto-applied immediately (git makes
/// them revertible, so no human prompt is needed). Any other edit
/// (a new file, a scratchpad / non-tracked target) parks a pending
/// approval and returns [`PatchDispatch::Awaiting`] so the caller
/// suspends the invocation.
///
/// When `dry_run` is `true` (a later sibling already needs approval)
/// the working tree is never mutated: auto-approved edits are
/// skipped and preview errors are not appended. The caller still
/// receives `Awaiting(Pending)` for edits that need a human.
#[expect(
    clippy::too_many_arguments,
    reason = "the dispatcher threads the shared tool-call context (session, messages, counters, \
              rules, executor) through in one call to keep dispatch borrows in one place"
)]
fn dispatch_patch_unapproved(
    tc: &ToolCall,
    executor: &ToolExecutor,
    permission_layers: &[(RuleScope, &[Rule])],
    authorization: &Authorization,
    session: &mut Session,
    messages: &mut Vec<ChatMessage>,
    counters: &mut Counters,
    dry_run: bool,
) -> io::Result<PatchDispatch> {
    let inv = match PatchInvocation::parse(&tc.arguments_json) {
        Ok(inv) => inv,
        Err(err) => {
            if !dry_run {
                let msg = err.message();
                let content = tool_error_json("patch_args", &msg);
                eprintln!("[patch] parse err: {msg}");
                counters.tool_errors += 1;
                append_tool(session, messages, &tc.id, content)?;
            }
            return Ok(PatchDispatch::Continue);
        }
    };
    let (preview_content, preview) = match executor.preview_patch(&inv) {
        Ok(x) => x,
        Err(e) => {
            if !dry_run {
                let (code, msg) = e.to_code_and_message();
                let content = tool_error_json(code, &msg);
                eprintln!("[patch] preview err: {msg}");
                counters.tool_errors += 1;
                append_tool(session, messages, &tc.id, content)?;
            }
            return Ok(PatchDispatch::Continue);
        }
    };
    // A patch auto-runs when either every edit is a git-tracked Update
    // (revertible, no prompt needed) or every edit is permitted by a
    // `write` `allow:true` rule. Any edit whose winning `write` rule is
    // `allow:false` forces approval, regardless of git tracking.
    // (`preview_patch` already applies the same `write` rules inside the
    // executor's Layer 3; this dispatch-level verdict decides whether the
    // human must be asked, not whether the path is writable at all.)
    let write_verdict =
        patch_write_verdict(&inv, permission_layers, authorization, executor.root());
    let auto_approve = match write_verdict {
        WriteVerdict::Denied => false,
        WriteVerdict::Allowed => true,
        WriteVerdict::Undecided => preview.auto_approve,
    };
    if auto_approve {
        if !dry_run {
            match executor.apply_patch(&inv, &preview_content) {
                Ok(paths) => {
                    let via = if matches!(write_verdict, WriteVerdict::Allowed) {
                        "write rule"
                    } else {
                        "git-tracked"
                    };
                    eprintln!("[patch] auto-approved: {} file(s) ({via})", paths.len());
                    eprintln!("{}", render_patch_diff(&inv));
                    append_tool(session, messages, &tc.id, patch_result_json(&paths))?;
                }
                Err(e) => {
                    let (code, msg) = e.to_code_and_message();
                    let content = tool_error_json(code, &msg);
                    eprintln!("[patch] apply err: {msg}");
                    counters.tool_errors += 1;
                    append_tool(session, messages, &tc.id, content)?;
                }
            }
        }
        Ok(PatchDispatch::Continue)
    } else {
        let preview_text = render_patch_preview_text(&preview, &inv);
        eprintln!("[patch] approval required");
        eprintln!("{preview_text}");
        // Re-state the approval request after the (possibly long) diff so the
        // decision prompt lands at the bottom of the terminal, next to the
        // summary the human needs, instead of being pushed off-screen by the
        // diff body.
        eprintln!("{}", render_patch_approval_footer(&preview));
        Ok(PatchDispatch::Awaiting(build_pending(
            tc,
            PendingToolKind::Patch,
            preview_text,
        )))
    }
}

/// One-line approval restatement shown after the diff body, so the human can
/// decide without scrolling back up past the diff.
fn render_patch_approval_footer(p: &PatchPreview) -> String {
    format!(
        "[patch] approval required: {} edit(s) across {} file(s), +{} / -{} lines",
        p.edit_count,
        p.target_paths.len(),
        p.added_lines,
        p.removed_lines
    )
}

fn render_patch_preview_text(p: &PatchPreview, inv: &PatchInvocation) -> String {
    let mut out = format!(
        "patch preview: {} edit(s) across {} file(s), +{} / -{} lines",
        p.edit_count,
        p.target_paths.len(),
        p.added_lines,
        p.removed_lines
    );
    for path in &p.target_paths {
        out.push_str("\n  ");
        out.push_str(path);
    }
    if let Some(reason) = &p.not_revertible {
        out.push_str("\n  NOTE: ");
        out.push_str(reason);
    }
    out.push('\n');
    out.push_str(&render_patch_diff(inv));
    out
}

/// Render a readable per-edit diff body (no hunk headers): each
/// `before` line as `- ...` and each `after` line as `+ ...`, with
/// `Add` content all `+`. Output is capped at
/// [`PATCH_PREVIEW_MAX_LINES`] lines so a pathological patch cannot
/// flood the terminal; the overflow is summarised as
/// `... (N more lines omitted)`.
fn render_patch_diff(inv: &PatchInvocation) -> String {
    let mut out = String::new();
    let mut shown: usize = 0;
    let mut omitted: usize = 0;
    // A line counts toward the cap if it carries a `-`/`+`/header;
    // this keeps the accounting honest even across many edits.
    let push = |out: &mut String, shown: &mut usize, omitted: &mut usize, line: String| {
        if *shown < PATCH_PREVIEW_MAX_LINES {
            out.push_str(&line);
            out.push('\n');
            *shown += 1;
        } else {
            *omitted += 1;
        }
    };
    for edit in &inv.edits {
        match edit {
            PatchTool::Add { path, content } => {
                push(&mut out, &mut shown, &mut omitted, format!("  add {path}"));
                for line in content.lines() {
                    push(&mut out, &mut shown, &mut omitted, format!("    + {line}"));
                }
            }
            PatchTool::Update {
                path,
                before,
                after,
            } => {
                push(
                    &mut out,
                    &mut shown,
                    &mut omitted,
                    format!("  update {path}"),
                );
                for line in before.lines() {
                    push(&mut out, &mut shown, &mut omitted, format!("    - {line}"));
                }
                for line in after.lines() {
                    push(&mut out, &mut shown, &mut omitted, format!("    + {line}"));
                }
            }
        }
    }
    if omitted > 0 {
        out.push_str(&format!("    ... ({omitted} more lines omitted)\n"));
    }
    out
}

fn build_pending(tc: &ToolCall, kind: PendingToolKind, preview: String) -> Pending {
    Pending {
        ts: now_unix_millis(),
        call_id: tc.id.clone(),
        tool_kind: kind,
        function_name: tc.function_name.clone(),
        arguments_json: tc.arguments_json.clone(),
        preview,
    }
}

fn execute_pending(
    pending: &Pending,
    executor: &ToolExecutor,
    timeout: Option<Duration>,
) -> io::Result<String> {
    match pending.tool_kind {
        PendingToolKind::Patch => {
            // Convert any patch parse / preview / apply failure into a
            // tool-error result so a batch approval always answers every
            // parked call instead of aborting mid-way and leaving a
            // partially-executed pending set behind.
            let inv = match PatchInvocation::parse(&pending.arguments_json) {
                Ok(inv) => inv,
                Err(e) => return Ok(tool_error_json("patch_args", &e.message())),
            };
            let (preview_content, _preview) = match executor.preview_patch(&inv) {
                Ok(x) => x,
                Err(e) => return Ok(tool_error_json_from_patch(&e)),
            };
            match executor.apply_patch(&inv, &preview_content) {
                Ok(paths) => Ok(patch_result_json(&paths)),
                Err(e) => Ok(tool_error_json_from_patch(&e)),
            }
        }
        PendingToolKind::Command => {
            let inv = CommandInvocation::parse(&pending.arguments_json)
                .map_err(|e| io::Error::other(format!("command args: {e:?}")))?;
            match run_command_sync(&inv, executor, timeout) {
                Ok(s) => Ok(s),
                Err(err) => {
                    let (code, msg) = err.to_code_and_message();
                    Ok(tool_error_json(code, &msg))
                }
            }
        }
        PendingToolKind::Read => {
            // A read approved to reach outside the workspace executes with
            // a one-shot extra root derived from the requested path, so the
            // boundary widens for exactly this call and is never persisted.
            let inv = match ReadOnlyTool::parse(&pending.function_name, &pending.arguments_json) {
                Ok(inv) => inv,
                Err(e) => return Ok(tool_error_json_from(&e)),
            };
            let Some(extra) = read_extra_root(&inv, executor.root()) else {
                return Ok(tool_error_json(
                    "read_args",
                    "approved read has no resolvable path",
                ));
            };
            match executor.execute_with_extra_read_root(inv, extra) {
                ToolOutcome::Ok(payload) => Ok(payload),
                ToolOutcome::Err(e) => Ok(tool_error_json_from(&e)),
            }
        }
    }
}

/// Resolve the configured `command` timeout into a [`Duration`], or
/// `None` when the cap is disabled (`--command-timeout 0`).
fn command_timeout(cfg: &TellConfig) -> Option<Duration> {
    match cfg.command_timeout_seconds {
        Some(0) | None => None,
        Some(secs) => Some(Duration::from_secs(secs)),
    }
}

fn run_command_sync(
    inv: &CommandInvocation,
    executor: &ToolExecutor,
    timeout: Option<Duration>,
) -> Result<String, CommandError> {
    let started = Instant::now();
    // argv is guaranteed non-empty by CommandInvocation::parse.
    let mut cmd = Command::new(&inv.argv[0]);
    cmd.args(&inv.argv[1..]).current_dir(executor.root());
    let output = crate::child_output::run_streamed(&mut cmd, timeout).map_err(|e| {
        CommandError::SpawnFailed {
            message: e.to_string(),
        }
    })?;
    let elapsed = started.elapsed();
    let termination_reason = if output.timed_out {
        "timeout"
    } else if output.status.code().is_some() {
        "exited"
    } else {
        "signaled"
    };
    Ok(command_result_json(
        &output.stdout,
        &output.stderr,
        output.status.code(),
        termination_reason,
        elapsed,
        output.truncated,
    ))
}

/// A synthetic tool result that must be persisted to the session
/// transcript and inserted into the in-memory message list because
/// the original `tool_call` was never answered (e.g. an unapproved
/// sibling left behind when the loop suspended awaiting approval).
#[derive(Debug, Clone, PartialEq, Eq)]
struct OrphanedToolCall {
    call_id: String,
    content: String,
}

/// Pure, testable core of [`repair_orphaned_tool_calls`]: scan a
/// message list and return a repaired copy in which every assistant
/// message's unanswered `tool_calls` get an explicit reject / cancel
/// `tool` result inserted immediately after the assistant's existing
/// tool results, preserving conversation order. Also returns the
/// list of synthetic results so the caller can persist them to the
/// session transcript.
///
/// Rather than assuming tool results are contiguous, this indexes every
/// tool message by the `call_id` it answers, so an assistant's tool
/// results are associated with it even when the on-disk transcript has
/// interleaved records (e.g. a `user` turn appended between an
/// assistant's `tool_calls` and a synthetic reject persisted for it).
/// Each assistant's answers are emitted immediately after it and stray
/// / duplicate tool messages are dropped, restoring the
/// "assistant(tool_calls) -> tool, tool, ..." invariant that the API
/// requires.
///
/// An assistant message whose `tool_calls` are all answered is left
/// untouched; an assistant with no `tool_calls` is copied verbatim.
fn repair_messages(messages: &[ChatMessage]) -> (Vec<ChatMessage>, Vec<OrphanedToolCall>) {
    let mut tools_by_call: BTreeMap<String, VecDeque<ChatMessage>> = BTreeMap::new();
    for msg in messages {
        if let ChatMessage::Tool { tool_call_id, .. } = msg {
            tools_by_call
                .entry(tool_call_id.clone())
                .or_default()
                .push_back(msg.clone());
        }
    }

    let mut repaired: Vec<ChatMessage> = Vec::with_capacity(messages.len());
    let mut orphans: Vec<OrphanedToolCall> = Vec::new();
    // Call ids for which we already emitted (or synthesised) a tool
    // result in `repaired`. A later tool message for one of these ids
    // is a misplaced / duplicate record and is dropped.
    let mut placed: BTreeSet<String> = BTreeSet::new();

    for msg in messages {
        match msg {
            ChatMessage::Assistant { tool_calls, .. } if !tool_calls.is_empty() => {
                repaired.push(msg.clone());
                for tc in tool_calls {
                    if placed.contains(&tc.id) {
                        continue;
                    }
                    if let Some(queue) = tools_by_call.get_mut(&tc.id)
                        && let Some(tool_msg) = queue.pop_front()
                    {
                        repaired.push(tool_msg);
                        placed.insert(tc.id.clone());
                        continue;
                    }
                    let content = tool_error_json(
                        "unanswered_tool_call",
                        "this tool call was left unapproved and is cancelled before continuing",
                    );
                    orphans.push(OrphanedToolCall {
                        call_id: tc.id.clone(),
                        content: content.clone(),
                    });
                    repaired.push(ChatMessage::Tool {
                        tool_call_id: tc.id.clone(),
                        content,
                    });
                    placed.insert(tc.id.clone());
                }
            }
            ChatMessage::Tool { tool_call_id, .. } => {
                if placed.contains(tool_call_id) {
                    continue; // already emitted as this assistant's tool result
                }
                placed.insert(tool_call_id.clone());
                repaired.push(msg.clone());
            }
            _ => repaired.push(msg.clone()),
        }
    }
    (repaired, orphans)
}

/// Repair a transcript before it is sent to the model: for every
/// assistant `tool_call` that has no answering `tool` result in
/// `messages`, synthesize an explicit reject / cancel result, insert
/// it at the correct position, and persist the corresponding
/// `ToolApproval` / `Tool` records to `session` so the on-disk
/// transcript is healed and the same orphan does not recur on a
/// later invocation. If the cancelled call corresponds to a pending
/// approval that the caller bypassed with a fresh prompt, the pending
/// is cleared so a later `--approve` does not double-run
/// it.
///
/// Even when no new synthetic result is required, the repaired message
/// order is always adopted. `repair_messages` may have moved a tool
/// result that was persisted out of order (e.g. after a `user` turn)
/// back to immediately follow its assistant, and that in-memory
/// correction is the list actually sent to the model; the on-disk
/// records are left intact.
///
/// Returns the number of synthetic tool results inserted.
fn repair_orphaned_tool_calls(
    session: &mut Session,
    messages: &mut Vec<ChatMessage>,
) -> io::Result<usize> {
    let (repaired, orphans) = repair_messages(messages);
    if !orphans.is_empty() {
        for orphan in &orphans {
            // If the orphan is the very call that the previous invocation
            // parked in pending.json and the caller resumed with a fresh
            // prompt (bypassing --approve), drop the pending so
            // a later resume does not execute the now-cancelled call.
            if let Some(pendings) = session.load_pending()?
                && pendings.iter().any(|p| p.call_id == orphan.call_id)
            {
                session.clear_pending()?;
            }
            session.append(&SessionRecord::ToolApproval {
                ts: now_unix_millis(),
                call_id: orphan.call_id.clone(),
                decision: ApprovalDecision::Reject,
                auto_decided_by: Some(AutoDecidedBy {
                    scope: "repair".to_string(),
                    args_prefix: Vec::new(),
                    allow: false,
                    matches: Vec::new(),
                }),
            })?;
            session.append(&SessionRecord::Tool {
                ts: now_unix_millis(),
                call_id: orphan.call_id.clone(),
                content: orphan.content.clone(),
            })?;
            eprintln!(
                "[repair] cancelled unanswered tool_call {} (left unapproved)",
                orphan.call_id
            );
        }
    }
    *messages = repaired;
    Ok(orphans.len())
}

fn append_tool(
    session: &mut Session,
    messages: &mut Vec<ChatMessage>,
    call_id: &str,
    content: String,
) -> io::Result<()> {
    session.append(&SessionRecord::Tool {
        ts: now_unix_millis(),
        call_id: call_id.to_string(),
        content: content.clone(),
    })?;
    messages.push(ChatMessage::Tool {
        tool_call_id: call_id.to_string(),
        content,
    });
    Ok(())
}

fn load_pending_or_err(session: &Session) -> io::Result<Vec<Pending>> {
    session
        .load_pending()?
        .ok_or_else(|| io::Error::other("no pending.json — nothing to approve"))
}

fn tool_error_json_from(err: &ToolExecutionError) -> String {
    tool_error_json("execution_error", &err.message())
}

fn tool_error_json_from_patch(err: &PatchError) -> String {
    let (code, message) = err.to_code_and_message();
    tool_error_json(code, &message)
}

fn tool_error_json(code: &str, message: &str) -> String {
    struct Payload<'a> {
        code: &'a str,
        message: &'a str,
    }
    impl DisplayJson for Payload<'_> {
        fn fmt(&self, f: &mut nojson::JsonFormatter<'_, '_>) -> std::fmt::Result {
            f.object(|f| {
                f.member("error", self.code)?;
                f.member("message", self.message)
            })
        }
    }
    nojson::Json(Payload { code, message }).to_string()
}

fn patch_result_json(applied: &[PathBuf]) -> String {
    struct Payload<'a> {
        applied: &'a [PathBuf],
    }
    impl DisplayJson for Payload<'_> {
        fn fmt(&self, f: &mut nojson::JsonFormatter<'_, '_>) -> std::fmt::Result {
            f.object(|f| {
                f.member("ok", true)?;
                f.member(
                    "applied",
                    self.applied
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>(),
                )
            })
        }
    }
    nojson::Json(Payload { applied }).to_string()
}

fn command_result_json(
    stdout: &str,
    stderr: &str,
    exit_code: Option<i32>,
    termination_reason: &str,
    elapsed: Duration,
    truncated: bool,
) -> String {
    struct Payload<'a> {
        stdout: &'a str,
        stderr: &'a str,
        exit_code: Option<i32>,
        termination_reason: &'a str,
        duration_ms: u64,
        truncated: bool,
    }
    impl DisplayJson for Payload<'_> {
        fn fmt(&self, f: &mut nojson::JsonFormatter<'_, '_>) -> std::fmt::Result {
            f.object(|f| {
                match self.exit_code {
                    Some(code) => f.member("exit_code", code)?,
                    None => f.member("exit_code", Option::<i32>::None)?,
                }
                f.member("termination_reason", self.termination_reason)?;
                f.member("duration_ms", self.duration_ms)?;
                f.member("truncated", self.truncated)?;
                f.member("stdout", self.stdout)?;
                f.member("stderr", self.stderr)
            })
        }
    }
    let duration_ms = elapsed.as_millis().min(u64::MAX as u128) as u64;
    nojson::Json(Payload {
        stdout,
        stderr,
        exit_code,
        termination_reason,
        duration_ms,
        truncated,
    })
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn user(ts: u64) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::User(format!("u{ts}")),
            ts,
        }
    }

    fn assistant_plain(ts: u64) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::assistant_text(format!("a{ts}")),
            ts,
        }
    }

    fn assistant_with_tool_call(ts: u64) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::Assistant {
                content: String::new(),
                tool_calls: vec![ToolCall {
                    id: format!("call_{ts}"),
                    function_name: "read".to_string(),
                    arguments_json: "{}".to_string(),
                }],
            },
            ts,
        }
    }

    fn tool(ts: u64) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::Tool {
                tool_call_id: format!("call_{ts}"),
                content: "{}".to_string(),
            },
            ts,
        }
    }

    #[test]
    fn safe_tail_start_returns_zero_when_short_history() {
        let records = vec![user(1), assistant_plain(2)];
        assert_eq!(safe_tail_start(&records, 10), 0);
    }

    #[test]
    fn safe_tail_start_lands_on_user_record() {
        // Target keep = 2 → naive cutoff at index 3 (assistant plain).
        // That is already a safe boundary, so cutoff stays.
        let records = vec![
            user(1),
            assistant_plain(2),
            user(3),
            assistant_plain(4),
            user(5),
        ];
        assert_eq!(safe_tail_start(&records, 2), 3);
    }

    #[test]
    fn safe_tail_start_advances_past_tool_record() {
        // Target keep = 2 → naive cutoff at index 3 (tool), which is
        // unsafe because it would orphan the tool from its assistant.
        // The safe cutoff is the next user record at index 4.
        let records = vec![
            user(1),
            assistant_plain(2),
            assistant_with_tool_call(3),
            tool(4),
            user(5),
        ];
        assert_eq!(safe_tail_start(&records, 2), 4);
    }

    #[test]
    fn safe_tail_start_advances_past_assistant_with_tool_calls() {
        // Target keep = 2 → naive cutoff at index 2 (assistant with
        // tool_calls). Cutting there would drop the tool_call context
        // but keep the tool response, so it is unsafe. Move forward
        // to the next safe boundary at index 4 (user).
        let records = vec![
            user(1),
            user(2),
            assistant_with_tool_call(3),
            tool(4),
            user(5),
        ];
        assert_eq!(safe_tail_start(&records, 3), 4);
    }

    #[test]
    fn safe_tail_start_bails_when_no_safe_boundary_in_tail() {
        // Tail is a single unresolved assistant→tool pair; no safe
        // boundary between naive index (1) and end. Bail with 0 so
        // we do not orphan tools this round.
        let records = vec![user(1), assistant_with_tool_call(2), tool(3)];
        assert_eq!(safe_tail_start(&records, 1), 0);
    }

    #[test]
    fn is_safe_boundary_classifies_records_as_expected() {
        assert!(is_safe_boundary(&ChatMessage::User("u".to_string())));
        assert!(is_safe_boundary(&ChatMessage::assistant_text("a")));
        assert!(!is_safe_boundary(&ChatMessage::Assistant {
            content: String::new(),
            tool_calls: vec![ToolCall {
                id: "x".to_string(),
                function_name: "read".to_string(),
                arguments_json: "{}".to_string(),
            }],
        }));
        assert!(!is_safe_boundary(&ChatMessage::Tool {
            tool_call_id: "x".to_string(),
            content: "{}".to_string(),
        }));
        assert!(!is_safe_boundary(&ChatMessage::System("s".to_string())));
    }

    fn big_user(ts: u64, len: usize) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::User(format!("u{ts}:{}", "x".repeat(len))),
            ts,
        }
    }

    #[test]
    fn truncate_prose_keeps_head_and_notes_dropped_chars() {
        let s = "abcdefghij".repeat(2000); // 20_000 chars
        let out = truncate_prose(&s, 1000);
        assert!(out.starts_with("abc"));
        assert!(out.contains("[truncated 19000 chars]"));
        assert!(out.chars().count() < 2000);
    }

    #[test]
    fn render_summary_transcript_fits_all_within_budget() {
        let records = vec![user(1), assistant_plain(2), tool(3)];
        let out = render_summary_transcript(&records);
        assert!(!out.contains("[Note:"), "unexpected note: {out}");
        assert!(out.contains("user: u1"));
        assert!(out.contains("assistant: a2"));
        assert!(out.contains("[tool result:"));
    }

    #[test]
    fn render_summary_transcript_drops_oldest_when_over_budget() {
        // Each record is over SUMMARY_RECORD_MAX_CHARS so each renders
        // to ~SUMMARY_RECORD_MAX_CHARS of prose + a truncation marker.
        // Fourteen such blocks exceed SUMMARY_MAX_CHARS, so the newest
        // ones are kept and the oldest are dropped (with a note).
        let mut records = Vec::new();
        for i in 1..=14 {
            records.push(big_user(i, SUMMARY_RECORD_MAX_CHARS + 100));
        }
        let out = render_summary_transcript(&records);
        assert!(out.contains("[Note:"), "expected a truncation note");
        assert!(out.contains("u14:"), "newest record should be kept");
        let kept_oldest_marker = records
            .len()
            .checked_sub(2)
            .map(|_| format!("u{}:", records.len().saturating_sub(2)))
            .unwrap_or_default();
        // The newest two are definitely kept; the absolute oldest is dropped.
        assert!(!out.contains("u1:"), "oldest record should be dropped");
        assert!(
            out.contains(&kept_oldest_marker),
            "a kept record ({kept_oldest_marker}) should be present"
        );
    }

    #[test]
    fn render_summary_block_truncates_huge_tool_result() {
        let huge = "y".repeat(50_000);
        let rec = ChatMessageWithTs {
            message: ChatMessage::Tool {
                tool_call_id: "call_1".to_string(),
                content: huge,
            },
            ts: 1,
        };
        let out = render_summary_block(&rec);
        assert!(
            out.contains("[truncated"),
            "tool result not truncated: {}",
            out.len()
        );
        assert!(out.chars().count() < 1_000);
    }

    fn big_tool(ts: u64, len: usize) -> ChatMessageWithTs {
        ChatMessageWithTs {
            message: ChatMessage::Tool {
                tool_call_id: format!("call_{ts}"),
                content: "z".repeat(len),
            },
            ts,
        }
    }

    #[test]
    fn compaction_cutoff_returns_none_when_too_short() {
        let records = vec![user(1), assistant_plain(2)];
        assert_eq!(compaction_cutoff(&records, 10, 1000), None);
    }

    #[test]
    fn compaction_cutoff_returns_safe_tail_start_within_budget() {
        let records = vec![
            user(1),
            assistant_plain(2),
            user(3),
            assistant_plain(4),
            user(5),
        ];
        let keep = safe_tail_start(&records, 2);
        assert!(keep > 0);
        assert_eq!(compaction_cutoff(&records, 2, 100_000), Some(keep));
    }

    #[test]
    fn compaction_cutoff_folds_few_but_huge_records() {
        // The trigger hole: very few records but one enormous tool
        // result dominates the history. `latest_prompt_tokens` would
        // be stale/small, so the size-based guard must fire even when
        // `n <= target_keep`. The cutoff should walk past the huge
        // record and fold it (returning `Some(n)` when no safe
        // boundary is reachable, or a boundary that fits the budget).
        let records = vec![user(1), assistant_with_tool_call(2), big_tool(3, 300_000)];
        assert_eq!(compaction_cutoff(&records, 10, 1000), Some(records.len()));
    }

    #[test]
    fn compaction_cutoff_skips_when_few_and_small() {
        // Few records that all fit the budget: nothing to fold.
        let records = vec![user(1), assistant_plain(2)];
        assert_eq!(compaction_cutoff(&records, 10, 1000), None);
    }

    #[test]
    fn should_auto_compact_fires_on_token_threshold() {
        // Last successful turn was large enough: compact on the token
        // threshold alone, even if the recorded size is tiny.
        assert!(should_auto_compact(COMPACTION_TRIGGER_TOKENS, 0));
        assert!(should_auto_compact(COMPACTION_TRIGGER_TOKENS + 1, 100));
    }

    #[test]
    fn should_auto_compact_fires_on_record_size_when_tokens_stale() {
        // The trigger hole: the token count is stale/small because the
        // previous turn suspended, but the real records are huge. The
        // size guard must fire even below the token threshold.
        assert!(should_auto_compact(0, RECORDS_TOTAL_MAX_CHARS + 1));
        assert!(should_auto_compact(1000, RECORDS_TOTAL_MAX_CHARS + 1));
    }

    #[test]
    fn should_auto_compact_stays_quiet_when_everything_is_small() {
        // Both signals below their thresholds: no compaction.
        assert!(!should_auto_compact(0, RECORDS_TOTAL_MAX_CHARS));
        assert!(!should_auto_compact(COMPACTION_TRIGGER_TOKENS - 1, 10));
    }

    #[test]
    fn compaction_cutoff_folds_huge_tail_to_the_end() {
        // A giant tool result sits at the very end, with no safe
        // boundary after it. The retained tail cannot be shrunk by
        // folding older records, so the cutoff walks to the end and
        // everything is folded into the summary.
        let records = vec![
            user(1),
            assistant_plain(2),
            assistant_with_tool_call(3),
            big_tool(4, 50_000),
        ];
        assert_eq!(compaction_cutoff(&records, 2, 100), Some(records.len()));
    }

    #[test]
    fn compaction_cutoff_folds_middle_huge_record_normally() {
        // A huge tool result before a clearly safe recent tail does not
        // force fold-all: safe_tail_start already lands after it.
        let records = vec![
            user(1),
            assistant_with_tool_call(2),
            big_tool(3, 50_000),
            user(4),
            assistant_plain(5),
        ];
        let keep = safe_tail_start(&records, 2);
        assert!(keep > 0 && keep < records.len());
        assert_eq!(compaction_cutoff(&records, 2, 100), Some(keep));
    }

    // -------------------------------------------------------------
    // Automatic pruning
    // -------------------------------------------------------------

    fn prune_tempdir(name: &str) -> std::path::PathBuf {
        let base =
            std::env::temp_dir().join(format!("attini-prune-test-{}-{}", name, std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).expect("create tempdir");
        base
    }

    fn write_lines(path: &std::path::Path, lines: &[&str]) {
        use std::io::Write as _;
        let mut f = std::fs::File::create(path).expect("create");
        for l in lines {
            f.write_all(l.as_bytes()).expect("write");
            f.write_all(b"\n").expect("newline");
        }
        f.sync_all().expect("sync");
    }

    #[test]
    fn line_is_safe_boundary_classifies_records_as_expected() {
        assert!(line_is_safe_boundary(
            r#"{"kind":"user","ts":1,"text":"hi"}"#
        ));
        assert!(line_is_safe_boundary(
            r#"{"kind":"assistant","ts":2,"text":"done","tool_calls":[]}"#
        ));
        // Assistant with empty text but no tool calls is a final answer.
        assert!(line_is_safe_boundary(
            r#"{"kind":"assistant","ts":3,"text":"","tool_calls":[]}"#
        ));
        // Assistant awaiting tools is unsafe.
        assert!(!line_is_safe_boundary(
            r#"{"kind":"assistant","ts":4,"text":"","tool_calls":[{"id":"c"}]}"#
        ));
        assert!(!line_is_safe_boundary(
            r#"{"kind":"tool","ts":5,"text":"x"}"#
        ));
        assert!(!line_is_safe_boundary(r#"{"kind":"summary","ts":6}"#));
        assert!(!line_is_safe_boundary("not json"));
        assert!(!line_is_safe_boundary(""));
    }

    #[test]
    fn prune_offset_past_midpoint_lands_on_safe_boundary_after_half() {
        let dir = prune_tempdir("midpoint");
        let path = dir.join("conv.jsonl");
        // Pad the file so the midpoint falls inside the first chunks.
        let pad = "x".repeat(400);
        let lines = [
            format!(r#"{{"kind":"user","ts":1,"text":"{pad}"}}"#),
            format!(r#"{{"kind":"tool","ts":2,"text":"{pad}"}}"#),
            format!(r#"{{"kind":"assistant","ts":3,"text":"{pad}","tool_calls":[]}}"#),
            format!(r#"{{"kind":"user","ts":4,"text":"{pad}"}}"#),
        ];
        let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        write_lines(&path, &refs);
        let size = std::fs::metadata(&path).expect("meta").len();
        let (offset, dropped) = prune_offset_past_midpoint(&path, size)
            .expect("ok")
            .expect("boundary");
        // The chosen line must be a safe boundary at/after the midpoint.
        assert!(offset >= size / 2);
        assert!(dropped >= 1);
        // Compute the start offset of the first safe line at/after the
        // midpoint by replaying the line lengths.
        let mut cursor: u64 = 0;
        let mut expected: Option<(u64, u64)> = None;
        for (i, l) in refs.iter().enumerate() {
            let start = cursor;
            cursor += l.len() as u64 + 1;
            if start >= size / 2 && line_is_safe_boundary(l) {
                expected = Some((start, i as u64));
                break;
            }
        }
        assert_eq!(Some((offset, dropped)), expected);
    }

    #[test]
    fn prune_offset_past_midpoint_returns_none_when_pair_spans_tail() {
        let dir = prune_tempdir("no_safe");
        let path = dir.join("conv.jsonl");
        let pad = "x".repeat(400);
        // Past the midpoint the file is a single unresolved
        // assistant -> tool pair with no safe boundary, so no cut.
        let lines = [
            format!(r#"{{"kind":"user","ts":1,"text":"{pad}"}}"#),
            r#"{"kind":"assistant","ts":2,"text":"","tool_calls":[{"id":"c"}]}"#.to_string(),
            format!(r#"{{"kind":"tool","ts":3,"text":"{pad}"}}"#),
        ];
        let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        write_lines(&path, &refs);
        let size = std::fs::metadata(&path).expect("meta").len();
        assert!(
            prune_offset_past_midpoint(&path, size)
                .expect("ok")
                .is_none()
        );
    }

    #[test]
    fn rewrite_file_from_offset_keeps_suffix_only() {
        let dir = prune_tempdir("rewrite");
        let path = dir.join("conv.jsonl");
        let lines = [
            r#"{"kind":"user","ts":1,"text":"first"}"#,
            r#"{"kind":"summary","ts":2,"text":"s1"}"#,
            r#"{"kind":"user","ts":3,"text":"after"}"#,
        ];
        write_lines(&path, &lines);
        let offset: u64 = (lines[0].len() + 1 + lines[1].len() + 1) as u64;
        rewrite_file_from_offset(&path, offset).expect("rewrite ok");
        let contents = std::fs::read_to_string(&path).expect("read");
        let kept: Vec<&str> = contents.trim_end_matches('\n').split('\n').collect();
        assert_eq!(kept.len(), 1);
        assert!(kept[0].contains("after"));
    }

    // -------------------------------------------------------------
    // ToolCallGate
    // -------------------------------------------------------------

    fn gate_config(
        turn_limit: usize,
        rate: Option<RateLimit>,
        session_max: Option<usize>,
    ) -> TellConfig {
        TellConfig {
            session_name: String::new(),
            model: String::new(),
            max_tokens: None,
            workspace_root: PathBuf::new(),
            system_prompt: None,
            max_turns: 0,
            turn_tool_call_limit: turn_limit,
            tool_call_rate: rate,
            session_tool_call_max: session_max,
            authorization: Authorization::PerTool,
            temperature: None,
            grant_request: GrantRequest::None,
            command_timeout_seconds: None,
        }
    }

    #[test]
    fn gate_turn_limit_admits_up_to_boundary_then_rejects() {
        let cfg = gate_config(3, None, None);
        let mut gate = ToolCallGate::new(&cfg);
        gate.begin_turn();
        let now = Instant::now();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::TurnLimitExceeded);
    }

    #[test]
    fn gate_turn_limit_resets_after_begin_turn() {
        let cfg = gate_config(2, None, None);
        let mut gate = ToolCallGate::new(&cfg);
        let now = Instant::now();
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::TurnLimitExceeded);
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
    }

    #[test]
    fn gate_rate_admits_up_to_boundary_within_window_then_rejects() {
        let cfg = gate_config(
            100,
            Some(RateLimit {
                calls: 2,
                window: Duration::from_secs(10),
            }),
            None,
        );
        let mut gate = ToolCallGate::new(&cfg);
        gate.begin_turn();
        let t0 = Instant::now();
        assert_eq!(gate.admit(t0), GateDecision::Proceed);
        assert_eq!(gate.admit(t0), GateDecision::Proceed);
        assert_eq!(gate.admit(t0), GateDecision::RateLimitExceeded);
    }

    #[test]
    fn gate_rate_window_slides_and_admits_again() {
        let cfg = gate_config(
            100,
            Some(RateLimit {
                calls: 2,
                window: Duration::from_secs(10),
            }),
            None,
        );
        let mut gate = ToolCallGate::new(&cfg);
        gate.begin_turn();
        let t0 = Instant::now();
        assert_eq!(gate.admit(t0), GateDecision::Proceed);
        assert_eq!(gate.admit(t0), GateDecision::Proceed);
        assert_eq!(gate.admit(t0), GateDecision::RateLimitExceeded);
        // Advance well past the window; the deque should drain.
        let t1 = t0 + Duration::from_secs(11);
        assert_eq!(gate.admit(t1), GateDecision::Proceed);
    }

    #[test]
    fn gate_rate_rejection_does_not_consume_window_slot() {
        // If a rejected call filled the deque, the next call after
        // window sliding would immediately be rejected again. Verify
        // rejected calls are not pushed.
        let cfg = gate_config(
            100,
            Some(RateLimit {
                calls: 1,
                window: Duration::from_secs(10),
            }),
            None,
        );
        let mut gate = ToolCallGate::new(&cfg);
        gate.begin_turn();
        let t0 = Instant::now();
        assert_eq!(gate.admit(t0), GateDecision::Proceed);
        // Multiple rejections at t0 must not affect anything.
        assert_eq!(gate.admit(t0), GateDecision::RateLimitExceeded);
        assert_eq!(gate.admit(t0), GateDecision::RateLimitExceeded);
        // After the window slides, exactly one admit is possible.
        let t1 = t0 + Duration::from_secs(11);
        assert_eq!(gate.admit(t1), GateDecision::Proceed);
        assert_eq!(gate.admit(t1), GateDecision::RateLimitExceeded);
    }

    #[test]
    fn gate_session_backstop_admits_up_to_max_then_exhausts() {
        let cfg = gate_config(100, None, Some(3));
        let mut gate = ToolCallGate::new(&cfg);
        let now = Instant::now();
        // Session count spans multiple turns.
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        assert_eq!(gate.admit(now), GateDecision::SessionExhausted);
    }

    #[test]
    fn gate_none_options_disable_the_check() {
        let cfg = gate_config(100, None, None);
        let mut gate = ToolCallGate::new(&cfg);
        gate.begin_turn();
        let now = Instant::now();
        for _ in 0..50 {
            assert_eq!(gate.admit(now), GateDecision::Proceed);
        }
    }

    #[test]
    fn gate_rejection_does_not_consume_session_or_turn_budget() {
        // Turn cap rejects, but session_count and rate_deque should
        // not have advanced by the rejected call.
        let cfg = gate_config(
            1,
            Some(RateLimit {
                calls: 100,
                window: Duration::from_secs(10),
            }),
            Some(3),
        );
        let mut gate = ToolCallGate::new(&cfg);
        let now = Instant::now();
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        // Rejected by turn cap; must not count against session_max.
        assert_eq!(gate.admit(now), GateDecision::TurnLimitExceeded);
        assert_eq!(gate.admit(now), GateDecision::TurnLimitExceeded);
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::Proceed);
        // Now session_count == 3, backstop rejects (turn cap would
        // also apply on the 2nd of this turn but session runs first
        // per the order).
        gate.begin_turn();
        assert_eq!(gate.admit(now), GateDecision::SessionExhausted);
    }

    // -------------------------------------------------------------
    // pick_summary_text
    // -------------------------------------------------------------

    fn call_result(content: &str) -> curl::CallResult {
        curl::CallResult {
            content: content.to_string(),
            tool_calls: Vec::new(),
            finish_reason: None,
            usage: None,
        }
    }

    #[test]
    fn pick_summary_text_returns_content_when_present() {
        let r = call_result("hello summary");
        assert_eq!(pick_summary_text(&r), Some("hello summary".to_string()));
    }

    #[test]
    fn pick_summary_text_returns_none_when_content_is_blank() {
        let r = call_result("   ");
        assert_eq!(pick_summary_text(&r), None);
    }

    // -----------------------------------------------------------------
    // abbreviate_args / render_records_prose
    // -----------------------------------------------------------------

    #[test]
    fn abbreviate_args_strips_newlines_and_truncates() {
        let long = "{\"path\":\"src/tell_cli.rs\",\n\"pattern\":\"".repeat(40);
        let out = abbreviate_args(&long);
        assert!(!out.contains('\n'));
        assert!(out.chars().count() <= 91); // 90 + ellipsis
        assert!(out.ends_with('…'));
    }

    #[test]
    fn abbreviate_args_handles_empty() {
        assert_eq!(abbreviate_args(""), "");
        assert_eq!(abbreviate_args("   "), "");
    }

    #[test]
    fn render_records_prose_strips_raw_tool_format() {
        let records = vec![
            user(1),
            ChatMessageWithTs {
                message: ChatMessage::Assistant {
                    content: "looking at the file".to_string(),
                    tool_calls: vec![ToolCall {
                        id: "call_1".to_string(),
                        function_name: "search".to_string(),
                        arguments_json: "{\"pattern\":\"foo\"}".to_string(),
                    }],
                },
                ts: 2,
            },
            ChatMessageWithTs {
                message: ChatMessage::Tool {
                    tool_call_id: "call_1".to_string(),
                    content: "a file
"
                    .repeat(300),
                },
                ts: 3,
            },
        ];
        let out = render_records_prose(&records);
        assert!(out.contains("user: u1"));
        assert!(out.contains("assistant: looking at the file"));
        assert!(out.contains("[tool call: search ({\"pattern\":\"foo\"})]"));
        assert!(out.contains("[tool result: a file"));
        // Raw JSON / agentic XML must not leak into the rendered prose.
        assert!(!out.contains("tool_calls"));
        assert!(!out.contains("<invoke"));
        assert!(!out.contains("function_name"));
        // Tool result is truncated (~200-char brief), not the full ~2100 chars.
        assert!(out.len() < 600);
        assert!(out.contains('…'));
    }

    // -----------------------------------------------------------------
    // command_result_json
    // -----------------------------------------------------------------

    #[test]
    fn command_result_json_keeps_full_output_text() {
        let stdout = "line 1\nline 2\n".repeat(200);
        let stderr = "warning: something\n".repeat(50);
        let json = command_result_json(
            &stdout,
            &stderr,
            Some(1),
            "exited",
            Duration::from_millis(123),
            false,
        );
        assert!(json.contains("\"stdout\":\"line 1\\nline 2\\n"));
        assert!(json.contains("\"stderr\":\"warning: something\\n"));
        assert!(json.contains("\"exit_code\":1"));
        assert!(json.contains("\"termination_reason\":\"exited\""));
        assert!(json.contains("\"duration_ms\":123"));
        assert!(json.contains("\"truncated\":false"));
    }

    #[test]
    fn command_result_json_roundtrips_no_exit_code() {
        let json = command_result_json("out", "", None, "signaled", Duration::ZERO, true);
        assert!(json.contains("\"exit_code\":null"));
        assert!(json.contains("\"termination_reason\":\"signaled\""));
        assert!(json.contains("\"truncated\":true"));
    }

    #[test]
    fn command_result_json_includes_truncated_flag() {
        let json = command_result_json("out", "", Some(0), "exited", Duration::ZERO, true);
        assert!(json.contains("\"truncated\":true"));
        assert!(!json.contains("\"truncated\":false"));
    }

    // -----------------------------------------------------------------
    // command_timeout
    // -----------------------------------------------------------------

    #[test]
    fn command_timeout_zero_and_none_disable_the_cap() {
        let mut cfg = gate_config(1, None, None);
        cfg.command_timeout_seconds = None;
        assert_eq!(command_timeout(&cfg), None);
        cfg.command_timeout_seconds = Some(0);
        assert_eq!(command_timeout(&cfg), None);
    }

    #[test]
    fn command_timeout_seconds_becomes_a_duration() {
        let mut cfg = gate_config(1, None, None);
        cfg.command_timeout_seconds = Some(180);
        assert_eq!(command_timeout(&cfg), Some(Duration::from_secs(180)));
    }

    // -------------------------------------------------------------
    // repair_messages (transcript integrity)
    // -------------------------------------------------------------

    fn assistant_calls(ids: &[&str]) -> ChatMessage {
        ChatMessage::Assistant {
            content: String::new(),
            tool_calls: ids
                .iter()
                .map(|id| ToolCall {
                    id: id.to_string(),
                    function_name: "command".to_string(),
                    arguments_json: "{}".to_string(),
                })
                .collect(),
        }
    }

    fn tool_result(call_id: &str) -> ChatMessage {
        ChatMessage::Tool {
            tool_call_id: call_id.to_string(),
            content: "{}".to_string(),
        }
    }

    #[test]
    fn repair_messages_inserts_reject_for_unanswered_sibling() {
        // assistant issues two calls; only the first is answered. The
        // second must get a synthetic reject inserted after the first
        // tool result, preserving order.
        let messages = vec![
            assistant_calls(&["call_00", "call_01"]),
            tool_result("call_00"),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert_eq!(orphans.len(), 1);
        assert_eq!(orphans[0].call_id, "call_01");
        assert!(orphans[0].content.contains("unanswered_tool_call"));
        // Two assistants? No: assistant + two tool messages.
        assert_eq!(repaired.len(), 3);
        assert!(matches!(&repaired[0], ChatMessage::Assistant { .. }));
        match &repaired[1] {
            ChatMessage::Tool { tool_call_id, .. } => assert_eq!(tool_call_id, "call_00"),
            other => panic!("expected tool call_00, got {other:?}"),
        }
        match &repaired[2] {
            ChatMessage::Tool {
                tool_call_id,
                content,
            } => {
                assert_eq!(tool_call_id, "call_01");
                assert!(content.contains("unanswered_tool_call"));
            }
            other => panic!("expected synthetic tool call_01, got {other:?}"),
        }
    }

    #[test]
    fn repair_messages_leaves_complete_transcript_untouched() {
        let messages = vec![
            assistant_calls(&["call_00", "call_01"]),
            tool_result("call_00"),
            tool_result("call_01"),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert!(orphans.is_empty());
        assert_eq!(repaired, messages);
    }

    #[test]
    fn repair_messages_handles_multiple_unanswered_calls() {
        // No tool results at all: every call is answered by a synthetic
        // reject, all inserted after the assistant message.
        let messages = vec![assistant_calls(&["call_00", "call_01", "call_02"])];
        let (repaired, orphans) = repair_messages(&messages);
        assert_eq!(orphans.len(), 3);
        assert_eq!(repaired.len(), 4);
        for (idx, id) in ["call_00", "call_01", "call_02"].iter().enumerate() {
            match &repaired[idx + 1] {
                ChatMessage::Tool { tool_call_id, .. } => assert_eq!(tool_call_id, id),
                other => panic!("expected tool {id}, got {other:?}"),
            }
        }
    }

    #[test]
    fn repair_messages_places_synthetic_before_next_user() {
        // The synthetic reject must be inserted immediately after the
        // assistant's tool results, before a subsequent user message.
        let messages = vec![
            assistant_calls(&["call_00", "call_01"]),
            tool_result("call_00"),
            ChatMessage::User("continue".to_string()),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert_eq!(orphans.len(), 1);
        assert_eq!(repaired.len(), 4);
        assert!(matches!(&repaired[2], ChatMessage::Tool { .. }));
        assert!(matches!(&repaired[3], ChatMessage::User(_)));
    }

    #[test]
    fn repair_messages_skips_assistant_without_tool_calls() {
        let messages = vec![
            ChatMessage::assistant_text("intro"),
            assistant_calls(&["call_00"]),
            tool_result("call_00"),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert!(orphans.is_empty());
        assert_eq!(repaired, messages);
    }

    #[test]
    fn repair_messages_moves_misplaced_tool_before_user() {
        // The bug this fix addresses: a synthetic tool result was
        // persisted *after* a user turn. It must be moved back to
        // immediately follow its assistant so the assistant -> tool
        // continuity holds, with the user message after the tool
        // results, and no extra orphan synthetic is generated.
        let messages = vec![
            assistant_calls(&["call_00", "call_01"]),
            tool_result("call_00"),
            ChatMessage::User("tudukete".to_string()),
            tool_result("call_01"),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert!(orphans.is_empty());
        assert_eq!(repaired.len(), 4);
        assert!(matches!(&repaired[0], ChatMessage::Assistant { .. }));
        match &repaired[1] {
            ChatMessage::Tool { tool_call_id, .. } => assert_eq!(tool_call_id, "call_00"),
            other => panic!("expected tool call_00, got {other:?}"),
        }
        match &repaired[2] {
            ChatMessage::Tool { tool_call_id, .. } => assert_eq!(tool_call_id, "call_01"),
            other => panic!("expected tool call_01, got {other:?}"),
        }
        assert!(matches!(&repaired[3], ChatMessage::User(_)));
    }

    #[test]
    fn repair_messages_drops_duplicate_tool_result() {
        // A stray / duplicate tool message for an already-answered call
        // is dropped rather than re-emitted.
        let messages = vec![
            assistant_calls(&["call_00"]),
            tool_result("call_00"),
            tool_result("call_00"),
        ];
        let (repaired, orphans) = repair_messages(&messages);
        assert!(orphans.is_empty());
        assert_eq!(repaired.len(), 2);
        assert!(matches!(&repaired[0], ChatMessage::Assistant { .. }));
        assert!(matches!(&repaired[1], ChatMessage::Tool { .. }));
    }

    // -------------------------------------------------------------
    // render_tell_status_line
    // -------------------------------------------------------------

    #[test]
    fn status_line_render_includes_session_and_ctx() {
        let line = render_tell_status_line("deepseek-v4-flash", "main", 20736);
        assert_eq!(
            line,
            "[tell] model=deepseek-v4-flash session=main ctx=20736"
        );
    }

    #[test]
    fn status_line_uses_passed_ctx_as_current_size() {
        let line = render_tell_status_line("m", "s", 1000);
        assert!(line.contains("ctx=1000"));
        assert!(line.contains("model=m"));
        assert!(line.contains("session=s"));
    }

    // -------------------------------------------------------------
    // max_turns_error / RESUME_PROMPT
    // -------------------------------------------------------------

    #[test]
    fn max_turns_error_points_at_approve_and_tell() {
        let msg = max_turns_error(20);
        assert!(msg.contains("max_turns=20"));
        // The continuation command sits on its own line, ready to copy,
        // and does not restate the (implicit) session name.
        assert!(msg.contains("\nattini approve  # or give a new instruction"));
        assert!(!msg.contains("-s "));
    }

    #[test]
    fn resume_prompt_is_non_empty() {
        assert!(!RESUME_PROMPT.trim().is_empty());
    }

    // -------------------------------------------------------------
    // normalise_pending_free_approve
    // -------------------------------------------------------------

    #[test]
    fn pending_free_approve_retries_a_transport_error() {
        let cont = normalise_pending_free_approve(Some(InvocationEndReason::TransportError));
        assert!(matches!(cont, Continuation::Retry));
    }

    #[test]
    fn pending_free_approve_continues_after_other_endings() {
        for last in [
            Some(InvocationEndReason::Completed),
            Some(InvocationEndReason::AwaitingApproval),
            Some(InvocationEndReason::Error),
            Some(InvocationEndReason::SessionToolCallExhausted),
            None,
        ] {
            let cont = normalise_pending_free_approve(last);
            match cont {
                Continuation::Prompt(text) => assert_eq!(text, RESUME_PROMPT),
                Continuation::Retry => panic!("expected Prompt for {last:?}, got Retry"),
                Continuation::Approve => {
                    panic!("expected Prompt for {last:?}, got Approve")
                }
            }
        }
    }

    // -------------------------------------------------------------
    // render_tool_batching_note
    // -------------------------------------------------------------

    #[test]
    fn tool_batching_note_forbids_read_only_after_approval_gated_call() {
        let note = render_tool_batching_note();
        assert!(note.contains("Tool call batching"));
        assert!(note.contains("approval"));
        assert!(note.contains("last"));
        assert!(note.contains("read"));
        assert!(note.contains("search"));
        assert!(note.contains("do not put"));
    }

    // -------------------------------------------------------------
    // grant_prefix / plan_grant
    // -------------------------------------------------------------

    fn command_pending(call_id: &str, argv: &[&str]) -> Pending {
        let argv_json = argv
            .iter()
            .map(|a| format!("\"{a}\""))
            .collect::<Vec<_>>()
            .join(",");
        Pending {
            ts: 0,
            call_id: call_id.to_string(),
            tool_kind: PendingToolKind::Command,
            function_name: "command".to_string(),
            arguments_json: format!("{{\"argv\":[{argv_json}]}}"),
            preview: String::new(),
        }
    }

    #[test]
    fn grant_prefix_truncates_to_two_elements() {
        assert_eq!(grant_prefix(&[]), None);
        assert_eq!(
            grant_prefix(&["cargo".to_string()]),
            Some(vec!["cargo".to_string()])
        );
        assert_eq!(
            grant_prefix(&["cargo".to_string(), "test".to_string(), "-q".to_string()]),
            Some(vec!["cargo".to_string(), "test".to_string()])
        );
    }

    fn read_pending(call_id: &str, path: &str) -> Pending {
        Pending {
            ts: 0,
            call_id: call_id.to_string(),
            tool_kind: PendingToolKind::Read,
            function_name: "read".to_string(),
            arguments_json: format!("{{\"path\":\"{path}\"}}"),
            preview: String::new(),
        }
    }

    #[test]
    fn plan_grant_none_and_oneshot_never_persist() {
        let root = std::env::temp_dir();
        let pendings = vec![command_pending("c1", &["cargo", "test"])];
        assert!(
            plan_grant(GrantRequest::None, &pendings, &root)
                .unwrap()
                .is_none()
        );
        assert!(
            plan_grant(GrantRequest::Oneshot, &pendings, &root)
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn plan_grant_session_resolves_command_prefix() {
        let root = std::env::temp_dir();
        let pendings = vec![command_pending("c1", &["cargo", "test", "--all"])];
        match plan_grant(GrantRequest::Session, &pendings, &root).unwrap() {
            Some(GrantIntent::Command(prefix)) => {
                assert_eq!(prefix, vec!["cargo".to_string(), "test".to_string()]);
            }
            other => panic!("expected a command grant, got {other:?}"),
        }
    }

    fn patch_pending(call_id: &str, edits_json: &str) -> Pending {
        Pending {
            ts: 0,
            call_id: call_id.to_string(),
            tool_kind: PendingToolKind::Patch,
            function_name: "patch".to_string(),
            arguments_json: format!("{{\"edits\":[{edits_json}]}}"),
            preview: String::new(),
        }
    }

    #[test]
    fn plan_grant_resolves_patch_path_relative_to_workspace() {
        let dir = std::env::temp_dir().join(format!("attini-patch-grant-{}", std::process::id()));
        let sub = dir.join("sub");
        let _ = std::fs::create_dir_all(&sub);
        let file = sub.join("note.txt");
        std::fs::write(&file, "hi").expect("write");
        let edit = r#"{"kind":"add","path":"sub/note.txt","content":"new"}"#;
        let pendings = vec![patch_pending("p1", edit)];
        match plan_grant(GrantRequest::Session, &pendings, &dir).unwrap() {
            Some(GrantIntent::Write(path)) => assert_eq!(path, "sub/note.txt"),
            other => panic!("expected a write grant, got {other:?}"),
        }
        let _ = std::fs::remove_file(&file);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn plan_grant_rejects_multi_path_patch() {
        let root = std::env::temp_dir();
        let edit = concat!(
            r#"{"kind":"add","path":"a.txt","content":"x"},"#,
            r#"{"kind":"add","path":"b.txt","content":"y"}"#
        );
        let pendings = vec![patch_pending("p1", edit)];
        let err = plan_grant(GrantRequest::Session, &pendings, &root).unwrap_err();
        assert!(err.to_string().contains("multiple paths"), "{err}");
    }

    #[test]
    fn plan_grant_rejects_multiple_pending_commands() {
        let root = std::env::temp_dir();
        let pendings = vec![
            command_pending("c1", &["cargo", "test"]),
            command_pending("c2", &["git", "status"]),
        ];
        let err = plan_grant(GrantRequest::Workspace, &pendings, &root).unwrap_err();
        assert!(err.to_string().contains("ambiguous"), "{err}");
    }

    #[test]
    fn plan_grant_session_resolves_read_path() {
        let dir = std::env::temp_dir().join(format!("attini-plan-grant-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("outside.txt");
        std::fs::write(&file, "hi").expect("write");
        // A workspace root elsewhere makes the absolute target "outside".
        let root = std::env::temp_dir().join("attini-plan-grant-other");
        let pendings = vec![read_pending("r1", &file.display().to_string())];
        match plan_grant(GrantRequest::Session, &pendings, &root).unwrap() {
            Some(GrantIntent::Read(path)) => {
                assert_eq!(path, file.canonicalize().unwrap().display().to_string());
            }
            other => panic!("expected a read grant, got {other:?}"),
        }
        let _ = std::fs::remove_file(&file);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn plan_grant_rejects_unresolvable_read() {
        let root = std::env::temp_dir();
        let pendings = vec![read_pending("r1", "no-such-file-xyz.txt")];
        let err = plan_grant(GrantRequest::Session, &pendings, &root).unwrap_err();
        assert!(err.to_string().contains("no resolvable path"), "{err}");
    }

    // -------------------------------------------------------------
    // render_patch_diff / render_patch_preview_text
    // -------------------------------------------------------------

    fn patch_inv(edits: Vec<PatchTool>) -> PatchInvocation {
        PatchInvocation { edits }
    }

    #[test]
    fn patch_diff_shows_before_and_after_lines() {
        let inv = patch_inv(vec![PatchTool::Update {
            path: "src/a.rs".to_string(),
            before: "let x = 1;\nlet y = 2;".to_string(),
            after: "let x = 1;\nlet y = 3;".to_string(),
        }]);
        let out = render_patch_diff(&inv);
        assert!(out.contains("  update src/a.rs"), "{out}");
        assert!(out.contains("    - let y = 2;"), "{out}");
        assert!(out.contains("    + let y = 3;"), "{out}");
    }

    #[test]
    fn patch_diff_shows_add_content() {
        let inv = patch_inv(vec![PatchTool::Add {
            path: "src/new.rs".to_string(),
            content: "fn main() {}".to_string(),
        }]);
        let out = render_patch_diff(&inv);
        assert!(out.contains("  add src/new.rs"), "{out}");
        assert!(out.contains("    + fn main() {}"), "{out}");
    }

    #[test]
    fn patch_diff_caps_output_and_notes_omissions() {
        let many: String = (0..(PATCH_PREVIEW_MAX_LINES + 50))
            .map(|i| format!("line {i}\n"))
            .collect();
        let inv = patch_inv(vec![PatchTool::Add {
            path: "big.txt".to_string(),
            content: many,
        }]);
        let out = render_patch_diff(&inv);
        assert!(out.contains("more lines omitted"), "{out}");
        // The cap applies to body lines; total printed lines are bounded.
        assert!(
            out.lines().count() <= PATCH_PREVIEW_MAX_LINES + 1,
            "printed {} lines",
            out.lines().count()
        );
    }

    #[test]
    fn patch_preview_text_includes_diff() {
        let inv = patch_inv(vec![PatchTool::Update {
            path: "src/a.rs".to_string(),
            before: "old".to_string(),
            after: "new".to_string(),
        }]);
        let preview = PatchPreview {
            target_paths: vec!["src/a.rs".to_string()],
            added_lines: 1,
            removed_lines: 1,
            edit_count: 1,
            auto_approve: true,
            not_revertible: None,
        };
        let out = render_patch_preview_text(&preview, &inv);
        assert!(out.contains("patch preview: 1 edit(s)"), "{out}");
        assert!(out.contains("    - old"), "{out}");
        assert!(out.contains("    + new"), "{out}");
    }

    #[test]
    fn patch_approval_footer_restates_summary() {
        let preview = PatchPreview {
            target_paths: vec!["src/a.rs".to_string(), "src/b.rs".to_string()],
            added_lines: 3,
            removed_lines: 1,
            edit_count: 2,
            auto_approve: false,
            not_revertible: None,
        };
        let plain = render_patch_approval_footer(&preview);
        assert_eq!(
            plain,
            "[patch] approval required: 2 edit(s) across 2 file(s), +3 / -1 lines"
        );
    }

    // -------------------------------------------------------------
    // read_content_preview
    // -------------------------------------------------------------

    #[test]
    fn read_preview_renders_content_lines() {
        let payload =
            r#"{"content":"line one\nline two","start_line":1,"end_line":2,"truncated":false}"#;
        let out = read_content_preview(payload).expect("preview");
        assert!(out.contains("  | line one"), "{out}");
        assert!(out.contains("  | line two"), "{out}");
    }

    #[test]
    fn read_preview_caps_and_notes_omissions() {
        let many: String = (0..(READ_PREVIEW_MAX_LINES + 7))
            .map(|i| format!("l{i}"))
            .collect::<Vec<_>>()
            .join("\\n");
        let payload =
            format!(r#"{{"content":"{many}","start_line":1,"end_line":1,"truncated":false}}"#);
        let out = read_content_preview(&payload).expect("preview");
        assert!(out.contains("7 more lines omitted"), "{out}");
        assert!(out.lines().count() <= READ_PREVIEW_MAX_LINES + 1, "{out}");
    }

    #[test]
    fn read_preview_is_none_for_non_read_payloads() {
        // A list/search result has no `content` member.
        assert!(read_content_preview(r#"{"entries":[],"truncated":false}"#).is_none());
        assert!(read_content_preview("not json").is_none());
    }

    // -------------------------------------------------------------
    // read approval (outside-workspace reads)
    // -------------------------------------------------------------

    #[test]
    fn read_only_target_reads_the_path_field() {
        let read = ReadOnlyTool::Read {
            path: "../foo.txt".to_string(),
            line_range: None,
        };
        assert_eq!(read_only_target(&read), Some("../foo.txt"));
        let search = ReadOnlyTool::Search {
            pattern: "x".to_string(),
            path_prefix: None,
            case_sensitive: false,
            max_results: 10,
        };
        assert_eq!(read_only_target(&search), None);
    }

    #[test]
    fn read_extra_root_is_none_for_missing_path() {
        let root = std::env::temp_dir();
        let inv = ReadOnlyTool::Read {
            path: "definitely-missing-__attini__.txt".to_string(),
            line_range: None,
        };
        assert!(read_extra_root(&inv, &root).is_none());
    }

    #[test]
    fn read_extra_root_canonicalises_existing_path() {
        // The workspace root itself always exists; requesting it as a
        // read target yields a canonical extra root.
        let root = std::env::temp_dir();
        let expected = root.canonicalize().unwrap();
        let inv = ReadOnlyTool::List {
            path: ".".to_string(),
            recursive: false,
            max_entries: 10,
            include_hidden: false,
        };
        assert_eq!(read_extra_root(&inv, &root), Some(expected));
    }

    #[test]
    fn run_read_only_needs_approval_outside_workspace() {
        // A temp workspace with no granted roots; reading an absolute
        // path elsewhere on disk (the real cwd) is outside it.
        let workspace =
            std::env::temp_dir().join(format!("attini-read-approval-ws-{}", std::process::id()));
        std::fs::create_dir_all(&workspace).unwrap();
        let executor = ToolExecutor::new(&workspace, Vec::new(), "t".to_string()).unwrap();
        let cwd_file = std::env::current_dir().unwrap().join("Cargo.toml");
        if !cwd_file.exists() {
            // Unexpected working directory; skip rather than false-fail.
            let _ = std::fs::remove_dir_all(&workspace);
            return;
        }
        let tc = ToolCall {
            id: "call_x".to_string(),
            function_name: "read".to_string(),
            arguments_json: format!(r#"{{"path":"{}"}}"#, cwd_file.display()),
        };
        match run_read_only(&tc, &executor) {
            ReadOnlyDispatch::NeedsApproval { summary, preview } => {
                assert!(summary.contains("approval required"), "{summary}");
                assert!(preview.contains("outside workspace"), "{preview}");
            }
            ReadOnlyDispatch::Done { content, .. } => {
                panic!("expected approval request, got: {content}")
            }
        }
        let _ = std::fs::remove_dir_all(&workspace);
    }
}