linthis 0.23.0

A fast, cross-platform multi-language linter and formatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! Script generation for git hooks (thin wrappers, global scripts, agent fix blocks).

use crate::cli::commands::{AgentFixProvider, HookEvent, HookTool};

/// Build a thin wrapper script that delegates to `linthis hook run` at runtime.
///
/// The wrapper is 3 lines:
/// ```sh
/// #!/bin/sh
/// exec linthis hook run --event <event> --type <type> [--provider <p>] [--global] "$@"
/// ```
/// This means hook logic always comes from the installed linthis binary,
/// so upgrading linthis automatically updates hook behaviour without reinstallation.
pub(crate) fn build_thin_wrapper_script(
    event: &HookEvent,
    hook_type: &HookTool,
    provider: Option<&str>,
    global: bool,
    provider_args: Option<&str>,
) -> String {
    let provider_arg = provider
        .filter(|p| !p.is_empty())
        .map(|p| format!(" --provider {p}"))
        .unwrap_or_default();
    let provider_args_arg = provider_args
        .filter(|a| !a.is_empty())
        .map(|a| format!(" --provider-args '{}'", a.replace('\'', "'\\''")))
        .unwrap_or_default();
    let global_arg = if global { " --global" } else { "" };
    format!(
        "#!/bin/sh\nexec linthis hook run --event {} --type {}{}{}{} \"$@\"\n",
        event.as_str(),
        hook_type.as_str(),
        provider_arg,
        provider_args_arg,
        global_arg,
    )
}

/// Shell snippet that sets up a temporary git worktree for the initial
/// pre-push lint check, so linthis sees the content being pushed (HEAD) and
/// NOT the user's uncommitted working-tree edits.
///
/// Design decisions:
/// - Worktree lives at `~/.linthis/projects/<stub>/worktrees/<ts>-<pid>/` so
///   `rm -rf ~/.linthis/projects/<stub>/worktrees/` cleans everything for
///   one project. `<ts>-<pid>` keeps concurrent pushes unique.
/// - A sidecar meta file `<wt>/.linthis/.worktree-meta` carries the real
///   project root, and the Rust side's `get_effective_project_root()` reads
///   it so that slug-based storage (reports, patches, caches) stays under
///   the user's real project slug, not a transient worktree slug.
/// - Startup prunes orphans older than 60 min (remnants from prior
///   Ctrl-C'd runs). Trap on EXIT/HUP/INT/TERM cleans up the current one.
/// - If `git worktree add` fails for any reason, we fall back to running
///   linthis in the original working tree with a clearly labeled warning —
///   the old buggy behavior, but at least the push isn't blocked.
///
/// Emits shell that, after running, leaves:
///   $_PREPUSH_WT         — worktree path, or empty if unavailable / failed
///   $_PREPUSH_REAL_ROOT  — user's real project root
///   $_PREPUSH_CWD        — saved pre-hook working directory
pub(crate) fn shell_pre_push_worktree_setup() -> String {
    "# Pre-push isolation via git worktree. The initial lint check will run\n\
     # inside the worktree so uncommitted working-tree edits don't block a\n\
     # push whose actual committed content is clean.\n\
     _PREPUSH_CWD=\"$(pwd)\"\n\
     _PREPUSH_REAL_ROOT=\"$(git rev-parse --show-toplevel 2>/dev/null)\"\n\
     _PREPUSH_WT=\"\"\n\
     if [ -n \"$_PREPUSH_REAL_ROOT\" ]; then\n\
     \x20 _PREPUSH_STUB=$(printf '%s' \"$_PREPUSH_REAL_ROOT\" | tr '/' '-' | sed 's/^-//')\n\
     \x20 _PREPUSH_WT_BASE=\"$HOME/.linthis/projects/$_PREPUSH_STUB/worktrees\"\n\
     \x20 mkdir -p \"$_PREPUSH_WT_BASE\" 2>/dev/null\n\
     \x20 # Prune orphans older than 60 minutes (remnants of Ctrl-C'd runs)\n\
     \x20 find \"$_PREPUSH_WT_BASE\" -mindepth 1 -maxdepth 1 -type d -mmin +60 2>/dev/null | \\\n\
     \x20   while IFS= read -r _old; do\n\
     \x20\x20\x20 [ -z \"$_old\" ] && continue\n\
     \x20\x20\x20 git worktree remove --force \"$_old\" >/dev/null 2>&1 || rm -rf \"$_old\"\n\
     \x20 done\n\
     \x20 git worktree prune >/dev/null 2>&1 || true\n\
     \x20 _PREPUSH_WT=\"$_PREPUSH_WT_BASE/$(date +%s)-$$\"\n\
     \x20 _prepush_cleanup_wt() {\n\
     \x20\x20\x20 if [ -n \"$_PREPUSH_WT\" ] && [ -d \"$_PREPUSH_WT\" ]; then\n\
     \x20\x20\x20\x20\x20 git worktree remove --force \"$_PREPUSH_WT\" >/dev/null 2>&1 || rm -rf \"$_PREPUSH_WT\"\n\
     \x20\x20\x20 fi\n\
     \x20 }\n\
     \x20 trap '_prepush_cleanup_wt' EXIT HUP INT TERM\n\
     \x20 if git worktree add --detach --quiet \"$_PREPUSH_WT\" HEAD >/dev/null 2>&1; then\n\
     \x20\x20\x20 mkdir -p \"$_PREPUSH_WT/.linthis\"\n\
     \x20\x20\x20 {\n\
     \x20\x20\x20\x20\x20 echo \"# Generated by linthis pre-push hook — do not commit\"\n\
     \x20\x20\x20\x20\x20 echo \"original_project_root = \\\"$_PREPUSH_REAL_ROOT\\\"\"\n\
     \x20\x20\x20\x20\x20 echo \"purpose = \\\"pre-push check\\\"\"\n\
     \x20\x20\x20\x20\x20 echo \"created_at = \\\"$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)\\\"\"\n\
     \x20\x20\x20 } > \"$_PREPUSH_WT/.linthis/.worktree-meta\"\n\
     \x20 else\n\
     \x20\x20\x20 echo \"[linthis] ⚠ Couldn't create isolated worktree — checking working tree instead (uncommitted errors may falsely block push).\" >&2\n\
     \x20\x20\x20 _PREPUSH_WT=\"\"\n\
     \x20\x20\x20 trap - EXIT HUP INT TERM\n\
     \x20 fi\n\
     fi\n\
     # Export a real-root-based review dir for the agent. The agent runs\n\
     # INSIDE the worktree, where `git rev-parse --show-toplevel` returns\n\
     # the worktree path — turning that into a slug yields a bizarre\n\
     # `~/.linthis/projects/<wt-path-as-slug>/` directory that the script\n\
     # (running outside the worktree) can't find later. Pre-computing the\n\
     # path here from `_PREPUSH_REAL_ROOT` (or git toplevel as fallback)\n\
     # keeps the agent's writes under the user's real project slug.\n\
     if [ -n \"$_PREPUSH_STUB\" ]; then\n\
     \x20 _LINTHIS_REVIEW_DIR=\"$HOME/.linthis/projects/$_PREPUSH_STUB/review/result\"\n\
     else\n\
     \x20 _FALLBACK_SLUG=$(git rev-parse --show-toplevel 2>/dev/null | tr '/' '-' | sed 's/^-//')\n\
     \x20 _LINTHIS_REVIEW_DIR=\"$HOME/.linthis/projects/$_FALLBACK_SLUG/review/result\"\n\
     fi\n\
     mkdir -p \"$_LINTHIS_REVIEW_DIR\" 2>/dev/null\n\
     export _LINTHIS_REVIEW_DIR\n"
        .to_string()
}

/// Enter the pre-push worktree (if one was created by
/// [`shell_pre_push_worktree_setup`]) so the next command runs against
/// HEAD content. No-op when setup failed or wasn't available.
pub(crate) fn shell_pre_push_worktree_enter() -> String {
    "# Enter the worktree for the lint check (so linthis reads HEAD content)\n\
     if [ -n \"$_PREPUSH_WT\" ]; then\n\
     \x20 cd \"$_PREPUSH_WT\" || _PREPUSH_WT=\"\"\n\
     fi\n"
        .to_string()
}

/// Leave the pre-push worktree, clean it up, and clear the EXIT trap. Run
/// immediately after the initial lint check so downstream flows (precise
/// fixup, agent review) operate in the user's real project root where
/// commits can actually land on the user's branch.
pub(crate) fn shell_pre_push_worktree_leave() -> String {
    "# Leave the worktree and tear it down before any commit-creating flow\n\
     # (precise fixup, agent review) kicks in — those flows need to run in\n\
     # the user's real project so their commits land on the user's branch.\n\
     if [ -n \"$_PREPUSH_WT\" ]; then\n\
     \x20 cd \"$_PREPUSH_REAL_ROOT\" >/dev/null 2>&1 || cd \"$_PREPUSH_CWD\" >/dev/null 2>&1 || true\n\
     \x20 _prepush_cleanup_wt\n\
     \x20 _PREPUSH_WT=\"\"\n\
     \x20 trap - EXIT HUP INT TERM\n\
     fi\n"
        .to_string()
}

/// cd back to the user's real project root, but KEEP the worktree alive (and
/// its EXIT trap armed) so a later phase — the agent review — can re-enter
/// it. Pair with [`shell_pre_push_worktree_enter`] (used again to re-enter)
/// and a final [`shell_pre_push_worktree_leave`] to tear it down.
///
/// Semantic difference from `shell_pre_push_worktree_leave`: leave runs
/// `_prepush_cleanup_wt` + clears the trap; this one does neither.
pub(crate) fn shell_pre_push_worktree_exit_no_cleanup() -> String {
    "# cd back to real root for any commit-creating step (lint-fix dance)\n\
     # but keep the worktree alive — agent review will re-enter it shortly\n\
     # so the user's working tree stays untouched during the long review.\n\
     if [ -n \"$_PREPUSH_WT\" ]; then\n\
     \x20 cd \"$_PREPUSH_REAL_ROOT\" >/dev/null 2>&1 || cd \"$_PREPUSH_CWD\" >/dev/null 2>&1 || true\n\
     fi\n"
        .to_string()
}

/// Capture the agent's diff (from HEAD → current worktree state) into
/// `$_AGENT_PATCH`. Emitted INSIDE the worktree, after the agent has
/// finished modifying files. Uses `--binary` so image/pb-style content
/// survives `git apply --3way --binary` in the real root.
pub(crate) fn shell_capture_agent_patch_in_wt() -> String {
    "# Capture the agent's diff (inside the worktree) as $_AGENT_PATCH.\n\
     # The worktree was created from HEAD, so `git diff HEAD` after the\n\
     # agent's edits is exactly the agent's change-set — scoped implicitly\n\
     # because the agent only touches files it cares about.\n\
     _AGENT_PATCH=$(mktemp \"${TMPDIR:-/tmp}/linthis-agent.XXXXXX\" 2>/dev/null || mktemp)\n\
     set --\n\
     while IFS= read -r _F; do\n\
     \x20 [ -z \"$_F\" ] && continue\n\
     \x20 set -- \"$@\" \"$_F\"\n\
     done <<_AGENT_PATCH_SCOPE_EOF_\n\
     $_PUSHED_FILES\n\
     _AGENT_PATCH_SCOPE_EOF_\n\
     git diff --binary HEAD -- \"$@\" > \"$_AGENT_PATCH\" 2>/dev/null || true\n"
        .to_string()
}

/// Shell snippet for applying agent patch in "dirty" mode.
/// Applies to working tree (NOT index), letting user re-stage manually.
fn shell_apply_dirty_mode(footer_dirty_applied: &str, footer_conflict: &str) -> String {
    format!(
        "# Apply to working tree (NOT index). User re-stages manually.\n\
         # We avoid `--3way` because it implies `--index`, which\n\
         # rejects benign blob-hash mismatches (index stat drift vs.\n\
         # patch's `a/` hash) with \"does not match index\".\n\
         if git apply --binary --whitespace=nowarn \"$_AGENT_PATCH\" 2>\"$_APPLY_ERR\"; then\n\
         \x20\x20\x20 rm -f \"$_APPLY_ERR\" 2>/dev/null\n\
         {footer_dirty_applied}\
         \x20\x20\x20 [ -f \"$_AGENT_PATCH\" ] && rm -f \"$_AGENT_PATCH\"\n\
         \x20\x20\x20 exit 1\n\
         \x20\x20\x20 else\n\
         {footer_conflict}\
         \x20\x20\x20 if [ -s \"$_APPLY_ERR\" ]; then\n\
         \x20\x20\x20\x20\x20 echo \"[linthis] git apply error:\" >&2\n\
         \x20\x20\x20\x20\x20 sed 's/^/[linthis]   /' \"$_APPLY_ERR\" >&2\n\
         \x20\x20\x20 fi\n\
         \x20\x20\x20 rm -f \"$_APPLY_ERR\" 2>/dev/null\n\
         \x20\x20\x20 echo \"[linthis] Patch kept at: $_AGENT_PATCH\" >&2\n\
         \x20\x20\x20 exit 1\n\
         \x20\x20\x20 fi\n"
    )
}

/// Shell snippet for the apply failure handling in squash/fixup mode.
/// Restores stash and reports the error.
fn shell_apply_failure_handler(footer_conflict: &str) -> String {
    format!(
        "# Apply failed (rare — patch was generated from same\n\
         \x20\x20\x20\x20\x20 # HEAD that we just reset to). Restore stash and bail.\n\
         \x20\x20\x20\x20\x20 _apply_cleanup_stash\n\
         \x20\x20\x20\x20\x20 _APPLY_RESTORED=1\n\
         \x20\x20\x20\x20\x20 trap - HUP INT TERM\n\
         {footer_conflict}\
         \x20\x20\x20\x20\x20 if [ -s \"$_APPLY_ERR\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 echo \"[linthis] git apply error:\" >&2\n\
         \x20\x20\x20\x20\x20\x20\x20 sed 's/^/[linthis]   /' \"$_APPLY_ERR\" >&2\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 rm -f \"$_APPLY_ERR\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20 echo \"[linthis] Patch kept at: $_AGENT_PATCH\" >&2\n\
         \x20\x20\x20\x20\x20 exit 1\n"
    )
}

/// Shell snippet for committing the agent's fixes and restoring user state.
/// Handles both squash and fixup modes.
fn shell_commit_and_restore(
    save_diff_cached: &str,
    footer_restore_conflict: &str,
    footer_squash_applied: &str,
    footer_fixup_applied: &str,
) -> String {
    format!(
        "{save_diff_cached}\
         \x20\x20\x20\x20\x20 # Phase 4: commit. Squash folds into HEAD via the\n\
         \x20\x20\x20\x20\x20 # `commit + reset --soft HEAD~2 + commit -C HEAD@{{2}}`\n\
         \x20\x20\x20\x20\x20 # dance; fixup creates a separate commit.\n\
         \x20\x20\x20\x20\x20 if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -m \"fix(linthis): auto-fix review issues\" >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20\x20\x20 git reset --soft HEAD~2 >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -C HEAD@{{2}} >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -m \"fix(linthis): auto-fix review issues\" >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 # Phase 5: restore user state via 3-way merge so\n\
         \x20\x20\x20\x20\x20 # their staged + unstaged work lands back on top of\n\
         \x20\x20\x20\x20\x20 # the new HEAD. On overlap, conflict markers are\n\
         \x20\x20\x20\x20\x20 # left in the WT and the stash is kept (recoverable\n\
         \x20\x20\x20\x20\x20 # via `git stash list`).\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_USER_STASH\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 if ! git stash apply --index \"$_USER_STASH\" >/dev/null 2>&1; then\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 git stash store -m \"linthis: uncommitted state before pre-push squash\" \"$_USER_STASH\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 _APPLY_RESTORED=1\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 trap - HUP INT TERM\n\
         {footer_restore_conflict}\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 [ -f \"$_AGENT_PATCH\" ] && rm -f \"$_AGENT_PATCH\"\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 exit 1\n\
         \x20\x20\x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 _APPLY_RESTORED=1\n\
         \x20\x20\x20\x20\x20 trap - HUP INT TERM\n\
         \x20\x20\x20\x20\x20 if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         {footer_squash_applied}\
         \x20\x20\x20\x20\x20 else\n\
         {footer_fixup_applied}\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 [ -f \"$_AGENT_PATCH\" ] && rm -f \"$_AGENT_PATCH\"\n\
         \x20\x20\x20\x20\x20 # Write the fast-path sentinel BEFORE exiting. The next\n\
         \x20\x20\x20\x20\x20 # `git push` will see a HEAD SHA that matches what we\n\
         \x20\x20\x20\x20\x20 # just verified clean and skip the entire fix+review\n\
         \x20\x20\x20\x20\x20 # flow (which would otherwise re-run for 5+ minutes).\n\
         \x20\x20\x20\x20\x20 _SENTINEL_SHA=$(git rev-parse HEAD 2>/dev/null)\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_SENTINEL_SHA\" ] && [ -n \"$_PREPUSH_STUB\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 _SENTINEL_DIR=\"$HOME/.linthis/projects/$_PREPUSH_STUB\"\n\
         \x20\x20\x20\x20\x20\x20\x20 mkdir -p \"$_SENTINEL_DIR\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20\x20\x20 printf '%s\\n' \"$_SENTINEL_SHA\" > \"$_SENTINEL_DIR/pre-push-sentinel\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 # MUST exit 1 here even though we just landed a clean\n\
         \x20\x20\x20\x20\x20 # squash/fixup commit. Reason: git pre-push collects the\n\
         \x20\x20\x20\x20\x20 # to-be-pushed SHA BEFORE invoking this hook. The squash\n\
         \x20\x20\x20\x20\x20 # dance just rewrote HEAD locally, but git push will still\n\
         \x20\x20\x20\x20\x20 # try to push the OLD (pre-squash) SHA. Exiting 0 here\n\
         \x20\x20\x20\x20\x20 # ships the unfixed commit to remote and leaves the local\n\
         \x20\x20\x20\x20\x20 # squashed HEAD diverged. Exiting 1 aborts the push so\n\
         \x20\x20\x20\x20\x20 # the user re-runs `git push` — that re-collects the SHA\n\
         \x20\x20\x20\x20\x20 # (now the squashed one) and ships the fixed version. The\n\
         \x20\x20\x20\x20\x20 # sentinel above lets the second push fast-skip the\n\
         \x20\x20\x20\x20\x20 # 5+ minute fix+review flow.\n\
         \x20\x20\x20\x20\x20 exit 1\n"
    )
}

/// Shell snippet for applying agent patch in "squash" or "fixup" mode.
/// Isolates agent's patch from user's uncommitted state, commits, then restores.
fn shell_apply_squash_fixup_mode(
    save_diff_cached: &str,
    footer_conflict: &str,
    footer_restore_conflict: &str,
    footer_squash_applied: &str,
    footer_fixup_applied: &str,
) -> String {
    let failure_handler = shell_apply_failure_handler(footer_conflict);
    let commit_restore = shell_commit_and_restore(
        save_diff_cached,
        footer_restore_conflict,
        footer_squash_applied,
        footer_fixup_applied,
    );

    format!(
        "# squash / fixup: ISOLATE agent's patch from any\n\
         \x20\x20\x20 # uncommitted user state in the user's WT/index, so the\n\
         \x20\x20\x20 # auto-created commit contains ONLY agent fixes — never\n\
         \x20\x20\x20 # the user's unrelated work-in-progress edits to the same\n\
         \x20\x20\x20 # pushed files. Mirrors `shell_prepush_precise_flow`'s\n\
         \x20\x20\x20 # snapshot/reset/apply/restore pattern, but the patch\n\
         \x20\x20\x20 # source here is the agent's diff (already in $_AGENT_PATCH)\n\
         \x20\x20\x20 # rather than `linthis -f`.\n\
         \x20\x20\x20 # Phase 0: snapshot user's full WT + index state. Empty\n\
         \x20\x20\x20 # string when there's nothing to stash (clean WT).\n\
         \x20\x20\x20 _USER_STASH=$(git stash create 2>/dev/null || echo \"\")\n\
         \x20\x20\x20 _APPLY_RESTORED=0\n\
         \x20\x20\x20 _apply_cleanup_stash() {{\n\
         \x20\x20\x20\x20\x20 if [ \"$_APPLY_RESTORED\" = \"0\" ] && [ -n \"$_USER_STASH\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 git stash apply --index \"$_USER_STASH\" >/dev/null 2>&1 || \\\n\
         \x20\x20\x20\x20\x20\x20\x20   git stash store -m \"linthis: pre-push apply recovery\" \"$_USER_STASH\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20 }}\n\
         \x20\x20\x20 trap '_apply_cleanup_stash' HUP INT TERM\n\
         \x20\x20\x20 # Phase 1: clear WT + index for pushed files only — leaves\n\
         \x20\x20\x20 # other working-tree state untouched.\n\
         \x20\x20\x20 while IFS= read -r _F; do\n\
         \x20\x20\x20\x20\x20 [ -z \"$_F\" ] && continue\n\
         \x20\x20\x20\x20\x20 git reset HEAD -- \"$_F\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20\x20\x20 git checkout HEAD -- \"$_F\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20 done <<_APPLY_RESET_EOF_\n\
         $_PUSHED_FILES\n\
         _APPLY_RESET_EOF_\n\
         \x20\x20\x20 # Phase 2: apply agent patch onto the clean (HEAD) version\n\
         \x20\x20\x20 # of the pushed files. No user state in the way → patch\n\
         \x20\x20\x20 # applies cleanly; no overlap surface.\n\
         \x20\x20\x20 if ! git apply --binary --whitespace=nowarn \"$_AGENT_PATCH\" 2>\"$_APPLY_ERR\"; then\n\
         {failure_handler}\
         \x20\x20\x20 fi\n\
         \x20\x20\x20 rm -f \"$_APPLY_ERR\" 2>/dev/null\n\
         \x20\x20\x20 # Phase 3: stage the pushed files. Index now contains ONLY\n\
         \x20\x20\x20 # the agent's diff — user's pre-existing staged/unstaged\n\
         \x20\x20\x20 # work was stashed in Phase 0 and is not visible here.\n\
         \x20\x20\x20 while IFS= read -r _F; do\n\
         \x20\x20\x20\x20\x20 [ -z \"$_F\" ] && continue\n\
         \x20\x20\x20\x20\x20 git add -- \"$_F\" 2>/dev/null || true\n\
         \x20\x20\x20 done <<_APPLY_STAGE_EOF_\n\
         $_PUSHED_FILES\n\
         _APPLY_STAGE_EOF_\n\
         \x20\x20\x20 _SCOPED_STAGED=$(git diff --cached --name-only)\n\
         \x20\x20\x20 if [ -n \"$_SCOPED_STAGED\" ]; then\n\
         {commit_restore}\
         \x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20 # Nothing to commit — restore stash and continue.\n\
         \x20\x20\x20\x20\x20 _apply_cleanup_stash\n\
         \x20\x20\x20\x20\x20 _APPLY_RESTORED=1\n\
         \x20\x20\x20\x20\x20 trap - HUP INT TERM\n\
         \x20\x20\x20 fi\n"
    )
}

/// Apply the captured agent patch to the user's real project root and
/// commit per `$_FIX_MODE`. Run AFTER [`shell_pre_push_worktree_leave`]
/// (patch is a tempfile, independent of the now-deleted worktree).
///
/// - `dirty`: `git apply --3way --binary` (no `--index`) → changes land
///   in the working tree unstaged; user reviews + commits manually.
/// - `squash`: `git apply --3way --binary --index` → staged → `git
///   commit` + `git reset --soft HEAD~2` + `git commit -C HEAD@{2}` to
///   fold the fix into the latest commit.
/// - `fixup`: `git apply --3way --binary --index` → staged → `git
///   commit` as a separate fix(linthis) commit.
///
/// Conflict handling: `git apply --3way` returns non-zero when the user's
/// uncommitted edits overlap with the agent's; conflict markers are left
/// in the working tree. The Conflict footer points the user at `git diff`
/// + manual resolution.
///
/// Fallbacks if `$_AGENT_PATCH` is empty: skip everything (agent made no
/// changes worth committing) but still invoke the Clean footer at the
/// caller level if desired.
pub(crate) fn shell_apply_agent_patch_by_mode() -> String {
    let save_diff_cached = shell_save_diff_patch_cached();
    let footer_dirty_applied = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Dirty,
        event: &HookEvent::PrePush,
        header: "Agent fixes left in working tree (dirty mode).",
        indent: "     ",
    });
    let footer_squash_applied = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PrePush,
        header: "Agent fixes squashed into latest commit. Review, then 'git push' again to ship the squashed version.",
        indent: "     ",
    });
    let footer_fixup_applied = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Fixup,
        event: &HookEvent::PrePush,
        header: "Created fixup commit with agent fixes. Review, then 'git push' again to ship the fixup commit.",
        indent: "     ",
    });
    let footer_conflict = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Conflict,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PrePush,
        header: "⚠ Your uncommitted changes overlap with agent fixes. Working tree has conflict markers — resolve, then 'git push' again.",
        indent: "     ",
    });
    let footer_restore_conflict = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Conflict,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PrePush,
        header: "⚠ Squash succeeded, but restoring your uncommitted changes left conflict markers in the working tree. Recovery: 'git stash list' (find 'linthis: pre-push').",
        indent: "     ",
    });

    let dirty_mode_script = shell_apply_dirty_mode(&footer_dirty_applied, &footer_conflict);
    let squash_fixup_script = shell_apply_squash_fixup_mode(
        &save_diff_cached,
        &footer_conflict,
        &footer_restore_conflict,
        &footer_squash_applied,
        &footer_fixup_applied,
    );

    format!(
        "# Apply agent's captured patch to the real project root per mode.\n\
         # Empty patch = agent made no changes → nothing to do.\n\
         if [ -s \"$_AGENT_PATCH\" ]; then\n\
         \x20 _APPLY_ERR=$(mktemp \"${{TMPDIR:-/tmp}}/linthis-apply-err.XXXXXX\" 2>/dev/null || mktemp)\n\
         \x20 if [ \"$_FIX_MODE\" = \"dirty\" ]; then\n\
         {dirty_mode_script}\
         \x20 else\n\
         {squash_fixup_script}\
         \x20 fi\n\
         fi\n\
         [ -f \"$_AGENT_PATCH\" ] && rm -f \"$_AGENT_PATCH\"\n"
    )
}

/// Build the shell preamble and local-hook argument style for pre-push events.
/// Returns (preamble_script, local_hook_args_expression).
///
/// Visibility: the preamble emits explicit `[linthis]` messages for every
/// early-exit path (tag push, empty diff) so users can see what happened
/// instead of a silent `exit 0`. It also falls back to `@{u}..HEAD` and then
/// `HEAD~1..HEAD` if the stdin-provided remote SHA isn't locally reachable
/// (which makes `git diff $_REMOTE_SHA..$_LOCAL_SHA` silently return nothing).
pub(crate) fn build_pre_push_preamble() -> (String, &'static str) {
    let preamble = "# For pre-push: save remote args, read stdin for push info\n\
         _REMOTE_NAME=\"$1\"\n\
         _REMOTE_URL=\"$2\"\n\
         # Read push info from stdin: <local_ref> <local_sha> <remote_ref> <remote_sha>\n\
         _IS_TAG=0\n\
         _LOCAL_SHA=\"\"\n\
         _REMOTE_SHA=\"\"\n\
         while read -r _LREF _LSHA _RREF _RSHA; do\n\
         \x20 # Skip tag pushes — no source code to check\n\
         \x20 case \"$_LREF\" in refs/tags/*) _IS_TAG=1 ;; esac\n\
         \x20 _LOCAL_SHA=\"$_LSHA\"\n\
         \x20 _REMOTE_SHA=\"$_RSHA\"\n\
         done\n\
         if [ \"$_IS_TAG\" = \"1\" ]; then\n\
         \x20 echo \"[linthis] Tag push detected — skipping pre-push check.\" >&2\n\
         \x20 exit 0\n\
         fi\n\
         # Compute changed files between remote and local, with fallbacks\n\
         # for when the remote SHA isn't locally reachable.\n\
         _ZERO_SHA=\"0000000000000000000000000000000000000000\"\n\
         if [ \"$_REMOTE_SHA\" = \"$_ZERO_SHA\" ]; then\n\
         \x20 # New branch: diff against upstream or HEAD~1\n\
         \x20 _BASE=$(git rev-parse '@{u}' 2>/dev/null || git rev-parse 'HEAD~1' 2>/dev/null || echo \"$_LOCAL_SHA\")\n\
         else\n\
         \x20 _BASE=\"$_REMOTE_SHA\"\n\
         fi\n\
         # Use `git diff --name-only` (tree delta between the two endpoints):\n\
         # if the net effect of the push range is identical content for a\n\
         # file (e.g. added then reverted within the push), that file's final\n\
         # state already exists in the remote tree and has already been\n\
         # reviewed — no need to re-lint. Only files whose final content\n\
         # differs from the remote's tree are worth checking.\n\
         _PUSHED_FILES=$(git diff --name-only \"$_BASE\"..\"$_LOCAL_SHA\" 2>/dev/null | grep -v '^$')\n\
         # Fallback: if diff failed or is empty (e.g. remote SHA not fetched),\n\
         # try upstream, then HEAD~1.\n\
         if [ -z \"$_PUSHED_FILES\" ]; then\n\
         \x20 _FALLBACK_BASE=$(git rev-parse '@{u}' 2>/dev/null || git rev-parse 'HEAD~1' 2>/dev/null)\n\
         \x20 if [ -n \"$_FALLBACK_BASE\" ] && [ \"$_FALLBACK_BASE\" != \"$_BASE\" ]; then\n\
         \x20\x20\x20 _PUSHED_FILES=$(git diff --name-only \"$_FALLBACK_BASE\"..HEAD 2>/dev/null | grep -v '^$')\n\
         \x20\x20\x20 if [ -n \"$_PUSHED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20 echo \"[linthis] Remote SHA not fetched locally — using $_FALLBACK_BASE as base.\" >&2\n\
         \x20\x20\x20 fi\n\
         \x20 fi\n\
         fi\n\
         # No files to push = nothing to check\n\
         if [ -z \"$_PUSHED_FILES\" ]; then\n\
         \x20 echo \"[linthis] No source files changed between $_BASE and local HEAD — skipping pre-push check.\" >&2\n\
         \x20 exit 0\n\
         fi\n\
         _LINTHIS_FILE_COUNT=$(printf \"%s\\n\" \"$_PUSHED_FILES\" | grep -c '^')\n\
         echo \"[linthis] Pre-push check: verifying $_LINTHIS_FILE_COUNT file(s)...\" >&2\n\
         set --\n\
         while IFS= read -r _F; do set -- \"$@\" -i \"$_F\"; done <<_EOF_\n\
         $_PUSHED_FILES\n\
         _EOF_\n\
         \n";
    let full = format!(
        "{preamble}{worktree_setup}",
        preamble = preamble,
        worktree_setup = shell_pre_push_worktree_setup(),
    );
    (full, "\"$_REMOTE_NAME\" \"$_REMOTE_URL\"")
}

/// Build the agent fix command for a given hook event.
pub(crate) fn agent_fix_cmd_for_event(
    provider: &AgentFixProvider,
    hook_event: &HookEvent,
) -> String {
    if matches!(hook_event, HookEvent::CommitMsg) {
        agent_fix_headless_cmd_commit_msg(provider, None)
    } else {
        let prompt = agent_fix_prompt_for_event(hook_event);
        agent_fix_headless_cmd(provider, &prompt, None)
    }
}

/// Shell snippet that gates an agent invocation behind the
/// `LINTHIS_AGENT_MAX_AUTO_FIX` threshold, prints a streaming header +
/// elapsed-time footer, and lets the agent's output flow straight to
/// stderr (no spinner — the spinner's `\033[1A\r\033[K` overwrites would
/// clobber the agent's per-tool-call output).
///
/// Exports `_AGENT_RAN=1` iff the agent actually ran (not skipped by
/// threshold), so callers can decide whether to re-verify.
///
/// - `indent` is the per-line prefix (spaces) matching the surrounding
///   if-block depth; pass `"     "` for two-nested, `"   "` for one.
/// - `error_msg` is the short verb used in the header ("Fix errors", etc.).
fn shell_agent_invoke_block(
    provider: &AgentFixProvider,
    agent_cmd: &str,
    error_msg: &str,
    indent: &str,
) -> String {
    // Thresholds: 0 disables the cap. Default picked to protect against
    // runaway sessions on huge error sets while still covering the common
    // case (a handful to a few dozen issues).
    // Important: parse `linthis report count` output without touching $@.
    // `set -- $counts` would clobber positional params, and the commit-msg
    // agent command relies on $1 to locate $_MSG_FILE — losing that made
    // Claude write its fix to a file literally named "0". Use parameter
    // expansion instead, which is POSIX-portable and side-effect-free.
    format!(
        "{i}_AGENT_RAN=0\n\
         {i}_AGENT_MAX=\"${{LINTHIS_AGENT_MAX_AUTO_FIX:-100}}\"\n\
         {i}_AGENT_COUNTS=$(linthis report count 2>/dev/null || echo \"0 0 0 0\")\n\
         {i}_AGENT_ERR=${{_AGENT_COUNTS%% *}}\n\
         {i}_AGENT_REM=${{_AGENT_COUNTS#* }}\n\
         {i}_AGENT_WARN=${{_AGENT_REM%% *}}\n\
         {i}_AGENT_FILES=${{_AGENT_COUNTS##* }}\n\
         {i}_AGENT_TOTAL=$((_AGENT_ERR + _AGENT_WARN))\n\
         {i}if [ \"$_AGENT_MAX\" != \"0\" ] && [ \"$_AGENT_TOTAL\" -gt \"$_AGENT_MAX\" ]; then\n\
         {i}  echo \"[linthis] ⚠ Too many issues ($_AGENT_TOTAL in $_AGENT_FILES files) — auto-fix skipped to avoid long blocking run\" >&2\n\
         {i}  echo \"[linthis]   Fix interactively (live progress): linthis fix --ai --provider {provider_cli}\" >&2\n\
         {i}  echo \"[linthis]   Raise the threshold: LINTHIS_AGENT_MAX_AUTO_FIX=$((_AGENT_TOTAL + 10)) git ...\" >&2\n\
         {i}  echo \"[linthis]   Disable the cap:    LINTHIS_AGENT_MAX_AUTO_FIX=0 git ...\" >&2\n\
         {i}else\n\
         {i}  printf \"${{_LINTHIS_W}}[linthis] {error_msg}. Found $_AGENT_TOTAL issues in $_AGENT_FILES files — invoking {provider}...${{_LINTHIS_R}}\\n\"\n\
         {i}  printf \"${{_LINTHIS_W}}[linthis] ─── {provider} output (streaming; Ctrl-C to cancel) ───${{_LINTHIS_R}}\\n\"\n\
         {i}  _AGENT_START=$(date +%s)\n\
         {i}  # Wrap the agent pipeline so each command's stderr (claude/codebuddy progress,\n\
         {i}  # agent-stream diagnostics) is merged into stdout. IDE terminals colour stderr\n\
         {i}  # red, and none of this output signals failure.\n\
         {i}  {{ {agent} ; }} 2>&1\n\
         {i}  _AGENT_ELAPSED=$(($(date +%s) - _AGENT_START))\n\
         {i}  printf \"${{_LINTHIS_W}}[linthis] ─── {provider} done in ${{_AGENT_ELAPSED}}s ───${{_LINTHIS_R}}\\n\"\n\
         {i}  _AGENT_RAN=1\n\
         {i}fi\n",
        i = indent,
        provider = provider,
        provider_cli = provider.as_str(),
        agent = agent_cmd,
        error_msg = error_msg,
    )
}

/// Shell snippet showing how to review/undo the agent's changes.
/// Printed after the agent finishes and before re-verify, so the user sees
/// the hint even if re-verify fails (and they need to undo).
///
/// Uses `git diff --cached` for viewing because linthis's own backup tracks
/// format changes (small), not the full agent rewrite. The staged diff
/// against HEAD shows exactly what the agent changed.
fn shell_agent_fix_hint(indent: &str) -> String {
    // stdout + IDE-safe colour wrapping (see shell_timer_functions for the
    // $_LINTHIS_W / $_LINTHIS_WR / $_LINTHIS_R convention).
    format!(
        "{i}printf \"${{_LINTHIS_W}}[linthis] \\033[0;32m✓${{_LINTHIS_WR}} Agent fix applied${{_LINTHIS_R}}\\n\"\n\
         {i}printf \"${{_LINTHIS_W}}[linthis]   View changes : \\033[0;36mgit diff --cached${{_LINTHIS_R}}\\n\"\n\
         {i}printf \"${{_LINTHIS_W}}[linthis]   Undo changes : \\033[0;33mlinthis backup undo${{_LINTHIS_R}}\\n\"\n",
        i = indent
    )
}

// ──────────────────────────────────────────────────────────────────────────
// Unified hook footer (step 1 of the isolation refactor).
//
// Replaces the ad-hoc `echo`/`printf` blocks that used to appear at the tail
// of every success/failure branch across pre-commit, pre-push, and
// post-commit hook scripts. The earlier output had two flavours and each
// branch picked one — some printed just `Tip : switch mode → ...`, others
// printed the long `Currently: --type` + per-mode description block + `View
// changes`/`Undo changes` hints. This helper is the union: one call site per
// branch emits a consistent, information-complete footer. Call sites are
// migrated in step 2; old helpers stay until the replacement is done.
// ──────────────────────────────────────────────────────────────────────────

/// Outcome category for the unified hook footer. Drives which optional
/// sections are emitted.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum FooterOutcome {
    /// Fixes landed (format or agent). Emits View/Undo lines and the
    /// optional "Undo (by patch created)" line when `$_DIFF_FILE` is set.
    Applied,
    /// Check passed with no action. Minimal footer (header only).
    Clean,
    /// Unfixable issues blocked the commit/push. Emits the Switch
    /// fix_commit_mode block, plus the hook-type upgrade hint when
    /// `hook_type == HookTypeLabel::Git`.
    Blocked,
    /// `git apply --3way` (or `patch`) left conflict markers in the working
    /// tree. Same sections as Applied minus the undo lines — user must
    /// resolve by hand.
    Conflict,
}

/// Commit-handling mode for fixes. Mirrors `hook.<event>.fix_commit_mode`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum FixCommitMode {
    /// Leave fixes unstaged in the working tree; block the commit/push.
    Dirty,
    /// Fold fixes into the current commit (pre-commit) or latest commit
    /// (pre-push: `git reset --soft HEAD~2 && git commit -C HEAD@{2}`).
    Squash,
    /// Create a separate `fix(linthis)` commit on top.
    Fixup,
}

impl FixCommitMode {
    /// Plain slug — matches the config value. Used by step 2 (sentinel
    /// writer) and step 4 (post-commit fixup reader).
    #[allow(dead_code)]
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            FixCommitMode::Dirty => "dirty",
            FixCommitMode::Squash => "squash",
            FixCommitMode::Fixup => "fixup",
        }
    }

    /// Mode name + short alias in parens, padded so `=` aligns across
    /// all three mode lines. The short alias (`d`/`s`/`f`) is also a
    /// valid input anywhere `fix_commit_mode` is accepted — CLI flag
    /// (`--fix-commit-mode s`) and config (`linthis config set
    /// hook.<event>.fix_commit_mode s -g`).
    fn padded_name(self) -> &'static str {
        match self {
            FixCommitMode::Dirty => "dirty  (d)",
            FixCommitMode::Squash => "squash (s)",
            FixCommitMode::Fixup => "fixup  (f)",
        }
    }
}

/// Hook provider type. Controls whether the "Switch to git-with-agent"
/// upgrade hint is emitted on Blocked.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum HookTypeLabel {
    /// `--type git` — lint-only, no AI fallback.
    Git,
    /// `--type git-with-agent` — AI attempts to fix on lint failure.
    GitWithAgent,
}

/// Context needed to render `shell_hook_footer`.
///
/// `header` is emitted verbatim on the first line after `[linthis] `; the
/// caller chooses the exact wording so each branch can still describe its
/// own outcome (e.g. "Created fixup commit with format changes" vs
/// "✓ Agent fix applied").
pub(crate) struct FooterCtx<'a> {
    pub outcome: FooterOutcome,
    pub hook_type: HookTypeLabel,
    pub mode: FixCommitMode,
    pub event: &'a HookEvent,
    pub header: &'a str,
    pub indent: &'a str,
}

/// Config-key event slug for `hook.<event>.fix_commit_mode`. Note that
/// `PostCommit` is the *target* of the pre-commit fixup sentinel — its
/// footer still talks about `hook.pre_commit.fix_commit_mode` because that
/// is the config key the user tunes.
fn footer_event_config_key(event: &HookEvent) -> &'static str {
    match event {
        HookEvent::PreCommit | HookEvent::PostCommit => "pre_commit",
        HookEvent::PrePush => "pre_push",
        HookEvent::CommitMsg => "commit_msg",
    }
}

/// "View changes" command per (event, mode). For PostCommit the hook always
/// creates a fixup commit on top of the user's commit, so `HEAD~1` is the
/// stable anchor regardless of `mode`.
fn footer_view_cmd(event: &HookEvent, mode: FixCommitMode) -> &'static str {
    match (event, mode) {
        (HookEvent::PreCommit, FixCommitMode::Dirty) => "git diff",
        (HookEvent::PreCommit, FixCommitMode::Squash) => "git diff --cached",
        (HookEvent::PreCommit, FixCommitMode::Fixup) => "git diff HEAD~1",
        (HookEvent::PrePush, FixCommitMode::Dirty) => "git diff",
        (HookEvent::PrePush, FixCommitMode::Squash) => "git diff HEAD~1",
        (HookEvent::PrePush, FixCommitMode::Fixup) => "git diff HEAD~1",
        (HookEvent::PostCommit, _) => "git diff HEAD~1",
        (HookEvent::CommitMsg, _) => "git log -1",
    }
}

/// "Undo changes" command per (event, mode).
fn footer_undo_cmd(event: &HookEvent, mode: FixCommitMode) -> &'static str {
    match (event, mode) {
        (HookEvent::PreCommit, FixCommitMode::Dirty) => "linthis backup undo",
        (HookEvent::PreCommit, FixCommitMode::Squash) => "git reset HEAD",
        (HookEvent::PreCommit, FixCommitMode::Fixup) => "git reset HEAD~1",
        (HookEvent::PrePush, FixCommitMode::Dirty) => "linthis backup undo",
        (HookEvent::PrePush, FixCommitMode::Squash) => "git reset HEAD~1",
        (HookEvent::PrePush, FixCommitMode::Fixup) => "git reset HEAD~1",
        (HookEvent::PostCommit, _) => "git reset HEAD~1",
        (HookEvent::CommitMsg, _) => "git commit --amend",
    }
}

/// Closing marker shown as the very last line of the footer. Gives the
/// user an explicit "flow complete" signal and points at the next step.
///
/// Motivation: in modes that BLOCK the commit/push (dirty-Applied,
/// Blocked, Conflict), there's no downstream `[master xxxx] ...` git
/// summary to signal "flow done". Users have reported confusion over
/// whether the hook is still running after the Switch-fix_commit_mode
/// block — adding this line removes the ambiguity.
///
/// Skipped for:
/// - `Clean` outcome (nothing happened, no action needed)
/// - `CommitMsg` event (agent-fix flow already prints its own ✓ New
///   message line)
/// - `PostCommit` event (git's own commit summary follows)
fn footer_end_hint(
    outcome: FooterOutcome,
    mode: FixCommitMode,
    event: &HookEvent,
) -> Option<String> {
    if matches!(event, HookEvent::CommitMsg | HookEvent::PostCommit) {
        return None;
    }
    let retry_cmd = match event {
        HookEvent::PrePush => "git push",
        _ => "git commit",
    };
    match outcome {
        FooterOutcome::Clean => None,
        FooterOutcome::Applied => match mode {
            FixCommitMode::Dirty => Some(format!(
                "✓ Done — review with 'git diff', stage with 'git add', then '{retry_cmd}' again."
            )),
            FixCommitMode::Squash | FixCommitMode::Fixup => Some(format!(
                "✓ Done — review the auto-fix, then '{retry_cmd}' again."
            )),
        },
        FooterOutcome::Blocked => Some(format!(
            "✗ Blocked — fix the errors above manually, then '{retry_cmd}' again."
        )),
        FooterOutcome::Conflict => Some(format!(
            "⚠ Conflict — resolve markers in the working tree, then '{retry_cmd}' again."
        )),
    }
}

/// Per-mode description for the Switch block. Phrasing differs between
/// pre-commit and pre-push because the commit targets differ (the pending
/// commit vs. the latest commit). PostCommit reuses pre-commit phrasing
/// since its config key is also `hook.pre_commit.fix_commit_mode`.
fn footer_mode_desc(event: &HookEvent, mode: FixCommitMode) -> &'static str {
    match (event, mode) {
        (HookEvent::PreCommit | HookEvent::PostCommit, FixCommitMode::Dirty) => {
            "format left unstaged; commit blocks, you re-stage manually"
        }
        (HookEvent::PreCommit | HookEvent::PostCommit, FixCommitMode::Squash) => {
            "format auto-staged into your commit — one commit"
        }
        (HookEvent::PreCommit | HookEvent::PostCommit, FixCommitMode::Fixup) => {
            "commit proceeds; a separate auto-fix commit is created post-commit"
        }
        (HookEvent::PrePush, FixCommitMode::Dirty) => {
            "fixes left in working tree; push blocks, you re-stage manually"
        }
        (HookEvent::PrePush, FixCommitMode::Squash) => {
            "fixes squashed into latest commit; run 'git push' again"
        }
        (HookEvent::PrePush, FixCommitMode::Fixup) => {
            "fixes go into a separate fixup commit; run 'git push' again"
        }
        (HookEvent::CommitMsg, _) => "commit-msg has no fix_commit_mode",
    }
}

/// Emit the unified hook footer. Shape (top → bottom):
///
/// ```text
/// [linthis] <header>
/// [linthis]   View changes : <cmd>                          ── Applied / Conflict
/// [linthis]   Undo changes : <cmd>                          ── Applied only
/// [linthis]   Undo (by patch created) : git apply -R ...    ── Applied + $_DIFF_FILE non-empty
/// [linthis]   Currently: --type git                         ── Blocked + Git
/// [linthis]   → Want auto-fix + AI code review? Switch hook type:
/// [linthis]     linthis hook install -g --type git-with-agent --provider <...> --event <event> --force
/// [linthis]   → Switch fix_commit_mode: linthis config set hook.<event>.fix_commit_mode <mode> -g
/// [linthis]       dirty  (d) = <desc>  [(current) if active]
/// [linthis]       squash (s) = <desc>  [(current) if active]
/// [linthis]       fixup  (f) = <desc>  [(current) if active]
/// [linthis] ✓ Done — review ..., then 'git commit|push' again.     ── end marker
/// ```
///
/// All output is `printf` to stdout with the `${_LINTHIS_W}...${_LINTHIS_R}`
/// wrap — IDE VCS consoles do not colour stdout red, so these informational
/// lines don't look like errors. Genuine error streams (linthis's per-file
/// diagnostics, git's own failure output) are unaffected; they still go to
/// stderr from their own sources.
pub(crate) fn shell_hook_footer(ctx: &FooterCtx<'_>) -> String {
    let i = ctx.indent;
    let mut out = String::new();

    out.push_str(&format!(
        "{i}printf \"${{_LINTHIS_W}}[linthis] {header}${{_LINTHIS_R}}\\n\"\n",
        header = ctx.header,
    ));

    let applied = matches!(ctx.outcome, FooterOutcome::Applied);
    let conflict = matches!(ctx.outcome, FooterOutcome::Conflict);
    let blocked = matches!(ctx.outcome, FooterOutcome::Blocked);
    let clean = matches!(ctx.outcome, FooterOutcome::Clean);

    if applied || conflict {
        out.push_str(&format!(
            "{i}printf \"${{_LINTHIS_W}}[linthis]   View changes : \\033[0;36m{view}${{_LINTHIS_R}}\\n\"\n",
            view = footer_view_cmd(ctx.event, ctx.mode),
        ));
    }
    if applied {
        out.push_str(&format!(
            "{i}printf \"${{_LINTHIS_W}}[linthis]   Undo changes : \\033[0;33m{undo}${{_LINTHIS_R}}\\n\"\n",
            undo = footer_undo_cmd(ctx.event, ctx.mode),
        ));
        out.push_str(&format!(
            "{i}[ -n \"$_DIFF_FILE\" ] && printf \"${{_LINTHIS_W}}[linthis]   Undo (by patch created) : \\033[0;33mgit apply -R $_DIFF_FILE${{_LINTHIS_R}}\\n\"\n"
        ));
    }

    if blocked && matches!(ctx.hook_type, HookTypeLabel::Git) {
        let event_name = ctx.event.hook_filename();
        out.push_str(&format!(
            "{i}printf \"${{_LINTHIS_W}}[linthis]   Currently: --type git${{_LINTHIS_R}}\\n\"\n\
             {i}printf \"${{_LINTHIS_W}}[linthis]   → Want auto-fix + AI code review? Switch hook type:${{_LINTHIS_R}}\\n\"\n\
             {i}printf \"${{_LINTHIS_W}}[linthis]     linthis hook install -g --type git-with-agent --provider <claude|codebuddy|...> --event {event_name} --force${{_LINTHIS_R}}\\n\"\n"
        ));
    }

    // Switch fix_commit_mode block: emit for every outcome except Clean
    // (Clean means nothing happened — no mode guidance needed).
    if !clean && !matches!(ctx.event, HookEvent::CommitMsg) {
        let key = footer_event_config_key(ctx.event);
        out.push_str(&format!(
            "{i}printf \"${{_LINTHIS_W}}[linthis]   → Switch fix_commit_mode: \\033[0;36mlinthis config set hook.{key}.fix_commit_mode <mode> -g${{_LINTHIS_R}}\\n\"\n"
        ));
        for m in [
            FixCommitMode::Dirty,
            FixCommitMode::Squash,
            FixCommitMode::Fixup,
        ] {
            let padded = m.padded_name();
            let desc = footer_mode_desc(ctx.event, m);
            let current = if m == ctx.mode { " (current)" } else { "" };
            out.push_str(&format!(
                "{i}printf \"${{_LINTHIS_W}}[linthis]       {padded} = {desc}{current}${{_LINTHIS_R}}\\n\"\n"
            ));
        }
    }

    // Closing "flow complete" marker + next-step hint. Explicit end-of-
    // output signal for modes that don't have a trailing git summary to
    // signal completion (dirty, Blocked, Conflict).
    if let Some(hint) = footer_end_hint(ctx.outcome, ctx.mode, ctx.event) {
        out.push_str(&format!(
            "{i}printf \"${{_LINTHIS_W}}[linthis] {hint}${{_LINTHIS_R}}\\n\"\n"
        ));
    }

    out
}

/// Shell snippet that writes the pre-commit → post-commit fixup sentinel
/// at `.git/linthis/pending-fixup.json`.
///
/// The post-commit hook (both [`build_post_commit_script`] and
/// [`build_post_commit_with_agent_script`]) reads this file as its
/// activation gate: its existence means "pre-commit fixup mode ran, now
/// do the auto-fix commit". The file's CONTENTS are informational only
/// (the gate just tests for existence), so the JSON body is minimal —
/// just event/mode/timestamp for debugging and audit.
///
/// Path: resolved via `git rev-parse --git-dir` so it works in both
/// normal repositories and worktrees.
///
/// Failure mode: `mkdir` and the JSON write are LOUD — they print a
/// warning to stderr instead of silently swallowing errors. Without this,
/// a read-only / full / permission-broken `.git` would silently skip
/// post-commit fixup work; the user needs to see the warning to fix the
/// underlying environment problem.
fn shell_write_pending_fixup_sentinel(indent: &str) -> String {
    format!(
        "{i}# Write post-commit fixup sentinel. The post-commit hook gates\n\
         {i}# its activation on the presence of this file. Failures here are\n\
         {i}# loud (printed to stderr) so a broken .git won't silently skip\n\
         {i}# the post-commit fixup work.\n\
         {i}_GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)\n\
         {i}if [ -n \"$_GIT_DIR\" ]; then\n\
         {i}  if ! mkdir -p \"$_GIT_DIR/linthis\"; then\n\
         {i}    printf >&2 '[linthis] warning: failed to create %s/linthis (post-commit fixup will skip)\\n' \"$_GIT_DIR\"\n\
         {i}  else\n\
         {i}    if ! {{\n\
         {i}      echo '{{'\n\
         {i}      echo '  \"event\": \"pre_commit\",'\n\
         {i}      echo '  \"mode\": \"fixup\",'\n\
         {i}      printf '  \"created_at\": \"%s\"\\n' \"$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)\"\n\
         {i}      echo '}}'\n\
         {i}    }} > \"$_GIT_DIR/linthis/pending-fixup.json\"; then\n\
         {i}      printf >&2 '[linthis] warning: failed to write %s/linthis/pending-fixup.json (post-commit fixup will skip)\\n' \"$_GIT_DIR\"\n\
         {i}    fi\n\
         {i}  fi\n\
         {i}fi\n",
        i = indent,
    )
}

/// Save staged changes (format + agent) as a patch before the fixup commit.
/// Sets `_DIFF_FILE` to the saved path, or empty string if nothing to save.
/// Does NOT print anything — the caller prints `Diff Patch created:` after
/// the fixup commit so the message appears in the right order.
fn shell_save_diff_patch_for_post_commit(indent: &str) -> String {
    let keep = load_retention_diffs();
    format!(
        "{i}# Save staged changes as a patch before fixup commit\n\
         {i}_SLUG=$(git rev-parse --show-toplevel 2>/dev/null | tr '/' '-' | sed 's/^-//')\n\
         {i}_DIFF_DIR=\"$HOME/.linthis/projects/$_SLUG/diff\"\n\
         {i}mkdir -p \"$_DIFF_DIR\"\n\
         {i}_DIFF_FILE=\"$_DIFF_DIR/diff-$(date +%Y%m%d-%H%M%S).patch\"\n\
         {i}git diff --cached > \"$_DIFF_FILE\" 2>/dev/null\n\
         {i}if [ -s \"$_DIFF_FILE\" ]; then\n\
         {i}  ls -t \"$_DIFF_DIR\"/diff-*.patch 2>/dev/null | tail -n +{keep_plus_one} | xargs rm -f 2>/dev/null\n\
         {i}else\n\
         {i}  rm -f \"$_DIFF_FILE\"\n\
         {i}  _DIFF_FILE=\"\"\n\
         {i}fi\n",
        i = indent,
        keep_plus_one = keep + 1,
    )
}

/// Build the shell fix block that invokes an agent on lint failure.
pub(crate) fn build_agent_fix_block(provider: &AgentFixProvider, hook_event: &HookEvent) -> String {
    let agent_cmd = agent_fix_cmd_for_event(provider, hook_event);
    let agent_check = shell_agent_availability_check(provider);
    let error_msg = agent_fix_error_msg(hook_event);
    let new_msg_print = if matches!(hook_event, HookEvent::CommitMsg) {
        agent_fix_show_fixed_cmsg("   ")
    } else {
        String::new()
    };
    let agent_block = shell_agent_invoke_block(provider, &agent_cmd, error_msg, "     ");
    format!(
        "  if [ $LINTHIS_EXIT -ne 0 ]; then\n\
         \x20\x20\x20 {agent_check}\
         \x20\x20\x20 if [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]; then\n\
         {agent_block}\
         \x20\x20\x20\x20\x20 if [ \"$_AGENT_RAN\" = \"1\" ]; then\n\
         {agent_hint}\
         \x20\x20\x20\x20\x20\x20\x20 printf \"${{_LINTHIS_W}}[linthis] Re-verifying...${{_LINTHIS_R}}\\n\"\n\
         \x20\x20\x20\x20\x20\x20\x20 _linthis_run_painted $LINTHIS_CMD \"$@\"\n\
         \x20\x20\x20\x20\x20\x20\x20 LINTHIS_EXIT=$?\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20 fi\n\
         {new_msg_print}\
         \x20 fi\n",
        agent_block = agent_block,
        agent_check = agent_check,
        agent_hint = shell_agent_fix_hint("       "),
        new_msg_print = new_msg_print,
    )
}

/// Build the linthis command variable for the global hook script.
/// For commit-msg, strips "$1" so it can be forwarded via "$@".
pub(crate) fn build_linthis_cmd_var(hook_event: &HookEvent, args: &Option<String>) -> String {
    let cmd = build_hook_command(hook_event, args);
    match hook_event {
        HookEvent::CommitMsg => cmd.trim_end_matches(" \"$1\"").to_string(),
        _ => cmd,
    }
}

/// Resolve preamble and local-hook argument style for a given event.
pub(crate) fn resolve_event_preamble(hook_event: &HookEvent) -> (String, &'static str) {
    if matches!(hook_event, HookEvent::PrePush) {
        build_pre_push_preamble()
    } else {
        (String::new(), "\"$@\"")
    }
}

/// Resolve the fix block, review block, and timer block for the global hook script.
pub(crate) fn resolve_global_hook_blocks(
    hook_event: &HookEvent,
    fix_provider: Option<&AgentFixProvider>,
) -> (String, String, &'static str, &'static str) {
    let fix_block = fix_provider
        .map(|p| build_agent_fix_block(p, hook_event))
        .unwrap_or_default();
    let fix_block_direct = fix_provider
        .map(|p| build_agent_fix_block(p, hook_event))
        .unwrap_or_default();
    let review_block = if matches!(hook_event, HookEvent::PrePush) {
        "\n# Trigger background AI code review (non-blocking)\n\
         linthis review --background 2>/dev/null &\n"
    } else {
        ""
    };
    // Always include the timer/paint preamble — even without an agent the
    // generated script calls `_linthis_run_painted` and `_linthis_paint`,
    // which live in `shell_timer_functions`. Previously this was gated on
    // `fix_provider.is_some()`, causing `--type git` (e.g. pre-push) to
    // error with "_linthis_run_painted: command not found".
    let timer_block = shell_timer_functions();
    (fix_block, fix_block_direct, review_block, timer_block)
}

/// Build the global hook script with the hook event name substituted.
pub(crate) fn build_global_hook_script_for_event(
    hook_event: &HookEvent,
    args: &Option<String>,
    fix_provider: Option<&AgentFixProvider>,
) -> String {
    let linthis_cmd_var = build_linthis_cmd_var(hook_event, args);
    let (pre_push_preamble, local_hook_orig_args) = resolve_event_preamble(hook_event);
    let (fix_block, fix_block_direct, review_block, timer_block) =
        resolve_global_hook_blocks(hook_event, fix_provider);
    let event_name = hook_event.hook_filename();

    let fix_commit_mode_section = if matches!(hook_event, HookEvent::PreCommit) {
        shell_read_fix_commit_mode("pre_commit")
    } else if matches!(hook_event, HookEvent::PrePush) {
        shell_read_fix_commit_mode("pre_push")
    } else {
        String::new()
    };

    let git_fix_commit_mode_handler = shell_git_fix_commit_mode_handler(hook_event);

    // Pre-push only: wrap the initial lint check in a git worktree so it
    // sees HEAD content (what's being pushed), not the user's working-tree
    // edits. Empty for other events — variables are never set, snippets are
    // no-ops if they somehow run.
    let (wt_enter, wt_leave) = if matches!(hook_event, HookEvent::PrePush) {
        (
            shell_pre_push_worktree_enter(),
            shell_pre_push_worktree_leave(),
        )
    } else {
        (String::new(), String::new())
    };

    format!(
        "#!/bin/sh\n\
         # linthis-hook\n\
         {timer}\
         LINTHIS_CMD=\"{linthis}\"\n\
         {fix_commit_mode}\
         # Snapshot pre-format state for stash (squash mode)\n\
         if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         \x20 _STASH_REF=$(git stash create 2>/dev/null)\n\
         fi\n\
         {pre_push_preamble}\
         # Locate the local project hook (git-dir aware)\n\
         GIT_DIR=\"$(git rev-parse --git-dir 2>/dev/null)\"\n\
         LOCAL_HOOK=\"\"\n\
         if [ -n \"$GIT_DIR\" ]; then\n\
         \x20 LOCAL_HOOK=\"$GIT_DIR/hooks/{event}\"\n\
         fi\n\
         \n\
         if [ -f \"$LOCAL_HOOK\" ] && [ -x \"$LOCAL_HOOK\" ]; then\n\
         \x20 if grep -qE '^[^#]*linthis' \"$LOCAL_HOOK\" 2>/dev/null; then\n\
         \x20\x20\x20 # Local hook already calls linthis — delegate entirely\n\
         \x20\x20\x20 exec \"$LOCAL_HOOK\" {local_hook_orig_args}\n\
         \x20 else\n\
         \x20\x20\x20 # Local hook exists but has no linthis — run linthis first, then delegate.\n\
         \x20\x20\x20 # _linthis_run_painted folds stderr into stdout and pipes through the\n\
         \x20\x20\x20 # VCS-console white filter while preserving linthis's exit status.\n\
         {wt_enter}\
         \x20\x20\x20 _linthis_run_painted $LINTHIS_CMD \"$@\"\n\
         \x20\x20\x20 LINTHIS_EXIT=$?\n\
         {wt_leave}\
         {git_fix_handler}\
         {fix_local}\
         \x20\x20\x20 \"$LOCAL_HOOK\" {local_hook_orig_args}\n\
         \x20\x20\x20 LOCAL_EXIT=$?\n\
         {review}\
         \x20\x20\x20 [ $LINTHIS_EXIT -ne 0 ] && exit $LINTHIS_EXIT\n\
         \x20\x20\x20 exit $LOCAL_EXIT\n\
         \x20 fi\n\
         else\n\
         \x20 # No local hook — run linthis directly.\n\
         {wt_enter}\
         \x20 _linthis_run_painted $LINTHIS_CMD \"$@\"\n\
         \x20 LINTHIS_EXIT=$?\n\
         {wt_leave}\
         {git_fix_handler}\
         {fix_direct}\
         {review}\
         \x20 exit $LINTHIS_EXIT\n\
         fi\n",
        timer = timer_block,
        linthis = linthis_cmd_var,
        fix_commit_mode = fix_commit_mode_section,
        pre_push_preamble = pre_push_preamble,
        event = event_name,
        local_hook_orig_args = local_hook_orig_args,
        wt_enter = wt_enter,
        wt_leave = wt_leave,
        git_fix_handler = git_fix_commit_mode_handler,
        fix_local = fix_block,
        fix_direct = fix_block_direct,
        review = review_block,
    )
}

/// Return the binary name used to invoke the agent CLI headlessly.
/// Used for PATH detection via `which`.
pub(crate) fn agent_fix_bin(provider: &AgentFixProvider) -> std::borrow::Cow<'static, str> {
    match provider {
        AgentFixProvider::Claude => "claude".into(),
        AgentFixProvider::Codex => "codex".into(),
        AgentFixProvider::Gemini => "gemini".into(),
        AgentFixProvider::Cursor => "cursor-agent".into(),
        AgentFixProvider::Droid => "droid".into(),
        AgentFixProvider::Auggie => "auggie".into(),
        AgentFixProvider::Codebuddy => "codebuddy".into(),
        AgentFixProvider::Openclaw => "openclaw".into(),
        AgentFixProvider::Custom { bin, .. } => bin.clone().into(),
    }
}

/// Build the headless shell command that invokes the agent with a prompt.
///
/// Commands confirmed from official docs:
/// - Claude:    `claude -p '...'`             (claude -p / --print)
/// - Codex:     `codex exec '...'`            (codex exec subcommand for non-interactive)
/// - Gemini:    `gemini -p '...'`             (gemini -p / --prompt)
/// - Cursor:    `cursor-agent chat '...'`     (cursor-agent chat subcommand)
/// - Droid:     `droid exec --auto low '...'` (droid exec with --auto for edits)
/// - Auggie:    `auggie --print '...'`        (auggie --print for headless/non-interactive)
/// - Codebuddy: `codebuddy -p '...'`         (codebuddy -p / --prompt)
pub(crate) fn agent_fix_headless_cmd(
    provider: &AgentFixProvider,
    prompt: &str,
    provider_args: Option<&str>,
) -> String {
    // Escape single quotes in prompt for shell safety
    let escaped = prompt.replace('\'', "'\\''");
    let extra = provider_args
        .filter(|a| !a.is_empty())
        .map(|a| format!(" {a}"))
        .unwrap_or_default();
    // Streaming strategy per provider:
    //   claude / codebuddy: `-p` buffers text output; use `--output-format
    //     stream-json --verbose` and pipe through `linthis agent-stream`
    //     to pretty-print events (text, tool_use) as they arrive.
    //   codex / cursor / droid: already stream by default.
    //   gemini / auggie / openclaw: no official streaming flag known — kept
    //     as-is; output appears when the call completes.
    match provider {
        AgentFixProvider::Claude => format!(
            "claude -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions '{}' | linthis agent-stream",
            escaped
        ),
        AgentFixProvider::Codex => {
            format!("codex exec{extra} --ask-for-approval never '{}'", escaped)
        }
        AgentFixProvider::Gemini => {
            format!("gemini -p{extra} --approval-mode=auto_edit '{}'", escaped)
        }
        AgentFixProvider::Cursor => format!("cursor-agent chat{extra} --force '{}'", escaped),
        AgentFixProvider::Droid => format!("droid exec{extra} --auto high '{}'", escaped),
        AgentFixProvider::Auggie => format!("auggie{extra} --print '{}'", escaped),
        AgentFixProvider::Codebuddy => format!(
            "codebuddy -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions '{}' | linthis agent-stream",
            escaped
        ),
        AgentFixProvider::Openclaw => format!("openclaw agent{extra} --message '{}'", escaped),
        AgentFixProvider::Custom { bin, style } => match style.as_str() {
            "claude" | "claude-cli" | "codebuddy" | "codebuddy-cli" => format!(
                "{bin} -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions '{}' | linthis agent-stream",
                escaped
            ),
            "codex" | "codex-cli" => format!("{bin} exec{extra} --ask-for-approval never '{}'", escaped),
            "gemini" | "gemini-cli" => format!("{bin} -p{extra} --approval-mode=auto_edit '{}'", escaped),
            "cursor" => format!("{bin} chat{extra} --force '{}'", escaped),
            "droid" => format!("{bin} exec{extra} --auto high '{}'", escaped),
            "auggie" => format!("{bin}{extra} --print '{}'", escaped),
            "openclaw" => format!("{bin} agent{extra} --message '{}'", escaped),
            _ => format!("{bin}{extra} '{}'", escaped),
        },
    }
}

/// Generate a shell snippet that checks whether the provider binary exists in PATH.
///
/// If the binary is not found, prints a friendly message suggesting installation
/// or provider change, then gracefully degrades (skips the agent invocation).
/// The snippet sets `_LINTHIS_AGENT_OK=1` if available, `_LINTHIS_AGENT_OK=0` otherwise.
pub(crate) fn shell_agent_availability_check(provider: &AgentFixProvider) -> String {
    let bin = agent_fix_bin(provider);
    format!(
        "if command -v {bin} >/dev/null 2>&1; then\n\
         \x20 _LINTHIS_AGENT_OK=1\n\
         else\n\
         \x20 _LINTHIS_AGENT_OK=0\n\
         \x20 echo \"[linthis] ⚠ '{bin}' not found in PATH — skipping AI auto-fix\" >&2\n\
         \x20 echo \"[linthis]   To install: https://docs.anthropic.com/en/docs/claude-code\" >&2\n\
         \x20 echo \"[linthis]   To change provider: linthis hook install -g --type git-with-agent --provider <name> --event <event> --force\" >&2\n\
         \x20 echo \"[linthis]   Please fix the issues manually and retry.\" >&2\n\
         fi\n",
        bin = bin,
    )
}

/// Agent fix prompt for post-commit: files are committed (not staged), use report show.
fn agent_fix_prompt_for_post_commit() -> String {
    "Lint issues remain in committed files after auto-formatting. A backup has been created. \
     Follow these steps: \
     (1) Run 'linthis report show' to inspect all remaining issues. \
     (2) Group the issues by file. For files with independent errors (no cross-file dependencies), \
     fix them in parallel using concurrent tool calls — each tool call fixes one file. \
     For files with cross-file dependencies (e.g. shared type renames, API signature changes), \
     fix them sequentially in dependency order. \
     Fix by editing the code directly (do NOT use linthis --fix). \
     (3) Re-run 'linthis report show' and verify remaining issues. \
     If none remain, you are done. Otherwise keep fixing. \
     (4) Display a Changes Summary showing each modified file, \
     what was changed, and why (e.g. which lint rule). Then show the full diff output."
        .to_string()
}

/// Build the agent fix prompt based on the hook event type.
/// Note: CommitMsg uses agent_fix_headless_cmd_commit_msg() instead (needs $1 expansion).
pub(crate) fn agent_fix_prompt_for_event(hook_event: &HookEvent) -> String {
    // Pre-push needs a different prompt: there are no STAGED files (HEAD is
    // already committed), and the agent runs inside a temp git worktree of
    // HEAD. So `linthis -s` (staged-files check) returns "no issues" and
    // confuses the agent into reporting nothing to fix. Direct it at the
    // saved result file via `linthis report show` instead.
    if matches!(hook_event, HookEvent::PrePush) {
        return "Lint issues were found in the commits about to be pushed (HEAD content). \
                You are running inside a temporary git worktree of HEAD — there are NO staged \
                files; do NOT run `linthis -s`. A backup has been created. \
                CRITICAL: DO NOT run `git commit`, `git add`, or any git command that mutates \
                history or the index. Leave your fixes as UNCOMMITTED edits in the working \
                tree — the linthis hook will capture your diff with `git diff HEAD` and replay \
                it onto the user's real project per their fix_commit_mode (squash / fixup / \
                dirty). If you commit, the hook sees an empty diff and your fixes never reach \
                the user. \
                Follow these steps: \
                (1) Run `linthis report show` to see the latest lint result with file paths, \
                line numbers, and rule names. \
                (2) Group the issues by file. For files with independent errors (no cross-file \
                dependencies), fix them in parallel using concurrent tool calls — each tool call \
                fixes one file. For files with cross-file dependencies (e.g. shared type renames, \
                API signature changes), fix them sequentially in dependency order. \
                Fix by editing the code directly (do NOT use linthis --fix). \
                (3) Re-check by running `linthis -i <file>` for each modified file (use one \
                `-i` flag per file when checking multiple). Exit code 0 = all clean. \
                Non-zero = issues remain — keep fixing until exit code is 0. \
                (4) Run the project build/test to ensure fixes don't break anything \
                (detect project type: cargo check && cargo test for Rust, \
                go build ./... && go test ./... for Go, \
                npx tsc --noEmit for TypeScript, python -m py_compile for Python). \
                If build/tests fail, revert the problematic fix and try again. \
                (5) Display a Changes Summary showing each modified file, \
                what was changed, and why (e.g. which lint rule). Then show the full diff \
                output (read-only — no commit)."
            .to_string();
    }
    "Lint issues were found in staged files. A backup has been created. \
     Follow these steps: \
     (1) Run 'linthis -s' to inspect all issues. \
     (2) Group the issues by file. For files with independent errors (no cross-file dependencies), \
     fix them in parallel using concurrent tool calls — each tool call fixes one file. \
     For files with cross-file dependencies (e.g. shared type renames, API signature changes), \
     fix them sequentially in dependency order. \
     Fix by editing the code directly (do NOT use linthis --fix). \
     (3) Re-run 'linthis -s' and check the exit code. \
     Exit code 0 means all checks passed — you are done. \
     Non-zero means issues remain — keep fixing until exit code is 0. \
     (4) Run the project build/test to ensure fixes don't break anything \
     (detect project type: cargo check && cargo test for Rust, \
     go build ./... && go test ./... for Go, \
     npx tsc --noEmit for TypeScript, python -m py_compile for Python). \
     If build/tests fail, revert the problematic fix and try again. \
     (5) Display a Changes Summary showing each modified file, \
     what was changed, and why (e.g. which lint rule). Then show the full diff output."
        .to_string()
}

/// Shell snippet printed after a successful agent commit-msg fix.
/// Shows the fixed message in green so it's visible in the terminal.
/// `indent` is the per-line prefix (spaces) matching the surrounding if-block depth.
///
/// Reads `$_REAL_MSG` (the actual `.git/COMMIT_EDITMSG`), not `$_MSG_FILE`,
/// because the latter points at a temp file the agent_cmd already deleted.
pub(crate) fn agent_fix_show_fixed_cmsg(indent: &str) -> String {
    format!(
        "{i}if [ $LINTHIS_EXIT -eq 0 ] && [ -n \"$_REAL_MSG\" ] && [ -f \"$_REAL_MSG\" ]; then\n\
         {i}  printf '\\033[0;32m[linthis] ✓ New message: %s\\033[0m\\n' \"$(cat \"$_REAL_MSG\")\" >&2\n\
         {i}fi\n",
        i = indent,
    )
}

/// Build the agent command for commit-msg hook: captures $1 in _MSG_FILE then invokes agent.
/// Uses double-quoted prompt string so $_MSG_FILE expands at shell runtime.
pub(crate) fn agent_fix_headless_cmd_commit_msg(
    provider: &AgentFixProvider,
    provider_args: Option<&str>,
) -> String {
    // We can't have the agent write directly to .git/COMMIT_EDITMSG: Claude
    // Code (and similar tools) flag .git/ as a sensitive path and refuse the
    // write even with --dangerously-skip-permissions. Workaround: stage the
    // current message into a temp file, point the agent at the temp file,
    // and copy the temp file back to .git/COMMIT_EDITMSG when the agent
    // returns. The agent never touches .git/ directly.
    let prompt = "Commit message validation failed (not in Conventional Commits format). \
        Fix the commit message in $_MSG_FILE (this is a TEMP FILE outside .git/ — \
        do NOT try to write to .git/COMMIT_EDITMSG, that path is blocked; \
        write to $_MSG_FILE only): \
        (1) read $_MSG_FILE for the current message, \
        (2) run 'git diff --cached --stat' to understand what actually changed, \
        (3) run 'git log -n 5 --oneline' to check recent commit style AND the language used \
        (Chinese or English) — match that language for the description, \
        (4) choose the correct type (feat/fix/refactor/perf/docs/style/test/build/ci/chore/revert) \
        based on the diff, \
        (5) rewrite to: type(scope)?: description — lowercase type, ≤72 chars, no trailing period. \
        Overwrite $_MSG_FILE in place. \
        Verify with 'linthis cmsg $_MSG_FILE' until it passes.";
    // Escape backslashes and double quotes for use in double-quoted shell string
    let escaped = prompt.replace('\\', "\\\\").replace('"', "\\\"");
    let bin_cmd = build_commit_msg_agent_bin_cmd(provider, &escaped, provider_args);
    // Capture the real .git/COMMIT_EDITMSG path in $_REAL_MSG, point
    // $_MSG_FILE at a writable temp file (the agent can't touch .git/),
    // and copy back when the agent finishes if it actually changed anything.
    format!(
        "_REAL_MSG=\"$1\"; \
         _MSG_FILE=$(mktemp \"${{TMPDIR:-/tmp}}/linthis-cmsg.XXXXXX\" 2>/dev/null || echo \"/tmp/linthis-cmsg.$$\"); \
         cp \"$_REAL_MSG\" \"$_MSG_FILE\" 2>/dev/null; \
         {bin_cmd}; \
         if [ -s \"$_MSG_FILE\" ] && ! cmp -s \"$_REAL_MSG\" \"$_MSG_FILE\" 2>/dev/null; then \
           cp \"$_MSG_FILE\" \"$_REAL_MSG\"; \
         fi; \
         rm -f \"$_MSG_FILE\"",
        bin_cmd = bin_cmd
    )
}

/// Build the binary command portion for commit-msg agent fix.
/// Extracted to reduce cyclomatic complexity of `agent_fix_headless_cmd_commit_msg`.
fn build_commit_msg_agent_bin_cmd(
    provider: &AgentFixProvider,
    escaped: &str,
    provider_args: Option<&str>,
) -> String {
    let extra = provider_args
        .filter(|a| !a.is_empty())
        .map(|a| format!(" {a}"))
        .unwrap_or_default();
    match provider {
        AgentFixProvider::Claude => format!(
            "claude -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions \"{}\" | linthis agent-stream",
            escaped
        ),
        AgentFixProvider::Codex => {
            format!("codex exec{extra} --ask-for-approval never \"{}\"", escaped)
        }
        AgentFixProvider::Gemini => {
            format!("gemini -p{extra} --approval-mode=auto_edit \"{}\"", escaped)
        }
        AgentFixProvider::Cursor => format!("cursor-agent chat{extra} --force \"{}\"", escaped),
        AgentFixProvider::Droid => format!("droid exec{extra} --auto high \"{}\"", escaped),
        AgentFixProvider::Auggie => format!("auggie{extra} --print \"{}\"", escaped),
        AgentFixProvider::Codebuddy => format!(
            "codebuddy -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions \"{}\" | linthis agent-stream",
            escaped
        ),
        AgentFixProvider::Openclaw => format!("openclaw agent{extra} --message \"{}\"", escaped),
        AgentFixProvider::Custom { bin, style } => {
            build_custom_commit_msg_cmd(bin, style, &extra, escaped)
        }
    }
}

/// Build commit-msg command for custom provider based on CLI style.
fn build_custom_commit_msg_cmd(bin: &str, style: &str, extra: &str, escaped: &str) -> String {
    match style {
        "claude" | "claude-cli" | "codebuddy" | "codebuddy-cli" => format!(
            "{bin} -p{extra} --verbose --output-format stream-json --dangerously-skip-permissions \"{}\" | linthis agent-stream",
            escaped
        ),
        "codex" | "codex-cli" => format!("{bin} exec{extra} --ask-for-approval never \"{}\"", escaped),
        "gemini" | "gemini-cli" => format!("{bin} -p{extra} --approval-mode=auto_edit \"{}\"", escaped),
        "cursor" => format!("{bin} chat{extra} --force \"{}\"", escaped),
        "droid" => format!("{bin} exec{extra} --auto high \"{}\"", escaped),
        "auggie" => format!("{bin}{extra} --print \"{}\"", escaped),
        "openclaw" => format!("{bin} agent{extra} --message \"{}\"", escaped),
        _ => format!("{bin}{extra} \"{}\"", escaped),
    }
}

/// Error message for agent fix echo based on hook event type.
pub(crate) fn agent_fix_error_msg(hook_event: &HookEvent) -> &'static str {
    match hook_event {
        HookEvent::CommitMsg => "Commit message validation failed",
        _ => "Lint errors detected",
    }
}

/// Shell function to print a colored review summary box.
pub(crate) fn shell_review_box_fn() -> &'static str {
    r#"
_print_review_box() {
  if [ "$1" = "passed" ]; then
    _RH="✓ Linthis 📤 [Pre-push] Review Passed"
    _RC="\033[32m"
    _RHP="           "
  else
    _RH="✗ Linthis 📤 [Pre-push] Review Blocked"
    _RC="\033[31m"
    _RHP="          "
  fi
  _RN="\033[0m"
  _RM=$(printf "%-48s" "$2")
  printf "${_RC}╭──────────────────────────────────────────────────╮${_RN}\n" >&2
  printf "${_RC}│ ${_RH}${_RHP}│${_RN}\n" >&2
  printf "${_RC}├──────────────────────────────────────────────────┤${_RN}\n" >&2
  printf "${_RC}│ ${_RM} │${_RN}\n" >&2
  if [ "$1" != "passed" ]; then
    printf "${_RC}├──────────────────────────────────────────────────┤${_RN}\n" >&2
    printf "${_RC}│ To skip this check:                              │${_RN}\n" >&2
    printf "${_RC}│   git push --no-verify                           │${_RN}\n" >&2
  fi
  printf "${_RC}╰──────────────────────────────────────────────────╯${_RN}\n" >&2
}
"#
}

/// Shell snippet: a background elapsed-time spinner, plus "VCS console"
/// colour wrapping. The latter guards against hosts (e.g. JetBrains' Git tool
/// window) that render every unformatted line of hook output red. Detection:
///
///   * `LINTHIS_HOOK_COLOR=auto|off|white` overrides.
///   * Default (`auto`) wraps only when stdout is **not a TTY** AND the common
///     CI env vars are absent — i.e. IDE VCS consoles (pipe, interactive),
///     never real terminals and never CI logs.
///
/// Three shell variables are exported:
///   `$_LINTHIS_W`  — initial white ANSI prefix (or empty)
///   `$_LINTHIS_WR` — "resume white after an inner colour" (or reset)
///   `$_LINTHIS_R`  — trailing reset (always `\033[0m`)
/// Plus `_linthis_paint`, a filter that wraps every line read on stdin. Used
/// on `git commit` output so its `[master HASH] message` summary picks up the
/// wrapping too.
pub(crate) fn shell_timer_functions() -> &'static str {
    r#"
_linthis_timer_pid=""
start_timer() {
  _linthis_label="$1"
  printf "[linthis] ⠋ %s (0s)\n" "$_linthis_label" >&2
  (
    _i=0
    _s=0
    while true; do
      sleep 0.1
      _i=$((_i + 1))
      case $((_i % 10)) in
        0) _spin="⠋" ;;
        1) _spin="⠙" ;;
        2) _spin="⠹" ;;
        3) _spin="⠸" ;;
        4) _spin="⠼" ;;
        5) _spin="⠴" ;;
        6) _spin="⠦" ;;
        7) _spin="⠧" ;;
        8) _spin="⠇" ;;
        9) _spin="⠏" ;;
      esac
      if [ $((_i % 10)) -eq 0 ]; then
        _s=$((_s + 1))
      fi
      printf "\033[1A\r[linthis] %s %s (%ds)\033[K\n" "$_spin" "$_linthis_label" "$_s" >&2
    done
  ) &
  _linthis_timer_pid=$!
}
stop_timer() {
  if [ -n "$_linthis_timer_pid" ]; then
    kill "$_linthis_timer_pid" 2>/dev/null
    wait "$_linthis_timer_pid" 2>/dev/null
    _linthis_timer_pid=""
    printf "\r\033[K" >&2
  fi
}

# ---- IDE "VCS console" colour compensation ----
_LINTHIS_W=""
_LINTHIS_WR=$(printf '\033[0m')
_LINTHIS_R=$(printf '\033[0m')
case "${LINTHIS_HOOK_COLOR:-auto}" in
  off)
    ;;
  white)
    _LINTHIS_W=$(printf '\033[0;37m')
    _LINTHIS_WR=$(printf '\033[0;37m')
    ;;
  auto|*)
    if [ ! -t 1 ] \
        && [ -z "$CI" ] \
        && [ -z "$GITHUB_ACTIONS" ] \
        && [ -z "$GITLAB_CI" ] \
        && [ -z "$CIRCLECI" ] \
        && [ -z "$BUILDKITE" ] \
        && [ -z "$CONTINUOUS_INTEGRATION" ]; then
      _LINTHIS_W=$(printf '\033[0;37m')
      _LINTHIS_WR=$(printf '\033[0;37m')
    fi
    ;;
esac

# Expose paint state to child processes so the outer `linthis hook run`
# (invoked by git, above this script) and any sub-linthis can align without
# re-running the detection. CLICOLOR_FORCE makes `colored`-crate output still
# emit codes under a pipe.
if [ -n "$_LINTHIS_W" ]; then
  export LINTHIS_HOOK_PAINT=white
  export CLICOLOR_FORCE=1
fi

_linthis_paint() {
  if [ -z "$_LINTHIS_W" ]; then
    cat
  else
    # awk filter: replace every `ESC[0m` (reset) with `ESC[0;37m` so text
    # after an inner colour block continues in white, then wrap the whole
    # line with white + final reset. Existing coloured segments (cyan tips,
    # green ✓, red ✗, box borders) keep their colour; only unformatted
    # stretches gain the white tint that IDE VCS consoles need.
    # gsub takes a regex, so escape the `[` in the RESET pattern.
    awk 'BEGIN { ESC = sprintf("\033"); RESET = ESC "[0m"; RESET_RE = ESC "\\[0m"; WHITE = ESC "[0;37m" }
         { gsub(RESET_RE, WHITE); print WHITE $0 RESET; fflush() }'
  fi
}

# Run "$@" with stderr folded into stdout, pipe the combined output through
# _linthis_paint, and propagate the command's exit status. A bare pipe would
# report awk's (always 0) exit, which silently broke the caller's
# `if [ $LINTHIS_EXIT -ne 0 ]` flow. Tempfile path is POSIX-portable; no
# PIPESTATUS or `set -o pipefail` (both non-POSIX) required.
_linthis_run_painted() {
  if [ -z "$_LINTHIS_W" ]; then
    "$@" 2>&1
    return $?
  fi
  _lrp_xf=$(mktemp 2>/dev/null || printf '/tmp/linthis-exit.%d' "$$")
  { "$@" 2>&1; printf '%s\n' "$?" > "$_lrp_xf"; } | _linthis_paint
  _lrp_rc=$(cat "$_lrp_xf" 2>/dev/null || echo 1)
  rm -f "$_lrp_xf"
  return "$_lrp_rc"
}
"#
}

/// The review prompt for the pre-push agent code review.
pub(crate) fn prepush_review_prompt() -> &'static str {
    "Perform a structured pre-push code review using the lt.review skill. \
     Steps: \
     (1) Run: BASE_SHA=$(git merge-base HEAD origin/main 2>/dev/null || git rev-parse HEAD~1); \
     git diff $BASE_SHA..HEAD --stat; git diff $BASE_SHA..HEAD --name-status; git diff $BASE_SHA..HEAD. \
     (2) Review for Critical (security, data loss, broken API, logic errors), \
     Important (missing error handling, performance), and Minor issues. \
     (3) The review directory is pre-set as $_LINTHIS_REVIEW_DIR (already created and \
     resolves to the user's real project slug — DO NOT recompute it from `git rev-parse \
     --show-toplevel`, which would return the temporary worktree path inside this hook). \
     Write the review to \"$_LINTHIS_REVIEW_DIR/review-$(date +%Y%m%d-%H%M%S).md\". \
     (4) If Critical OR Important issues found: save a snapshot with 'git diff', \
     auto-fix the issues, then run build/test to verify fixes don't break anything \
     (detect project type: cargo check && cargo test for Rust, \
     go build ./... && go test ./... for Go, \
     npx tsc --noEmit for TypeScript, python -m py_compile for Python). \
     If build/tests fail, revert and retry with a different approach. \
     CRITICAL: DO NOT run `git commit`, `git add`, or any git command that mutates \
     history or the index. Leave fixes as UNCOMMITTED edits in the working tree — \
     the linthis hook will capture your diff with `git diff HEAD` and replay it onto \
     the user's real project per their fix_commit_mode (squash / fixup / dirty). \
     If you commit, the hook sees an empty diff and your fixes never reach the user. \
     After fixing, display a Changes Summary showing each file, what changed, and why, \
     plus the full git diff (read-only — no commit). Then re-run the review. \
     Minor issues are informational — DO NOT auto-fix them; just note them in the \
     review report. \
     Print '❌ Push blocked — fix Critical issues first' and exit 1 if Critical issues \
     remain after auto-fix attempts. \
     If only Important issues remain (couldn't fully auto-fix): print '⚠️ Push with \
     caution — Important issues remain'. \
     If only Minor or none: print '✅ Review passed'. \
     Exit 0 unless Critical issues were found."
}

/// Generate shell snippet to check the latest review report for critical issues.
/// Returns a shell snippet that sets _HAS_CRITICAL=1 if critical issues found.
fn shell_review_report_check() -> String {
    r#"
         # Find the latest review report and check for critical issues.
         # Use $_LINTHIS_REVIEW_DIR (exported by worktree_setup) so we hit
         # the same path the agent wrote to — single source of truth, and
         # robust whether we're inside or outside the worktree.
         REVIEW_REPORT=$(ls -t "${_LINTHIS_REVIEW_DIR:-/dev/null}"/review-*.md 2>/dev/null | head -1)
         if [ -n "$REVIEW_REPORT" ]; then
           # Check for actual critical issues (agent exit code is unreliable)
           _CRITICAL=$(awk '/^## Critical Issues/{{found=1;next}} found && /^## /{{found=0}} found && /^- \[/{{print}}' "$REVIEW_REPORT")
           if [ -n "$_CRITICAL" ]; then
             _print_review_box "blocked" "Critical issues found — fix before pushing"
             echo "[linthis] Review saved: $REVIEW_REPORT" >&2
             [ -f "$_AGENT_PATCH" ] && rm -f "$_AGENT_PATCH"
             exit 1
           else
             _print_review_box "passed" "No critical issues found"
             echo "[linthis] Review saved: $REVIEW_REPORT" >&2
           fi
         fi
"#
    .to_string()
}

/// Shell snippet that runs the agent FIX prompt inside the existing pre-push
/// worktree and re-runs the lint check, updating `$LINTHIS_EXIT` and
/// `$_LINT_OUT`. Sets `_AGENT_FIX_ATTEMPTED=1` so callers can distinguish
/// "lint passed because agent fixed it" from "lint passed initially".
///
/// Mirrors pre-commit's `shell_sandbox_agent_fix` pattern (fix → re-check →
/// update exit) but uses the real `git worktree` already set up by
/// [`shell_pre_push_worktree_setup`] instead of a fake-worktree sandbox.
///
/// Caller must ensure `_LINTHIS_AGENT_OK` is set before this snippet runs
/// (via [`shell_agent_availability_check`]).
fn shell_prepush_agent_fix_in_wt(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    agent_fix_cmd: &str,
) -> String {
    format!(
        "# Agent fix on lint failure — runs for ALL fix_commit_modes so the\n\
         # agent gets a chance to repair issues before mode-specific handling\n\
         # decides whether to block the push or fold fixes into a commit.\n\
         # Runs inside the existing worktree so the user's real working tree\n\
         # stays untouched while the agent (often minutes-long) is editing.\n\
         \x20 _AGENT_FIX_ATTEMPTED=0\n\
         \x20 if [ \"$LINTHIS_EXIT\" -ne 0 ] && [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]; then\n\
         \x20\x20\x20 _AGENT_FIX_ATTEMPTED=1\n\
         \x20\x20\x20 echo \"[linthis] Lint errors detected — invoking {provider} to fix...\" >&2\n\
         {worktree_enter}\
         \x20\x20\x20 start_timer \"Fixing with {provider}\"\n\
         \x20\x20\x20 {agent_fix}\n\
         \x20\x20\x20 stop_timer\n\
         {worktree_exit_no_cleanup}\
         \x20\x20\x20 echo \"[linthis] Re-checking after agent fix...\" >&2\n\
         {worktree_enter}\
         \x20\x20\x20 _LINT_OUT=$({linthis} \"$@\" 2>&1)\n\
         \x20\x20\x20 LINTHIS_EXIT=$?\n\
         {worktree_exit_no_cleanup}\
         \x20 fi\n",
        provider = fix_provider,
        agent_fix = agent_fix_cmd,
        linthis = linthis_cmd,
        worktree_enter = shell_pre_push_worktree_enter(),
        worktree_exit_no_cleanup = shell_pre_push_worktree_exit_no_cleanup(),
    )
}

/// Shell snippet for fast-path sentinel check.
///
/// When the previous push squashed/fixed-up agent changes into HEAD,
/// a sentinel containing the new HEAD SHA was written. If that SHA still
/// matches HEAD, skip the expensive fix+review cycle.
fn shell_fast_path_sentinel_check() -> String {
    "\x20# Fast-path: when the previous push squashed/fixed-up agent\n\
     \x20# changes into HEAD it wrote a sentinel containing the new HEAD\n\
     \x20# SHA. If that SHA still matches HEAD, the content was just\n\
     \x20# verified clean and reviewed — skip the 5+ minute fix+review\n\
     \x20# cycle entirely. Sentinel is consumed (deleted) on use so a\n\
     \x20# subsequent unrelated push runs the full flow.\n\
     \x20_FAST_REAL_ROOT=\"$(git rev-parse --show-toplevel 2>/dev/null)\"\n\
     \x20if [ -n \"$_FAST_REAL_ROOT\" ]; then\n\
     \x20\x20 _FAST_STUB=$(printf '%s' \"$_FAST_REAL_ROOT\" | tr '/' '-' | sed 's/^-//')\n\
     \x20\x20 _FAST_SENTINEL=\"$HOME/.linthis/projects/$_FAST_STUB/pre-push-sentinel\"\n\
     \x20\x20 if [ -f \"$_FAST_SENTINEL\" ]; then\n\
     \x20\x20\x20 _FAST_SAVED_SHA=$(cat \"$_FAST_SENTINEL\" 2>/dev/null | tr -d '[:space:]')\n\
     \x20\x20\x20 _FAST_HEAD_SHA=$(git rev-parse HEAD 2>/dev/null)\n\
     \x20\x20\x20 if [ -n \"$_FAST_SAVED_SHA\" ] && [ \"$_FAST_SAVED_SHA\" = \"$_FAST_HEAD_SHA\" ]; then\n\
     \x20\x20\x20\x20 echo \"[linthis] Fast-path: HEAD ($_FAST_HEAD_SHA) matches the recent squash/fixup — skipping fix and review.\" >&2\n\
     \x20\x20\x20\x20 rm -f \"$_FAST_SENTINEL\" 2>/dev/null\n\
     \x20\x20\x20\x20 exit 0\n\
     \x20\x20\x20 fi\n\
     \x20\x20\x20 # Sentinel exists but HEAD has moved on — stale, drop it.\n\
     \x20\x20\x20 rm -f \"$_FAST_SENTINEL\" 2>/dev/null\n\
     \x20\x20 fi\n\
     \x20 fi\n"
        .to_string()
}

/// Build the pre-push hook script that ALWAYS triggers an agent code review.
///
/// Isolation model (path A from the refactor plan): the same worktree that
/// isolates the lint check is KEPT ALIVE across the lint-fix handler and
/// the agent review. The agent runs inside the worktree, so the user's
/// real working tree is untouched for the full duration of the review —
/// they can edit / save files freely while the review is running. After
/// the agent finishes, its diff is captured as a tempfile patch, the
/// worktree is torn down, and the patch is applied to the real root with
/// `git apply --3way` (which surfaces any user-vs-agent edit conflicts as
/// standard conflict markers for manual resolution).
pub(crate) fn build_git_with_agent_prepush_script(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    provider_args: Option<&str>,
) -> String {
    let agent_cmd = agent_fix_headless_cmd(fix_provider, prepush_review_prompt(), provider_args);
    let agent_fix_cmd = agent_fix_headless_cmd(
        fix_provider,
        &agent_fix_prompt_for_event(&HookEvent::PrePush),
        provider_args,
    );
    let timer_fns = shell_timer_functions();
    let review_box = shell_review_box_fn();
    let fix_commit_mode_section = shell_read_fix_commit_mode("pre_push");
    let agent_fix_in_wt = shell_prepush_agent_fix_in_wt(linthis_cmd, fix_provider, &agent_fix_cmd);
    let footer_dirty_post_fix = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Dirty,
        event: &HookEvent::PrePush,
        header: "Agent fixes applied to your working tree (dirty mode). \
                 Push blocked — review the changes, commit, then 'git push' again.",
        indent: "   ",
    });
    let fast_path = shell_fast_path_sentinel_check();
    format!(
        "#!/bin/sh\n\
         {timer}\
         {review_box}\
         {fast_path}\
         \n\
         # Read fix_commit_mode from config\n\
         {fix_commit_mode}\n\
         \n\
         # Tree-delta semantics: net-no-change files don't need re-linting.\n\
         _BASE=$(git rev-parse '@{{u}}' 2>/dev/null || \\\n\
         \x20       git merge-base HEAD origin/main 2>/dev/null || \\\n\
         \x20       git rev-parse 'HEAD~1' 2>/dev/null)\n\
         _PUSHED_FILES=$(git diff --name-only \"$_BASE\"..HEAD 2>/dev/null | grep -v '^$')\n\
         \n\
         {worktree_setup}\
         # Check agent provider availability up-front so both the fix path\n\
         # (lint failure → auto-fix) and the review path can gate on it.\n\
         {agent_check}\
         # Run lint check on pushed files only (skip if no file changes, e.g. empty commits)\n\
         # Build -i <file> args for each pushed file (linthis uses -i, not positional paths)\n\
         _LINTHIS_CHECKED=0\n\
         _AGENT_FIX_ATTEMPTED=0\n\
         if [ -n \"$_PUSHED_FILES\" ]; then\n\
         \x20 set --\n\
         \x20 while IFS= read -r _F; do set -- \"$@\" -i \"$_F\"; done <<_EOF_\n\
         $_PUSHED_FILES\n\
         _EOF_\n\
         {worktree_enter}\
         \x20 _LINT_OUT=$({linthis} \"$@\" 2>&1)\n\
         \x20 LINTHIS_EXIT=$?\n\
         {worktree_exit_no_cleanup}\
         {agent_fix_in_wt}\
         \x20 printf \"%s\\n\" \"$_LINT_OUT\" >&2\n\
         \x20 # Extract actual number of files checked from linthis output\n\
         \x20 _LINTHIS_CHECKED=$(printf \"%s\" \"$_LINT_OUT\" | sed -n 's/.*Files checked:[[:space:]]*\\([0-9]*\\).*/\\1/p' | tail -1)\n\
         \x20 _LINTHIS_CHECKED=${{_LINTHIS_CHECKED:-0}}\n\
         {prepush_fix_commit_mode_handler}\\
         fi\n\
         \n\
         # Skip agent review if no files were actually checked\n\
         if [ -z \"$_PUSHED_FILES\" ] || [ \"$_LINTHIS_CHECKED\" = \"0\" ]; then\n\
         \x20 echo \"[linthis] No files to review — skipping code review\" >&2\n\
         {worktree_leave}\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Skip review if agent unavailable (already warned above).\n\
         if [ \"$_LINTHIS_AGENT_OK\" = \"0\" ]; then\n\
         {worktree_leave}\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Re-enter the worktree so the agent review runs in an isolated\n\
         # HEAD snapshot — user's real working tree stays untouched for the\n\
         # entire (often minutes-long) review.\n\
         {worktree_enter}\
         echo \"[linthis] Invoking {provider} code review...\" >&2\n\
         start_timer \"Reviewing with {provider}\"\n\
         {agent}\n\
         REVIEW_EXIT=$?\n\
         stop_timer\n\
         \n\
         # Capture the agent's change-set as a patch file (inside the wt).\n\
         {capture_agent_patch}\
         \n\
         # Leave + tear down the worktree BEFORE parsing the review report\n\
         # (the report lives under the real project slug, and applying the\n\
         # patch needs the real root).\n\
         {worktree_leave}\
         {review_report_check}\
         # Apply the agent's captured patch to the user's real project root\n\
         # per fix_commit_mode. If $_AGENT_PATCH is empty (agent made no edits)\n\
         # this is a no-op.\n\
         {apply_agent_patch}\
         \n\
         # In dirty mode, an agent fix attempt produces unstaged WT changes\n\
         # in the user's real project. The pushed HEAD content is unchanged,\n\
         # so we MUST block the push — otherwise the user ships the unfixed\n\
         # commit and the agent's fixes sit unstaged. The user commits\n\
         # them (or amends HEAD), then re-runs `git push`.\n\
         if [ \"$_FIX_MODE\" = \"dirty\" ] && [ \"${{_AGENT_FIX_ATTEMPTED:-0}}\" = \"1\" ]; then\n\
         {footer_dirty_post_fix}\
         \x20 exit 1\n\
         fi\n\
         \n\
         exit $REVIEW_EXIT\n",
        timer = timer_fns,
        review_box = review_box,
        fast_path = fast_path,
        fix_commit_mode = fix_commit_mode_section,
        prepush_fix_commit_mode_handler = shell_prepush_fix_commit_mode_handler(linthis_cmd),
        capture_agent_patch = shell_capture_agent_patch_in_wt(),
        apply_agent_patch = shell_apply_agent_patch_by_mode(),
        review_report_check = shell_review_report_check(),
        linthis = linthis_cmd,
        provider = fix_provider,
        agent = agent_cmd,
        agent_check = shell_agent_availability_check(fix_provider),
        agent_fix_in_wt = agent_fix_in_wt,
        footer_dirty_post_fix = footer_dirty_post_fix,
        worktree_setup = shell_pre_push_worktree_setup(),
        worktree_enter = shell_pre_push_worktree_enter(),
        worktree_exit_no_cleanup = shell_pre_push_worktree_exit_no_cleanup(),
        worktree_leave = shell_pre_push_worktree_leave(),
    )
}

/// Build the commit-msg agent-fix shell snippet. Runs the agent directly
/// on the in-progress commit message file (passed via `$@`) — no race
/// with user edits since the agent only touches the commit-msg tempfile
/// git created for the commit, not the working tree or index.
fn shell_worktree_agent_fix(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    agent_cmd: &str,
    error_msg: &str,
) -> String {
    let agent_check = shell_agent_availability_check(fix_provider);
    let agent_block = shell_agent_invoke_block(fix_provider, agent_cmd, error_msg, "   ");
    format!(
        "\x20 # Check if agent provider is available before attempting fix\n\
         \x20 {agent_check}\
         \x20 if [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]; then\n\
         \x20\x20\x20 # Backup staged files (safety net for linthis backup undo hook)\n\
         \x20\x20\x20 if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | tr '\\n' '\\0' | xargs -0 {linthis} backup create -d \"hook-agent-fix\" 2>/dev/null\n\
         \x20\x20\x20 fi\n\
         \x20\x20\x20 # Agent fixes directly in main working tree (backup provides safety net)\n\
         {agent_block}\
         \x20\x20\x20 if [ \"$_AGENT_RAN\" = \"1\" ]; then\n\
         {agent_hint}\
         \x20\x20\x20\x20\x20 # Re-stage files modified by agent\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 # Re-verify after agent fix\n\
         \x20\x20\x20\x20\x20 printf \"${{_LINTHIS_W}}[linthis] Re-verifying...${{_LINTHIS_R}}\\n\"\n\
         \x20\x20\x20\x20\x20 _linthis_run_painted $LINTHIS_CMD\n\
         \x20\x20\x20\x20\x20 LINTHIS_EXIT=$?\n\
         \x20\x20\x20 fi\n\
         \x20 fi\n",
        agent_check = agent_check,
        agent_block = agent_block,
        agent_hint = shell_agent_fix_hint("     "),
        linthis = linthis_cmd,
    )
}

/// Phase 1 of path B: detect real root + create the fake-worktree
/// sandbox under `$TMPDIR/linthis-sandbox-<ts>-<pid>`. Installs an
/// EXIT/HUP/INT/TERM trap to clean up the sandbox on early termination.
/// Leaves `$_SANDBOX` set when setup succeeded (or empty on failure —
/// caller falls back to direct run).
///
/// Why `$TMPDIR` and NOT `$HOME/.linthis/projects/<slug>/fake-worktrees`
/// (the earlier design): linthis has a default exclude pattern that
/// skips files under `.linthis/` (so it doesn't lint its own state).
/// Placing the sandbox under `$HOME/.linthis/...` caused every file in
/// the sandbox to match that exclude → `linthis -s` inside the sandbox
/// reported "no issues" even when there were real staged errors. The
/// `$TMPDIR` path is outside any project-relative exclude and OS-clean
/// on reboot.
fn shell_sandbox_setup() -> String {
    "\x20\x20\x20 # Path B sandbox: can't `git worktree add` during pre-commit\n\
     \x20\x20\x20 # (index.lock is held), so mirror staged content into a plain\n\
     \x20\x20\x20 # tempdir instead. User's real working tree is untouched for\n\
     \x20\x20\x20 # the entire agent run.\n\
     \x20\x20\x20 _SB_REAL_ROOT=\"$(git rev-parse --show-toplevel 2>/dev/null)\"\n\
     \x20\x20\x20 _SB_CWD=\"$(pwd)\"\n\
     \x20\x20\x20 _SANDBOX=\"\"\n\
     \x20\x20\x20 if [ -n \"$_SB_REAL_ROOT\" ]; then\n\
     \x20\x20\x20\x20\x20 # Use $TMPDIR to stay OUTSIDE any `.linthis/` exclude tree.\n\
     \x20\x20\x20\x20\x20 _SB_BASE=\"${TMPDIR:-/tmp}\"\n\
     \x20\x20\x20\x20\x20 # Prune our own orphans >60 min old (Ctrl-C'd runs).\n\
     \x20\x20\x20\x20\x20 find \"$_SB_BASE\" -maxdepth 1 -name 'linthis-sandbox-*' -type d -mmin +60 2>/dev/null -exec rm -rf {} + 2>/dev/null\n\
     \x20\x20\x20\x20\x20 _SANDBOX=\"$_SB_BASE/linthis-sandbox-$(date +%s)-$$\"\n\
     \x20\x20\x20\x20\x20 mkdir -p \"$_SANDBOX\"\n\
     \x20\x20\x20\x20\x20 _sb_cleanup() { [ -n \"$_SANDBOX\" ] && [ -d \"$_SANDBOX\" ] && rm -rf \"$_SANDBOX\" 2>/dev/null; }\n\
     \x20\x20\x20\x20\x20 trap '_sb_cleanup' EXIT HUP INT TERM\n\
     \x20\x20\x20 fi\n"
        .to_string()
}

/// Phase 2 of path B: materialize `$_STAGED_FILES` into the sandbox via
/// `git show :<file>` (index content, not working tree), then init the
/// sandbox as a git repo and `git add` the files to the index — but do
/// NOT commit. This leaves the files in STAGED state (index != empty
/// HEAD), which is what `linthis -s` needs to discover them. A commit
/// would move them into HEAD, and `linthis -s`'s "staged" query returns
/// empty (`git diff --cached` against HEAD is empty when index == HEAD).
///
/// Capture-time diff (see `shell_sandbox_capture_and_apply`) uses
/// `git diff` (WT vs index) to pick up agent modifications, so the
/// missing HEAD isn't a problem there.
fn shell_sandbox_materialize() -> String {
    "\x20\x20\x20 if [ -n \"$_SANDBOX\" ]; then\n\
     \x20\x20\x20\x20\x20 while IFS= read -r _F; do\n\
     \x20\x20\x20\x20\x20\x20\x20 [ -z \"$_F\" ] && continue\n\
     \x20\x20\x20\x20\x20\x20\x20 _SB_DIR=$(dirname \"$_F\")\n\
     \x20\x20\x20\x20\x20\x20\x20 [ \"$_SB_DIR\" != \".\" ] && mkdir -p \"$_SANDBOX/$_SB_DIR\"\n\
     \x20\x20\x20\x20\x20\x20\x20 git show \":$_F\" > \"$_SANDBOX/$_F\" 2>/dev/null || :\n\
     \x20\x20\x20\x20\x20 done <<_SB_MATERIALIZE_EOF_\n\
     $_STAGED_FILES\n\
     _SB_MATERIALIZE_EOF_\n\
     \x20\x20\x20\x20\x20 ( cd \"$_SANDBOX\" && git init -q && git -c user.email=linthis@local -c user.name=linthis add -A ) 2>/dev/null\n\
     \x20\x20\x20 fi\n"
        .to_string()
}

/// Phase 3 of path B: cd into sandbox (if setup succeeded) so the agent
/// runs inside. On failure, prints a clearly-labeled fallback notice
/// and the agent runs on the real working tree (backup provides safety).
fn shell_sandbox_enter_or_fallback() -> String {
    "\x20\x20\x20 if [ -n \"$_SANDBOX\" ] && [ -d \"$_SANDBOX/.git\" ]; then\n\
     \x20\x20\x20\x20\x20 cd \"$_SANDBOX\" || true\n\
     \x20\x20\x20 else\n\
     \x20\x20\x20\x20\x20 echo \"[linthis] ⚠ Couldn't set up sandbox — running agent on working tree (backup provides safety net).\" >&2\n\
     \x20\x20\x20 fi\n"
        .to_string()
}

/// Phase 4 of path B: capture the agent's diff inside the sandbox,
/// return to the real root, and replay via `git apply --3way`. On
/// 3-way conflict, the patch is kept on disk + the Conflict footer is
/// printed for manual resolution.
fn shell_sandbox_capture_and_apply(footer_conflict: &str) -> String {
    format!(
        "\x20\x20\x20\x20\x20 if [ -n \"$_SANDBOX\" ] && [ -d \"$_SANDBOX/.git\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 _SB_PATCH=$(mktemp \"${{TMPDIR:-/tmp}}/linthis-sandbox.XXXXXX\" 2>/dev/null || mktemp)\n\
         \x20\x20\x20\x20\x20\x20\x20 # WT vs index (no HEAD since materialize skipped commit) —\n\
         \x20\x20\x20\x20\x20\x20\x20 # captures exactly the agent's modifications.\n\
         \x20\x20\x20\x20\x20\x20\x20 ( cd \"$_SANDBOX\" && git diff --binary ) > \"$_SB_PATCH\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20\x20\x20 cd \"$_SB_REAL_ROOT\" >/dev/null 2>&1 || cd \"$_SB_CWD\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20\x20\x20\x20\x20 if [ -s \"$_SB_PATCH\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 _SB_APPLY_ERR=$(mktemp \"${{TMPDIR:-/tmp}}/linthis-apply-err.XXXXXX\" 2>/dev/null || mktemp)\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 # Plain `--binary` apply — `--3way` would imply `--index`\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 # and trip on blob-hash mismatch (see post-commit fix).\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 if ! git apply --binary --whitespace=nowarn \"$_SB_PATCH\" 2>\"$_SB_APPLY_ERR\"; then\n\
         {footer_conflict}\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 if [ -s \"$_SB_APPLY_ERR\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 echo \"[linthis] git apply error:\" >&2\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 sed 's/^/[linthis]   /' \"$_SB_APPLY_ERR\" >&2\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 echo \"[linthis] Patch kept at: $_SB_PATCH\" >&2\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20 rm -f \"$_SB_PATCH\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 rm -f \"$_SB_APPLY_ERR\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 rm -f \"$_SB_PATCH\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20\x20\x20 _sb_cleanup\n\
         \x20\x20\x20\x20\x20\x20\x20 trap - EXIT HUP INT TERM\n\
         \x20\x20\x20\x20\x20 fi\n"
    )
}

/// Phase 5 of path B: tear down an unused sandbox when the agent did
/// not run (e.g. availability check failed). Restores cwd to the real
/// root and clears the trap.
fn shell_sandbox_teardown_if_unused() -> String {
    "\x20\x20\x20\x20\x20 if [ -n \"$_SANDBOX\" ]; then\n\
     \x20\x20\x20\x20\x20\x20\x20 cd \"$_SB_REAL_ROOT\" >/dev/null 2>&1 || cd \"$_SB_CWD\" >/dev/null 2>&1 || true\n\
     \x20\x20\x20\x20\x20\x20\x20 _sb_cleanup\n\
     \x20\x20\x20\x20\x20\x20\x20 trap - EXIT HUP INT TERM\n\
     \x20\x20\x20\x20\x20 fi\n"
        .to_string()
}

/// Pre-commit agent-fix using a fake-worktree sandbox (Path B).
///
/// Composition of `shell_sandbox_{setup,materialize,enter_or_fallback,
/// capture_and_apply,teardown_if_unused}`. See each helper's docstring
/// for the phase-level semantics.
///
/// Limitation: only staged files are materialized — provider config
/// (`.claude/`, `CLAUDE.md`, `.mcp.json`, etc.) is NOT copied, so agent
/// providers that rely on those paths may see degraded behavior inside
/// the sandbox. Acceptable trade-off for the MVP; can be extended later
/// by enumerating per-provider config paths.
fn shell_sandbox_agent_fix(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    agent_cmd: &str,
    error_msg: &str,
) -> String {
    let agent_check = shell_agent_availability_check(fix_provider);
    let agent_block = shell_agent_invoke_block(fix_provider, agent_cmd, error_msg, "     ");
    let footer_conflict = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Conflict,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PreCommit,
        header:
            "⚠ Agent's fix conflicts with your uncommitted edits. Patch kept — resolve manually.",
        indent: "       ",
    });
    let sb_setup = shell_sandbox_setup();
    let sb_materialize = shell_sandbox_materialize();
    let sb_enter = shell_sandbox_enter_or_fallback();
    let sb_capture_apply = shell_sandbox_capture_and_apply(&footer_conflict);
    let sb_teardown_unused = shell_sandbox_teardown_if_unused();
    format!(
        "\x20 {agent_check}\
         \x20 if [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]; then\n\
         \x20\x20\x20 # Backup staged files (safety net for `linthis backup undo`)\n\
         \x20\x20\x20 if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | tr '\\n' '\\0' | xargs -0 {linthis} backup create -d \"hook-agent-fix\" 2>/dev/null\n\
         \x20\x20\x20 fi\n\
         {sb_setup}\
         {sb_materialize}\
         {sb_enter}\
         {agent_block}\
         \x20\x20\x20 if [ \"$_AGENT_RAN\" = \"1\" ]; then\n\
         {sb_capture_apply}\
         {agent_hint}\
         \x20\x20\x20\x20\x20 if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 printf \"${{_LINTHIS_W}}[linthis] Re-verifying...${{_LINTHIS_R}}\\n\"\n\
         \x20\x20\x20\x20\x20 _linthis_run_painted $LINTHIS_CMD\n\
         \x20\x20\x20\x20\x20 LINTHIS_EXIT=$?\n\
         \x20\x20\x20 else\n\
         {sb_teardown_unused}\
         \x20\x20\x20 fi\n\
         \x20 fi\n",
        agent_check = agent_check,
        agent_block = agent_block,
        agent_hint = shell_agent_fix_hint("     "),
        linthis = linthis_cmd,
    )
}

/// Build the git-with-agent script for commit-msg hooks (no fix_commit_mode branching).
fn build_git_with_agent_commitmsg_script(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    provider_args: Option<&str>,
) -> String {
    let agent_cmd = agent_fix_headless_cmd_commit_msg(fix_provider, provider_args);
    let error_msg = agent_fix_error_msg(&HookEvent::CommitMsg);
    let timer_fns = shell_timer_functions();
    let new_msg_print = agent_fix_show_fixed_cmsg("  ");
    let worktree_fix = shell_worktree_agent_fix(linthis_cmd, fix_provider, &agent_cmd, error_msg);
    format!(
        "#!/bin/sh\n\
         {timer}\
         LINTHIS_CMD=\"{linthis}\"\n\
         _STAGED_FILES=$(git diff --cached --name-only)\n\
         \n\
         if [ -z \"$_STAGED_FILES\" ]; then\n\
         \x20 exit 0\n\
         fi\n\
         \n\
         _linthis_run_painted $LINTHIS_CMD\n\
         LINTHIS_EXIT=$?\n\
         if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         fi\n\
         \n\
         if [ $LINTHIS_EXIT -ne 0 ]; then\n\
         {worktree_fix}\
         {new_msg_print}\
         fi\n\
         \n\
         exit $LINTHIS_EXIT\n",
        timer = timer_fns,
        linthis = linthis_cmd,
        worktree_fix = worktree_fix,
        new_msg_print = new_msg_print,
    )
}

pub(crate) fn build_git_with_agent_hook_script(
    linthis_cmd: &str,
    fix_provider: &AgentFixProvider,
    hook_event: &HookEvent,
    provider_args: Option<&str>,
) -> String {
    if matches!(hook_event, HookEvent::PrePush) {
        return build_git_with_agent_prepush_script(linthis_cmd, fix_provider, provider_args);
    }
    if matches!(hook_event, HookEvent::CommitMsg) {
        return build_git_with_agent_commitmsg_script(linthis_cmd, fix_provider, provider_args);
    }

    let prompt = agent_fix_prompt_for_event(hook_event);
    let agent_cmd = agent_fix_headless_cmd(fix_provider, &prompt, provider_args);
    let error_msg = agent_fix_error_msg(hook_event);
    let timer_fns = shell_timer_functions();
    // Path B: pre-commit agent runs inside a fake-worktree sandbox so the
    // user's real working tree is untouched during the (multi-minute) agent
    // run. Real `git worktree` isn't usable here because pre-commit holds
    // the index lock.
    let worktree_fix = shell_sandbox_agent_fix(linthis_cmd, fix_provider, &agent_cmd, error_msg);

    // For pre-commit (and post-commit), add fix_commit_mode branching
    let fix_commit_mode_section = shell_read_fix_commit_mode("pre_commit");
    let linthis_check_only = linthis_cmd.replace("-c -f", "-c");
    let save_diff = shell_save_diff_patch();

    format!(
        "#!/bin/sh\n\
         {timer}\
         _STAGED_FILES=$(git diff --cached --name-only)\n\
         \n\
         # Skip entirely if no staged files (empty commit)\n\
         if [ -z \"$_STAGED_FILES\" ]; then\n\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Read fix_commit_mode from config\n\
         {fix_commit_mode}\
         \n\
         if [ \"$_FIX_MODE\" = \"fixup\" ]; then\n\
         \x20 # fixup: check only, let commit through, post-commit handles format\n\
         \x20 _linthis_run_painted {linthis_check_only}\n\
         {sentinel_write}\
         \x20 exit 0\n\
         fi\n\
         \n\
         # squash / dirty: run check + format\n\
         # Snapshot pre-format state for stash (squash mode)\n\
         if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         \x20 _STASH_REF=$(git stash create 2>/dev/null)\n\
         fi\n\
         \n\
         LINTHIS_CMD=\"{linthis}\"\n\
         _linthis_run_painted $LINTHIS_CMD\n\
         LINTHIS_EXIT=$?\n\
         \n\
         # Agent fallback runs BEFORE mode-specific handling so BOTH\n\
         # `dirty` and `squash` modes get a chance to auto-fix via the\n\
         # agent before we decide whether to block the commit. Earlier\n\
         # the dirty branch exited 1 before reaching this block, so the\n\
         # agent never ran for dirty + --type git-with-agent.\n\
         if [ $LINTHIS_EXIT -ne 0 ]; then\n\
         {worktree_fix}\
         fi\n\
         \n\
         {save_diff}\
         if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         \x20 # Re-stage files modified by linthis -f (auto-format) or agent.\n\
         \x20 if [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         \x20 fi\n\
         \x20 # Save stash if files were formatted\n\
         \x20 if [ -n \"$_STASH_REF\" ]; then\n\
         \x20\x20\x20 git stash store -m \"linthis: pre-format snapshot\" \"$_STASH_REF\" 2>/dev/null\n\
         \x20 fi\n\
         \x20 if [ \"$LINTHIS_EXIT\" -eq 0 ]; then\n\
         {footer_squash_success}\
         \x20 else\n\
         \x20\x20\x20 echo \"[linthis] Format fixes staged — will fold into your next 'git commit' (squash mode).\" >&2\n\
         {footer_squash_blocked}\
         \x20 fi\n\
         elif [ \"$_FIX_MODE\" = \"dirty\" ]; then\n\
         \x20 # dirty: do NOT re-stage, block commit if files changed\n\
         \x20 _DIRTY=$(git diff --name-only)\n\
         \x20 if [ -n \"$_DIRTY\" ]; then\n\
         {footer_dirty}\
         \x20\x20\x20 exit 1\n\
         \x20 fi\n\
         fi\n\
         \n\
         exit $LINTHIS_EXIT\n",
        timer = timer_fns,
        fix_commit_mode = fix_commit_mode_section,
        linthis_check_only = linthis_check_only,
        linthis = linthis_cmd,
        worktree_fix = worktree_fix,
        save_diff = save_diff,
        footer_squash_success = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::GitWithAgent,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PreCommit,
            header: "Format fixes folded into your commit (squash mode — single commit).",
            indent: "   ",
        }),
        footer_squash_blocked = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Blocked,
            hook_type: HookTypeLabel::GitWithAgent,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PreCommit,
            header: "✗ Unfixable lint issues above — THIS commit blocked. Fix manually, then 'git commit' again.",
            indent: "   ",
        }),
        footer_dirty = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::GitWithAgent,
            mode: FixCommitMode::Dirty,
            event: &HookEvent::PreCommit,
            header: "Files formatted but not staged (dirty mode).",
            indent: "   ",
        }),
        sentinel_write = shell_write_pending_fixup_sentinel(" "),
    )
}

/// Generate the pre-push fix_commit_mode handler shell snippet.
///
/// - `dirty` mode: exit with the lint exit code, no auto-commit, working tree
///   untouched.
/// - `squash` / `fixup` modes: precise-isolation flow — the auto-created
///   fixup/squash commit contains ONLY linthis's format diff, even when the
///   user has uncommitted staged or unstaged work in the pushed files. The
///   user's state is preserved in the working tree via `git stash create` +
///   `git stash apply --index` (3-way merge restores their staged + unstaged
///   changes on top of the new HEAD; conflicts produce standard Git conflict
///   markers).
///
/// Uses `trap` for Ctrl-C / crash safety so the stash is always recoverable.
fn shell_prepush_fix_commit_mode_handler(linthis_cmd: &str) -> String {
    let precise = shell_prepush_precise_flow(linthis_cmd);
    let footer_dirty_blocked = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Blocked,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Dirty,
        event: &HookEvent::PrePush,
        header: "✗ Lint check failed (dirty mode) — push blocked. Fix the issues above and retry.",
        indent: "   ",
    });
    format!(
        "\x20 # Handle fix_commit_mode for pre-push\n\
         \x20 if [ \"$LINTHIS_EXIT\" -ne 0 ] && [ \"$_FIX_MODE\" = \"dirty\" ]; then\n\
         {footer_dirty_blocked}\
         \x20\x20\x20 exit $LINTHIS_EXIT\n\
         \x20 fi\n\
         \x20 if [ \"$LINTHIS_EXIT\" -ne 0 ] && {{ [ \"$_FIX_MODE\" = \"squash\" ] || [ \"$_FIX_MODE\" = \"fixup\" ]; }}; then\n\
         {precise}\
         \x20 fi\n",
    )
}

/// Precise-isolation flow shared by pre-push squash and fixup modes.
///
/// Produces a shell snippet that:
/// 1. Snapshots user's full staged + unstaged state via `git stash create`
/// 2. Clears the index and resets pushed files' working tree to HEAD
/// 3. Runs `linthis -f` on the clean HEAD content
/// 4. Captures the format-only diff as a temp patch file
/// 5. Stages linthis's format (scoped to pushed files)
/// 6. Commits (squash: 3-commit dance to fold into previous; fixup: single commit)
/// 7. Restores user state via `git stash apply --index` (3-way merge)
///
/// Installs a `trap` for HUP/INT/TERM so the stash is restored even on
/// interrupt. The stash ref (a loose commit reachable via reflog) is saved
/// to the stash list on failure so the user can recover via `git stash list`.
fn shell_prepush_precise_flow(linthis_cmd: &str) -> String {
    let setup = shell_precise_setup_and_trap();
    let reset_format = shell_precise_reset_and_format(linthis_cmd);
    let stage = shell_precise_stage_scoped();
    let commit_block = shell_precise_commit_and_restore();
    let skip_block = shell_precise_skip_restore();
    format!(
        "\x20\x20\x20 # Precise-fixup flow: isolate linthis's format diff from user's\n\
         \x20\x20\x20 # uncommitted work so the commit contains ONLY format changes.\n\
         {setup}\
         {reset_format}\
         {stage}\
         \x20\x20\x20 _SCOPED_STAGED=$(git diff --cached --name-only)\n\
         \x20\x20\x20 if [ -n \"$_SCOPED_STAGED\" ]; then\n\
         {commit_block}\
         \x20\x20\x20 fi\n\
         \x20\x20\x20 \n\
         {skip_block}",
    )
}

/// Phase 0: snapshot user state + install trap for Ctrl-C / crash safety.
fn shell_precise_setup_and_trap() -> String {
    "\x20\x20\x20 _USER_STASH=$(git stash create 2>/dev/null || echo \"\")\n\
     \x20\x20\x20 _LINTHIS_PATCH=$(mktemp \"${TMPDIR:-/tmp}/linthis-precise.XXXXXX\" 2>/dev/null || mktemp)\n\
     \x20\x20\x20 _PRECISE_RESTORED=0\n\
     \x20\x20\x20 \n\
     \x20\x20\x20 _linthis_precise_cleanup() {\n\
     \x20\x20\x20\x20\x20 if [ \"$_PRECISE_RESTORED\" = \"0\" ] && [ -n \"$_USER_STASH\" ]; then\n\
     \x20\x20\x20\x20\x20\x20\x20 git stash apply --index \"$_USER_STASH\" >/dev/null 2>&1 || \\\n\
     \x20\x20\x20\x20\x20\x20\x20   git stash store -m \"linthis: pre-push recovery snapshot\" \"$_USER_STASH\" >/dev/null 2>&1 || true\n\
     \x20\x20\x20\x20\x20 fi\n\
     \x20\x20\x20\x20\x20 [ -f \"$_LINTHIS_PATCH\" ] && rm -f \"$_LINTHIS_PATCH\"\n\
     \x20\x20\x20 }\n\
     \x20\x20\x20 trap '_linthis_precise_cleanup' HUP INT TERM\n\
     \x20\x20\x20 \n"
        .to_string()
}

/// Phases 1-3: clear index, reset pushed files to HEAD, run `linthis -f`,
/// then capture the format-only diff as `$_LINTHIS_PATCH`.
fn shell_precise_reset_and_format(linthis_cmd: &str) -> String {
    format!(
        "\x20\x20\x20 # Phase 1: clear index + reset pushed files' working tree to HEAD\n\
         \x20\x20\x20 git reset -q HEAD -- . >/dev/null 2>&1 || true\n\
         \x20\x20\x20 while IFS= read -r _F; do\n\
         \x20\x20\x20   [ -z \"$_F\" ] && continue\n\
         \x20\x20\x20   git checkout HEAD -- \"$_F\" >/dev/null 2>&1 || true\n\
         \x20\x20\x20 done <<_PRECISE_RESET_EOF_\n\
         $_PUSHED_FILES\n\
         _PRECISE_RESET_EOF_\n\
         \x20\x20\x20 \n\
         \x20\x20\x20 # Phase 2: format the clean HEAD content\n\
         \x20\x20\x20 {linthis} \"$@\" -f 2>&1 || true\n\
         \x20\x20\x20 \n\
         \x20\x20\x20 # Phase 3: capture the format-only diff (HEAD → formatted)\n\
         \x20\x20\x20 set --\n\
         \x20\x20\x20 while IFS= read -r _F; do\n\
         \x20\x20\x20   [ -z \"$_F\" ] && continue\n\
         \x20\x20\x20   set -- \"$@\" \"$_F\"\n\
         \x20\x20\x20 done <<_PRECISE_LIST_EOF_\n\
         $_PUSHED_FILES\n\
         _PRECISE_LIST_EOF_\n\
         \x20\x20\x20 git diff --binary -- \"$@\" > \"$_LINTHIS_PATCH\" 2>/dev/null || true\n\
         \x20\x20\x20 \n",
        linthis = linthis_cmd,
    )
}

/// Phase 4: stage linthis's format changes, scoped to `$_PUSHED_FILES`.
fn shell_precise_stage_scoped() -> String {
    "\x20\x20\x20 # Phase 4: stage linthis's format (scoped to pushed files)\n\
     \x20\x20\x20 while IFS= read -r _F; do\n\
     \x20\x20\x20   [ -z \"$_F\" ] && continue\n\
     \x20\x20\x20   git add -- \"$_F\" >/dev/null 2>&1 || true\n\
     \x20\x20\x20 done <<_PRECISE_ADD_EOF_\n\
     $_PUSHED_FILES\n\
     _PRECISE_ADD_EOF_\n\
     \x20\x20\x20 \n"
        .to_string()
}

/// Phases 5-6: commit (mode-specific) and restore user state. Emitted inside
/// the `if [ -n "$_SCOPED_STAGED" ]` guard.
fn shell_precise_commit_and_restore() -> String {
    let save_diff_cached = shell_save_diff_patch_cached();
    let footer_squash = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PrePush,
        header:
            "Lint fixes squashed into latest commit (format-only). Review, then 'git push' again.",
        indent: "       ",
    });
    let footer_fixup = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Fixup,
        event: &HookEvent::PrePush,
        header: "Created fixup commit (format-only). Review, then 'git push' again.",
        indent: "       ",
    });
    let footer_conflict_squash = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Conflict,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Squash,
        event: &HookEvent::PrePush,
        header: "⚠ Your uncommitted changes overlap with format fixes. Working tree has conflict markers — resolve, then 'git push' again. Recovery: 'git stash list' (find 'linthis: uncommitted').",
        indent: "           ",
    });
    format!(
        "\x20\x20\x20\x20\x20 {save_diff_cached}\
         \x20\x20\x20\x20\x20 # Phase 5: commit (mode-specific)\n\
         \x20\x20\x20\x20\x20 if [ \"$_FIX_MODE\" = \"squash\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -m \"fix(linthis): auto-fix lint issues\" >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20\x20\x20 git reset --soft HEAD~2 >/dev/null 2>&1\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -C HEAD@{{2}} >/dev/null 2>&1\n\
         {footer_squash}\
         \x20\x20\x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20\x20\x20 git commit --no-verify -m \"fix(linthis): auto-fix lint issues\" >/dev/null 2>&1\n\
         {footer_fixup}\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 \n\
         \x20\x20\x20\x20\x20 # Phase 6: restore user state (staged + unstaged) via 3-way merge.\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_USER_STASH\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 if ! git stash apply --index \"$_USER_STASH\" >/dev/null 2>&1; then\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20 git stash store -m \"linthis: uncommitted state before fixup\" \"$_USER_STASH\" >/dev/null 2>&1 || true\n\
         {footer_conflict_squash}\
         \x20\x20\x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 _PRECISE_RESTORED=1\n\
         \x20\x20\x20\x20\x20 rm -f \"$_LINTHIS_PATCH\"\n\
         \x20\x20\x20\x20\x20 trap - HUP INT TERM\n\
         \x20\x20\x20\x20\x20 exit 1\n",
    )
}

/// Emitted after the commit guard: nothing was staged, so restore user state
/// and let the outer script continue (agent review, etc.).
fn shell_precise_skip_restore() -> String {
    "\x20\x20\x20 # Nothing staged by linthis — restore user state and continue.\n\
     \x20\x20\x20 if [ -n \"$_USER_STASH\" ]; then\n\
     \x20\x20\x20\x20\x20 git stash apply --index \"$_USER_STASH\" >/dev/null 2>&1 || \\\n\
     \x20\x20\x20\x20\x20   git stash store -m \"linthis: pre-push recovery snapshot\" \"$_USER_STASH\" >/dev/null 2>&1 || true\n\
     \x20\x20\x20 fi\n\
     \x20\x20\x20 _PRECISE_RESTORED=1\n\
     \x20\x20\x20 rm -f \"$_LINTHIS_PATCH\"\n\
     \x20\x20\x20 trap - HUP INT TERM\n"
        .to_string()
}

/// Generate shell snippet for `git` type fix_commit_mode handling.
/// For pre-commit: re-stage formatted files based on mode.
/// For pre-push: handle format changes based on mode.
fn shell_git_fix_commit_mode_handler(hook_event: &HookEvent) -> String {
    if matches!(hook_event, HookEvent::PreCommit) {
        // Pre-commit: handle staged files after format
        let save_diff = shell_save_diff_patch();
        let footer_squash_success = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PreCommit,
            header: "Format fixes folded into your commit (squash mode — single commit).",
            indent: "       ",
        });
        let footer_squash_blocked_after_format = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Blocked,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PreCommit,
            header: "✗ Unfixable lint issues above — THIS commit blocked. Fix manually, then 'git commit' again.",
            indent: "       ",
        });
        let footer_squash_blocked_no_format = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Blocked,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PreCommit,
            header: "✗ Lint check failed (squash mode) — commit blocked. Fix the errors above and retry.",
            indent: "       ",
        });
        let footer_dirty = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Dirty,
            event: &HookEvent::PreCommit,
            header: "Files formatted but not staged (dirty mode).",
            indent: "       ",
        });
        format!(
        "\x20\x20\x20 _STAGED_FILES=$(git diff --cached --name-only)\n\
         \x20\x20\x20 _DIRTY=$(git diff --name-only)\n\
         \x20\x20\x20 if [ \"$_FIX_MODE\" = \"squash\" ] && [ -n \"$_DIRTY\" ]; then\n\
         \x20\x20\x20\x20\x20 {save_diff}\
         \x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         \x20\x20\x20\x20\x20 # Save stash snapshot\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_STASH_REF\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 git stash store -m \"linthis: pre-format snapshot\" \"$_STASH_REF\" 2>/dev/null\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20\x20\x20 if [ \"$LINTHIS_EXIT\" -eq 0 ]; then\n\
         {footer_squash_success}\
         \x20\x20\x20\x20\x20 else\n\
         \x20\x20\x20\x20\x20\x20\x20 echo \"[linthis] Format fixes staged — will fold into your next 'git commit' (squash mode).\" >&2\n\
         {footer_squash_blocked_after_format}\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20 elif [ \"$_FIX_MODE\" = \"squash\" ] && [ -n \"$_STAGED_FILES\" ]; then\n\
         \x20\x20\x20\x20\x20 echo \"$_STAGED_FILES\" | xargs git add\n\
         \x20\x20\x20\x20\x20 if [ \"$LINTHIS_EXIT\" -ne 0 ]; then\n\
         {footer_squash_blocked_no_format}\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20 elif [ \"$_FIX_MODE\" = \"dirty\" ]; then\n\
         \x20\x20\x20\x20\x20 _DIRTY=$(git diff --name-only)\n\
         \x20\x20\x20\x20\x20 if [ -n \"$_DIRTY\" ]; then\n\
         \x20\x20\x20\x20\x20\x20\x20 {save_diff}\
         {footer_dirty}\
         \x20\x20\x20\x20\x20\x20\x20 exit 1\n\
         \x20\x20\x20\x20\x20 fi\n\
         \x20\x20\x20 elif [ \"$_FIX_MODE\" = \"fixup\" ]; then\n\
         \x20\x20\x20\x20\x20 # fixup for git type: check only, no format (post-commit handles it)\n\
         {sentinel_write}\
         \x20\x20\x20 fi\n",
         save_diff = save_diff,
         sentinel_write = shell_write_pending_fixup_sentinel("     "),
        )
    } else if matches!(hook_event, HookEvent::PrePush) {
        // `--type git` pre-push: check-only, no auto-fix/commit dance. Emit
        // pass/fail via the unified footer; failure carries the upgrade hint
        // because `hook_type = Git`.
        let footer_clean = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Clean,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PrePush,
            header: "✓ Pre-push check passed — push proceeding.",
            indent: "   ",
        });
        let footer_blocked = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Blocked,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Squash,
            event: &HookEvent::PrePush,
            header: "✗ Pre-push check failed — push blocked. Fix the errors above and retry.",
            indent: "   ",
        });
        format!(
            "\x20 # --type git pre-push: report result explicitly.\n\
             \x20 if [ \"$LINTHIS_EXIT\" -eq 0 ]; then\n\
             {footer_clean}\
             \x20 else\n\
             {footer_blocked}\
             \x20 fi\n",
        )
    } else {
        String::new()
    }
}

/// Generate shell snippet to save linthis changes as a git patch file.
/// Must be called while changes are still unstaged (before `git add`).
/// Uses `_SLUG` variable which must be set earlier in the script.
fn shell_save_diff_patch() -> String {
    let keep = load_retention_diffs();
    format!(
        "# Save linthis changes as a git patch for review/revert\n\
         _SLUG=$(git rev-parse --show-toplevel 2>/dev/null | tr '/' '-' | sed 's/^-//')\n\
         _DIFF_DIR=\"$HOME/.linthis/projects/$_SLUG/diff\"\n\
         mkdir -p \"$_DIFF_DIR\"\n\
         _DIFF_FILE=\"$_DIFF_DIR/diff-$(date +%Y%m%d-%H%M%S).patch\"\n\
         git diff > \"$_DIFF_FILE\" 2>/dev/null\n\
         if [ -s \"$_DIFF_FILE\" ]; then\n\
         \x20 echo \"[linthis] Patch saved: $_DIFF_FILE\" >&2\n\
         \x20 echo \"  Revert: git apply -R $_DIFF_FILE\" >&2\n\
         \x20 ls -t \"$_DIFF_DIR\"/diff-*.patch 2>/dev/null | tail -n +{keep_plus_one} | xargs rm -f 2>/dev/null\n\
         else\n\
         \x20 rm -f \"$_DIFF_FILE\"\n\
         fi\n",
        keep_plus_one = keep + 1,
    )
}

/// Same as `shell_save_diff_patch` but for staged changes (after `git add`).
fn shell_save_diff_patch_cached() -> String {
    let keep = load_retention_diffs();
    format!(
        "# Save linthis changes as a git patch for review/revert\n\
         _SLUG=$(git rev-parse --show-toplevel 2>/dev/null | tr '/' '-' | sed 's/^-//')\n\
         _DIFF_DIR=\"$HOME/.linthis/projects/$_SLUG/diff\"\n\
         mkdir -p \"$_DIFF_DIR\"\n\
         _DIFF_FILE=\"$_DIFF_DIR/diff-$(date +%Y%m%d-%H%M%S).patch\"\n\
         git diff --cached > \"$_DIFF_FILE\" 2>/dev/null\n\
         if [ -s \"$_DIFF_FILE\" ]; then\n\
         \x20 echo \"[linthis] Patch saved: $_DIFF_FILE\" >&2\n\
         \x20 echo \"  Revert: git apply -R $_DIFF_FILE\" >&2\n\
         \x20 ls -t \"$_DIFF_DIR\"/diff-*.patch 2>/dev/null | tail -n +{keep_plus_one} | xargs rm -f 2>/dev/null\n\
         else\n\
         \x20 rm -f \"$_DIFF_FILE\"\n\
         fi\n",
        keep_plus_one = keep + 1,
    )
}

/// Load retention.diffs config value.
fn load_retention_diffs() -> usize {
    let project_root = linthis::utils::get_project_root();
    linthis::config::Config::load_merged(&project_root)
        .retention
        .diffs
}

/// Generate a POSIX shell snippet that re-stages ONLY working-tree changes to
/// files listed in `$_FILES` (the set produced by the post-commit script from
/// `git diff-tree ... HEAD`).
///
/// Without this restriction, `git diff --name-only | xargs git add` would also
/// pick up unrelated, previously-unstaged modifications to other files, and
/// they'd leak into the fixup commit. We iterate the committed scope instead
/// so a file is only staged if it was part of the original commit AND was
/// further modified by linthis/agent.
fn shell_restage_committed_scope(indent: &str) -> String {
    // Heredoc body and terminator MUST start at column 0 (unquoted `<<EOF`
    // form — `<<-` would only strip tabs, and shell syntax requires the
    // closing marker to match verbatim at the beginning of a line). If we
    // indented `$_FILES` or `_RESTAGE_EOF_`, the heredoc would never close
    // and the shell would fail with "unexpected end of file", and the first
    // filename would be prefixed with stray leading whitespace.
    format!(
        "{i}# Re-stage only files in the committed scope that were further modified.\n\
         {i}# (Prevents unrelated unstaged working-tree changes from leaking into the fixup commit.)\n\
         {i}while IFS= read -r _F; do\n\
         {i}  [ -z \"$_F\" ] && continue\n\
         {i}  git add -- \"$_F\" 2>/dev/null || true\n\
         {i}done <<_RESTAGE_EOF_\n\
         $_FILES\n\
         _RESTAGE_EOF_\n",
        i = indent,
    )
}

/// Generate shell snippet to read fix_commit_mode from linthis config.
fn shell_read_fix_commit_mode(config_section: &str) -> String {
    let default = if config_section == "pre_commit" {
        "squash"
    } else {
        "dirty"
    };
    // Try project config first, then global config, then built-in default.
    // `linthis config get` without `--global` errors out when no project
    // config exists (`.linthis/config.toml` missing), so we need to fall
    // through to `--global` explicitly to honour user's global setting.
    format!(
        "_FIX_MODE=$(linthis config get hook.{section}.fix_commit_mode 2>/dev/null || \
         linthis config get hook.{section}.fix_commit_mode --global 2>/dev/null || \
         echo \"{default}\")\n",
        section = config_section,
        default = default,
    )
}

/// Build a post-commit hook script for fixup fix mode.
///
/// Activation gate: runs ONLY when the pre-commit fixup sentinel
/// exists (`.git/linthis/pending-fixup.json`, written by pre-commit
/// fixup mode — step 5). Without the sentinel, pre-commit did not run
/// (e.g. `git commit --no-verify` bypassed it) and there's nothing to
/// fix up. The sentinel is consumed at the end regardless of outcome
/// so a broken run doesn't loop forever.
pub(crate) fn build_post_commit_script(linthis_cmd: &str) -> String {
    let timer_fns = shell_timer_functions();
    let restage_scope = shell_restage_committed_scope(" ");
    format!(
        "#!/bin/sh\n\
         {timer}\
         # Activation gate: the pre-commit fixup sentinel.\n\
         # Sentinel presence = pre-commit fixup branch ran and deferred\n\
         # work to us. Without it (e.g. when --no-verify bypassed\n\
         # pre-commit) there's nothing to fix up.\n\
         _SENTINEL=\"$(git rev-parse --git-dir 2>/dev/null)/linthis/pending-fixup.json\"\n\
         if [ ! -f \"$_SENTINEL\" ]; then\n\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Get files from the commit that was just created\n\
         _FILES=$(git diff-tree --no-commit-id --name-only -r HEAD)\n\
         if [ -z \"$_FILES\" ]; then\n\
         \x20 [ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\"\n\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Build -i <file> args and run linthis once for all committed files\n\
         # (single invocation = single [Post-commit] output box)\n\
         set --\n\
         while IFS= read -r _F; do set -- \"$@\" -i \"$_F\"; done <<_EOF_\n\
         $_FILES\n\
         _EOF_\n\
         _linthis_run_painted {linthis} \"$@\"\n\
         \n\
         # Restrict staging to the committed scope, then make the fixup commit\n\
         # only if that scope actually changed.\n\
         {restage}\
         _STAGED=$(git diff --cached --name-only)\n\
         if [ -n \"$_STAGED\" ]; then\n\
         \x20 # Pipe git's commit summary through _linthis_paint so IDE VCS\n\
         \x20 # consoles don't render it red.\n\
         \x20 git commit --no-verify -m \"fix(linthis): auto-fix lint issues\" 2>&1 | _linthis_paint\n\
         {footer}\
         fi\n\
         # Consume the sentinel regardless of outcome — no retry on failure.\n\
         [ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\"\n",
        timer = timer_fns,
        linthis = linthis_cmd,
        restage = restage_scope,
        footer = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::Git,
            mode: FixCommitMode::Fixup,
            event: &HookEvent::PostCommit,
            header: "Created fixup commit with format changes",
            indent: " ",
        }),
    )
}

/// Generate shell snippet for the patch apply success path.
fn shell_post_commit_apply_success(
    footer_agent: &str,
    footer_format: &str,
    footer_conflict: &str,
    save_diff: &str,
) -> String {
    format!(
        r#"           rm -f "$_APPLY_ERR" 2>/dev/null
             # Step 4: stage + commit (scoped to in-commit files)
             while IFS= read -r _F; do
               [ -z "$_F" ] && continue
               git add -- "$_F" 2>/dev/null || true
             done <<_POST_COMMIT_STAGE_EOF_
$_FILES
_POST_COMMIT_STAGE_EOF_
{save_diff}\
             _STAGED=$(git diff --cached --name-only)
             if [ -n "$_STAGED" ]; then
               git commit --no-verify -m "fix(linthis): auto-fix lint issues" 2>&1 | _linthis_paint
               if [ "$_AGENT_RAN" = "1" ]; then
{footer_agent}\
               else
{footer_format}\
               fi
             fi
             # Step 5: restore user's uncommitted state on top of the
             # new HEAD via git-stash's internal 3-way merge.
             if [ -n "$_USER_STASH" ]; then
               if git stash apply --index "$_USER_STASH" >/dev/null 2>&1; then
                 _USER_RESTORED=1
               else
                 git stash store -m "linthis: uncommitted state before fixup" "$_USER_STASH" >/dev/null 2>&1 || true
                 _USER_RESTORED=1
{footer_conflict}\
                 echo "[linthis]   Recovery: 'git stash list' (find 'linthis: uncommitted')" >&2
               fi
             else
               _USER_RESTORED=1
             fi
             [ -f "$_AGENT_PATCH" ] && rm -f "$_AGENT_PATCH"
             trap - HUP INT TERM
"#,
        save_diff = save_diff,
        footer_agent = footer_agent,
        footer_format = footer_format,
        footer_conflict = footer_conflict,
    )
}

/// Generate shell snippet for the patch apply failure path.
fn shell_post_commit_apply_failure(footer_conflict: &str) -> String {
    format!(
        r#"           # Apply failed even against clean HEAD content — patch itself
             # is malformed or references missing blobs. Restore user's
             # state and surface the error.
             if [ -n "$_USER_STASH" ]; then
               git stash apply --index "$_USER_STASH" >/dev/null 2>&1 || \
                 git stash store -m "linthis: post-commit recovery snapshot" "$_USER_STASH" >/dev/null 2>&1 || true
             fi
             _USER_RESTORED=1
             trap - HUP INT TERM
{footer_conflict}\
             if [ -s "$_APPLY_ERR" ]; then
               echo "[linthis] git apply error:" >&2
               sed 's/^/[linthis]   /' "$_APPLY_ERR" >&2
             fi
             rm -f "$_APPLY_ERR" 2>/dev/null
             echo "[linthis] Patch kept at: $_AGENT_PATCH" >&2
"#,
        footer_conflict = footer_conflict,
    )
}

/// Generate shell snippet for applying the post-commit patch with stash/restore logic.
/// This handles the complex case of applying a patch when the user has uncommitted changes.
fn shell_post_commit_apply_patch(
    footer_agent: &str,
    footer_format: &str,
    footer_conflict: &str,
    save_diff: &str,
) -> String {
    let success_block =
        shell_post_commit_apply_success(footer_agent, footer_format, footer_conflict, save_diff);
    let failure_block = shell_post_commit_apply_failure(footer_conflict);
    format!(
        r#" if [ -s "$_AGENT_PATCH" ]; then
           _APPLY_ERR=$(mktemp "${{TMPDIR:-/tmp}}/linthis-apply-err.XXXXXX" 2>/dev/null || mktemp)
           _USER_STASH=$(git stash create 2>/dev/null || echo "")
           _USER_RESTORED=0
           _linthis_post_commit_cleanup() {{
             if [ "$_USER_RESTORED" = "0" ] && [ -n "$_USER_STASH" ]; then
               git stash apply --index "$_USER_STASH" >/dev/null 2>&1 || \
                 git stash store -m "linthis: post-commit recovery snapshot" "$_USER_STASH" >/dev/null 2>&1 || true
             fi
           }}
           trap '_linthis_post_commit_cleanup' HUP INT TERM
           # Step 2: reset the in-commit files to HEAD so patch base matches WT
           while IFS= read -r _F; do
             [ -z "$_F" ] && continue
             git checkout HEAD -- "$_F" >/dev/null 2>&1 || true
           done <<_POST_COMMIT_RESET_EOF_
$_FILES
_POST_COMMIT_RESET_EOF_
           # Step 3: apply the auto-fix patch to now-clean WT
           if git apply --binary --whitespace=nowarn "$_AGENT_PATCH" 2>"$_APPLY_ERR"; then
{success_block}\
           else
{failure_block}\
           fi
         fi
"#,
        success_block = success_block,
        failure_block = failure_block,
    )
}

/// Build a post-commit hook script for git-with-agent fixup mode.
/// Formats committed files, then invokes the agent for any remaining issues,
/// and creates a single fixup commit with all changes.
/// Build a post-commit hook script for git-with-agent fixup mode.
///
/// Path A physical isolation: the formatter and agent both run INSIDE a
/// detached worktree at HEAD (the commit the user just made), so the
/// user's real working tree is untouched for the entire (potentially
/// multi-minute) agent review. After both finish, the full diff
/// (format + agent) is captured as a tempfile patch, the worktree is
/// torn down, and `git apply --3way --index` replays the patch onto the
/// real root where `git commit` creates the fixup commit.
///
/// Activation gate: runs ONLY when the pre-commit fixup sentinel
/// exists (`.git/linthis/pending-fixup.json`, written by pre-commit
/// fixup mode — step 5). Without the sentinel, pre-commit did not
/// run (e.g. `git commit --no-verify` bypassed it) and there's
/// nothing to fix up. The sentinel is consumed at the end regardless
/// of outcome (no retry on failure) so a broken run doesn't loop
/// forever.
pub(crate) fn build_post_commit_with_agent_script(
    linthis_fmt_cmd: &str,
    fix_provider: &AgentFixProvider,
    provider_args: Option<&str>,
) -> String {
    let timer_fns = shell_timer_functions();
    let prompt = agent_fix_prompt_for_post_commit();
    let agent_cmd = agent_fix_headless_cmd(fix_provider, &prompt, provider_args);
    let error_msg = "Lint issues remain after formatting";
    let agent_check = shell_agent_availability_check(fix_provider);
    let agent_block = shell_agent_invoke_block(fix_provider, &agent_cmd, error_msg, "    ");
    let save_diff = shell_save_diff_patch_for_post_commit("     ");
    let footer_agent = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Fixup,
        event: &HookEvent::PostCommit,
        header: "✓ Agent fix applied",
        indent: "     ",
    });
    let footer_format = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Applied,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Fixup,
        event: &HookEvent::PostCommit,
        header: "Created fixup commit with format changes",
        indent: "     ",
    });
    let footer_conflict = shell_hook_footer(&FooterCtx {
        outcome: FooterOutcome::Conflict,
        hook_type: HookTypeLabel::GitWithAgent,
        mode: FixCommitMode::Fixup,
        event: &HookEvent::PostCommit,
        header: "⚠ Your uncommitted changes overlap with auto-fix. Working tree has conflict markers — resolve manually.",
        indent: "   ",
    });
    let apply_patch =
        shell_post_commit_apply_patch(&footer_agent, &footer_format, &footer_conflict, &save_diff);
    format!(
        "#!/bin/sh\n\
         {timer}\
         # Activation gate: the pre-commit fixup sentinel.\n\
         # Sentinel presence = pre-commit fixup branch ran and deferred\n\
         # work to us. Without it (e.g. when --no-verify bypassed\n\
         # pre-commit) there's nothing to fix up.\n\
         _SENTINEL=\"$(git rev-parse --git-dir 2>/dev/null)/linthis/pending-fixup.json\"\n\
         if [ ! -f \"$_SENTINEL\" ]; then\n\
         \x20 exit 0\n\
         fi\n\
         \n\
         # Get files from the commit that was just created\n\
         _FILES=$(git diff-tree --no-commit-id --name-only -r HEAD)\n\
         if [ -z \"$_FILES\" ]; then\n\
         \x20 [ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\"\n\
         \x20 exit 0\n\
         fi\n\
         # Alias for capture_agent_patch_in_wt (which reads $_PUSHED_FILES).\n\
         _PUSHED_FILES=\"$_FILES\"\n\
         \n\
         # Physical isolation: format + agent run inside a detached worktree\n\
         # at HEAD, so the user's real working tree is untouched during the\n\
         # (potentially multi-minute) agent phase.\n\
         {worktree_setup}\
         {worktree_enter}\
         \n\
         # Build -i <file> args and run formatter on all committed files\n\
         set --\n\
         while IFS= read -r _F; do set -- \"$@\" -i \"$_F\"; done <<_POST_COMMIT_FILES_EOF_\n\
         $_FILES\n\
         _POST_COMMIT_FILES_EOF_\n\
         _linthis_run_painted {linthis_fmt} \"$@\"\n\
         _FMT_EXIT=$?\n\
         \n\
         # If formatter didn't fully fix, try agent (still in worktree)\n\
         _AGENT_RAN=0\n\
         _DIFF_FILE=\"\"\n\
         if [ \"$_FMT_EXIT\" -ne 0 ]; then\n\
         \x20 {agent_check}\
         \x20 if [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]; then\n\
         {agent_block}\
         \x20\x20\x20 if [ \"$_AGENT_RAN\" = \"1\" ]; then\n\
         \x20\x20\x20\x20\x20 printf \"${{_LINTHIS_W}}[linthis] Re-verifying...${{_LINTHIS_R}}\\n\"\n\
         \x20\x20\x20\x20\x20 _linthis_run_painted {linthis_fmt} \"$@\"\n\
         \x20\x20\x20 fi\n\
         \x20 fi\n\
         fi\n\
         \n\
         # Capture format + agent changes as a patch (still inside worktree).\n\
         {capture_agent_patch}\
         \n\
         # Leave + tear down the worktree. Patch is a tempfile in $TMPDIR,\n\
         # independent of the (now deleted) worktree.\n\
         {worktree_leave}\
         \n\
         {apply_patch}\
         # Consume the sentinel regardless of outcome — no retry on failure.\n\
         [ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\"\n",
        timer = timer_fns,
        linthis_fmt = linthis_fmt_cmd,
        agent_check = agent_check,
        agent_block = agent_block,
        apply_patch = apply_patch,
        worktree_setup = shell_pre_push_worktree_setup(),
        worktree_enter = shell_pre_push_worktree_enter(),
        worktree_leave = shell_pre_push_worktree_leave(),
        capture_agent_patch = shell_capture_agent_patch_in_wt(),
    )
}

/// Build the linthis command for a hook based on event type and extra args
pub(crate) fn build_hook_command(hook_event: &HookEvent, args: &Option<String>) -> String {
    match hook_event {
        HookEvent::PreCommit => {
            // For pre-commit: check + format staged files
            // Default "-c -f" = RunMode::Both (check AND format)
            let extra = args.as_deref().unwrap_or("-c -f");
            format!("linthis -s {} --hook-event=pre-commit", extra)
        }
        HookEvent::PrePush => {
            // For pre-push: check only (formatting should happen at pre-commit stage)
            // Default "-c" = RunMode::CheckOnly
            let extra = args.as_deref().unwrap_or("-c");
            format!("linthis {} --hook-event=pre-push", extra)
        }
        HookEvent::CommitMsg => {
            // For commit-msg: validate commit message using the msg file passed as $1
            "linthis cmsg \"$1\"".to_string()
        }
        HookEvent::PostCommit => {
            // For post-commit: check + format (same as pre-commit) so lint-only
            // rules like line-too-long are caught and passed to the agent.
            // Using only "-f" silently skips rules the formatter can't auto-fix.
            let extra = args.as_deref().unwrap_or("-c -f");
            format!("linthis {} --hook-event=post-commit", extra)
        }
    }
}

/// Get the git action for a hook event
pub(crate) fn hook_action(hook_event: &HookEvent) -> &'static str {
    match hook_event {
        HookEvent::PreCommit => "commit",
        HookEvent::PrePush => "push",
        HookEvent::CommitMsg => "commit",
        HookEvent::PostCommit => "commit",
    }
}

/// All AgentFixProvider variants in detection-priority order
pub(crate) const ALL_AGENT_FIX_PROVIDERS: &[AgentFixProvider] = &[
    AgentFixProvider::Claude,
    AgentFixProvider::Codex,
    AgentFixProvider::Gemini,
    AgentFixProvider::Cursor,
    AgentFixProvider::Droid,
    AgentFixProvider::Auggie,
    AgentFixProvider::Codebuddy,
    AgentFixProvider::Openclaw,
];

/// Split a `provider[/model]` string into (provider_name, Option<model>).
///
/// Examples:
///   "claude"       → ("claude", None)
///   "claude/opus"  → ("claude", Some("opus"))
///   "gemini/flash" → ("gemini", Some("flash"))
pub(crate) fn parse_provider_with_model(raw: &str) -> (&str, Option<&str>) {
    match raw.split_once('/') {
        Some((provider, model)) if !model.is_empty() => (provider, Some(model)),
        _ => (raw, None),
    }
}

/// Merge a model extracted from `provider/model` syntax into existing provider_args.
///
/// If `--provider-args` already contains `--model`, the `/model` part is ignored
/// and a warning is printed (explicit `--provider-args` takes precedence).
pub(crate) fn merge_model_into_provider_args(
    model: Option<&str>,
    existing: Option<&str>,
) -> Option<String> {
    use colored::Colorize;
    // Check if existing provider_args already specifies --model
    if let (Some(m), Some(pa)) = (model, existing) {
        if pa.contains("--model") {
            eprintln!(
                "{}: --provider-args already contains --model, ignoring '{}' from provider/model syntax",
                "Warning".yellow(), m
            );
            return Some(pa.to_string());
        }
    }
    match (model, existing) {
        (Some(m), Some(pa)) => Some(format!("--model {} {}", m, pa)),
        (Some(m), None) => Some(format!("--model {}", m)),
        (None, Some(pa)) => Some(pa.to_string()),
        (None, None) => None,
    }
}

/// Detect which AgentFixProvider CLIs are available in PATH
pub(crate) fn detect_agent_fix_providers() -> Vec<AgentFixProvider> {
    ALL_AGENT_FIX_PROVIDERS
        .iter()
        .filter(|p| super::is_command_available(agent_fix_bin(p).as_ref()))
        .cloned()
        .collect()
}

/// Resolve AgentFixProvider from an optional --provider string.
/// - If specified: parse and validate.
/// - If not specified + yes: auto-detect first available CLI.
/// - If not specified + interactive: show selection menu.
pub(crate) fn resolve_agent_fix_provider(
    provider: Option<&str>,
    yes: bool,
) -> Result<AgentFixProvider, std::process::ExitCode> {
    use colored::Colorize;
    use std::process::ExitCode;

    if let Some(p) = provider {
        if let Some(known) = parse_agent_fix_provider_name(p) {
            return Ok(known);
        }
        // Not a built-in provider — look up in [ai.custom_providers] config
        let cwd = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
        let custom = linthis::config::Config::load_project_config(&cwd)
            .as_ref()
            .and_then(|c| c.ai.custom_providers.get(p).cloned())
            .or_else(|| {
                linthis::config::Config::load_user_config()
                    .as_ref()
                    .and_then(|c| c.ai.custom_providers.get(p).cloned())
            });
        if let Some(custom) = custom {
            let bin = match &custom.command {
                Some(c) => c.to_string(),
                None => {
                    eprintln!(
                        "{}: custom provider '{}' requires a 'command' field in [ai.custom_providers.{}]",
                        "Error".red(), p, p
                    );
                    return Err(ExitCode::from(1));
                }
            };
            let style = match &custom.cli_style {
                Some(s) => s.to_string(),
                None => {
                    eprintln!(
                        "{}: custom provider '{}' requires 'cli_style' in [ai.custom_providers.{}]\n  Valid styles: claude, codex, gemini, cursor, droid, auggie, codebuddy, openclaw",
                        "Error".red(), p, p
                    );
                    return Err(ExitCode::from(1));
                }
            };
            return Ok(AgentFixProvider::Custom { bin, style });
        }
        eprintln!(
            "{}: Unknown provider '{}'. Add it to config:\n  [ai.custom_providers.{}]\n  command = \"{}\"\n  cli_style = \"claude\"  # or codex, gemini, cursor, droid, auggie, codebuddy, openclaw",
            "Error".red(), p, p, p
        );
        return Err(ExitCode::from(1));
    }

    let detected = detect_agent_fix_providers();

    if yes {
        // Auto-detect: use first available, default to claude
        return Ok(detected
            .into_iter()
            .next()
            .unwrap_or(AgentFixProvider::Claude));
    }

    // Interactive menu
    use std::io::{self, Write};

    println!("{}", "Select AI agent for automatic fix:".bold());
    println!();

    for (i, p) in ALL_AGENT_FIX_PROVIDERS.iter().enumerate() {
        let available = super::is_command_available(agent_fix_bin(p).as_ref());
        let tag = if available {
            format!(" {}", "(detected)".cyan())
        } else {
            String::new()
        };
        println!("  {}. {}{}", i + 1, p, tag);
    }
    println!();
    print!("Choose [1-{}]: ", ALL_AGENT_FIX_PROVIDERS.len());
    io::stdout().flush().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).ok();
    let n: usize = input.trim().parse().unwrap_or(0);

    if n >= 1 && n <= ALL_AGENT_FIX_PROVIDERS.len() {
        Ok(ALL_AGENT_FIX_PROVIDERS[n - 1].clone())
    } else {
        println!("Installation cancelled");
        Err(ExitCode::SUCCESS)
    }
}

/// Parse a provider string into an AgentFixProvider.
pub(crate) fn parse_agent_fix_provider_name(name: &str) -> Option<AgentFixProvider> {
    match name.to_lowercase().as_str() {
        "claude" => Some(AgentFixProvider::Claude),
        "codex" => Some(AgentFixProvider::Codex),
        "gemini" => Some(AgentFixProvider::Gemini),
        "cursor" => Some(AgentFixProvider::Cursor),
        "droid" => Some(AgentFixProvider::Droid),
        "auggie" | "aug" | "augment" => Some(AgentFixProvider::Auggie),
        "codebuddy" => Some(AgentFixProvider::Codebuddy),
        "openclaw" => Some(AgentFixProvider::Openclaw),
        _ => None,
    }
}

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

    #[test]
    fn claude_headless_pipes_through_agent_stream() {
        // `claude -p` alone buffers output; real streaming requires
        // --output-format stream-json piped through `linthis agent-stream`
        // for human-readable rendering.
        let cmd = agent_fix_headless_cmd(&AgentFixProvider::Claude, "hi", None);
        assert!(cmd.contains("--verbose"), "got: {cmd}");
        assert!(cmd.contains("--output-format stream-json"), "got: {cmd}");
        assert!(cmd.contains("linthis agent-stream"), "got: {cmd}");
        assert!(cmd.contains(" | "), "must pipe; got: {cmd}");
    }

    #[test]
    fn codebuddy_headless_pipes_through_agent_stream() {
        let cmd = agent_fix_headless_cmd(&AgentFixProvider::Codebuddy, "hi", None);
        assert!(cmd.contains("--output-format stream-json"), "got: {cmd}");
        assert!(cmd.contains("linthis agent-stream"), "got: {cmd}");
    }

    #[test]
    fn commit_msg_claude_pipes_through_agent_stream() {
        let cmd = agent_fix_headless_cmd_commit_msg(&AgentFixProvider::Claude, None);
        assert!(cmd.contains("--output-format stream-json"), "got: {cmd}");
        assert!(cmd.contains("linthis agent-stream"), "got: {cmd}");
    }

    #[test]
    fn fix_block_has_threshold_guard_and_no_spinner() {
        let block = build_agent_fix_block(&AgentFixProvider::Claude, &HookEvent::PreCommit);
        // Threshold guard present and references the env var
        assert!(block.contains("LINTHIS_AGENT_MAX_AUTO_FIX"), "got: {block}");
        // Streaming banner restored now that we actually stream via agent-stream.
        assert!(block.contains("streaming"), "got: {block}");
        // Spinner removed around the agent invocation — start_timer and
        // stop_timer must no longer wrap the agent call in this block.
        assert!(
            !block.contains("start_timer \"Fixing"),
            "spinner should be gone; got: {block}"
        );
        assert!(block.contains("linthis report count"), "got: {block}");
    }

    #[test]
    fn fix_block_reverifies_only_when_agent_actually_ran() {
        let block = build_agent_fix_block(&AgentFixProvider::Claude, &HookEvent::PreCommit);
        // Re-verify branch must be gated on _AGENT_RAN — when the threshold
        // skips the agent, running linthis again is pointless and would
        // just re-print the same failure.
        assert!(block.contains("_AGENT_RAN"), "got: {block}");
        assert!(block.contains("Re-verifying"), "got: {block}");
    }

    #[test]
    fn threshold_parser_does_not_clobber_positional_params() {
        // Regression: `set -- $counts` used to overwrite $@, which broke the
        // commit-msg flow because its agent command depends on $1 holding
        // the commit-message file path. Claude ended up writing its fix
        // to a file literally named "0" (the zero-error count).
        let block = build_agent_fix_block(&AgentFixProvider::Claude, &HookEvent::PreCommit);
        assert!(
            !block.contains("set -- $_AGENT_COUNTS"),
            "parser must not clobber positional params; got: {block}"
        );
        // Positive: uses parameter expansion (%%, ##, #) to split the count string.
        assert!(
            block.contains("_AGENT_ERR=${_AGENT_COUNTS%% *}"),
            "got: {block}"
        );
        assert!(
            block.contains("_AGENT_FILES=${_AGENT_COUNTS##* }"),
            "got: {block}"
        );
    }

    #[test]
    fn commit_msg_block_preserves_msg_file_through_agent_fix() {
        // The cmsg agent command must capture $1 (the real .git/COMMIT_EDITMSG
        // path) before anything else — otherwise the threshold guard's
        // command substitution or $@-mutating shell idioms would clobber it.
        let agent_cmd = agent_fix_headless_cmd_commit_msg(&AgentFixProvider::Claude, None);
        assert!(
            agent_cmd.starts_with("_REAL_MSG=\"$1\";"),
            "cmsg agent command must capture $1 first; got: {agent_cmd}"
        );
        // And the outer fix block must not `set --` or otherwise reassign $@.
        let outer = build_agent_fix_block(&AgentFixProvider::Claude, &HookEvent::CommitMsg);
        assert!(
            !outer.contains("set --"),
            "no positional-param mutation allowed around cmsg agent; got: {outer}"
        );
    }

    #[test]
    fn commit_msg_uses_temp_file_to_bypass_dotgit_block() {
        // Claude (and similar tools) refuse writes to .git/ even with
        // --dangerously-skip-permissions. Workaround: agent edits a temp
        // file, the shell copies it back to $_REAL_MSG. Verify that
        // structure is in place so a future refactor can't quietly break it.
        let cmd = agent_fix_headless_cmd_commit_msg(&AgentFixProvider::Claude, None);

        // Temp file allocation
        assert!(
            cmd.contains("mktemp"),
            "must allocate temp file; got: {cmd}"
        );
        // Seed temp with current message so the agent can read it
        assert!(
            cmd.contains("cp \"$_REAL_MSG\" \"$_MSG_FILE\""),
            "must seed temp file with current message; got: {cmd}"
        );
        // Copy-back conditional on actual change
        assert!(
            cmd.contains("cp \"$_MSG_FILE\" \"$_REAL_MSG\""),
            "must copy fixed message back to .git/; got: {cmd}"
        );
        assert!(cmd.contains("cmp -s"), "must check for changes; got: {cmd}");
        // Cleanup
        assert!(
            cmd.contains("rm -f \"$_MSG_FILE\""),
            "must clean temp; got: {cmd}"
        );
        // Prompt warns the agent off .git/
        assert!(
            cmd.contains("TEMP FILE outside .git/"),
            "prompt must steer agent away from .git/; got: {cmd}"
        );
    }

    #[test]
    fn post_commit_script_restages_only_committed_scope() {
        let s = build_post_commit_script("linthis -c -f --hook-event=post-commit");
        // Must iterate committed files instead of staging every dirty path.
        assert!(
            s.contains("while IFS= read -r _F; do"),
            "restage loop missing: {s}"
        );
        assert!(
            s.contains("git add -- \"$_F\""),
            "per-file scoped add missing: {s}"
        );
        assert!(
            s.contains("<<_RESTAGE_EOF_"),
            "restage heredoc missing: {s}"
        );
        // Old unrestricted-scope staging must be gone so unstaged unrelated
        // changes can no longer leak into the fixup commit.
        assert!(
            !s.contains("echo \"$_CHANGED\" | xargs git add"),
            "unrestricted xargs git add should be removed: {s}"
        );
    }

    /// Path A post-commit: format + agent run INSIDE a detached worktree
    /// at HEAD, so the user's real working tree is untouched throughout.
    /// Staging happens atomically via `git apply --3way --index` on the
    /// captured patch, not via per-phase `git add` loops.
    #[test]
    fn post_commit_with_agent_script_runs_in_worktree_with_patch_replay() {
        let s = build_post_commit_with_agent_script(
            "linthis -c -f --hook-event=post-commit",
            &AgentFixProvider::Claude,
            None,
        );

        // Worktree setup/enter/leave emitted once each.
        assert!(
            s.contains("_PREPUSH_WT=\"\""),
            "worktree setup missing from post-commit script: {s}"
        );
        let enter_count = s.matches("cd \"$_PREPUSH_WT\"").count();
        assert!(
            enter_count >= 1,
            "post-commit must cd into worktree at least once (got {enter_count}): {s}"
        );
        assert!(
            s.contains("_prepush_cleanup_wt"),
            "worktree cleanup marker missing: {s}"
        );

        // Format + agent capture the committed-files set inside the wt.
        assert!(
            s.contains("_PUSHED_FILES=\"$_FILES\""),
            "committed-files alias for capture helper missing: {s}"
        );
        assert!(
            s.contains("git diff --binary HEAD -- \"$@\" > \"$_AGENT_PATCH\""),
            "in-worktree patch capture missing: {s}"
        );

        // Patch replay onto the real root uses PLAIN `--binary` — no
        // `--3way`, no `--index`. `--3way` implies `--index` (per
        // `git-apply(1)`), which rejects benign blob-hash mismatches
        // (e.g. index-stat drift after a fresh commit) with "does not
        // match index". Staging happens explicitly via `git add` against
        // the committed-files scope (`$_FILES`) via the post-commit
        // heredoc (`_POST_COMMIT_STAGE_EOF_`).
        assert!(
            s.contains("git apply --binary --whitespace=nowarn \"$_AGENT_PATCH\""),
            "plain --binary patch replay missing: {s}"
        );
        assert!(
            !s.contains("git apply --3way"),
            "patch replay must NOT use --3way (implies --index → false positives): {s}"
        );
        assert!(
            !s.contains("git apply --binary --index"),
            "patch replay must NOT use --index: {s}"
        );
        assert!(
            s.contains("<<_POST_COMMIT_STAGE_EOF_"),
            "explicit per-file staging heredoc missing: {s}"
        );
        assert!(
            !s.contains("<<_RESTAGE_EOF_"),
            "old per-phase restage heredoc must be removed (patch replay supersedes it): {s}"
        );
        assert!(
            !s.contains("echo \"$_FMT_CHANGED\" | xargs git add"),
            "unrestricted FMT xargs git add should be removed: {s}"
        );
        assert!(
            !s.contains("echo \"$_AGENT_CHANGED\" | xargs git add"),
            "unrestricted AGENT xargs git add should be removed: {s}"
        );
    }

    /// Path B: pre-commit (git-with-agent, non-fixup) must run the agent
    /// inside a fake-worktree sandbox so the user's real working tree is
    /// untouched during the (multi-minute) agent run. Real `git worktree`
    /// can't be used here (index.lock held by the in-progress commit), so
    /// the sandbox is a plain tempdir seeded via `git show :<file>` + a
    /// local `git init` for diff/apply.
    #[test]
    fn pre_commit_agent_runs_in_fake_worktree_sandbox() {
        use crate::cli::commands::HookEvent;

        let s = build_git_with_agent_hook_script(
            "linthis -s -c -f --hook-event=pre-commit",
            &AgentFixProvider::Claude,
            &HookEvent::PreCommit,
            None,
        );

        // Sandbox base path lives under $TMPDIR (NOT $HOME/.linthis/...)
        // so that `linthis -s` inside the sandbox isn't silenced by the
        // default `.linthis/` exclude pattern. The directory name is
        // `linthis-sandbox-<timestamp>-<pid>` to make orphans pruneable.
        assert!(
            s.contains("\"${TMPDIR:-/tmp}\""),
            "pre-commit sandbox base must be $TMPDIR (not ~/.linthis/): {s}"
        );
        assert!(
            s.contains("linthis-sandbox-"),
            "pre-commit sandbox must use `linthis-sandbox-<ts>-<pid>` naming: {s}"
        );
        assert!(
            !s.contains("/.linthis/projects/") || !s.contains("fake-worktrees"),
            "sandbox MUST NOT live under .linthis/ — that's where linthis's \
             own exclude pattern silences everything: {s}"
        );
        // Orphan pruning: 60 min cap, same cadence as the real worktree.
        assert!(
            s.contains("-mmin +60"),
            "sandbox must prune orphans older than 60 min: {s}"
        );
        // Trap cleans up on EXIT/HUP/INT/TERM so Ctrl-C doesn't leak.
        assert!(
            s.contains("trap '_sb_cleanup' EXIT HUP INT TERM"),
            "sandbox must install a cleanup trap: {s}"
        );
        // Staged content is materialized from the index (not the working
        // tree) via `git show :<file>`.
        assert!(
            s.contains("git show \":$_F\" > \"$_SANDBOX/$_F\""),
            "staged content must be materialized via `git show :<file>`: {s}"
        );
        // Sandbox is a git repo with files STAGED (not committed) so
        // that `linthis -s` inside the sandbox can discover them —
        // committing would collapse index into HEAD and leave nothing
        // "staged" for linthis to work on.
        assert!(
            s.contains(
                "git init -q && git -c user.email=linthis@local -c user.name=linthis add -A"
            ),
            "sandbox must init + stage files (no commit): {s}"
        );
        assert!(
            !s.contains("commit -q --no-verify -m \"baseline\""),
            "sandbox must NOT commit — that hides files from `linthis -s`: {s}"
        );
        // Patch capture uses `git diff` (WT vs index) since there's no
        // HEAD (materialize skipped the baseline commit).
        assert!(
            s.contains("git diff --binary ) > \"$_SB_PATCH\"")
                || s.contains("git diff --binary) > \"$_SB_PATCH\""),
            "sandbox must capture via `git diff --binary` (WT vs index, no HEAD): {s}"
        );
        assert!(
            !s.contains("git diff --binary HEAD"),
            "sandbox capture must NOT reference HEAD (no baseline commit): {s}"
        );
        assert!(
            s.contains("git apply --binary --whitespace=nowarn \"$_SB_PATCH\""),
            "sandbox patch must replay with plain --binary to real root: {s}"
        );
        assert!(
            !s.contains("git apply --3way"),
            "sandbox patch replay must NOT use --3way (implies --index): {s}"
        );
        // Fallback label when sandbox setup failed.
        assert!(
            s.contains("Couldn't set up sandbox"),
            "pre-commit agent must print a clearly-labeled fallback message: {s}"
        );
    }

    /// Regression: in pre-commit --type git-with-agent, the agent
    /// invocation must happen BEFORE the mode-specific handling, so
    /// BOTH `dirty` and `squash` modes get a chance to auto-fix via the
    /// agent. Earlier the dirty branch exited 1 before the agent block,
    /// so the agent never ran for dirty mode.
    #[test]
    fn pre_commit_agent_runs_before_mode_specific_handling() {
        use crate::cli::commands::HookEvent;
        let s = build_git_with_agent_hook_script(
            "linthis -s -c -f --hook-event=pre-commit",
            &AgentFixProvider::Claude,
            &HookEvent::PreCommit,
            None,
        );
        // The sandbox agent entry point (phase-1 setup probe) must appear
        // BEFORE the dirty branch's exit-1.
        let agent_idx = s
            .find("_SB_REAL_ROOT=")
            .expect("sandbox setup marker missing");
        let dirty_branch_idx = s
            .find("elif [ \"$_FIX_MODE\" = \"dirty\" ]")
            .expect("dirty branch missing");
        assert!(
            agent_idx < dirty_branch_idx,
            "agent invocation must precede mode-specific handling \
             (got agent@{agent_idx}, dirty_branch@{dirty_branch_idx}): {s}"
        );
        // Sanity: the `exit 1` in the dirty branch must come AFTER the
        // agent block (otherwise we're back to the old bug).
        let dirty_exit_idx = s[dirty_branch_idx..]
            .find("exit 1")
            .map(|i| i + dirty_branch_idx)
            .expect("dirty branch exit 1 missing");
        assert!(
            agent_idx < dirty_exit_idx,
            "dirty branch's exit 1 must follow agent invocation \
             (got agent@{agent_idx}, dirty_exit@{dirty_exit_idx}): {s}"
        );
    }

    /// Pre-commit fixup mode must write the sentinel so the post-commit
    /// hook knows to run the agent. Both hook types (git-with-agent via
    /// `build_git_with_agent_hook_script` and --type git via
    /// `build_global_hook_script_for_event`) emit the sentinel write in
    /// their fixup branch. Sentinel path: `.git/linthis/pending-fixup.json`.
    #[test]
    fn pre_commit_fixup_writes_post_commit_sentinel() {
        use crate::cli::commands::HookEvent;

        let pre_commit_agent = build_git_with_agent_hook_script(
            "linthis -s -c -f --hook-event=pre-commit",
            &AgentFixProvider::Claude,
            &HookEvent::PreCommit,
            None,
        );
        assert!(
            pre_commit_agent.contains("pending-fixup.json"),
            "pre-commit (git-with-agent) fixup branch must write sentinel: {pre_commit_agent}"
        );
        // Sentinel write must live INSIDE the fixup branch, not at top.
        let fixup_branch_start = pre_commit_agent
            .find("if [ \"$_FIX_MODE\" = \"fixup\" ]; then")
            .expect("fixup branch missing");
        let after_fixup = &pre_commit_agent[fixup_branch_start..];
        assert!(
            after_fixup.contains("pending-fixup.json"),
            "sentinel write must appear within the fixup branch: {after_fixup}"
        );

        let pre_commit_git = build_global_hook_script_for_event(&HookEvent::PreCommit, &None, None);
        assert!(
            pre_commit_git.contains("pending-fixup.json"),
            "pre-commit (git type) fixup branch must write sentinel: {pre_commit_git}"
        );

        // Non-fixup pre-commit builds must NOT write the sentinel (dirty/
        // squash handle their own fixes in-band).
        // We can't easily suppress the sentinel path at config-time, but we
        // can still check the write is guarded by `_FIX_MODE = fixup`.
        assert!(
            pre_commit_git.contains("elif [ \"$_FIX_MODE\" = \"fixup\" ]"),
            "git-type pre-commit fixup gate missing: {pre_commit_git}"
        );
    }

    /// Sentinel write must FAIL LOUDLY. Without this, a read-only or
    /// permission-broken `.git` directory would silently swallow the
    /// `mkdir`/redirect failures, leaving no sentinel and no signal —
    /// post-commit would skip fixup work and the user would have no way
    /// to know why the auto-format never happened.
    ///
    /// This test guards two regressions:
    ///   1. The mkdir/write commands must NOT redirect stderr to /dev/null.
    ///   2. They must emit a `[linthis] warning:` to stderr on failure.
    #[test]
    fn pending_fixup_sentinel_write_fails_loudly() {
        let snippet = shell_write_pending_fixup_sentinel(" ");

        // No silent fallback — the mkdir and the JSON write must be loud.
        assert!(
            !snippet.contains("mkdir -p \"$_GIT_DIR/linthis\" 2>/dev/null"),
            "mkdir of $_GIT_DIR/linthis must not silently swallow errors: {snippet}"
        );
        assert!(
            !snippet.contains("> \"$_GIT_DIR/linthis/pending-fixup.json\" 2>/dev/null"),
            "sentinel JSON write must not silently swallow errors: {snippet}"
        );

        // Both failure paths emit a stderr warning the user can act on.
        assert!(
            snippet.contains(
                "printf >&2 '[linthis] warning: failed to create %s/linthis (post-commit fixup will skip)\\n'"
            ),
            "mkdir failure must print a stderr warning: {snippet}"
        );
        assert!(
            snippet.contains(
                "printf >&2 '[linthis] warning: failed to write %s/linthis/pending-fixup.json (post-commit fixup will skip)\\n'"
            ),
            "JSON write failure must print a stderr warning: {snippet}"
        );

        // The `date` fallback inside `created_at` is allowed to be silent —
        // it's a cosmetic field and `date` without args is a hard fallback.
        assert!(
            snippet.contains("date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date"),
            "created_at timestamp fallback should remain: {snippet}"
        );
    }

    /// Sentinel-only activation gate: post-commit fires ONLY when
    /// `.git/linthis/pending-fixup.json` exists (written by the
    /// pre-commit fixup path in step 5). This makes `git commit
    /// --no-verify` a clean opt-out — without pre-commit running, no
    /// sentinel is written, so post-commit cleanly exits 0. The sentinel
    /// is consumed at the end regardless of outcome — no retry on failure.
    #[test]
    fn post_commit_with_agent_script_gates_on_sentinel_only() {
        let s = build_post_commit_with_agent_script(
            "linthis -c -f --hook-event=post-commit",
            &AgentFixProvider::Claude,
            None,
        );
        assert!(
            s.contains(
                "_SENTINEL=\"$(git rev-parse --git-dir 2>/dev/null)/linthis/pending-fixup.json\""
            ),
            "sentinel path resolution missing: {s}"
        );
        assert!(
            s.contains("if [ ! -f \"$_SENTINEL\" ]; then"),
            "sentinel-only activation gate missing: {s}"
        );
        assert!(
            !s.contains("\"$_FIX_MODE\" != \"fixup\""),
            "post-commit must not gate on _FIX_MODE — it lets --no-verify leak through: {s}"
        );
        assert!(
            s.contains("[ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\""),
            "sentinel consumption on exit missing: {s}"
        );
    }

    /// The plain (non-agent) post-commit script must use the same
    /// sentinel-only gate so `--no-verify` cleanly bypasses both
    /// flavors. Before this fix the plain script gated only on
    /// `_FIX_MODE`, which meant fixup-mode users still ran a stray
    /// post-commit even after `--no-verify`.
    #[test]
    fn post_commit_script_gates_on_sentinel_only() {
        let s = build_post_commit_script("linthis -c -f --hook-event=post-commit");
        assert!(
            s.contains(
                "_SENTINEL=\"$(git rev-parse --git-dir 2>/dev/null)/linthis/pending-fixup.json\""
            ),
            "sentinel path resolution missing: {s}"
        );
        assert!(
            s.contains("if [ ! -f \"$_SENTINEL\" ]; then"),
            "sentinel-only activation gate missing: {s}"
        );
        assert!(
            !s.contains("\"$_FIX_MODE\" != \"fixup\""),
            "plain post-commit must not gate on _FIX_MODE — it lets --no-verify leak through: {s}"
        );
        assert!(
            s.contains("[ -f \"$_SENTINEL\" ] && rm -f \"$_SENTINEL\""),
            "sentinel consumption on exit missing: {s}"
        );
    }

    /// Heredoc terminator MUST live at column 0 (unquoted `<<EOF` form) or the
    /// shell swallows the rest of the script and errors with "unexpected end
    /// of file" — exactly the regression that hit the agent post-commit script
    /// when the terminator was indented alongside the enclosing `if` block.
    #[test]
    fn restage_heredoc_terminator_is_at_column_zero() {
        for indent in ["", " ", "      "] {
            let snippet = shell_restage_committed_scope(indent);
            for marker in ["$_FILES", "_RESTAGE_EOF_"] {
                let expected = format!("\n{marker}\n");
                assert!(
                    snippet.contains(&expected),
                    "`{marker}` must be on its own line with no leading whitespace \
                     (indent={indent:?}); got:\n{snippet}"
                );
            }
        }
    }

    /// IDE terminals (VS Code, JetBrains) colour stderr red. The post-commit
    /// informational output — git's commit summary, "Created fixup commit…",
    /// the Agent-fix-applied hint, the fix-commit-mode tip, and the "Undo (by
    /// patch created)" line — must therefore go through stdout, not stderr.
    /// Real errors/warnings in this file still use `>&2` and are not checked
    /// here.
    #[test]
    fn post_commit_informational_output_is_stdout() {
        let plain = build_post_commit_script("linthis -c -f --hook-event=post-commit");
        let agent = build_post_commit_with_agent_script(
            "linthis -c -f --hook-event=post-commit",
            &AgentFixProvider::Claude,
            None,
        );

        for (name, script) in [("plain", &plain), ("agent", &agent)] {
            for offender in [
                "Created fixup commit with format changes\" >&2",
                "Agent fix applied\\n\" >&2",
                "switch mode → \\033[0;36mlinthis config set hook.pre_commit.fix_commit_mode",
            ] {
                // The tip line is always present; assert the whole indented
                // printf does not end with `>&2` by checking the contextual
                // substring for its stderr variant.
                if offender.starts_with("switch mode") {
                    let stderr_form =
                        format!("{offender} [dirty|squash|fixup] -g\\033[0m\\n\" >&2");
                    assert!(
                        !script.contains(&stderr_form),
                        "{name}: fix-commit-mode tip must not end with >&2"
                    );
                } else {
                    assert!(
                        !script.contains(offender),
                        "{name}: `{offender}` found — informational output must not be stderr"
                    );
                }
            }
            // git's own commit summary must be merged into stdout AND piped
            // through _linthis_paint for the IDE VCS-console white wrap.
            assert!(
                script.contains(
                    "git commit --no-verify -m \"fix(linthis): auto-fix lint issues\" 2>&1 | _linthis_paint"
                ),
                "{name}: git commit summary must be merged + painted: {script}"
            );
        }

        // Agent-specific lines: Re-verifying + Undo-by-patch printf.
        assert!(
            !agent.contains("echo \"[linthis] Re-verifying...\" >&2"),
            "Re-verifying must be stdout"
        );
        assert!(
            !agent
                .contains("[linthis]   Undo (by patch created) : \\033[0;33mgit apply -R $_DIFF_FILE\\033[0m\\n\" >&2"),
            "Undo-by-patch hint must be stdout"
        );

        // Every linthis child-process invocation in the post-commit scripts
        // must route through _linthis_run_painted (which folds stderr in and
        // pipes through the VCS-console white filter while preserving exit
        // status) — or, if still inline, at least carry 2>&1.
        for (name, script) in [("plain", &plain), ("agent", &agent)] {
            let linthis_invocations = script.lines().filter(|l| {
                let trimmed = l.trim_start();
                (trimmed.contains("linthis ")
                    || trimmed.contains("$LINTHIS_CMD")
                    || trimmed.contains("hook-event=post-commit"))
                    && !trimmed.starts_with("#")
                    && !trimmed.starts_with("LINTHIS_CMD=")
                    && trimmed.contains("\"$@\"")
            });
            for line in linthis_invocations {
                let ok = line.contains("_linthis_run_painted") || line.contains("2>&1");
                assert!(
                    ok,
                    "{name}: linthis invocation missing _linthis_run_painted/2>&1 (would leak red stderr to IDE):\n  {line}\n---script---\n{script}"
                );
            }
        }
    }

    #[test]
    #[ignore = "diagnostic dump — run with: cargo test --release --bin linthis -- --ignored dump_pre_commit"]
    fn dump_pre_commit() {
        use crate::cli::commands::HookEvent;
        let linthis_cmd = super::build_hook_command(&HookEvent::PreCommit, &None);
        let script = build_git_with_agent_hook_script(
            &linthis_cmd,
            &AgentFixProvider::Codebuddy,
            &HookEvent::PreCommit,
            Some("--model glm-5.0-ioa"),
        );
        println!("---BEGIN PRE-COMMIT SCRIPT---");
        println!("{script}");
        println!("---END PRE-COMMIT SCRIPT---");
    }

    #[test]
    #[ignore = "diagnostic dump — run with: cargo test --release --bin linthis -- --ignored dump_pre_push"]
    fn dump_pre_push() {
        let script = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );
        println!("---BEGIN PRE-PUSH SCRIPT---");
        println!("{script}");
        println!("---END PRE-PUSH SCRIPT---");
    }

    #[test]
    #[ignore = "diagnostic dump — run with: cargo test --release --bin linthis -- --ignored dump_post_commit_agent"]
    fn dump_post_commit_agent() {
        let script = build_post_commit_with_agent_script(
            "linthis -c -f --hook-event=post-commit",
            &AgentFixProvider::Codebuddy,
            None,
        );
        println!("---BEGIN POST-COMMIT-AGENT SCRIPT---");
        println!("{script}");
        println!("---END POST-COMMIT-AGENT SCRIPT---");
    }

    /// The IDE-VCS-console colour compensation must:
    ///   * wrap our own informational lines with `${_LINTHIS_W}…${_LINTHIS_R}`
    ///   * pipe `git commit`'s summary through `_linthis_paint`
    ///   * honour LINTHIS_HOOK_COLOR via the shell `case` so a real TTY gets
    ///     empty wrap variables (i.e. no visible change).
    /// Runtime behaviour is exercised by piping the script to `sh` with the
    /// env var controlling the mode; we assert stdout is painted in
    /// `force-white` mode and left plain in `off` mode.
    #[test]
    fn ide_color_wrapping_toggles_by_env() {
        use std::io::Write;
        use std::process::{Command, Stdio};

        // Tiny standalone snippet: just the color setup + a sample printf.
        let script = format!(
            "{}\nprintf \"${{_LINTHIS_W}}[linthis] hello${{_LINTHIS_R}}\\n\"\n\
             echo '[plain]' | _linthis_paint\n",
            shell_timer_functions()
        );

        let run = |env_value: Option<&str>| -> String {
            let mut cmd = Command::new("sh");
            cmd.arg("-c")
                .arg(&script)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                // Force "non-TTY, non-CI" so auto mode engages.
                .env_remove("CI")
                .env_remove("GITHUB_ACTIONS")
                .env_remove("GITLAB_CI")
                .env_remove("CIRCLECI")
                .env_remove("BUILDKITE")
                .env_remove("CONTINUOUS_INTEGRATION");
            match env_value {
                Some(v) => {
                    cmd.env("LINTHIS_HOOK_COLOR", v);
                }
                None => {
                    cmd.env_remove("LINTHIS_HOOK_COLOR");
                }
            }
            let out = cmd.output().expect("spawn sh");
            assert!(out.status.success(), "sh failed: {:?}", out);
            String::from_utf8_lossy(&out.stdout).into_owned()
        };

        let forced = run(Some("white"));
        assert!(
            forced.contains("\x1b[0;37m[linthis] hello\x1b[0m"),
            "white must wrap printf; got: {forced:?}"
        );
        assert!(
            forced.contains("\x1b[0;37m[plain]\x1b[0m"),
            "white must wrap _linthis_paint input; got: {forced:?}"
        );

        let off = run(Some("off"));
        // In "off" mode, `_LINTHIS_W` is empty so no white prefix is emitted.
        // `_LINTHIS_R` stays at `\033[0m` so an inner colour (e.g. green ✓)
        // in a line like `printf "${_LINTHIS_W}[linthis] \033[0;32m✓…${_LINTHIS_R}"`
        // still resets properly. A trailing bare reset is visually neutral.
        assert!(
            !off.contains("\x1b[0;37m"),
            "off must not emit white ANSI; got: {off:?}"
        );
        assert!(
            off.contains("[linthis] hello"),
            "off must emit the line text; got: {off:?}"
        );
        // _linthis_paint in off mode is `cat`, no wrapping at all.
        assert!(
            off.contains("[plain]\n"),
            "off must pass _linthis_paint through cat; got: {off:?}"
        );
        let paint_line = off.lines().find(|l| l.contains("[plain]")).unwrap();
        assert!(
            !paint_line.contains("\x1b["),
            "off's _linthis_paint must not add ANSI; got: {paint_line:?}"
        );
    }

    /// `--type git` global hook scripts (used for e.g. pre-push) must still
    /// carry `_linthis_run_painted` / `_linthis_paint` even though they have
    /// no agent. Earlier the `timer_block` was gated on `fix_provider.is_some()`,
    /// so pre-push aborted with `_linthis_run_painted: command not found`.
    #[test]
    fn git_type_global_hook_defines_paint_helpers() {
        use crate::cli::commands::HookEvent;
        for event in [HookEvent::PreCommit, HookEvent::PrePush] {
            let script = build_global_hook_script_for_event(&event, &None, None);
            assert!(
                script.contains("_linthis_run_painted()"),
                "{event:?}: _linthis_run_painted definition missing — \
                 pre-push without agent would break: {script}"
            );
            assert!(
                script.contains("_linthis_paint()"),
                "{event:?}: _linthis_paint definition missing: {script}"
            );
            // And the call sites must still refer to the helper, not bare 2>&1.
            assert!(
                script.contains("_linthis_run_painted $LINTHIS_CMD"),
                "{event:?}: call site not wired to helper: {script}"
            );
        }
    }

    /// `sh -n` parse-check the generated post-commit and pre-push scripts so
    /// any future refactor that breaks heredoc termination fails CI, not
    /// production.
    #[test]
    fn generated_hook_scripts_pass_sh_parse_check() {
        use std::io::Write;
        use std::process::{Command, Stdio};

        let scripts = [
            (
                "post_commit_script",
                build_post_commit_script("linthis -c -f --hook-event=post-commit"),
            ),
            (
                "post_commit_with_agent_script",
                build_post_commit_with_agent_script(
                    "linthis -c -f --hook-event=post-commit",
                    &AgentFixProvider::Claude,
                    None,
                ),
            ),
            (
                "pre_push_with_agent_script",
                build_git_with_agent_prepush_script(
                    "linthis -c --hook-event=pre-push",
                    &AgentFixProvider::Codebuddy,
                    None,
                ),
            ),
        ];

        for (name, body) in scripts {
            let mut child = Command::new("sh")
                .arg("-n")
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
                .expect("spawn sh -n");
            child
                .stdin
                .as_mut()
                .expect("stdin")
                .write_all(body.as_bytes())
                .expect("write script");
            let out = child.wait_with_output().expect("wait sh -n");
            assert!(
                out.status.success(),
                "`sh -n` rejected generated {name}:\nstderr: {}\n---script---\n{}",
                String::from_utf8_lossy(&out.stderr),
                body,
            );
        }
    }

    /// Pre-push handler must stage ONLY files in the pushed scope, not every
    /// dirty path in the working tree. Otherwise unrelated modified-but-unstaged
    /// user changes leak into the auto-created fixup/squash commit.
    ///
    /// Both paths (lint-fix and agent-review) now use the precise-isolation
    /// flow, so the commit contains ONLY linthis's / the agent's diff.
    #[test]
    fn pre_push_handler_stages_only_pushed_scope() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Scoped per-file `git add` used by both precise flows.
        assert!(
            s.contains("$_PUSHED_FILES"),
            "handler must reference $_PUSHED_FILES for scoping: {s}"
        );
        assert!(
            s.contains("git add -- \"$_F\""),
            "per-file scoped add missing: {s}"
        );

        // Old unrestricted-scope staging patterns must be gone. They pulled
        // every working-tree change into the auto-created commit.
        assert!(
            !s.contains("echo \"$_CHANGED\" | xargs git add"),
            "unrestricted $_CHANGED xargs git add must be removed: {s}"
        );
        assert!(
            !s.contains("echo \"$_AGENT_CHANGED\" | xargs git add"),
            "unrestricted $_AGENT_CHANGED xargs git add must be removed: {s}"
        );
    }

    /// Pre-push lint-fix path (squash/fixup) must use the precise-isolation
    /// flow so the auto-created commit contains ONLY linthis's format diff —
    /// not the user's uncommitted work that happens to live in the same
    /// pushed file.
    #[test]
    fn pre_push_lint_fix_uses_precise_isolation() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Phase 1: snapshot user state via git stash create
        assert!(
            s.contains("_USER_STASH=$(git stash create"),
            "stash snapshot missing: {s}"
        );

        // Phase 2: reset pushed files to HEAD before formatting
        assert!(
            s.contains("git checkout HEAD -- \"$_F\""),
            "reset-to-HEAD missing: {s}"
        );

        // Phase 3: capture format-only diff to a temp patch file
        assert!(
            s.contains("git diff --binary -- \"$@\" > \"$_LINTHIS_PATCH\""),
            "format patch capture missing: {s}"
        );

        // Phase 6: restore user state with 3-way merge
        assert!(
            s.contains("git stash apply --index \"$_USER_STASH\""),
            "stash restore via --index missing: {s}"
        );

        // Trap for Ctrl-C / crash safety must be installed
        assert!(
            s.contains("trap '_linthis_precise_cleanup'"),
            "safety trap missing: {s}"
        );

        // On unrecoverable restore failure, the stash is saved to the stash
        // list (not just left dangling in reflog) so the user can find it.
        assert!(
            s.contains("git stash store -m \"linthis:"),
            "stash-store fallback missing: {s}"
        );

        // Dirty mode must remain simple: just exit with the lint code.
        // No stash, no format, no commit in the dirty branch.
        let dirty_branch = s
            .split("[ \"$_FIX_MODE\" = \"dirty\" ]")
            .nth(1)
            .and_then(|after| after.split("[ \"$_FIX_MODE\" =").next())
            .unwrap_or("");
        assert!(
            dirty_branch.contains("exit $LINTHIS_EXIT"),
            "dirty branch must exit immediately: {dirty_branch}"
        );
        assert!(
            !dirty_branch.contains("git stash create"),
            "dirty branch must not run precise flow: {dirty_branch}"
        );
        assert!(
            !dirty_branch.contains("git commit"),
            "dirty branch must not commit: {dirty_branch}"
        );
    }

    /// Heredoc terminators in the pushed-scope loops must live at column 0 —
    /// otherwise the shell swallows the rest of the script.
    ///
    /// Path A removed the in-place stash/reset isolation (`_PRE_AGENT_*`,
    /// `_AGENT_LIST_EOF_`, `_AGENT_ADD_EOF_`) in favour of worktree
    /// isolation, and the agent-patch capture now uses one new heredoc
    /// (`_AGENT_PATCH_SCOPE_EOF_`).
    #[test]
    fn pushed_scope_heredoc_terminators_at_column_zero() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );
        for marker in [
            "_PRECISE_RESET_EOF_",
            "_PRECISE_LIST_EOF_",
            "_PRECISE_ADD_EOF_",
            "_AGENT_PATCH_SCOPE_EOF_",
        ] {
            let expected = format!("\n{marker}\n");
            assert!(
                s.contains(&expected),
                "`{marker}` must be on its own line with no leading whitespace; \
                 got script:\n{s}"
            );
        }
    }

    /// Path A: the agent review runs INSIDE the pre-push worktree so the
    /// user's real working tree is untouched for the entire (minutes-long)
    /// review. After the agent finishes, its diff is captured as a tempfile
    /// patch, the worktree is torn down, and `git apply --3way` replays the
    /// patch onto the real root with mode-specific commit behavior.
    #[test]
    fn pre_push_agent_review_runs_in_worktree_with_patch_replay() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Worktree setup (creates `_PREPUSH_WT`) must appear before the agent
        // invocation.
        let setup_idx = s
            .find("_PREPUSH_WT=\"\"")
            .expect("worktree setup marker missing");
        let agent_invoke_idx = s.find("Invoking").expect("agent invocation line missing");
        assert!(
            setup_idx < agent_invoke_idx,
            "worktree setup must appear BEFORE agent invocation (got setup@{setup_idx}, \
             invoke@{agent_invoke_idx}): {s}"
        );

        // The agent-phase enter must re-enter the worktree AFTER the lint
        // phase (which had its own enter). Two `cd "$_PREPUSH_WT"` calls.
        let enter_count = s.matches("cd \"$_PREPUSH_WT\"").count();
        assert!(
            enter_count >= 2,
            "agent phase must re-enter the worktree (expected ≥ 2 cd into \
             $_PREPUSH_WT, got {enter_count}): {s}"
        );

        // The old in-place isolation (`git stash create` + `git reset HEAD` +
        // `git checkout HEAD -- <file>` before the agent) must be GONE — the
        // worktree IS the isolation.
        assert!(
            !s.contains("_PRE_AGENT_STASH="),
            "in-place pre-agent stash must be removed (worktree replaces it): {s}"
        );
        assert!(
            !s.contains("_linthis_agent_cleanup"),
            "in-place pre-agent cleanup trap must be removed: {s}"
        );

        // Agent patch capture happens inside the worktree, scoped to pushed
        // files, before `worktree_leave`.
        let capture_idx = s
            .find("git diff --binary HEAD -- \"$@\" > \"$_AGENT_PATCH\"")
            .expect("in-worktree agent patch capture missing");
        let leave_idx = s
            .rfind("_prepush_cleanup_wt")
            .expect("worktree cleanup marker missing");
        assert!(
            agent_invoke_idx < capture_idx && capture_idx < leave_idx,
            "ordering must be: agent invoke → capture patch → worktree leave \
             (got invoke@{agent_invoke_idx}, capture@{capture_idx}, leave@{leave_idx}): {s}"
        );

        // Patch is replayed with PLAIN `git apply --binary` (no --3way,
        // no --index). `--3way` implies `--index` per git-apply(1), which
        // rejects benign blob-hash mismatches with "does not match index".
        // We apply to the working tree and `git add` explicitly for modes
        // that need staging (squash/fixup).
        assert!(
            s.contains("git apply --binary --whitespace=nowarn \"$_AGENT_PATCH\""),
            "plain --binary patch apply missing: {s}"
        );
        assert!(
            !s.contains("git apply --3way"),
            "apply must NOT use --3way (implies --index → false positives): {s}"
        );
        assert!(
            !s.contains("git apply --binary --index"),
            "apply must NOT use --index: {s}"
        );
        // Squash/fixup path must stage via explicit `git add` heredoc.
        assert!(
            s.contains("<<_APPLY_STAGE_EOF_"),
            "squash/fixup must stage via explicit `git add` heredoc: {s}"
        );

        // Squash path must still do the 3-commit fold dance on top of the
        // applied patch.
        assert!(
            s.contains("git reset --soft HEAD~2"),
            "squash fold dance missing after patch apply: {s}"
        );
    }

    /// On lint failure the pre-push hook must invoke the agent FIX prompt
    /// inside the existing worktree, re-run the lint check, and only then
    /// fall through to the mode-specific handler / agent review. Locks in
    /// the "fix → re-check → review" sequence the user requested so any
    /// future refactor that re-orders these phases is caught here.
    #[test]
    fn pre_push_runs_agent_fix_then_relint_before_mode_handler() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Agent fix block exists, gated on lint failure AND agent availability.
        assert!(
            s.contains("[ \"$LINTHIS_EXIT\" -ne 0 ] && [ \"$_LINTHIS_AGENT_OK\" = \"1\" ]"),
            "agent fix block must be gated on LINTHIS_EXIT and _LINTHIS_AGENT_OK: {s}"
        );

        // _AGENT_FIX_ATTEMPTED flag set inside the fix branch — used later
        // by the dirty-mode post-fix block.
        assert!(
            s.contains("_AGENT_FIX_ATTEMPTED=1"),
            "fix block must set _AGENT_FIX_ATTEMPTED=1: {s}"
        );

        // Re-check lint after the agent fixes. The pattern is a second
        // `_LINT_OUT=$(... 2>&1)` capture inside the fix branch.
        let relint_count = s.matches("_LINT_OUT=$(").count();
        assert!(
            relint_count >= 2,
            "must re-run lint after agent fix (expected ≥ 2 captures of \
             _LINT_OUT, got {relint_count}): {s}"
        );

        // The fix prompt must NOT use the review skill — that runs later in
        // the review phase. The fix prompt mentions running 'linthis -s' to
        // inspect issues; the review prompt mentions the lt.review skill.
        let fix_idx = s
            .find("Lint issues were found")
            .expect("fix-prompt anchor missing");
        let review_idx = s
            .find("structured pre-push code review")
            .expect("review-prompt anchor missing");
        assert!(
            fix_idx < review_idx,
            "fix prompt must appear BEFORE review prompt (fix@{fix_idx}, \
             review@{review_idx}): {s}"
        );

        // The mode-specific handler (which exits early in dirty mode) must
        // appear AFTER the fix block — otherwise dirty short-circuits before
        // the agent gets a chance.
        let fix_block_idx = s
            .find("_AGENT_FIX_ATTEMPTED=1")
            .expect("fix block marker missing");
        let dirty_handler_idx = s
            .find("Handle fix_commit_mode for pre-push")
            .expect("mode handler marker missing");
        assert!(
            fix_block_idx < dirty_handler_idx,
            "agent fix block must appear BEFORE mode handler (fix@{fix_block_idx}, \
             handler@{dirty_handler_idx}): {s}"
        );
    }

    /// After squash/fixup commits land, write a sentinel containing the
    /// new HEAD SHA so the next `git push` (which the user runs to ship
    /// the squashed commit since git's pre-push uses the pre-hook SHA)
    /// can fast-skip the fix+review flow. Without this, every successful
    /// auto-fix forces the user through 5+ minutes of redundant agent
    /// work on the second push.
    #[test]
    fn squash_apply_writes_sentinel_for_fastpath() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Sentinel write must happen INSIDE the success block (after the
        // commit lands, before exit 1) so we don't write it on conflict
        // or no-op paths.
        assert!(
            s.contains("_SENTINEL_SHA=$(git rev-parse HEAD"),
            "squash apply success path must read post-commit HEAD SHA: {s}"
        );
        assert!(
            s.contains("$_SENTINEL_DIR/pre-push-sentinel"),
            "sentinel must be written under ~/.linthis/projects/<slug>/pre-push-sentinel: {s}"
        );
        // Sentinel write must use real-project slug ($_PREPUSH_STUB),
        // not git toplevel from inside the worktree.
        assert!(
            s.contains("\"$HOME/.linthis/projects/$_PREPUSH_STUB\""),
            "sentinel dir must derive from $_PREPUSH_STUB (real slug), \
             not git-rev-parse from inside worktree: {s}"
        );

        // Sentinel write must come BEFORE the success-path `exit 1`
        // (otherwise we lose it when the script exits).
        let sentinel_idx = s
            .find("printf '%s\\n' \"$_SENTINEL_SHA\"")
            .expect("sentinel printf marker missing");
        let success_marker = "Agent fixes squashed into latest commit";
        let success_idx = s
            .find(success_marker)
            .expect("squash success header missing");
        assert!(
            success_idx < sentinel_idx,
            "sentinel write must come AFTER success footer (success@{success_idx}, \
             sentinel@{sentinel_idx})"
        );
    }

    /// On the SECOND push (after squash) the hook must fast-path: read
    /// the sentinel, compare its SHA against current HEAD, and exit 0
    /// without running lint/fix/review when they match. Then delete
    /// sentinel so an unrelated future push runs the full flow.
    #[test]
    fn pre_push_fastpath_skips_when_sentinel_matches_head() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Fast-path block reads the sentinel.
        assert!(
            s.contains("_FAST_SENTINEL=\"$HOME/.linthis/projects/$_FAST_STUB/pre-push-sentinel\""),
            "fast-path must read $HOME/.linthis/projects/<slug>/pre-push-sentinel: {s}"
        );

        // Compares saved SHA to current HEAD before short-circuiting.
        assert!(
            s.contains("[ \"$_FAST_SAVED_SHA\" = \"$_FAST_HEAD_SHA\" ]"),
            "fast-path must compare sentinel SHA to current HEAD SHA: {s}"
        );

        // Consumes (deletes) sentinel on use AND on stale.
        let rm_count = s.matches("rm -f \"$_FAST_SENTINEL\"").count();
        assert!(
            rm_count >= 2,
            "fast-path must delete sentinel both on match (consume) and on \
             mismatch (stale) — found {rm_count} rm sites: {s}"
        );

        // Fast-path must come BEFORE the lint check (whole point is to
        // skip it). Anchor: compare position of the fast-path marker
        // and the lint check call.
        let fast_idx = s.find("Fast-path: HEAD").expect("fast-path marker missing");
        let lint_idx = s
            .find("_LINT_OUT=$(linthis")
            .expect("lint check marker missing");
        assert!(
            fast_idx < lint_idx,
            "fast-path must be evaluated BEFORE lint check (fast@{fast_idx}, \
             lint@{lint_idx})"
        );
    }

    /// Squash/fixup MUST `exit 1` after a successful apply, even though
    /// it just landed a clean commit. Reason: git collects the to-be-
    /// pushed SHA BEFORE invoking pre-push. Our squash dance rewrites
    /// HEAD locally, but git push still tries to ship the OLD (pre-
    /// squash) SHA. Exit 0 here would push the unfixed commit to the
    /// remote and leave the local squashed HEAD diverged from origin —
    /// the opposite of what the user asked for. Exit 1 aborts that
    /// push so the user re-runs `git push`, which re-collects the SHA
    /// (now the squashed one) and ships the fixed version.
    ///
    /// We tried `exit 0` once and it pushed unfixed code to remote —
    /// keeping the test as a tripwire so nobody flips it back without
    /// solving the SHA-snapshot problem first (e.g. via a sentinel that
    /// lets the second push fast-skip review).
    #[test]
    fn squash_apply_success_must_exit_1_so_pushed_sha_matches_squashed_head() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Find the success-path footer header.
        let success_marker = "Agent fixes squashed into latest commit";
        let success_idx = s
            .find(success_marker)
            .expect("squash success footer missing");
        // The next exit AFTER the success footer must be exit 1.
        let after_success = &s[success_idx..];
        let exit_one_idx = after_success.find("exit 1\n");
        let exit_zero_idx = after_success.find("exit 0\n");
        let exit_one_first = match (exit_one_idx, exit_zero_idx) {
            (Some(o), Some(z)) => o < z,
            (Some(_), None) => true,
            _ => false,
        };
        assert!(
            exit_one_first,
            "squash success path MUST exit 1 (git pushes pre-hook SHA; \
             exit 0 ships the unfixed commit). \
             exit_one_idx={exit_one_idx:?}, exit_zero_idx={exit_zero_idx:?}"
        );
    }

    /// Squash/fixup apply must ISOLATE the agent patch from any
    /// uncommitted user state in the user's WT/index. Old buggy flow
    /// did `git apply <patch>` then `git add <pushed_files>`, which
    /// staged the entire current state of the file (agent's diff +
    /// user's WIP edits + their pre-existing staged changes) and
    /// folded everything into the squash commit. Real-world hit:
    /// user had `MM broken.py` (staged + unstaged WIP), pushed,
    /// squash dance ate ALL their WIP into the rewritten commit.
    ///
    /// New flow mirrors `shell_prepush_precise_flow`:
    ///   `git stash create` → `git checkout HEAD -- <pushed>` →
    ///   `git apply <agent patch>` → `git add` → squash/fixup commit →
    ///   `git stash apply --index` to restore user state.
    #[test]
    fn squash_apply_isolates_agent_patch_from_user_wip() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Phase 0 marker: snapshot user state before touching anything.
        assert!(
            s.contains("_USER_STASH=$(git stash create"),
            "squash apply must snapshot user state via `git stash create`: {s}"
        );

        // Phase 1 marker: reset pushed files to HEAD before applying.
        // This is what guarantees the apply target is clean.
        assert!(
            s.contains("_APPLY_RESET_EOF_"),
            "squash apply must use the reset-to-HEAD heredoc: {s}"
        );

        // Trap installed for crash safety while we're holding the stash.
        assert!(
            s.contains("trap '_apply_cleanup_stash' HUP INT TERM"),
            "squash apply must trap signals to recover stash: {s}"
        );

        // Phase 5 marker: 3-way stash restore after the commit lands.
        assert!(
            s.contains("git stash apply --index \"$_USER_STASH\""),
            "squash apply must restore user state via 3-way merge: {s}"
        );

        // On stash-restore conflict, the stash is STORED so the user
        // can recover via `git stash list` — never silently dropped.
        assert!(
            s.contains("git stash store -m \"linthis: uncommitted state before pre-push squash\""),
            "stash-restore conflict path must store stash for recovery: {s}"
        );

        // The OLD bug pattern — staging the entire pushed file without
        // first resetting — must be GONE. (`git add -- "$_F"` still
        // appears, but only AFTER `git checkout HEAD -- "$_F"` cleared
        // the file first; the dangerous ordering was add-without-reset.)
        let reset_idx = s
            .find("_APPLY_RESET_EOF_")
            .expect("reset heredoc marker missing");
        let stage_idx = s
            .find("_APPLY_STAGE_EOF_")
            .expect("stage heredoc marker missing");
        assert!(
            reset_idx < stage_idx,
            "reset-to-HEAD must come BEFORE staging (got reset@{reset_idx}, stage@{stage_idx}): {s}"
        );
    }

    /// Both fix and review prompts must explicitly forbid the agent from
    /// running `git commit` or `git add` inside the worktree. If the
    /// agent commits, `capture_agent_patch_in_wt`'s `git diff HEAD`
    /// returns empty (HEAD already contains the changes), the apply
    /// branch is skipped, and the script falls through to
    /// `exit $REVIEW_EXIT = 0` — the hook silently approves the
    /// UNFIXED user HEAD and the agent's fixes never reach anywhere.
    #[test]
    fn pre_push_prompts_forbid_agent_committing_in_worktree() {
        let fix_prompt = super::agent_fix_prompt_for_event(&HookEvent::PrePush);
        let review_prompt = super::prepush_review_prompt();

        for (label, prompt) in [
            ("fix prompt", fix_prompt.as_str()),
            ("review prompt", review_prompt),
        ] {
            assert!(
                prompt.contains("DO NOT run `git commit`"),
                "{label} must explicitly forbid `git commit`: {prompt}"
            );
            assert!(
                prompt.contains("UNCOMMITTED edits in the working tree"),
                "{label} must instruct agent to leave changes uncommitted: {prompt}"
            );
        }
    }

    /// The review prompt must instruct the agent to auto-fix BOTH Critical
    /// AND Important issues. Restricting auto-fix to Critical only is what
    /// users see as "agent ignored review issues" — Important issues
    /// (unused vars, broken docstrings) are exactly what they expect the
    /// agent to clean up. Minor stays informational.
    #[test]
    fn prepush_review_prompt_auto_fixes_important_and_critical() {
        let prompt = super::prepush_review_prompt();

        // The auto-fix gate must mention both severities.
        assert!(
            prompt.contains("Critical OR Important"),
            "review prompt must auto-fix Critical OR Important issues: {prompt}"
        );

        // Minor must remain explicitly informational so the agent doesn't
        // bikeshed style-only nits in a long auto-fix loop.
        assert!(
            prompt.contains("Minor issues are informational") && prompt.contains("DO NOT auto-fix"),
            "review prompt must keep Minor issues informational only: {prompt}"
        );

        // Push-block gate is still tied to Critical — Important issues
        // shouldn't block the push if the agent couldn't fully clear them
        // (the user gets a "Push with caution" warning instead).
        assert!(
            prompt.contains("Push blocked — fix Critical issues first"),
            "push-block gate must still be Critical-only: {prompt}"
        );
    }

    /// Pre-push worktree setup must export `_LINTHIS_REVIEW_DIR` based on
    /// the user's REAL project root (`_PREPUSH_STUB`), NOT `git rev-parse
    /// --show-toplevel` (which returns the worktree path when the agent
    /// runs inside the worktree). Without this, agent-written review
    /// reports land in `~/.linthis/projects/<wt-path-as-slug>/...` and
    /// `shell_review_report_check` (running outside the wt) can't find
    /// them — silently skipping the critical-issue gate.
    #[test]
    fn pre_push_exports_review_dir_from_real_project_slug() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // Setup writes _LINTHIS_REVIEW_DIR rooted at $_PREPUSH_STUB
        // (the real project slug), not via `git rev-parse --show-toplevel`.
        assert!(
            s.contains(
                "_LINTHIS_REVIEW_DIR=\"$HOME/.linthis/projects/$_PREPUSH_STUB/review/result\""
            ),
            "review dir must be derived from $_PREPUSH_STUB (real project slug): {s}"
        );

        // Exported so the agent subprocess inherits it.
        assert!(
            s.contains("export _LINTHIS_REVIEW_DIR"),
            "_LINTHIS_REVIEW_DIR must be exported for agent: {s}"
        );

        // Review prompt instructs agent to USE the env var, not recompute.
        let review_prompt = super::prepush_review_prompt();
        assert!(
            review_prompt.contains("$_LINTHIS_REVIEW_DIR"),
            "review prompt must reference $_LINTHIS_REVIEW_DIR: {review_prompt}"
        );
        assert!(
            !review_prompt.contains("_SLUG=$(git rev-parse --show-toplevel"),
            "review prompt must NOT recompute slug from git toplevel \
             (returns wt path inside the hook): {review_prompt}"
        );

        // Report check uses the same var so reads/writes line up.
        assert!(
            s.contains("${_LINTHIS_REVIEW_DIR:-/dev/null}"),
            "review report check must read $_LINTHIS_REVIEW_DIR: {s}"
        );
    }

    /// The pre-push agent FIX prompt must NOT instruct the agent to run
    /// `linthis -s` — that's the staged-files check, which returns "no
    /// issues" in pre-push (HEAD is already committed; nothing is staged).
    /// Wrong tool here makes the agent report "nothing to fix" and exit,
    /// which is exactly the bug that prompted this whole flow.
    ///
    /// The right tool is `linthis report show`, which reads the saved
    /// result file — it works for any event (pre-commit, pre-push, etc.).
    #[test]
    fn pre_push_fix_prompt_uses_report_show_not_staged_check() {
        let prompt = super::agent_fix_prompt_for_event(&HookEvent::PrePush);
        // Must point the agent at report show (works regardless of staging).
        assert!(
            prompt.contains("linthis report show"),
            "pre-push fix prompt must instruct `linthis report show`: {prompt}"
        );
        // Must NOT instruct the agent to RUN `linthis -s` (staged-files
        // check). The prompt is allowed to mention `linthis -s` in a
        // negative ("do NOT run") context, so we look for the imperative
        // patterns that would set the agent off in the wrong direction.
        for forbidden in [
            "Run 'linthis -s'",
            "Run `linthis -s`",
            "Re-run 'linthis -s'",
            "Re-run `linthis -s`",
        ] {
            assert!(
                !prompt.contains(forbidden),
                "pre-push fix prompt must NOT instruct {forbidden:?} (returns \
                 empty in pre-push because nothing is staged): {prompt}"
            );
        }
        // Pre-commit prompt unchanged — sanity check.
        let pre_commit_prompt = super::agent_fix_prompt_for_event(&HookEvent::PreCommit);
        assert!(
            pre_commit_prompt.contains("linthis -s"),
            "pre-commit prompt should still use `linthis -s` (staged files): \
             {pre_commit_prompt}"
        );
    }

    /// Dirty mode + agent fix attempt must block the push EVEN IF the
    /// agent cleared the lint, because the fixes live in the user's
    /// working tree (unstaged) — the pushed HEAD content is unchanged
    /// and would ship the unfixed commit.
    #[test]
    fn pre_push_dirty_mode_blocks_after_agent_fix_attempt() {
        let s = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );

        // The dirty post-fix block must check the flag AND mode, then exit 1.
        assert!(
            s.contains(
                "[ \"$_FIX_MODE\" = \"dirty\" ] && [ \"${_AGENT_FIX_ATTEMPTED:-0}\" = \"1\" ]"
            ),
            "dirty post-fix block must gate on $_FIX_MODE and $_AGENT_FIX_ATTEMPTED: {s}"
        );

        // The block must come AFTER apply_agent_patch — otherwise the
        // agent's fixes don't make it to the user's WT before the block.
        let apply_idx = s
            .rfind("git apply --binary --whitespace=nowarn \"$_AGENT_PATCH\"")
            .expect("patch apply marker missing");
        let dirty_block_idx = s
            .find("[ \"$_FIX_MODE\" = \"dirty\" ] && [ \"${_AGENT_FIX_ATTEMPTED:-0}\" = \"1\" ]")
            .expect("dirty post-fix marker missing");
        assert!(
            apply_idx < dirty_block_idx,
            "dirty block must come AFTER patch apply (apply@{apply_idx}, \
             dirty_block@{dirty_block_idx}): {s}"
        );

        // The block must exit 1, not fall through to `exit $REVIEW_EXIT`.
        let after_block = &s[dirty_block_idx..];
        let exit1_idx = after_block
            .find("exit 1")
            .expect("exit 1 missing in dirty block");
        let next_fi_idx = after_block.find("\nfi").expect("closing fi missing");
        assert!(
            exit1_idx < next_fi_idx,
            "dirty block must `exit 1` BEFORE its closing `fi`: {after_block}"
        );
    }

    /// Every non-Clean outcome branch of every hook surface must carry the
    /// unified footer's `→ Switch fix_commit_mode` block so users discover
    /// the alternate modes. The block uses the new template
    /// `hook.<event>.fix_commit_mode <mode> -g` (the old short-tip literal
    /// `[dirty|squash|fixup]` was retired in the footer migration).
    #[test]
    fn dirty_mode_branches_emit_mode_switch_tip() {
        use crate::cli::commands::HookEvent;

        // Pre-push --type git-with-agent: 6 footer sites expect the pre_push
        // switch block (lint-fix dirty-blocked/squash-applied/fixup-applied +
        // agent-review dirty-applied/squash-applied/fixup-applied). There are
        // also Conflict branches emitting the same pointer, so allow ≥ 6.
        let prepush = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );
        let occurrences = prepush
            .matches("linthis config set hook.pre_push.fix_commit_mode <mode> -g")
            .count();
        assert!(
            occurrences >= 6,
            "pre-push script must include the unified pre_push switch block in all \
             final-outcome branches (expected >= 6 occurrences, got {occurrences}): {prepush}"
        );

        // Pre-commit git-with-agent: dirty branch carries the pre_commit block.
        let pre_commit_agent = build_git_with_agent_hook_script(
            "linthis -s -c -f --hook-event=pre-commit",
            &AgentFixProvider::Claude,
            &HookEvent::PreCommit,
            None,
        );
        assert!(
            pre_commit_agent
                .contains("linthis config set hook.pre_commit.fix_commit_mode <mode> -g"),
            "pre-commit (git-with-agent) must emit the unified pre_commit switch block: \
             {pre_commit_agent}"
        );

        // Pre-commit git-type: same requirement.
        let pre_commit_git = build_global_hook_script_for_event(&HookEvent::PreCommit, &None, None);
        assert!(
            pre_commit_git.contains("linthis config set hook.pre_commit.fix_commit_mode <mode> -g"),
            "pre-commit (git type) must emit the unified pre_commit switch block: \
             {pre_commit_git}"
        );
    }

    /// Squash-mode output on every hook surface must carry the user-facing
    /// success/failure header plus the unified footer's Switch block so
    /// users discover dirty/fixup as alternatives.
    #[test]
    fn squash_mode_branches_emit_message_and_tip() {
        use crate::cli::commands::HookEvent;

        // Pre-commit --type git: squash branches print distinct success and
        // failure headers. Success folds into the commit; failure keeps the
        // "Format fixes staged" progress echo, then the unified footer Blocked
        // header adds "Unfixable lint issues above — THIS commit blocked."
        let pre_commit_git = build_global_hook_script_for_event(&HookEvent::PreCommit, &None, None);
        assert!(
            pre_commit_git
                .contains("Format fixes folded into your commit (squash mode — single commit)"),
            "pre-commit (git type) squash SUCCESS header missing: {pre_commit_git}"
        );
        assert!(
            pre_commit_git.contains(
                "Format fixes staged — will fold into your next 'git commit' (squash mode)"
            ),
            "pre-commit (git type) squash FAILURE progress echo missing: {pre_commit_git}"
        );
        assert!(
            pre_commit_git.contains("✗ Unfixable lint issues above — THIS commit blocked"),
            "pre-commit (git type) squash FAILURE unified header missing: {pre_commit_git}"
        );
        // Failure footer (Blocked + Git) must carry:
        //   - Currently: --type git
        //   - Upgrade hint (Want auto-fix + AI code review? + install cmd)
        //   - Per-mode explanations with inline "(current)" marker on squash
        assert!(
            pre_commit_git.contains("Currently: --type git"),
            "pre-commit (git type) blocked footer must show current --type: {pre_commit_git}"
        );
        assert!(
            pre_commit_git.contains("Want auto-fix + AI code review? Switch hook type"),
            "pre-commit (git type) blocked footer must suggest git-with-agent: {pre_commit_git}"
        );
        assert!(
            pre_commit_git.contains("linthis hook install -g --type git-with-agent")
                && pre_commit_git.contains("--event pre-commit --force"),
            "pre-commit (git type) blocked footer must include install command with event: \
             {pre_commit_git}"
        );
        // Per-mode explanations carry the short alias in parens and the
        // `(current)` tag on the active mode (squash in the blocked
        // branch).
        for per_mode_line in [
            "dirty  (d) = format left unstaged",
            "squash (s) = format auto-staged into your commit — one commit (current)",
            "fixup  (f) = commit proceeds; a separate auto-fix commit is created post-commit",
        ] {
            assert!(
                pre_commit_git.contains(per_mode_line),
                "pre-commit (git type) footer must include {per_mode_line:?}: {pre_commit_git}"
            );
        }
        // The unified switch block must appear at least twice (squash success
        // + squash failure + dirty branch = 3+, but at least 2 is safe).
        let switch_block_count = pre_commit_git
            .matches("linthis config set hook.pre_commit.fix_commit_mode <mode> -g")
            .count();
        assert!(
            switch_block_count >= 2,
            "pre-commit (git type) must emit ≥ 2 unified switch blocks \
             (got {switch_block_count}): {pre_commit_git}"
        );

        // Pre-commit --type git-with-agent: same coverage minus the upgrade
        // hint (already in agent type).
        let pre_commit_agent = build_git_with_agent_hook_script(
            "linthis -s -c -f --hook-event=pre-commit",
            &AgentFixProvider::Claude,
            &HookEvent::PreCommit,
            None,
        );
        assert!(
            pre_commit_agent
                .contains("Format fixes folded into your commit (squash mode — single commit)"),
            "pre-commit (git-with-agent) squash SUCCESS header missing: {pre_commit_agent}"
        );
        assert!(
            pre_commit_agent.contains(
                "Format fixes staged — will fold into your next 'git commit' (squash mode)"
            ),
            "pre-commit (git-with-agent) squash FAILURE progress echo missing: {pre_commit_agent}"
        );
        assert!(
            pre_commit_agent.contains(
                "squash (s) = format auto-staged into your commit — one commit (current)"
            ),
            "pre-commit (git-with-agent) blocked footer must mark squash (current): \
             {pre_commit_agent}"
        );
        // Agent type: the Blocked footer must NOT print the upgrade hint (it's
        // already the upgraded type). Gate check: if the exact "Currently:
        // --type git" appears followed by the upgrade hint, that's a bug. In
        // agent type we never emit the Currently line at all.
        assert!(
            !pre_commit_agent.contains("Want auto-fix + AI code review"),
            "pre-commit (git-with-agent) must NOT suggest upgrading (already agent): \
             {pre_commit_agent}"
        );
        assert!(
            !pre_commit_agent.contains("Currently: --type git"),
            "pre-commit (git-with-agent) blocked footer must not emit the Currently line: \
             {pre_commit_agent}"
        );
    }

    /// Pre-push `_PUSHED_FILES` uses `git diff --name-only A..B` (tree-delta
    /// semantics): if a file is added then reverted inside the push range,
    /// its final content matches what's already reviewed on the remote, so
    /// there's nothing new to re-check. Using `git log --name-only` (union)
    /// would force re-linting for files with zero net change — wasted work.
    #[test]
    fn pre_push_uses_tree_delta_not_commit_union() {
        use crate::cli::commands::HookEvent;

        // --type git pre-push
        let git_script = build_global_hook_script_for_event(&HookEvent::PrePush, &None, None);
        assert!(
            git_script.contains("git diff --name-only \"$_BASE\"..\"$_LOCAL_SHA\""),
            "--type git pre-push must use `git diff --name-only` for tree-delta: {git_script}"
        );
        assert!(
            !git_script.contains("git log --name-only --pretty=format:"),
            "--type git pre-push must NOT use `git log --name-only` (that would force \
             re-linting files with zero net change): {git_script}"
        );

        // --type git-with-agent pre-push
        let agent_script = build_git_with_agent_prepush_script(
            "linthis -c --hook-event=pre-push",
            &AgentFixProvider::Codebuddy,
            None,
        );
        assert!(
            agent_script.contains("git diff --name-only \"$_BASE\"..HEAD"),
            "--type git-with-agent pre-push must use `git diff --name-only` for tree-delta: \
             {agent_script}"
        );
        assert!(
            !agent_script.contains("git log --name-only --pretty=format:"),
            "--type git-with-agent pre-push must NOT use `git log --name-only`: {agent_script}"
        );
    }

    /// `--type git` pre-push must print explicit messages so users see what
    /// happened (previously it was silent: preamble exited 0 on empty diff,
    /// handler was empty). Should emit:
    ///   - "Pre-push check: verifying N file(s)" before linthis runs
    ///   - Early-exit messages for tag push / no files
    ///   - Fallback base hint when remote SHA isn't fetched
    ///   - Success / failure message after linthis
    ///   - For failure: tip about switching to --type git-with-agent
    #[test]
    fn git_type_pre_push_is_visible() {
        use crate::cli::commands::HookEvent;

        let s = build_global_hook_script_for_event(&HookEvent::PrePush, &None, None);

        // Pre-linthis visibility: show file count.
        assert!(
            s.contains("Pre-push check: verifying"),
            "pre-push must announce how many files it will check: {s}"
        );

        // Early-exit paths must be visible too.
        assert!(
            s.contains("Tag push detected"),
            "pre-push must announce tag-push skip: {s}"
        );
        assert!(
            s.contains("No source files changed"),
            "pre-push must announce empty-diff skip: {s}"
        );

        // Fallback for unreachable remote SHA.
        assert!(
            s.contains("Remote SHA not fetched locally"),
            "pre-push must hint when falling back to upstream base: {s}"
        );
        assert!(
            s.contains("rev-parse '@{u}'"),
            "pre-push fallback must try @{{u}}: {s}"
        );

        // Post-linthis handler: pass/fail messaging + git-with-agent tip.
        assert!(
            s.contains("Pre-push check passed"),
            "pre-push must announce success: {s}"
        );
        assert!(
            s.contains("Pre-push check failed"),
            "pre-push must announce failure: {s}"
        );
        // Failure is Blocked + Git → unified footer adds the upgrade block.
        assert!(
            s.contains("Currently: --type git"),
            "pre-push failure footer must show current --type: {s}"
        );
        assert!(
            s.contains("Want auto-fix + AI code review") && s.contains("--type git-with-agent"),
            "pre-push failure footer must suggest git-with-agent: {s}"
        );
    }

    // ──────────────────────────────────────────────────────────────────
    // shell_hook_footer tests
    // ──────────────────────────────────────────────────────────────────

    fn footer(
        outcome: FooterOutcome,
        hook_type: HookTypeLabel,
        mode: FixCommitMode,
        event: &HookEvent,
        header: &str,
    ) -> String {
        shell_hook_footer(&FooterCtx {
            outcome,
            hook_type,
            mode,
            event,
            header,
            indent: "",
        })
    }

    #[test]
    fn footer_header_always_first_line_printf_stdout() {
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Fixup,
            &HookEvent::PreCommit,
            "✓ Agent fix applied",
        );
        // First line must be a printf to stdout (NOT echo >&2), and carry the
        // white-wrap variables so IDE VCS consoles don't render it red.
        let first_line = s.lines().next().expect("at least one line");
        assert!(
            first_line.contains("printf")
                && first_line.contains("${_LINTHIS_W}")
                && first_line.contains("${_LINTHIS_R}"),
            "header must be white-wrapped printf: {first_line}"
        );
        assert!(
            first_line.contains("[linthis] ✓ Agent fix applied"),
            "header text must appear verbatim: {first_line}"
        );
        for line in s.lines() {
            assert!(
                !line.contains(">&2"),
                "footer must not write to stderr: {line}"
            );
        }
    }

    #[test]
    fn footer_applied_emits_view_undo_and_patch_gate() {
        // Pre-push fixup (agent fix): View/Undo reference HEAD~1; patch-undo
        // line is shell-guarded on `$_DIFF_FILE` so it only prints when a
        // patch was actually saved.
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Fixup,
            &HookEvent::PrePush,
            "Created fixup commit with agent fixes",
        );
        assert!(s.contains("View changes : \\033[0;36mgit diff HEAD~1"));
        assert!(s.contains("Undo changes : \\033[0;33mgit reset HEAD~1"));
        assert!(s.contains(
            "[ -n \"$_DIFF_FILE\" ] && printf \"${_LINTHIS_W}[linthis]   Undo (by patch created) : \\033[0;33mgit apply -R $_DIFF_FILE"
        ));
    }

    #[test]
    fn footer_view_undo_match_event_and_mode() {
        // Pre-commit dirty: working-tree view + linthis backup undo.
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Dirty,
            &HookEvent::PreCommit,
            "Format fixes left unstaged",
        );
        assert!(s.contains("View changes : \\033[0;36mgit diff${_LINTHIS_R}"));
        assert!(s.contains("Undo changes : \\033[0;33mlinthis backup undo${_LINTHIS_R}"));

        // Pre-commit squash: staged view + soft-reset undo.
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Squash,
            &HookEvent::PreCommit,
            "Format fixes folded into your commit",
        );
        assert!(s.contains("View changes : \\033[0;36mgit diff --cached${_LINTHIS_R}"));
        assert!(s.contains("Undo changes : \\033[0;33mgit reset HEAD${_LINTHIS_R}"));
    }

    #[test]
    fn footer_blocked_git_type_emits_upgrade_hint() {
        let s = footer(
            FooterOutcome::Blocked,
            HookTypeLabel::Git,
            FixCommitMode::Squash,
            &HookEvent::PreCommit,
            "✗ Pre-commit check failed",
        );
        assert!(
            s.contains("Currently: --type git") && !s.contains("Currently: --type git-with-agent"),
            "blocked+git must show plain --type git: {s}"
        );
        assert!(
            s.contains("Want auto-fix + AI code review? Switch hook type"),
            "blocked+git must suggest upgrade: {s}"
        );
        assert!(
            s.contains("linthis hook install -g --type git-with-agent")
                && s.contains("--event pre-commit --force"),
            "upgrade hint must include install command with event name: {s}"
        );
    }

    #[test]
    fn footer_blocked_agent_type_omits_upgrade_hint() {
        let s = footer(
            FooterOutcome::Blocked,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Squash,
            &HookEvent::PreCommit,
            "✗ Pre-commit check failed",
        );
        assert!(
            !s.contains("Want auto-fix + AI code review"),
            "agent-type must not suggest upgrade to itself: {s}"
        );
        assert!(
            !s.contains("Currently: --type"),
            "agent-type blocked must not print the Currently line: {s}"
        );
    }

    #[test]
    fn footer_switch_mode_block_marks_current_and_uses_correct_event_key() {
        // Pre-push + current=fixup → config key is pre_push, fixup line carries (current).
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Fixup,
            &HookEvent::PrePush,
            "Created fixup commit with agent fixes",
        );
        assert!(
            s.contains(
                "→ Switch fix_commit_mode: \\033[0;36mlinthis config set hook.pre_push.fix_commit_mode <mode> -g"
            ),
            "pre_push config key wrong: {s}"
        );
        // Each mode name now carries its short alias in parens
        // (`dirty (d)` / `squash (s)` / `fixup (f)`) with padding so the
        // `=` column aligns. `(current)` goes to the active mode only.
        assert!(s.contains("dirty  (d) = fixes left in working tree"));
        assert!(s.contains("squash (s) = fixes squashed into latest commit"));
        assert!(s.contains(
            "fixup  (f) = fixes go into a separate fixup commit; run 'git push' again (current)"
        ));
        assert!(!s.contains(
            "dirty  (d) = fixes left in working tree; push blocks, you re-stage manually (current)"
        ));
        assert!(!s.contains(
            "squash (s) = fixes squashed into latest commit; run 'git push' again (current)"
        ));

        // Pre-commit + current=dirty → config key is pre_commit, dirty line
        // carries (current).
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Dirty,
            &HookEvent::PreCommit,
            "Format fixes left unstaged",
        );
        assert!(
            s.contains("hook.pre_commit.fix_commit_mode <mode>"),
            "pre_commit config key wrong: {s}"
        );
        assert!(s.contains(
            "dirty  (d) = format left unstaged; commit blocks, you re-stage manually (current)"
        ));
        assert!(s.contains("squash (s) = format auto-staged into your commit — one commit"));
        assert!(s.contains(
            "fixup  (f) = commit proceeds; a separate auto-fix commit is created post-commit"
        ));
        assert!(
            !s.contains("squash (s) = format auto-staged into your commit — one commit (current)")
        );
    }

    #[test]
    fn footer_post_commit_uses_pre_commit_config_key() {
        // Post-commit is the target of pre_commit fixup mode — its footer
        // still talks about hook.pre_commit.fix_commit_mode because that's
        // the key the user tunes.
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Fixup,
            &HookEvent::PostCommit,
            "Created fixup commit with format changes",
        );
        assert!(
            s.contains("hook.pre_commit.fix_commit_mode"),
            "post_commit footer must reference pre_commit config key: {s}"
        );
    }

    #[test]
    fn footer_clean_emits_header_only() {
        let s = footer(
            FooterOutcome::Clean,
            HookTypeLabel::Git,
            FixCommitMode::Squash,
            &HookEvent::PrePush,
            "✓ Pre-push check passed — push proceeding.",
        );
        // Only the header line — no View/Undo, no Switch block, and
        // no closing "Done" hint (Clean = nothing happened).
        assert!(s.contains("Pre-push check passed"));
        assert!(!s.contains("View changes"));
        assert!(!s.contains("Undo changes"));
        assert!(!s.contains("→ Switch fix_commit_mode"));
        assert!(!s.contains("Undo (by patch created)"));
        assert!(
            !s.contains("✓ Done — "),
            "Clean outcome must not emit a closing hint: {s}"
        );
    }

    /// Dirty-mode pre-commit Applied must emit a closing end-hint that
    /// tells the user the flow is over and the next step (re-stage +
    /// `git commit`). Without this the last line of the output was the
    /// per-mode Switch block, which doesn't signal "flow complete".
    #[test]
    fn footer_end_hint_dirty_applied_points_at_retry() {
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Dirty,
            &HookEvent::PreCommit,
            "Files formatted but not staged (dirty mode).",
        );
        assert!(
            s.contains(
                "✓ Done — review with 'git diff', stage with 'git add', then 'git commit' again."
            ),
            "pre-commit dirty footer must end with an explicit Done marker: {s}"
        );
        // And it's the LAST line of the output.
        let last = s.trim_end().lines().last().unwrap_or("");
        assert!(
            last.contains("✓ Done"),
            "end-hint must be the last line of the footer, got: {last:?}"
        );
    }

    /// Pre-push dirty swaps the retry command to `git push`.
    #[test]
    fn footer_end_hint_pre_push_uses_git_push() {
        let s = footer(
            FooterOutcome::Applied,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Dirty,
            &HookEvent::PrePush,
            "Agent fixes left in working tree (dirty mode).",
        );
        assert!(
            s.contains("✓ Done") && s.contains("'git push' again"),
            "pre-push end-hint must reference `git push`, not `git commit`: {s}"
        );
    }

    /// Blocked / Conflict also carry outcome-specific end-hints so the
    /// user knows the hook is done and what to do next.
    #[test]
    fn footer_end_hint_blocked_and_conflict() {
        let blocked = footer(
            FooterOutcome::Blocked,
            HookTypeLabel::Git,
            FixCommitMode::Squash,
            &HookEvent::PreCommit,
            "✗ Pre-commit check failed",
        );
        assert!(
            blocked.contains("✗ Blocked — fix the errors above manually, then 'git commit' again."),
            "Blocked must carry a ✗ end-hint: {blocked}"
        );

        let conflict = footer(
            FooterOutcome::Conflict,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Squash,
            &HookEvent::PreCommit,
            "⚠ overlap",
        );
        assert!(
            conflict.contains(
                "⚠ Conflict — resolve markers in the working tree, then 'git commit' again."
            ),
            "Conflict must carry a ⚠ end-hint: {conflict}"
        );
    }

    /// CommitMsg and PostCommit events skip the end-hint — those have
    /// their own downstream signals (✓ New message / git commit summary)
    /// so an explicit linthis "Done" would be redundant.
    #[test]
    fn footer_end_hint_skipped_for_commit_msg_and_post_commit() {
        for event in [HookEvent::CommitMsg, HookEvent::PostCommit] {
            let s = footer(
                FooterOutcome::Applied,
                HookTypeLabel::GitWithAgent,
                FixCommitMode::Fixup,
                &event,
                "✓ Agent fix applied",
            );
            assert!(
                !s.contains("✓ Done — "),
                "{event:?}: end-hint must be skipped (downstream signals handle it): {s}"
            );
        }
    }

    #[test]
    fn footer_conflict_emits_view_but_no_undo() {
        let s = footer(
            FooterOutcome::Conflict,
            HookTypeLabel::GitWithAgent,
            FixCommitMode::Squash,
            &HookEvent::PrePush,
            "⚠ Your uncommitted changes overlap with agent fixes",
        );
        // Conflict: user still benefits from a View hint to inspect markers,
        // but no Undo — they must resolve by hand.
        assert!(s.contains("View changes"));
        assert!(!s.contains("Undo changes"));
        assert!(!s.contains("Undo (by patch created)"));
        // Switch block still present so they can pivot to a different mode.
        assert!(s.contains("→ Switch fix_commit_mode"));
    }

    #[test]
    fn footer_indent_is_respected_on_every_line() {
        let indent = "       "; // 7 spaces, matches deepest pre-push nesting
        let s = shell_hook_footer(&FooterCtx {
            outcome: FooterOutcome::Applied,
            hook_type: HookTypeLabel::GitWithAgent,
            mode: FixCommitMode::Fixup,
            event: &HookEvent::PrePush,
            header: "✓ Agent fix applied",
            indent,
        });
        for line in s.lines() {
            if line.is_empty() {
                continue;
            }
            assert!(
                line.starts_with(indent),
                "every emitted line must carry the caller's indent ({indent:?}): {line:?}"
            );
        }
    }
}