sqz-engine 2.1.1

Context compression engine behind sqz: per-command formatters, SHA-256 session dedup, AST structural summaries, token counting and budget tracking for AI coding agents
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
/// PreToolUse hook integration for AI coding tools.
///
/// Provides transparent command interception: when an AI tool (Claude Code,
/// Cursor, Copilot, etc.) executes a bash command, the hook rewrites it to
/// pipe output through sqz for compression. The AI tool never knows it
/// happened — it just sees smaller output.
///
/// Supported hook formats (tools that support command rewriting via hooks):
/// - Claude Code: .claude/settings.local.json or ~/.claude/settings.json (nested
///   PreToolUse, matcher "Bash|PowerShell", plus PostToolUse for Bash and
///   two allow rules for the parts the rewrite adds)
/// - Gemini CLI: .gemini/settings.json (nested BeforeTool, matcher: "run_shell_command")
/// - OpenCode: ~/.config/opencode/plugins/sqz.ts (TypeScript plugin, tool.execute.before)
///
/// Tools that do NOT support command rewriting via hooks (use prompt-level
/// guidance via rules files instead):
/// - Codex: only supports deny in PreToolUse; updatedInput is parsed but ignored
/// - Windsurf: no documented hook API; uses .windsurfrules prompt-level guidance
/// - Cline: PreToolUse cannot rewrite commands; uses .clinerules prompt-level guidance
/// - Cursor: beforeShellExecution can't replace the command, and preToolUse
///   can only together with a permission decision, where "allow" would skip
///   Cursor's own approval. Uses .cursor/rules/sqz.mdc prompt-level guidance
///   instead; `sqz hook cursor` prints nothing and exits 1, which Cursor
///   treats as a failed hook, so its normal approval applies.

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

use crate::error::Result;

/// A tool hook configuration for a specific AI coding tool.
#[derive(Debug, Clone)]
pub struct ToolHookConfig {
    /// Name of the AI tool.
    pub tool_name: String,
    /// Path to the hook config file (relative to project root or home).
    pub config_path: PathBuf,
    /// The JSON/TOML content to write.
    pub config_content: String,
    /// Whether this is a project-level or user-level config.
    pub scope: HookScope,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookScope {
    /// Installed per-project (e.g., .claude/hooks/)
    Project,
    /// Installed globally for the user (e.g., ~/.claude/hooks/)
    User,
}

/// Which AI tool platform is invoking the hook.
/// Each platform has a different JSON output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookPlatform {
    /// Claude Code: hookSpecificOutput with updatedInput (camelCase)
    ClaudeCode,
    /// Cursor: no answer, so Cursor's own approval applies
    Cursor,
    /// Gemini CLI: decision + hookSpecificOutput.tool_input
    GeminiCli,
    /// Windsurf: exit-code based (no JSON rewriting support confirmed)
    Windsurf,
    /// Kiro: STDOUT with rewritten tool_input JSON, exit 0 = allow
    Kiro,
    /// Copilot CLI: { permissionDecision, modifiedArgs } (camelCase input:
    /// toolName + toolArgs)
    Copilot,
}

/// Process a PreToolUse hook invocation from an AI tool.
///
/// Reads a JSON payload from `input` describing the tool call, rewrites
/// bash commands to pipe through sqz, and returns the modified payload.
///
/// Input format (Claude Code):
/// ```json
/// {
///   "tool_name": "Bash",
///   "tool_input": {
///     "command": "git status"
///   }
/// }
/// ```
///
/// Output: same structure with command rewritten to pipe through sqz.
/// Exit code 0 = proceed with modified command.
/// Exit code 1 = block the tool call (not used here).
pub fn process_hook(input: &str) -> Result<String> {
    process_hook_for_platform(input, HookPlatform::ClaudeCode)
}

/// Process a hook invocation for Cursor: always an error, so Cursor's own
/// approval applies.
pub fn process_hook_cursor(_input: &str) -> Result<String> {
    Err(crate::error::SqzError::Other(
        "can't rewrite without approving the command; Cursor's own approval applies".into(),
    ))
}

/// Process a hook invocation for Gemini CLI.
///
/// Gemini uses: `{ "decision": "allow", "hookSpecificOutput": { "tool_input": { "command": "..." } } }`
pub fn process_hook_gemini(input: &str) -> Result<String> {
    process_hook_for_platform(input, HookPlatform::GeminiCli)
}

/// Process a hook invocation for Windsurf.
///
/// Windsurf hook support is limited. We attempt the same rewrite as Claude Code
/// but the output format may not be honored. Falls back to exit-code semantics.
pub fn process_hook_windsurf(input: &str) -> Result<String> {
    process_hook_for_platform(input, HookPlatform::Windsurf)
}

/// Process a hook invocation for Kiro (IDE and CLI).
///
/// Kiro's PreToolUse hook receives JSON on STDIN with `tool_name` and
/// `tool_input`. The hook outputs the modified tool_input JSON to STDOUT.
/// Exit code 0 = allow (proceed with modified input).
/// Exit code 2 = block.
///
/// Kiro uses `execute_bash` (alias `shell`) as the tool name for shell
/// commands, with `tool_input.command` containing the command string.
pub fn process_hook_kiro(input: &str) -> Result<String> {
    process_hook_for_platform(input, HookPlatform::Kiro)
}

/// Process a hook invocation for GitHub Copilot CLI.
///
/// Copilot's camelCase preToolUse payload carries `toolName` + `toolArgs`;
/// the response uses `permissionDecision` + `modifiedArgs`, which
/// substitutes the tool arguments wholesale, so unchanged fields are
/// carried over. Shell tools are `bash` and `powershell`.
pub fn process_hook_copilot(input: &str) -> Result<String> {
    process_hook_for_platform(input, HookPlatform::Copilot)
}

/// Platform-aware hook processing. Extracts the command from the tool-specific
/// input format, rewrites it, and returns the response in the correct format
/// for the target platform.
fn process_hook_for_platform(input: &str, platform: HookPlatform) -> Result<String> {
    if platform == HookPlatform::Cursor {
        return process_hook_cursor(input);
    }
    let mut parsed: serde_json::Value = serde_json::from_str(input)
        .map_err(|e| crate::error::SqzError::Other(format!("hook: invalid JSON input: {e}")))?;
    // Copilot CLI documents `toolArgs` as a JSON string.
    if let Some(args) = parsed
        .get("toolArgs")
        .and_then(|v| v.as_str())
        .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
        .filter(serde_json::Value::is_object)
    {
        parsed["toolArgs"] = args;
    }

    // Claude Code uses "tool_name" + "tool_input" (official docs).
    // Cursor uses "hook_event_name": "beforeShellExecution" with "command" at top level.
    // Some older references show "toolName" + "toolCall" — accept all.
    let tool_name = parsed
        .get("tool_name")
        .or_else(|| parsed.get("toolName"))
        .and_then(|v| v.as_str())
        .unwrap_or("");

    let hook_event = parsed
        .get("hook_event_name")
        .or_else(|| parsed.get("agent_action_name"))
        .and_then(|v| v.as_str())
        .unwrap_or("");

    // Only intercept Bash/shell tool calls.
    //
    // Claude Code's built-in tools (Read, Grep, Glob, Write) bypass shell
    // hooks entirely. A PostToolUse hook can now replace a result, but the
    // replacement must match each tool's own result shape and Read's
    // feeds Claude Code's edit tracking, so only Bash results are
    // replaced there (`claude_post_tool_use_target`). The MCP server
    // (sqz-mcp) provides compressed alternatives to the built-in tools.
    let is_shell = matches!(tool_name, "Bash" | "bash" | "Shell" | "shell" | "terminal"
        | "run_terminal_command" | "run_shell_command" | "execute_bash"
        | "PowerShell" | "powershell" | "pwsh")
        || matches!(hook_event, "beforeShellExecution" | "pre_run_command" | "preToolUse");

    if !is_shell {
        // Pass through non-bash tools unchanged.
        return Ok(passthrough(platform, input));
    }

    // Claude Code puts command in tool_input.command (official docs).
    // Cursor puts command at top level: { "command": "git status" }.
    // Windsurf puts command in tool_info.command_line.
    // Some older references show toolCall.command — accept all.
    let command = parsed
        .get("tool_input")
        .and_then(|v| v.get("command"))
        .and_then(|v| v.as_str())
        .or_else(|| parsed.get("command").and_then(|v| v.as_str()))
        .or_else(|| {
            parsed
                .get("tool_info")
                .and_then(|v| v.get("command_line"))
                .and_then(|v| v.as_str())
        })
        .or_else(|| {
            parsed
                .get("toolCall")
                .and_then(|v| v.get("command"))
                .and_then(|v| v.as_str())
        })
        .or_else(|| {
            // Copilot CLI camelCase payload: toolArgs.command
            parsed
                .get("toolArgs")
                .and_then(|v| v.get("command"))
                .and_then(|v| v.as_str())
        })
        .unwrap_or("");

    if command.is_empty() {
        return Ok(passthrough(platform, input));
    }

    // Don't intercept commands that are already piped through sqz.
    // Check the base command name specifically, not substring — so
    // "grep sqz logfile" or "cargo search sqz" aren't skipped.
    //
    // Guards:
    //   * base command is `sqz` (running sqz directly)
    //   * legacy `SQZ_CMD=…` sh-style prefix (from older sqz versions)
    //   * new shell-neutral `--cmd NAME` form — we need this because
    //     the new emission (issue #10 fix) uses `| sqz compress --cmd …`
    //     and without a guard the hook would re-wrap commands it had
    //     already rewritten once (runaway-prefix bug from issue #5).
    let base_cmd = extract_base_command(command);
    if base_cmd == "sqz"
        || command.starts_with("SQZ_CMD=")
        || command.contains("sqz compress --cmd ")
        || command.contains("sqz.exe compress --cmd ")
    {
        return Ok(passthrough(platform, input));
    }

    // A background call streams its output to the agent while it runs;
    // through sqz nothing would show until the command exits.
    if runs_in_background(&parsed) {
        return Ok(passthrough(platform, input));
    }

    // Rewrite: pipe the command's output through sqz compress.
    //
    // Issue #10: use `--cmd NAME` instead of a `SQZ_CMD=NAME` prefix so
    // the rewrite works in every shell. The sh-style inline env-var
    // assignment doesn't parse in PowerShell (the reporter's default on
    // Windows) or cmd.exe — both treat `SQZ_CMD=cmd` as a literal
    // command name and raise `CommandNotFoundException`. `--cmd NAME`
    // is a normal CLI argument and all three shells parse it fine.
    let is_powershell = matches!(tool_name, "PowerShell" | "powershell" | "pwsh");
    let rewritten = if platform == HookPlatform::ClaudeCode {
        let settings = claude_settings_files(&parsed);
        let shell = crate::shell_scan::Shell::from_env();
        match claude_rewrite(&parsed, command, is_powershell, &settings, shell) {
            Some(rewritten) => rewritten,
            None => return Ok(passthrough(platform, input)),
        }
    } else if is_powershell {
        // PowerShell pipes objects, so only plain commands are rewritten.
        if is_interactive_command(command) || has_shell_operators(command) {
            return Ok(passthrough(platform, input));
        }
        crate::exit_marker::powershell_rewrite(command, &shell_escape(command))
    } else {
        match crate::shell_scan::plan(command) {
            Ok(plan) => posix_rewrite_plan(&plan),
            Err(_) => return Ok(passthrough(platform, input)),
        }
    };

    // Claude Code's updatedInput and Gemini's tool_input both REPLACE the
    // arguments, so unchanged fields like run_in_background, timeout,
    // description or dir_path must be carried over or they are silently
    // dropped. Start from the original tool_input and swap only the command.
    let mut updated_input = parsed
        .get("tool_input")
        .or_else(|| parsed.get("toolArgs"))
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    updated_input.insert(
        "command".to_string(),
        serde_json::Value::String(rewritten.clone()),
    );
    let updated_input = serde_json::Value::Object(updated_input);

    // Build platform-specific output.
    //
    // Each AI tool expects a different JSON response format. Using the wrong
    // format causes silent failures (the tool ignores the rewrite).
    //
    // No output claims a permission decision. In Claude Code and Copilot CLI
    // an "allow" skips the approval prompt, so the user's own rules and
    // prompts would stop applying to every command sqz rewrites. Without a
    // decision the host applies the new input and runs its normal checks.
    //
    // Claude Code (code.claude.com/docs/en/hooks):
    //   hookSpecificOutput.hookEventName = "PreToolUse"
    //   hookSpecificOutput.updatedInput = { ... }  (replaces the entire input)
    //
    // Gemini CLI (geminicli.com/docs/hooks/reference):
    //   hookSpecificOutput.tool_input = { ... }. The scheduler replaces the
    //   call's arguments with it rather than merging, so it carries every
    //   original field.
    //
    // Codex (developers.openai.com/codex/hooks):
    //   Only "deny" works in PreToolUse. "allow", updatedInput, additionalContext
    //   are parsed but NOT supported — they fail open. AGENTS.md guidance is
    //   the working alternative; we do NOT generate hooks for Codex.
    let output = match platform {
        HookPlatform::ClaudeCode => serde_json::json!({
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "updatedInput": updated_input
            }
        }),
        HookPlatform::Cursor => return process_hook_cursor(input),
        HookPlatform::GeminiCli => serde_json::json!({
            "hookSpecificOutput": {
                "tool_input": updated_input
            }
        }),
        HookPlatform::Windsurf => {
            // Windsurf hook support is unconfirmed for command rewriting.
            // Use Claude Code format as best-effort; the hook may only work
            // via exit codes (0 = allow, 2 = block).
            serde_json::json!({
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "updatedInput": updated_input
                }
            })
        }
        HookPlatform::Copilot => serde_json::json!({
            "modifiedArgs": updated_input
        }),
        HookPlatform::Kiro => {
            // Kiro CLI/IDE: output the modified tool_input as JSON to STDOUT.
            // Exit code 0 means "allow with modifications".
            // The hook runner merges this back into the tool call.
            serde_json::json!({
                "tool_input": {
                    "command": rewritten
                }
            })
        }
    };

    serde_json::to_string(&output)
        .map_err(|e| crate::error::SqzError::Other(format!("hook: JSON serialize error: {e}")))
}

const SQZ_RULES_SENTINEL: &str = "<!-- sqz-rules (auto-installed by sqz init) -->";
const LEGACY_RULES_HEADING: &str = "# sqz \u{2014} Token-Optimized CLI Output";
const LEGACY_CURSOR_FRONTMATTER: &str = "---\ndescription: sqz \u{2014} Token-Optimized CLI Output\n";
const LEGACY_RULES_LAST_LINES: [&str; 3] = [
    "path is still what you want for most output.",
    "not on PATH, run commands normally.",
    "If sqz is not available, run commands normally.",
];

pub fn sqz_rules_content(tool_name: &str, sqz_path: &str) -> String {
    if tool_name == "Cline" {
        return crate::codex_integration::agents_md_guidance_block(sqz_path);
    }
    let body = format!(
        "{SQZ_RULES_SENTINEL}\n\n{}",
        crate::codex_integration::sqz_guidance(sqz_path)
    );
    if tool_name == "Cursor" {
        format!("---\ndescription: sqz output compression\nalwaysApply: true\n---\n{body}")
    } else {
        body
    }
}

fn is_sqz_rules(content: &str) -> bool {
    content.contains(SQZ_RULES_SENTINEL)
        || content.starts_with(LEGACY_RULES_HEADING)
        || content.replace("\r\n", "\n").starts_with(LEGACY_CURSOR_FRONTMATTER)
}

fn legacy_rules_end(content: &str) -> Option<usize> {
    if !content.starts_with(LEGACY_RULES_HEADING) {
        return None;
    }
    LEGACY_RULES_LAST_LINES.iter().find_map(|last| {
        let mut start = 0;
        content.split_inclusive('\n').find_map(|line| {
            let text = line.trim_end();
            let end = start + text.len();
            start += line.len();
            text.ends_with(last).then_some(end)
        })
    })
}

fn without_sqz_rules(content: &str) -> Option<String> {
    match legacy_rules_end(content) {
        Some(end) => Some(content[end..].trim_start_matches(['\r', '\n']).to_string()),
        None => crate::codex_integration::without_guidance(content),
    }
}

pub fn has_sqz_rules(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|content| without_sqz_rules(&content))
        .is_some()
}

pub fn remove_sqz_rules(path: &Path) -> Result<bool> {
    let Ok(content) = std::fs::read_to_string(path) else {
        return Ok(false);
    };
    let Some(rest) = without_sqz_rules(&content) else {
        return Ok(false);
    };
    if rest.trim().is_empty() {
        std::fs::remove_file(path).map_err(|e| {
            crate::error::SqzError::Other(format!("remove {}: {e}", path.display()))
        })?;
    } else {
        std::fs::write(path, rest)
            .map_err(|e| crate::error::SqzError::Other(format!("write {}: {e}", path.display())))?;
    }
    Ok(true)
}

pub fn sqz_rules_path(project_dir: &Path, tool_name: &str) -> Option<PathBuf> {
    match tool_name {
        "Cursor" => Some(project_dir.join(".cursor").join("rules").join("sqz.mdc")),
        "Windsurf" => Some(project_dir.join(".windsurf").join("rules").join("sqz.md")),
        "Cline" => {
            let base = project_dir.join(".clinerules");
            Some(if base.is_dir() { base.join("sqz.md") } else { base })
        }
        _ => None,
    }
}

pub fn sqz_rules_state(path: &Path, tool_name: &str) -> crate::kiro_integration::SteeringState {
    use crate::kiro_integration::SteeringState;
    let Ok(content) = std::fs::read_to_string(path) else {
        return SteeringState::Missing;
    };
    if tool_name == "Cline" {
        return if legacy_rules_end(&content).is_some() {
            SteeringState::Stale
        } else {
            crate::codex_integration::guidance_state(&content)
        };
    }
    if !is_sqz_rules(&content) {
        return SteeringState::UserAuthored;
    }
    match crate::kiro_integration::embedded_sqz_path(&content) {
        Some(p) if content.replace("\r\n", "\n") == sqz_rules_content(tool_name, p) => SteeringState::Current,
        _ => SteeringState::Stale,
    }
}

pub fn refresh_sqz_rules(path: &Path, tool_name: &str, fallback_sqz_path: &str) -> Result<bool> {
    if sqz_rules_state(path, tool_name) != crate::kiro_integration::SteeringState::Stale {
        return Ok(false);
    }
    let existing = std::fs::read_to_string(path)
        .map_err(|e| crate::error::SqzError::Other(format!("read {}: {e}", path.display())))?;
    if tool_name == "Cline" && legacy_rules_end(&existing).is_none() {
        return crate::codex_integration::refresh_agents_md_guidance(path, fallback_sqz_path);
    }
    let sqz_path = crate::kiro_integration::embedded_sqz_path(&existing)
        .filter(|p| Path::new(p).is_file())
        .unwrap_or(fallback_sqz_path)
        .to_string();
    install_sqz_rules(path, tool_name, &sqz_path)
}

pub fn sqz_rules_change(
    path: &Path,
    tool_name: &str,
    sqz_path: &str,
) -> crate::codex_integration::GuidanceChange {
    use crate::codex_integration::GuidanceChange;
    match rules_update(path, tool_name, sqz_path) {
        None => GuidanceChange::Unchanged,
        Some(_) if path.exists() => GuidanceChange::Replace,
        Some(_) => GuidanceChange::Create,
    }
}

fn rules_update(path: &Path, tool_name: &str, sqz_path: &str) -> Option<String> {
    let content = sqz_rules_content(tool_name, sqz_path);
    let Ok(existing) = std::fs::read_to_string(path) else {
        return (!path.exists()).then_some(content);
    };
    let updated = if tool_name != "Cline" {
        if !is_sqz_rules(&existing) {
            return None;
        }
        content
    } else if let Some(end) = legacy_rules_end(&existing) {
        format!("{}{}", content.trim_end_matches('\n'), &existing[end..])
    } else {
        crate::codex_integration::replaced_guidance(&existing, sqz_path)?
    };
    (updated != existing).then_some(updated)
}

fn install_sqz_rules(path: &Path, tool_name: &str, sqz_path: &str) -> Result<bool> {
    let Some(content) = rules_update(path, tool_name, sqz_path) else {
        return Ok(false);
    };
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            crate::error::SqzError::Other(format!("create {}: {e}", parent.display()))
        })?;
    }
    std::fs::write(path, content)
        .map_err(|e| crate::error::SqzError::Other(format!("write {}: {e}", path.display())))?;
    Ok(true)
}

/// Generate hook configuration files for all supported AI tools.
pub fn generate_hook_configs(sqz_path: &str) -> Vec<ToolHookConfig> {
    // On Windows, `sqz_path` contains backslashes (C:\Users\...\sqz.exe).
    // Embedding the raw path into JSON string values produces invalid JSON
    // because `\` must be escaped as `\\` per RFC 8259. Same rule applies
    // to JS/TS string literals. See issue #2.
    //
    // We keep TWO versions of the path:
    //   - `sqz_path_raw` — the original, shown in markdown files the user
    //     reads (.windsurfrules, .clinerules) where backslashes should
    //     render as-is so the user can copy-paste the command.
    //   - `sqz_path` — JSON/JS-escaped, used in every .json / .ts config.
    let sqz_path_raw = sqz_path;
    let sqz_path_json = json_escape_string_value(sqz_path);
    let sqz_path = &sqz_path_json;

    vec![
        // Claude Code — goes in .claude/settings.local.json (nested format)
        // Four hooks, each addressing a different concern, plus the two
        // allow rules the PreToolUse rewrite needs:
        //
        //   PreToolUse:   compress shell tool output before the agent sees it
        //                 (matcher "Bash|PowerShell" covers both Unix and
        //                 Windows shells without firing on Read/Edit/etc.)
        //   PostToolUse:  compress the output of a successful Bash command
        //                 the PreToolUse hook left alone
        //   PreCompact:   mark sqz's dedup refs stale before Claude Code
        //                 summarises older turns. Otherwise our §ref:HASH§
        //                 tokens would outlive the content they pointed at,
        //                 leading to dangling refs the agent can't resolve.
        //                 Documented by Anthropic at
        //                 docs.anthropic.com/en/docs/claude-code/hooks-guide.
        //   SessionStart: if the session was resumed via /compact, re-inject
        //                 sqz's session guide (handled by `sqz resume`).
        ToolHookConfig {
            tool_name: "Claude Code".to_string(),
            config_path: PathBuf::from(".claude/settings.local.json"),
            config_content: claude_settings_content(sqz_path_raw),
            scope: HookScope::Project,
        },
        // Cursor — beforeShellExecution hook can only allow/deny/ask; it
        // does NOT support rewriting the command via `updated_input` or any
        // other field (verified against Cursor's documented schema via
        // GitButler's deep-dive and Cupcake's reference, plus an empirical
        // trace against cursor-agent 2026.04.14-ee4b43a). We use the modern
        // .cursor/rules/*.mdc format (legacy .cursorrules is deprecated per
        // docs.cursor.com/en/context/rules). `alwaysApply: true` guarantees
        // the rule loads for every agent interaction.
        ToolHookConfig {
            tool_name: "Cursor".to_string(),
            config_path: PathBuf::from(".cursor/rules/sqz.mdc"),
            config_content: sqz_rules_content("Cursor", sqz_path_raw),
            scope: HookScope::Project,
        },
        // Windsurf — no hook API; prompt-level rules. Current docs only
        // document the .windsurf/rules/ directory; .windsurfrules is legacy.
        ToolHookConfig {
            tool_name: "Windsurf".to_string(),
            config_path: PathBuf::from(".windsurf/rules/sqz.md"),
            config_content: sqz_rules_content("Windsurf", sqz_path_raw),
            scope: HookScope::Project,
        },
        // Cline / Roo Code — prompt-level guidance. .clinerules can be a
        // single file or a directory; the install path handles both.
        ToolHookConfig {
            tool_name: "Cline".to_string(),
            config_path: PathBuf::from(".clinerules"),
            config_content: sqz_rules_content("Cline", sqz_path_raw),
            scope: HookScope::Project,
        },
        // Gemini CLI — goes in .gemini/settings.json (BeforeTool event)
        ToolHookConfig {
            tool_name: "Gemini CLI".to_string(),
            config_path: PathBuf::from(".gemini/settings.json"),
            config_content: format!(
                r#"{{
  "hooks": {{
    "BeforeTool": [
      {{
        "matcher": "run_shell_command",
        "hooks": [
          {{
            "type": "command",
            "command": "{sqz_path} hook gemini"
          }}
        ]
      }}
    ]
  }}
}}"#
            ),
            scope: HookScope::Project,
        },
        // Kiro — steering file + workspace MCP registration. Kiro's
        // PreToolUse hooks can't rewrite tool input, so the old hook-based
        // integration never worked in Kiro chat; the real install goes
        // through crate::kiro_integration.
        ToolHookConfig {
            tool_name: "Kiro".to_string(),
            config_path: PathBuf::from(".kiro/steering/sqz.md"),
            config_content: crate::kiro_integration::kiro_steering_content(sqz_path_raw),
            scope: HookScope::Project,
        },
        // OpenCode — TypeScript plugin at ~/.config/opencode/plugins/sqz.ts
        // plus a config file in project root (opencode.json or
        // opencode.jsonc). Unlike other tools, OpenCode uses a TS
        // plugin (not JSON hooks). The `config_path` below is the
        // fresh-install default; `install_tool_hooks` detects a
        // pre-existing `.jsonc` and merges into it instead. The actual
        // plugin (sqz.ts) is installed separately via
        // `install_opencode_plugin()`.
        ToolHookConfig {
            tool_name: "OpenCode".to_string(),
            config_path: PathBuf::from("opencode.json"),
            config_content: format!(
                r#"{{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {{
    "sqz": {{
      "type": "local",
      "command": ["sqz-mcp", "--transport", "stdio"]
    }}
  }},
  "plugin": ["sqz"]
}}"#
            ),
            scope: HookScope::Project,
        },
        // Codex (openai/codex) — no stable per-tool-call hook, only a
        // turn-end `notify` that fires after the agent is done and can't
        // rewrite tool output. Native integration is therefore two-part:
        //
        //   1. AGENTS.md at project root — prompt-level guidance telling
        //      Codex to pipe shell output through `sqz compress`. This is
        //      the shape Codex expects (the cross-tool AGENTS.md standard).
        //   2. ~/.codex/config.toml user-level [mcp_servers.sqz] — Codex
        //      merges this with any existing entries. Handled specially
        //      in `install_tool_hooks` via `install_codex_mcp_config`.
        //
        // The config_content below is the AGENTS.md guidance block; it
        // is only used as a placeholder for the (project-level) file and
        // for surfacing the "create AGENTS.md" line in the install plan.
        // The actual install goes through
        // `crate::codex_integration::install_agents_md_guidance` so
        // pre-existing AGENTS.md files are appended to, not clobbered.
        ToolHookConfig {
            tool_name: "Codex".to_string(),
            config_path: PathBuf::from("AGENTS.md"),
            config_content: crate::codex_integration::agents_md_guidance_block(
                sqz_path_raw,
            ),
            scope: HookScope::Project,
        },
        // Zed (issue #38) has no command-rewrite hooks, so the
        // integration is instructions + MCP registration:
        //
        //   1. Project guidance appended to the file Zed's Agent
        //      actually reads (`.rules` when present — it shadows
        //      everything — otherwise `AGENTS.md`).
        //   2. `context_servers.sqz` merged into Zed's settings.json
        //      (user-level), which exposes the sqz MCP tools to the
        //      Zed Agent — including local models.
        //
        // The config_path/content below are placeholders for the
        // install plan display; the real install goes through
        // `crate::zed_integration` so existing files are appended to,
        // not clobbered, and JSONC settings are never rewritten.
        ToolHookConfig {
            tool_name: "Zed".to_string(),
            config_path: PathBuf::from("AGENTS.md"),
            config_content: crate::zed_integration::zed_guidance_block(sqz_path_raw),
            scope: HookScope::Project,
        },
        // Copilot CLI — user-level hook file at ~/.copilot/hooks/sqz.json.
        // preToolUse supports modifiedArgs (documented), so this is a full
        // rewrite host like Claude Code. Install goes through
        // install_copilot_hook and only runs when ~/.copilot exists.
        ToolHookConfig {
            tool_name: "Copilot CLI".to_string(),
            config_path: PathBuf::from(".copilot/hooks/sqz.json"),
            config_content: copilot_hook_content(sqz_path_raw),
            scope: HookScope::User,
        },
    ]
}

/// Install hook configs for detected AI tools in the given project directory.
///
/// Install hook configs for detected AI tools in the given project directory.
///
/// Returns the list of tools that were configured.
pub fn install_tool_hooks(project_dir: &Path, sqz_path: &str) -> Vec<String> {
    install_tool_hooks_scoped(project_dir, sqz_path, InstallScope::Project)
}

/// Where hooks should be written.
///
/// The Claude Code scope table (docs.claude.com/en/docs/claude-code/settings)
/// defines four settings locations: managed, user, project, and local.
/// `sqz init` cares about the last three:
///
/// * `Project` — writes `.claude/settings.local.json` (per-project, gitignored).
///   This is what the bare `sqz init` has always done. Good for "I only
///   want sqz active inside this repo", but a common foot-gun because the
///   user expects it to work everywhere and then sees "caching nothing"
///   in every other project. Reported by 76vangel.
///
/// * `Global` — writes `~/.claude/settings.json` (user scope, applies to
///   every Claude Code session on this machine regardless of cwd).
///   This is what most users actually want on first install. Verified
///   against the official Anthropic scope table.
///
/// Precedence in Claude Code (highest to lowest): managed > local > project > user.
/// That means a project-level install can still override a global one —
/// and a user with `.claude/settings.local.json` in their worktree will
/// silently shadow the global setting. We do NOT auto-delete the local
/// file; the uninstall flow is responsible for whichever scope was asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallScope {
    /// Project-local (gitignored): `.claude/settings.local.json`, `.cursor/rules/`,
    /// etc. under `project_dir`.
    Project,
    /// User-level: `~/.claude/settings.json` and similar home-directory paths.
    /// Applies to every project on this machine.
    Global,
}

/// Which tools `sqz init` should configure.
///
/// By default sqz init writes hook configs for every supported tool
/// (Claude Code, Cursor, Windsurf, Cline, Gemini CLI, OpenCode, Codex,
/// Zed). Users who only use one agent have asked (issue #11,
/// @shochdoerfer) for a way to say "just OpenCode, please, leave the
/// rest alone." This filter is the plumbing for that.
///
/// Matching is by canonical tool name. The [`canonicalize_tool_name`]
/// helper normalises user input (lowercase, hyphens/underscores/spaces
/// collapsed, known aliases) so `Opencode`, `open-code`, `opencode`,
/// `OPENCODE` all refer to the same tool.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolFilter {
    /// Install hook configs for every supported tool. The historical
    /// default of `sqz init`.
    All,
    /// Install hook configs only for the named tools. Unknown names are
    /// surfaced to the caller as errors by the canonicalisation layer
    /// so we don't silently ignore typos.
    Only(Vec<String>),
    /// Install hook configs for every supported tool EXCEPT the named
    /// tools. Useful when the user is fine with everything but wants
    /// one integration skipped (e.g. a project shared with collaborators
    /// who don't want a `.windsurfrules` file in the repo).
    Skip(Vec<String>),
}

impl Default for ToolFilter {
    fn default() -> Self {
        ToolFilter::All
    }
}

impl ToolFilter {
    /// Return `true` if `tool_name` (as produced by [`generate_hook_configs`])
    /// should be installed under this filter.
    ///
    /// `tool_name` is the display name sqz uses internally:
    ///   * `"Claude Code"`, `"Cursor"`, `"Windsurf"`, `"Cline"`,
    ///     `"Gemini CLI"`, `"OpenCode"`, `"Codex"`.
    ///
    /// The caller is expected to have already canonicalised the filter
    /// entries via [`canonicalize_tool_name`] so the strings line up
    /// case- and alias-wise.
    pub fn includes(&self, tool_name: &str) -> bool {
        let canon = canonicalize_tool_name(tool_name);
        match self {
            ToolFilter::All => true,
            ToolFilter::Only(allow) => allow.iter().any(|n| {
                // `allow` entries have already been canonicalised by
                // parse_tool_list; compare canonical to canonical.
                n == &canon
            }),
            ToolFilter::Skip(deny) => !deny.iter().any(|n| n == &canon),
        }
    }
}

/// Every canonical tool name sqz knows about, in the same order
/// [`generate_hook_configs`] emits them. Used by the CLI to list valid
/// options in `--only`/`--skip` error messages, and by tests that
/// need to enumerate the supported set.
pub const SUPPORTED_TOOL_NAMES: &[&str] = &[
    "Claude Code",
    "Cursor",
    "Windsurf",
    "Cline",
    "Gemini CLI",
    "Kiro",
    "OpenCode",
    "Codex",
    "Zed",
    "Copilot CLI",
];

/// How sqz reaches a client's tool output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntegrationTier {
    /// A hook rewrites shell tool calls before they run, so output is
    /// compressed without the agent's help.
    Transparent,
    /// sqz can only ask: guidance files plus MCP tools the agent has to
    /// choose to call. The client's built-in shell and read tools bypass it.
    Advisory,
}

/// Which tier sqz's integration for `tool_name` falls in. Keep in step
/// with what [`generate_hook_configs`] actually installs.
pub fn integration_tier(tool_name: &str) -> IntegrationTier {
    match canonicalize_tool_name(tool_name).as_str() {
        "claudecode" | "copilot" | "gemini" | "opencode" => IntegrationTier::Transparent,
        _ => IntegrationTier::Advisory,
    }
}

/// Path of the user-level Copilot CLI hooks file sqz manages.
/// Honors `COPILOT_HOME` the same way the CLI does.
pub fn copilot_hooks_path() -> PathBuf {
    copilot_home().join("hooks").join("sqz.json")
}

fn copilot_home() -> PathBuf {
    if let Ok(home) = std::env::var("COPILOT_HOME") {
        if !home.trim().is_empty() {
            return PathBuf::from(home);
        }
    }
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("."));
    home.join(".copilot")
}

/// Path of the repo-level CI hook file, read by both local Copilot CLI
/// sessions in this repo and Copilot cloud agent jobs (the sandbox loads
/// only `.github/hooks/*.json` from the clone).
pub fn ci_hooks_path(project_dir: &Path) -> PathBuf {
    project_dir.join(".github").join("hooks").join("sqz.json")
}

/// CI hook config for Copilot cloud agent + repo-scoped Copilot CLI.
///
/// The cloud agent sandbox has no sqz preinstalled and restricts outbound
/// network to GitHub hosts — which is exactly where sqz's install script
/// and release binaries live, so a sessionStart hook can bootstrap it.
/// The preToolUse hook is fail-closed on non-zero exit in Copilot, so
/// every path ends in `exit 0` with either a decision or `{}` (fall
/// through) — a missing binary must never block the tool call.
pub fn ci_hook_content() -> String {
    r#"{
  "version": 1,
  "hooks": {
    "sessionStart": [
      {
        "type": "command",
        "bash": "command -v sqz >/dev/null 2>&1 || curl -fsSL https://raw.githubusercontent.com/ojuschugh1/sqz/main/install.sh | sh >/dev/null 2>&1 || true",
        "timeoutSec": 120
      }
    ],
    "preToolUse": [
      {
        "type": "command",
        "matcher": "bash|powershell",
        "bash": "SQZ_BIN=$(command -v sqz || echo $HOME/.local/bin/sqz); [ -x \"$SQZ_BIN\" ] && \"$SQZ_BIN\" hook copilot 2>/dev/null || echo '{}'",
        "timeoutSec": 10
      }
    ]
  }
}
"#
    .to_string()
}

/// Install the repo-level CI hook file. Skip-if-exists unless the existing
/// file is sqz-authored and stale.
pub fn install_ci_hook(project_dir: &Path) -> Result<bool> {
    let path = ci_hooks_path(project_dir);
    let content = ci_hook_content();
    if path.exists() {
        let existing = std::fs::read_to_string(&path).unwrap_or_default();
        if existing == content || !existing.contains("hook copilot") {
            return Ok(false);
        }
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            crate::error::SqzError::Other(format!("create {}: {e}", parent.display()))
        })?;
    }
    std::fs::write(&path, content).map_err(|e| {
        crate::error::SqzError::Other(format!("write {}: {e}", path.display()))
    })?;
    Ok(true)
}

/// Remove the CI hook file when sqz-authored.
pub fn remove_ci_hook(project_dir: &Path) -> Result<bool> {
    let path = ci_hooks_path(project_dir);
    if !path.exists() {
        return Ok(false);
    }
    let content = std::fs::read_to_string(&path).unwrap_or_default();
    if !content.contains("hook copilot") {
        return Ok(false);
    }
    std::fs::remove_file(&path).map_err(|e| {
        crate::error::SqzError::Other(format!("remove {}: {e}", path.display()))
    })?;
    Ok(true)
}

/// The Copilot CLI hook config sqz installs (v1 camelCase format).
pub fn copilot_hook_content(sqz_path: &str) -> String {
    let escaped = json_escape_string_value(sqz_path);
    format!(
        r#"{{
  "version": 1,
  "hooks": {{
    "preToolUse": [
      {{
        "type": "command",
        "matcher": "bash|powershell",
        "bash": "{escaped} hook copilot",
        "powershell": "{escaped} hook copilot",
        "timeoutSec": 10
      }}
    ]
  }}
}}
"#
    )
}

/// Install the Copilot CLI hook file. Returns `Ok(None)` when Copilot CLI
/// is not installed (no `~/.copilot` directory), `Ok(Some(changed))`
/// otherwise. Refreshes the file in place when the content is stale.
pub fn install_copilot_hook(sqz_path: &str) -> Result<Option<bool>> {
    install_copilot_hook_at(&copilot_home(), sqz_path)
}

fn install_copilot_hook_at(home: &Path, sqz_path: &str) -> Result<Option<bool>> {
    if !home.exists() {
        return Ok(None);
    }
    let path = home.join("hooks").join("sqz.json");
    let content = copilot_hook_content(sqz_path);
    if path.exists() {
        let existing = std::fs::read_to_string(&path).unwrap_or_default();
        if existing == content {
            return Ok(Some(false));
        }
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            crate::error::SqzError::Other(format!("create {}: {e}", parent.display()))
        })?;
    }
    std::fs::write(&path, content).map_err(|e| {
        crate::error::SqzError::Other(format!("write {}: {e}", path.display()))
    })?;
    Ok(Some(true))
}

/// Remove the sqz-managed Copilot hook file if present.
pub fn remove_copilot_hook() -> Result<bool> {
    let path = copilot_hooks_path();
    if !path.exists() {
        return Ok(false);
    }
    std::fs::remove_file(&path).map_err(|e| {
        crate::error::SqzError::Other(format!("remove {}: {e}", path.display()))
    })?;
    Ok(true)
}

/// Normalise a tool name or alias to its canonical form.
///
/// Canonical forms are lowercase and hyphen-free. Accepts common
/// variants:
///
/// | Input                                  | Canonical      |
/// |----------------------------------------|----------------|
/// | `Claude Code`, `claude-code`, `claude` | `claudecode`   |
/// | `Cursor`, `cursor`                     | `cursor`       |
/// | `Windsurf`, `windsurf`                 | `windsurf`     |
/// | `Cline`, `roo`, `roo-code`, `roocode`  | `cline`        |
/// | `Gemini CLI`, `gemini-cli`, `gemini`   | `gemini`       |
/// | `OpenCode`, `opencode`                 | `opencode`     |
/// | `Codex`, `codex`                       | `codex`        |
///
/// Returns the canonical string unchanged if no alias matches — the
/// caller decides whether unknown names are an error. This function
/// never fails.
pub fn canonicalize_tool_name(name: &str) -> String {
    let lowered: String = name
        .chars()
        .filter(|c| !c.is_whitespace())
        .flat_map(|c| c.to_lowercase())
        .filter(|c| *c != '-' && *c != '_')
        .collect();
    match lowered.as_str() {
        "claude" | "claudecode" => "claudecode".to_string(),
        "cursor" => "cursor".to_string(),
        "windsurf" => "windsurf".to_string(),
        // Cline is also sold as "Roo Code" — treat the two as one
        // integration because that's what sqz actually targets (same
        // .clinerules file).
        "cline" | "roo" | "roocode" => "cline".to_string(),
        "gemini" | "geminicli" => "gemini".to_string(),
        "kiro" | "kirocli" | "kiroide" => "kiro".to_string(),
        "opencode" => "opencode".to_string(),
        "codex" => "codex".to_string(),
        "zed" | "zededitor" | "zedagent" => "zed".to_string(),
        "copilot" | "copilotcli" | "githubcopilot" | "ghcopilot" => "copilot".to_string(),
        other => other.to_string(),
    }
}

/// Parse a user-supplied tool list (comma-separated, whitespace-tolerant)
/// into a vector of canonical names.
///
/// Returns an error if any entry does not match a known tool — we never
/// silently drop typos because the failure mode ("my filter didn't
/// work") is hard to debug.
///
/// The error message lists every accepted name so the user can see
/// exactly what's valid.
pub fn parse_tool_list(raw: &str) -> Result<Vec<String>> {
    let mut out = Vec::new();
    let known: std::collections::HashSet<String> = SUPPORTED_TOOL_NAMES
        .iter()
        .map(|n| canonicalize_tool_name(n))
        .collect();
    for part in raw.split(',') {
        let trimmed = part.trim();
        if trimmed.is_empty() {
            continue;
        }
        let canon = canonicalize_tool_name(trimmed);
        if !known.contains(&canon) {
            let valid: Vec<String> = SUPPORTED_TOOL_NAMES
                .iter()
                .map(|n| canonicalize_tool_name(n))
                .collect();
            return Err(crate::error::SqzError::Other(format!(
                "unknown agent name '{}'. Valid options: {}",
                trimmed,
                valid.join(", ")
            )));
        }
        if !out.contains(&canon) {
            out.push(canon);
        }
    }
    Ok(out)
}

/// Like [`install_tool_hooks`] but lets the caller choose between
/// project-local and user-global scope. This is the function `sqz init`
/// and `sqz init --global` both call.
///
/// For `InstallScope::Global`:
///
/// * Claude Code hook is merged into `~/.claude/settings.json` (the user
///   settings file). We merge rather than overwrite because the user may
///   already have permissions, env, statusLine, or other hooks there —
///   blindly writing would nuke their config. Any existing sqz hook
///   entries are replaced in place; unrelated fields are preserved.
///
/// * Cursor, Windsurf, Cline, Gemini CLI rules files don't have a
///   user-level equivalent that Cursor/etc. actually load. We keep those
///   at project scope and note it in the plan. Users who want Cursor
///   compressed across all projects should follow the Cursor docs
///   (docs.cursor.com/en/context/rules) and add the rule at user scope
///   manually — Cursor honours ~/.cursor/rules/*.mdc but only within
///   workspaces that opt in.
///
/// * OpenCode plugin is already user-level by design (lives at
///   `~/.config/opencode/plugins/sqz.ts`), so scope doesn't matter here.
///
/// * Codex MCP config is always user-level (`~/.codex/config.toml`).
///   AGENTS.md stays per-project because that's where it belongs.
pub fn install_tool_hooks_scoped(
    project_dir: &Path,
    sqz_path: &str,
    scope: InstallScope,
) -> Vec<String> {
    install_tool_hooks_scoped_filtered(project_dir, sqz_path, scope, &ToolFilter::All)
}

/// Like [`install_tool_hooks_scoped`] but honours a [`ToolFilter`] so
/// callers can restrict `sqz init` to a subset of the supported tools.
///
/// The filter applies to hook-config writes AND to the OpenCode
/// TypeScript plugin at `~/.config/opencode/plugins/sqz.ts` — we only
/// install the plugin file when OpenCode passes the filter. Writing
/// the plugin file to a machine where the user filtered OpenCode out
/// would be surprising (they'd see sqz fire next time they opened
/// OpenCode even though they never asked for it).
///
/// Shell hook (rc file) and the default preset are NOT gated by this
/// filter — they're user-scoped and not specific to any agent.
/// `cmd_init` handles those separately.
pub fn install_tool_hooks_scoped_filtered(
    project_dir: &Path,
    sqz_path: &str,
    scope: InstallScope,
    filter: &ToolFilter,
) -> Vec<String> {
    install_tool_hooks_at(project_dir, sqz_path, scope, filter, None)
}

/// [`install_tool_hooks_scoped_filtered`] with every user-level root under `home_override`.
fn install_tool_hooks_at(
    project_dir: &Path,
    sqz_path: &str,
    scope: InstallScope,
    filter: &ToolFilter,
    home_override: Option<&Path>,
) -> Vec<String> {
    let configs = generate_hook_configs(sqz_path);
    let mut installed = Vec::new();
    let kiro_root =
        home_override.map_or_else(crate::kiro_integration::kiro_user_root, |h| h.join(".kiro"));

    for config in &configs {
        // Apply the user's agent filter before we touch anything.
        // Each tool the filter rejects is completely skipped — no
        // plan lines, no files written, no logging.
        if !filter.includes(&config.tool_name) {
            continue;
        }

        // OpenCode config files are special: they live alongside the
        // user's own config and must be *merged* rather than clobbered.
        // The placeholder `config_content` is only used on a fresh
        // install; `update_opencode_config_detailed` handles both the
        // create-new and merge-into-existing cases, AND picks the
        // right file extension (opencode.jsonc vs opencode.json) —
        // fixes issue #6 where the old write-if-missing logic created
        // a parallel `opencode.json` next to an existing `.jsonc`.
        if config.tool_name == "OpenCode" {
            match crate::opencode_plugin::update_opencode_config_detailed(project_dir) {
                Ok((updated, _comments_lost)) => {
                    if updated && !installed.iter().any(|n| n == "OpenCode") {
                        installed.push("OpenCode".to_string());
                    }
                }
                Err(_e) => {
                    // Non-fatal — leave OpenCode out of the installed
                    // list and continue with other tools.
                }
            }
            continue;
        }

        // Codex has the same merge-not-clobber concern on two fronts:
        // the project-level AGENTS.md (may contain unrelated user
        // content) and the USER-level ~/.codex/config.toml (may contain
        // other MCP servers). Both go through the surgical helpers.
        if config.tool_name == "Codex" {
            let agents_changed = crate::codex_integration::install_agents_md_guidance(
                project_dir, sqz_path,
            )
            .unwrap_or(false);
            let mcp_changed = crate::codex_integration::install_codex_mcp_config_at(
                home_override.map(|h| h.join(".codex")).as_deref(),
            )
            .unwrap_or(false);
            if (agents_changed || mcp_changed)
                && !installed.iter().any(|n| n == "Codex")
            {
                installed.push("Codex".to_string());
            }
            continue;
        }

        // Windsurf: current docs only document .windsurf/rules/; migrate a
        // legacy sqz-authored .windsurfrules to the new location.
        if config.tool_name == "Windsurf" {
            let legacy = project_dir.join(".windsurfrules");
            let target = project_dir.join(&config.config_path);
            let mut changed = install_sqz_rules(&target, "Windsurf", sqz_path).unwrap_or(false);
            if target.exists() && remove_sqz_rules(&legacy).unwrap_or(false) {
                changed = true;
            }
            if changed && !installed.iter().any(|n| n == "Windsurf") {
                installed.push("Windsurf".to_string());
            }
            continue;
        }

        if config.tool_name == "Cursor" {
            let target = project_dir.join(&config.config_path);
            if install_sqz_rules(&target, "Cursor", sqz_path).unwrap_or(false)
                && !installed.iter().any(|n| n == "Cursor")
            {
                installed.push("Cursor".to_string());
            }
            continue;
        }

        // Cline: .clinerules can be a single file or a directory of md
        // files; when it's a directory, install .clinerules/sqz.md.
        if config.tool_name == "Cline" {
            let Some(target) = sqz_rules_path(project_dir, "Cline") else {
                continue;
            };
            if install_sqz_rules(&target, "Cline", sqz_path).unwrap_or(false)
                && !installed.iter().any(|n| n == "Cline")
            {
                installed.push("Cline".to_string());
            }
            continue;
        }

        // Copilot CLI: user-level hook file, only when Copilot is installed.
        if config.tool_name == "Copilot CLI" {
            let copilot_root = home_override.map_or_else(copilot_home, |h| h.join(".copilot"));
            if let Ok(Some(changed)) = install_copilot_hook_at(&copilot_root, sqz_path) {
                if changed && !installed.iter().any(|n| n == "Copilot CLI") {
                    installed.push("Copilot CLI".to_string());
                }
            }
            continue;
        }

        // Kiro: steering file + MCP config, plus cleanup of the legacy
        // hook file that Kiro never recognized. At global scope both go
        // to the user level (~/.kiro), which Kiro applies to every
        // workspace; at project scope they stay in the workspace.
        if config.tool_name == "Kiro" {
            let _ = crate::kiro_integration::remove_kiro_legacy_hook(project_dir);
            let user_steering = kiro_root.join("steering").join("sqz.md");
            let (steering_changed, mcp_changed) = if scope == InstallScope::Global {
                let steering = crate::kiro_integration::install_kiro_steering_at(
                    &user_steering,
                    &crate::kiro_integration::kiro_user_steering_content(sqz_path),
                )
                .unwrap_or(false);
                let mcp = matches!(
                    crate::kiro_integration::install_kiro_mcp_config_at(
                        &kiro_root.join("settings").join("mcp.json")
                    ),
                    Ok(crate::kiro_integration::KiroMcpInstall::Created)
                        | Ok(crate::kiro_integration::KiroMcpInstall::Merged)
                );
                (steering, mcp)
            } else {
                // The user-level copy already reaches this workspace.
                let user_installed = matches!(
                    crate::kiro_integration::kiro_steering_state(&user_steering, true),
                    crate::kiro_integration::SteeringState::Current
                        | crate::kiro_integration::SteeringState::Stale
                );
                let steering = !user_installed
                    && crate::kiro_integration::install_kiro_steering(project_dir, sqz_path)
                        .unwrap_or(false);
                let mcp = matches!(
                    crate::kiro_integration::install_kiro_mcp_config(project_dir),
                    Ok(crate::kiro_integration::KiroMcpInstall::Created)
                        | Ok(crate::kiro_integration::KiroMcpInstall::Merged)
                );
                (steering, mcp)
            };
            if (steering_changed || mcp_changed) && !installed.iter().any(|n| n == "Kiro") {
                installed.push("Kiro".to_string());
            }
            continue;
        }

        // Zed (issue #38): guidance into the instruction file Zed
        // actually reads, plus context_servers.sqz in the user-level
        // settings.json. Both are surgical; JSONC settings are never
        // rewritten (the CLI surfaces manual instructions instead).
        if config.tool_name == "Zed" {
            let guidance_changed =
                crate::zed_integration::install_zed_guidance(project_dir, sqz_path)
                    .unwrap_or(false);
            let zed_settings = home_override.map_or_else(
                crate::zed_integration::zed_settings_path,
                |h| h.join(".config").join("zed").join("settings.json"),
            );
            let mcp_changed = matches!(
                crate::zed_integration::install_zed_mcp_config_at(&zed_settings),
                Ok(crate::zed_integration::ZedMcpInstall::Created)
                    | Ok(crate::zed_integration::ZedMcpInstall::Merged)
            );
            if (guidance_changed || mcp_changed) && !installed.iter().any(|n| n == "Zed") {
                installed.push("Zed".to_string());
            }
            continue;
        }

        // Claude Code at global scope: merge into ~/.claude/settings.json
        // instead of writing a fresh .claude/settings.local.json in cwd.
        // This is the fix for "sqz init does nothing outside the project
        // I ran it in" — reported by 76vangel.
        //
        // Also triggers the issue #12 companion installs (CLAUDE.md
        // guidance + ~/.claude.json MCP server registration) since those
        // belong to Claude Code conceptually — if you're installing the
        // hook, you want the guidance and MCP wiring too.
        if config.tool_name == "Claude Code" && scope == InstallScope::Global {
            let hook_installed = match install_claude_global_at(sqz_path, home_override) {
                Ok(v) => v,
                Err(_) => false,
            };
            let md_changed = crate::claude_md_integration::install_claude_md_guidance(
                project_dir, sqz_path,
            )
            .unwrap_or(false);
            let mcp_changed =
                crate::claude_md_integration::install_claude_mcp_config_at(home_override)
                    .unwrap_or(false);
            if (hook_installed || md_changed || mcp_changed)
                && !installed.iter().any(|n| n == "Claude Code")
            {
                installed.push("Claude Code".to_string());
            }
            continue;
        }

        // User-level hooks already run here; a project copy would run them twice.
        if config.tool_name == "Claude Code"
            && home_override
                .map(|h| h.join(".claude").join("settings.json"))
                .or_else(claude_user_settings_path)
                .is_some_and(|p| claude_settings_have_sqz_hooks(&p))
        {
            let md_changed = crate::claude_md_integration::install_claude_md_guidance(
                project_dir, sqz_path,
            )
            .unwrap_or(false);
            let mcp_changed =
                crate::claude_md_integration::install_claude_mcp_config_at(home_override)
                    .unwrap_or(false);
            if (md_changed || mcp_changed) && !installed.iter().any(|n| n == "Claude Code") {
                installed.push("Claude Code".to_string());
            }
            continue;
        }

        let full_path = project_dir.join(&config.config_path);

        // Don't overwrite existing hook configs
        if full_path.exists() {
            // Project-scope Claude Code file already exists. Don't skip:
            // merge our entries in, replacing any stale sqz entries. This
            // is what upgrades a pre-issue-#26 `"matcher": "Bash"` install
            // to `"Bash|PowerShell"` when the user re-runs `sqz init` —
            // with the old skip-if-exists behavior, Windows installs kept
            // the stale matcher forever and PowerShell tool calls never
            // reached the hook. User keys (permissions, env, other hooks)
            // are preserved; only sqz's own entries are replaced.
            if config.tool_name == "Claude Code" {
                let hook_changed =
                    merge_sqz_hooks_into_settings(&full_path, sqz_path).unwrap_or(false);
                let md_changed =
                    crate::claude_md_integration::install_claude_md_guidance(
                        project_dir, sqz_path,
                    )
                    .unwrap_or(false);
                let mcp_changed =
                    crate::claude_md_integration::install_claude_mcp_config_at(home_override)
                        .unwrap_or(false);
                if (hook_changed || md_changed || mcp_changed)
                    && !installed.iter().any(|n| n == "Claude Code")
                {
                    installed.push("Claude Code".to_string());
                }
            }
            if config.tool_name == "Gemini CLI"
                && merge_sqz_gemini_hook(&full_path, sqz_path).unwrap_or(false)
            {
                installed.push(config.tool_name.clone());
            }
            continue;
        }

        // Create parent directories
        if let Some(parent) = full_path.parent() {
            if std::fs::create_dir_all(parent).is_err() {
                continue;
            }
        }

        if std::fs::write(&full_path, &config.config_content).is_ok() {
            installed.push(config.tool_name.clone());
            // Claude Code at project scope: also install the issue #12
            // companion artifacts (CLAUDE.md guidance + ~/.claude.json
            // MCP registration). The agent needs all three pieces to
            // actually use sqz — the hook catches Bash, the MCP server
            // provides sqz_read_file/grep/list_dir, and the CLAUDE.md
            // tells it when to pick which.
            if config.tool_name == "Claude Code" {
                let _ = crate::claude_md_integration::install_claude_md_guidance(
                    project_dir, sqz_path,
                );
                let _ = crate::claude_md_integration::install_claude_mcp_config_at(home_override);
            }
        }
    }

    // Also install the OpenCode TypeScript plugin (user-level). The
    // config merge above has already put OpenCode in `installed` if it
    // wrote anything, so this call only matters for machines where no
    // project config existed — we still want the user-level plugin so
    // future OpenCode sessions see sqz.
    //
    // Gated by the filter: if the user ran `sqz init --skip opencode`
    // we must NOT drop the plugin file in `~/.config/opencode/plugins/`.
    // Leaving it there would surprise them on their next OpenCode run
    // (sqz would start firing uninvited, reverting the skip).
    if filter.includes("OpenCode") {
        let plugin = home_override.map_or_else(
            crate::opencode_plugin::opencode_plugin_path,
            |h| h.join(".config").join("opencode").join("plugins").join("sqz.ts"),
        );
        if let Ok(true) = crate::opencode_plugin::install_opencode_plugin_at(&plugin, sqz_path) {
            if !installed.iter().any(|n| n == "OpenCode") {
                installed.push("OpenCode".to_string());
            }
        }
    }

    installed
}

// ── Claude Code user-scope hook install ──────────────────────────────────

/// Resolve `~/.claude/settings.json` for the current user.
///
/// This is the "User" scope file per the Anthropic scope table
/// (docs.claude.com/en/docs/claude-code/settings). Applies to every
/// Claude Code session on this machine regardless of cwd.
///
/// Precedence: Managed > Local (`.claude/settings.local.json`) >
/// Project (`.claude/settings.json`) > User (this file). Users with a
/// local settings file in a worktree can still override the global
/// sqz hook — that's intended.
pub fn claude_user_settings_path() -> Option<PathBuf> {
    dirs_next::home_dir().map(|h| h.join(".claude").join("settings.json"))
}

/// Merge sqz's PreToolUse / PreCompact / SessionStart hook entries
/// into `~/.claude/settings.json`.
///
/// * Creates the file if missing, with just our hooks.
/// * If the file exists, parses it as JSON, replaces any existing sqz
///   entries (matched by `command` containing `sqz hook` / `sqz resume` /
///   `sqz hook precompact`), and inserts ours. Everything else — the
///   user's permissions, env, statusLine, other PreToolUse matchers —
///   stays untouched.
/// * Writes atomically (temp file + rename) so a crash halfway through
///   can't leave the user with a corrupted settings.json.
///
/// Returns `Ok(true)` if the file was created or changed, `Ok(false)`
/// if our hook entries were already present identically.
///
/// `home_override` replaces the home directory in tests. Avoids
/// `std::env::set_var("HOME")` which races with parallel tests that
/// also read HOME (e.g. the api_proxy property tests that open
/// `~/.sqz/sessions.db`).
fn install_claude_global_at(sqz_path: &str, home_override: Option<&Path>) -> Result<bool> {
    let path = match home_override {
        Some(h) => h.join(".claude").join("settings.json"),
        None => claude_user_settings_path().ok_or_else(|| {
            crate::error::SqzError::Other(
                "Could not resolve home directory for ~/.claude/settings.json".to_string(),
            )
        })?,
    };
    merge_sqz_hooks_into_settings(&path, sqz_path)
}

/// Dry-run probe for `sqz init`'s plan phase: would merging sqz's hook
/// entries change the Claude Code settings file at `path`?
///
/// Returns `Ok(true)` when the file is missing, or exists with stale or
/// absent sqz entries (e.g. the pre-issue-#26 `"Bash"`-only matcher, or
/// an outdated binary path). Returns `Ok(false)` when our entries are
/// already present identically. Errors on unparseable files — same as
/// the real merge, which refuses to touch those.
///
/// Without this probe the CLI's plan phase treated any existing file as
/// "nothing to do" and exited before the installer ran, so the healing
/// merge below was unreachable in practice.
pub fn claude_project_settings_needs_update(path: &Path, sqz_path: &str) -> Result<bool> {
    if !path.exists() {
        return Ok(true);
    }
    let content = std::fs::read_to_string(path).map_err(|e| {
        crate::error::SqzError::Other(format!("read {}: {e}", path.display()))
    })?;
    let mut root: serde_json::Value = if content.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(&content).map_err(|e| {
            crate::error::SqzError::Other(format!("parse {}: {e}", path.display()))
        })?
    };
    let Some(root_obj) = root.as_object_mut() else {
        return Err(crate::error::SqzError::Other(format!(
            "{} is not a JSON object",
            path.display()
        )));
    };

    let before = serde_json::to_string(&root_obj).unwrap_or_default();
    let hooks = root_obj
        .entry("hooks".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    let Some(hooks_obj) = hooks.as_object_mut() else {
        return Ok(true);
    };
    for (event, entry, sentinel) in sqz_hook_entries(sqz_path) {
        upsert_sqz_hook_entry(hooks_obj, event, entry, sentinel);
    }
    upsert_claude_allow_rules(root_obj);
    let after = serde_json::to_string(&root_obj).unwrap_or_default();
    Ok(before != after)
}

/// A fresh Claude Code settings file holding only sqz's hooks and rules.
fn claude_settings_content(sqz_path: &str) -> String {
    let mut hooks = serde_json::Map::new();
    for (event, entry, sentinel) in sqz_hook_entries(sqz_path) {
        upsert_sqz_hook_entry(&mut hooks, event, entry, sentinel);
    }
    let mut root = serde_json::Map::new();
    root.insert("hooks".to_string(), serde_json::Value::Object(hooks));
    upsert_claude_allow_rules(&mut root);
    serde_json::to_string_pretty(&serde_json::Value::Object(root))
        .expect("a map of strings always serializes")
}

/// The hook entries sqz installs into Claude Code settings files, as
/// `(event_name, entry_json, sentinel)` tuples. Single source of truth for
/// the real merge, the dry-run probe and uninstall.
fn sqz_hook_entries(sqz_path: &str) -> [(&'static str, serde_json::Value, &'static str); 4] {
    [
        (
            "PreToolUse",
            serde_json::json!({
                "matcher": "Bash|PowerShell",
                "hooks": [{ "type": "command", "command": format!("{sqz_path} hook claude") }]
            }),
            "hook claude",
        ),
        (
            "PostToolUse",
            serde_json::json!({
                "matcher": "Bash",
                "hooks": [{ "type": "command", "command": format!("{sqz_path} hook claude-post") }]
            }),
            "hook claude-post",
        ),
        (
            "PreCompact",
            serde_json::json!({
                "hooks": [{ "type": "command", "command": format!("{sqz_path} hook precompact") }]
            }),
            "hook precompact",
        ),
        (
            "SessionStart",
            serde_json::json!({
                "matcher": "compact",
                "hooks": [{ "type": "command", "command": format!("{sqz_path} resume") }]
            }),
            "resume",
        ),
    ]
}

/// Merge sqz's three hook entries into a Claude Code settings JSON at
/// `path` — either `~/.claude/settings.json` (global scope) or a
/// project's `.claude/settings.local.json`. Shared by both install
/// scopes so re-running `sqz init` upgrades stale sqz entries (an old
/// `"Bash"`-only matcher, an outdated binary path) at project scope
/// too, instead of skipping any file that already exists. That skip is
/// how Windows installs from before the issue #26 fix stayed broken:
/// their project settings kept the pre-PowerShell matcher forever.
fn merge_sqz_hooks_into_settings(path: &Path, sqz_path: &str) -> Result<bool> {
    // Parse the existing file, or start from an empty object.
    let mut content = String::new();
    let mut root: serde_json::Value = if path.exists() {
        content = std::fs::read_to_string(&path).map_err(|e| {
            crate::error::SqzError::Other(format!(
                "read {}: {e}",
                path.display()
            ))
        })?;
        if content.trim().is_empty() {
            serde_json::Value::Object(serde_json::Map::new())
        } else {
            serde_json::from_str(&content).map_err(|e| {
                crate::error::SqzError::Other(format!(
                    "parse {}: {e} — please fix or move the file before re-running sqz init",
                    path.display()
                ))
            })?
        }
    } else {
        serde_json::Value::Object(serde_json::Map::new())
    };

    // Ensure root is an object (users occasionally have arrays or
    // corrupted files; we refuse to touch those).
    let root_obj = root.as_object_mut().ok_or_else(|| {
        crate::error::SqzError::Other(format!(
            "{} is not a JSON object — refusing to overwrite",
            path.display()
        ))
    })?;

    // Snapshot the "before" state for change detection.
    let before = serde_json::to_string(&root_obj).unwrap_or_default();

    // Get or create the top-level "hooks" object.
    let hooks = root_obj
        .entry("hooks".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    let hooks_obj = hooks.as_object_mut().ok_or_else(|| {
        crate::error::SqzError::Other(format!(
            "{}: `hooks` is not an object — refusing to overwrite",
            path.display()
        ))
    })?;

    for (event, entry, sentinel) in sqz_hook_entries(sqz_path) {
        upsert_sqz_hook_entry(hooks_obj, event, entry, sentinel);
    }
    upsert_claude_allow_rules(root_obj);

    let after = serde_json::to_string(&root_obj).unwrap_or_default();
    if before == after && path.exists() {
        // Already present and unchanged — no write needed.
        return Ok(false);
    }

    // Ensure parent directory exists.
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            crate::error::SqzError::Other(format!(
                "create {}: {e}",
                parent.display()
            ))
        })?;
    }

    // Atomic write: tempfile in same directory + rename. Keeps the old
    // file intact if serialization or write fails halfway.
    write_json_config(path, &serde_json::Value::Object(root_obj.clone()), &content)?;

    Ok(true)
}

/// Remove sqz's hook entries from `~/.claude/settings.json` without
/// touching any other keys. Symmetric with `install_claude_global_at`.
///
/// Returns:
/// * `Ok(Some((path, true)))` — file existed, sqz entries found and
///   stripped. If the resulting `hooks` object is empty, we also remove
///   the `hooks` key entirely. If the resulting root object is empty,
///   we remove the file — matches the uninstall UX of every other sqz
///   surface.
/// * `Ok(Some((path, false)))` — file existed but contained no sqz
///   entries. No write.
/// * `Ok(None)` — file did not exist.
/// * `Err(_)` — file existed but could not be read or parsed.
pub fn remove_claude_global_hook() -> Result<Option<(PathBuf, bool)>> {
    remove_claude_global_hook_at(None)
}

/// Internal: home-dir-injectable counterpart used by tests. See
/// `install_claude_global_at` for rationale.
fn remove_claude_global_hook_at(
    home_override: Option<&Path>,
) -> Result<Option<(PathBuf, bool)>> {
    let path = match home_override {
        Some(h) => h.join(".claude").join("settings.json"),
        None => match claude_user_settings_path() {
            Some(p) => p,
            None => return Ok(None),
        },
    };
    remove_sqz_from_claude_settings(path, true)
}

/// Remove sqz's entries from a project's `.claude/settings.local.json`,
/// keeping whatever else is in it, such as the permissions Claude Code
/// saves there when you pick "don't ask again". Same results as
/// [`remove_claude_global_hook`].
pub fn remove_claude_project_hook(project_dir: &Path) -> Result<Option<(PathBuf, bool)>> {
    remove_sqz_from_claude_settings(project_dir.join(".claude").join("settings.local.json"), true)
}

/// Remove sqz's hooks from the project's `.claude/settings.local.json`, keeping every permission.
pub fn remove_claude_project_hooks_only(project_dir: &Path) -> Result<Option<(PathBuf, bool)>> {
    remove_sqz_from_claude_settings(project_dir.join(".claude").join("settings.local.json"), false)
}

/// Whether the Claude Code settings file at `path` holds any of sqz's hooks.
pub fn claude_settings_have_sqz_hooks(path: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(path) else { return false };
    let Ok(root) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
    sqz_hook_entries("").iter().any(|(event, _, args)| {
        root.pointer(&format!("/hooks/{event}"))
            .and_then(|v| v.as_array())
            .is_some_and(|a| a.iter().any(|e| hook_entry_runs_sqz(e, args)))
    })
}

/// Whether uninstall would take sqz's hooks or allow rules out of the settings file at `path`.
pub fn claude_settings_have_sqz(path: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(path) else { return false };
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(mut root) => root.as_object_mut().is_some_and(|o| strip_sqz_claude_entries(o, true)),
        Err(_) => text.contains("sqz"),
    }
}

/// Whether `~/.claude/settings.json` holds sqz's hooks, which run in every project.
pub fn claude_user_hooks_installed() -> bool {
    claude_user_settings_path().is_some_and(|p| claude_settings_have_sqz_hooks(&p))
}

/// Strip sqz's hook entries, and its allow rules with `rules`, from the Claude Code
/// settings file at `path`, deleting the file if nothing else is left in it.
fn remove_sqz_from_claude_settings(path: PathBuf, rules: bool) -> Result<Option<(PathBuf, bool)>> {
    if !path.exists() {
        return Ok(None);
    }

    let content = std::fs::read_to_string(&path).map_err(|e| {
        crate::error::SqzError::Other(format!("read {}: {e}", path.display()))
    })?;
    if content.trim().is_empty() {
        return Ok(Some((path, false)));
    }

    let mut root: serde_json::Value = serde_json::from_str(&content).map_err(|e| {
        crate::error::SqzError::Other(format!(
            "parse {}: {e} — refusing to rewrite an unparseable file",
            path.display()
        ))
    })?;
    let Some(root_obj) = root.as_object_mut() else {
        return Ok(Some((path, false)));
    };

    let changed = strip_sqz_claude_entries(root_obj, rules);

    if !changed {
        return Ok(Some((path, false)));
    }

    // If root is now completely empty, delete the file — matches the
    // "leave nothing behind" behaviour of the OpenCode/Codex uninstall
    // paths.
    if root_obj.is_empty() {
        std::fs::remove_file(&path).map_err(|e| {
            crate::error::SqzError::Other(format!(
                "remove {}: {e}",
                path.display()
            ))
        })?;
        return Ok(Some((path, true)));
    }

    // Atomic rewrite.
    write_json_config(&path, &root, &content)?;

    Ok(Some((path, true)))
}

/// Remove sqz's hooks, its allow rules with `rules`, and the keys that leaves empty.
fn strip_sqz_claude_entries(
    root: &mut serde_json::Map<String, serde_json::Value>,
    rules: bool,
) -> bool {
    let mut changed = rules && remove_claude_allow_rules(root);
    let Some(hooks) = root.get_mut("hooks").and_then(|h| h.as_object_mut()) else {
        return changed;
    };
    let mut emptied = false;
    for (event, _, sentinel) in &sqz_hook_entries("") {
        let Some(arr) = hooks.get_mut(*event).and_then(|v| v.as_array_mut()) else {
            continue;
        };
        if !remove_sqz_hook_commands(arr, sentinel) {
            continue;
        }
        changed = true;
        if arr.is_empty() {
            hooks.remove(*event);
            emptied = true;
        }
    }
    if emptied && hooks.is_empty() {
        root.remove("hooks");
    }
    changed
}

/// The sqz binary in `command` when it is `<sqz path> <args>`, as every sqz version wrote it.
fn sqz_command_binary<'a>(command: &'a str, args: &str) -> Option<&'a str> {
    let bin = command.strip_suffix(args)?.strip_suffix(' ')?;
    let path = unquoted(bin);
    let absolute = path.starts_with(['/', '\\']) || path.as_bytes().get(1) == Some(&b':');
    if path.contains(['"', '\'', '$', '`', '\n'])
        || (path == bin
            && (bin.contains([';', '&', '|', '<', '>', '(', ')'])
                || (bin.contains(char::is_whitespace) && !absolute)
                || bin
                    .split_whitespace()
                    .skip(1)
                    .any(|w| w.starts_with(['/', '-', '~']) || w.contains('='))))
    {
        return None;
    }
    let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
    let stem = match name.len().checked_sub(4) {
        Some(i) if name.is_char_boundary(i) && name[i..].eq_ignore_ascii_case(".exe") => &name[..i],
        _ => name,
    };
    (stem == "sqz").then_some(bin)
}

/// `bin` without one pair of surrounding double or single quotes.
fn unquoted(bin: &str) -> &str {
    ['"', '\'']
        .into_iter()
        .find_map(|q| bin.strip_prefix(q)?.strip_suffix(q))
        .unwrap_or(bin)
}

/// The file a config's sqz binary names: a bare name is looked up on PATH, nothing is run.
pub fn resolve_sqz_binary(bin: &str) -> Option<PathBuf> {
    let path = unquoted(bin);
    if !path.contains(['/', '\\']) {
        let dirs = std::env::var_os("PATH")?;
        return std::env::split_paths(&dirs).find_map(|dir| {
            let exe = dir.join(format!("{path}.exe"));
            [dir.join(path)]
                .into_iter()
                .chain(cfg!(windows).then_some(exe))
                .find(|p| p.is_file())
        });
    }
    let file = match path.strip_prefix("~/").filter(|_| path == bin) {
        Some(rest) => PathBuf::from(std::env::var_os("HOME")?).join(rest),
        None => PathBuf::from(path),
    };
    file.is_file().then_some(file)
}

/// The Cline hook script sqz wrote before it moved Cline to rules only.
const LEGACY_CLINE_SCRIPT: &str = "#!/usr/bin/env bash\n# sqz hook for Cline \u{2014} passes through all tool calls.\n# Cline's PreToolUse cannot rewrite commands, so compression\n# is handled by the sqz-mcp server instead.\necho '{\"cancel\": false}'\nexit 0\n";

/// Hook files older sqz versions wrote, with the command sqz put in each (`None`: the Cline script).
fn legacy_hook_files(
    project_dir: &Path,
    home_override: Option<&Path>,
) -> Vec<(PathBuf, Option<&'static str>)> {
    let mut files = vec![
        (project_dir.join(".cursor").join("hooks.json"), Some("hook cursor")),
        (project_dir.join(".windsurf").join("hooks.json"), Some("hook windsurf")),
        (project_dir.join(".cline").join("hooks.json"), Some("hook cline")),
        (project_dir.join(".clinerules").join("hooks").join("PreToolUse"), None),
    ];
    let home = home_override.map(Path::to_path_buf).or_else(|| {
        std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
    });
    if let Some(home) = home {
        files.push((home.join(".cursor").join("hooks.json"), Some("hook cursor")));
    }
    files
}

/// The file's JSON without sqz's hooks; `Some(None)` when nothing else is left, `None` without sqz hooks.
fn legacy_hooks_cut(text: &str, args: Option<&str>) -> Option<Option<serde_json::Value>> {
    let Some(args) = args else {
        return (text.replace("\r\n", "\n") == LEGACY_CLINE_SCRIPT).then_some(None);
    };
    let mut root: serde_json::Value = serde_json::from_str(text).ok()?;
    let obj = root.as_object_mut()?;
    let hooks = obj.get_mut("hooks")?.as_object_mut()?;
    let mut changed = false;
    let mut emptied = Vec::new();
    for (event, entries) in hooks.iter_mut() {
        let Some(arr) = entries.as_array_mut() else { continue };
        let before = arr.len();
        arr.retain(|e| !hook_runs_sqz(e, args));
        if remove_sqz_hook_commands(arr, args) || arr.len() != before {
            changed = true;
            if arr.is_empty() {
                emptied.push(event.clone());
            }
        }
    }
    if !changed {
        return None;
    }
    for event in &emptied {
        hooks.remove(event);
    }
    if hooks.is_empty() {
        obj.remove("hooks");
    }
    let only_version = obj.len() == 1 && obj.get("version") == Some(&serde_json::json!(1));
    Some((!obj.is_empty() && !only_version).then_some(root))
}

/// Hook files an older sqz wrote that still hold its hooks.
pub fn legacy_sqz_hook_files(project_dir: &Path) -> Vec<PathBuf> {
    legacy_sqz_hook_files_at(project_dir, None)
}

fn legacy_sqz_hook_files_at(project_dir: &Path, home_override: Option<&Path>) -> Vec<PathBuf> {
    legacy_hook_files(project_dir, home_override)
        .into_iter()
        .filter(|(path, args)| {
            std::fs::read_to_string(path).is_ok_and(|text| legacy_hooks_cut(&text, *args).is_some())
        })
        .map(|(path, _)| path)
        .collect()
}

/// Remove sqz's hooks from those files, deleting emptied ones; returns each changed file and if it went.
pub fn remove_legacy_sqz_hooks(project_dir: &Path) -> Result<Vec<(PathBuf, bool)>> {
    remove_legacy_sqz_hooks_at(project_dir, None)
}

fn remove_legacy_sqz_hooks_at(
    project_dir: &Path,
    home_override: Option<&Path>,
) -> Result<Vec<(PathBuf, bool)>> {
    let mut changed = Vec::new();
    for (path, args) in legacy_hook_files(project_dir, home_override) {
        let Ok(text) = std::fs::read_to_string(&path) else { continue };
        match legacy_hooks_cut(&text, args) {
            None => continue,
            Some(None) => std::fs::remove_file(&path).map_err(|e| {
                crate::error::SqzError::Other(format!("remove {}: {e}", path.display()))
            })?,
            Some(Some(rest)) => write_json_config(&path, &rest, &text)?,
        }
        let deleted = !path.exists();
        changed.push((path, deleted));
    }
    Ok(changed)
}

/// Every command a sqz version has written into a hook file, after the binary.
const SQZ_HOOK_ARGS: [&str; 9] = [
    "hook claude",
    "hook claude-post",
    "hook precompact",
    "resume",
    "hook gemini",
    "hook copilot",
    "hook cursor",
    "hook windsurf",
    "hook cline",
];

/// The sqz binaries the hooks in a hook config or OpenCode plugin file run.
pub fn sqz_hook_binaries(path: &Path) -> Vec<String> {
    let Ok(text) = std::fs::read_to_string(path) else { return Vec::new() };
    let mut found = Vec::new();
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(root) => collect_sqz_hook_binaries(&root, &mut found),
        Err(_) => found.extend(text.lines().find_map(|line| {
            let literal = line.trim().strip_prefix("const SQZ_PATH = ")?.strip_suffix(';')?;
            serde_json::from_str::<String>(literal).ok()
        })),
    }
    found
}

fn collect_sqz_hook_binaries(value: &serde_json::Value, found: &mut Vec<String>) {
    match value {
        serde_json::Value::Object(map) => {
            for (key, v) in map {
                let command = v.as_str().filter(|_| matches!(key.as_str(), "command" | "bash" | "powershell"));
                match command.and_then(|c| SQZ_HOOK_ARGS.iter().find_map(|args| sqz_command_binary(c, args))) {
                    Some(bin) if !found.iter().any(|b| b == bin) => found.push(bin.to_string()),
                    Some(_) => {}
                    None => collect_sqz_hook_binaries(v, found),
                }
            }
        }
        serde_json::Value::Array(items) => {
            for v in items {
                collect_sqz_hook_binaries(v, found);
            }
        }
        _ => {}
    }
}

/// Whether a hook entry's commands include sqz's `args` command.
fn hook_entry_runs_sqz(entry: &serde_json::Value, args: &str) -> bool {
    entry
        .get("hooks")
        .and_then(|h| h.as_array())
        .is_some_and(|hooks| hooks.iter().any(|h| hook_runs_sqz(h, args)))
}

/// Whether one hook command is sqz's `args` command.
fn hook_runs_sqz(hook: &serde_json::Value, args: &str) -> bool {
    hook.get("command")
        .and_then(|c| c.as_str())
        .is_some_and(|c| sqz_command_binary(c, args).is_some())
}

/// Drop sqz's `args` commands and the entries left without one; true when any went.
fn remove_sqz_hook_commands(arr: &mut Vec<serde_json::Value>, args: &str) -> bool {
    let mut removed = false;
    arr.retain_mut(|entry| {
        let Some(hooks) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) else {
            return true;
        };
        let before = hooks.len();
        hooks.retain(|h| !hook_runs_sqz(h, args));
        if hooks.len() == before {
            return true;
        }
        removed = true;
        !hooks.is_empty()
    });
    removed
}

/// Replace (or insert) sqz's hook entry in the array under
/// `hooks[event_name]`. Only commands that run sqz with exactly the
/// arguments `sentinel` count as sqz's (see [`sqz_command_binary`]), so a
/// user hook that merely mentions `resume` or `hook precompact` stays.
///
/// Idempotent: calling this twice yields the same JSON.
fn upsert_sqz_hook_entry(
    hooks_obj: &mut serde_json::Map<String, serde_json::Value>,
    event_name: &str,
    new_entry: serde_json::Value,
    sentinel: &str,
) {
    let arr = hooks_obj
        .entry(event_name.to_string())
        .or_insert_with(|| serde_json::Value::Array(Vec::new()));
    let Some(arr) = arr.as_array_mut() else {
        // `hooks[event]` exists but isn't an array — overwrite it with
        // just our entry. Not ideal but matches the behavior the user
        // would get on a fresh install.
        hooks_obj.insert(
            event_name.to_string(),
            serde_json::Value::Array(vec![new_entry]),
        );
        return;
    };

    // Drop any existing entry whose command matches our sentinel.
    remove_sqz_hook_commands(arr, sentinel);

    arr.push(new_entry);
}

/// Add [`CLAUDE_ALLOW_RULES`] to `permissions.allow`, keeping the user's
/// own rules. A `permissions` or `allow` of an unexpected type is left alone.
fn upsert_claude_allow_rules(root: &mut serde_json::Map<String, serde_json::Value>) {
    let perms = root
        .entry("permissions".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    let Some(perms) = perms.as_object_mut() else { return };
    let allow = perms
        .entry("allow".to_string())
        .or_insert_with(|| serde_json::Value::Array(Vec::new()));
    let Some(allow) = allow.as_array_mut() else { return };
    for rule in CLAUDE_ALLOW_RULES {
        if !allow.iter().any(|r| r.as_str() == Some(rule)) {
            allow.push(serde_json::Value::String(rule.to_string()));
        }
    }
}

/// Take [`CLAUDE_ALLOW_RULES`] back out, dropping `allow` and `permissions`
/// if that leaves them empty. Returns whether anything was removed.
fn remove_claude_allow_rules(root: &mut serde_json::Map<String, serde_json::Value>) -> bool {
    let Some(perms) = root.get_mut("permissions").and_then(|p| p.as_object_mut()) else {
        return false;
    };
    let Some(allow) = perms.get_mut("allow").and_then(|a| a.as_array_mut()) else {
        return false;
    };
    let before = allow.len();
    allow.retain(|r| !r.as_str().is_some_and(|s| CLAUDE_ALLOW_RULES.contains(&s)));
    if allow.len() == before {
        return false;
    }
    if allow.is_empty() {
        perms.remove("allow");
    }
    if perms.is_empty() {
        root.remove("permissions");
    }
    true
}

/// The binary path in a settings file's sqz PreToolUse hook, if it has one.
fn claude_settings_sqz_path(root: &serde_json::Value) -> Option<String> {
    root.pointer("/hooks/PreToolUse")?.as_array()?.iter().find_map(|entry| {
        entry.get("hooks")?.as_array()?.iter().find_map(|h| {
            let command = h.get("command")?.as_str()?;
            sqz_command_binary(command, "hook claude").map(str::to_string)
        })
    })
}

/// Whether a Claude Code settings file has sqz's PreToolUse hook but not
/// the allow rules or PostToolUse hook `sqz init` now writes, as an
/// install from an older sqz does. Without the rules the hook leaves
/// every command alone outside bypass mode.
pub fn claude_settings_stale(path: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(path) else { return false };
    let Ok(root) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
    if claude_settings_sqz_path(&root).is_none() {
        return false;
    }
    let post_hook = root
        .pointer("/hooks/PostToolUse")
        .and_then(|v| v.as_array())
        .is_some_and(|a| a.iter().any(|e| hook_entry_runs_sqz(e, "hook claude-post")));
    !post_hook || !claude_rules_installed(&[path.to_path_buf()])
}

/// Bring a stale settings file (see [`claude_settings_stale`]) up to date,
/// keeping the sqz binary its hook already runs when that still exists.
pub fn refresh_claude_settings(path: &Path, fallback_sqz: &str) -> Result<bool> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| crate::error::SqzError::Other(format!("read {}: {e}", path.display())))?;
    let root: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| crate::error::SqzError::Other(format!("parse {}: {e}", path.display())))?;
    let sqz_path = claude_settings_sqz_path(&root)
        .filter(|p| resolve_sqz_binary(p).is_some())
        .unwrap_or_else(|| fallback_sqz.to_string());
    if resolve_sqz_binary(&sqz_path).is_none() {
        return Err(crate::error::SqzError::Other(format!(
            "{sqz_path} does not exist, so the hooks were left as they are"
        )));
    }
    merge_sqz_hooks_into_settings(path, &sqz_path)
}

// ── Gemini CLI project settings ───────────────────────────────────────────

/// The BeforeTool entry sqz adds to `.gemini/settings.json`.
fn gemini_hook_entry(sqz_path: &str) -> serde_json::Value {
    serde_json::json!({
        "matcher": "run_shell_command",
        "hooks": [{ "type": "command", "command": format!("{sqz_path} hook gemini") }]
    })
}

/// The file's text and its settings with sqz's hook merged in, or `None` when nothing changes.
fn gemini_settings_merged(
    path: &Path,
    sqz_path: &str,
) -> Result<Option<(String, serde_json::Value)>> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| crate::error::SqzError::Other(format!("read {}: {e}", path.display())))?;
    let mut root: serde_json::Value = if text.trim().is_empty() {
        serde_json::Value::Object(serde_json::Map::new())
    } else {
        serde_json::from_str(&text).map_err(|e| {
            crate::error::SqzError::Other(format!("{} is not plain JSON: {e}", path.display()))
        })?
    };
    let root_obj = root.as_object_mut().ok_or_else(|| {
        crate::error::SqzError::Other(format!("{} is not a JSON object", path.display()))
    })?;
    let before = serde_json::to_string(&root_obj).unwrap_or_default();
    let hooks = root_obj
        .entry("hooks".to_string())
        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
    let hooks_obj = hooks.as_object_mut().ok_or_else(|| {
        crate::error::SqzError::Other(format!("{}: `hooks` is not an object", path.display()))
    })?;
    upsert_sqz_hook_entry(hooks_obj, "BeforeTool", gemini_hook_entry(sqz_path), "hook gemini");
    let after = serde_json::to_string(&root_obj).unwrap_or_default();
    Ok((before != after).then_some((text, root)))
}

/// Whether `sqz init` would create or change the Gemini CLI settings at `path`.
pub fn gemini_settings_needs_update(path: &Path, sqz_path: &str) -> Result<bool> {
    if !path.exists() {
        return Ok(true);
    }
    Ok(gemini_settings_merged(path, sqz_path)?.is_some())
}

/// Merge sqz's hook into existing Gemini CLI settings, keeping everything else.
pub fn merge_sqz_gemini_hook(path: &Path, sqz_path: &str) -> Result<bool> {
    let Some((text, root)) = gemini_settings_merged(path, sqz_path)? else {
        return Ok(false);
    };
    write_json_config(path, &root, &text)?;
    Ok(true)
}

/// Whether the Gemini CLI settings at `path` hold sqz's hook (by its text when not plain JSON).
pub fn gemini_settings_has_sqz(path: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(path) else { return false };
    match serde_json::from_str::<serde_json::Value>(&text) {
        Ok(root) => root
            .pointer("/hooks/BeforeTool")
            .and_then(|v| v.as_array())
            .is_some_and(|a| a.iter().any(|e| hook_entry_runs_sqz(e, "hook gemini"))),
        Err(_) => text.contains(" hook gemini"),
    }
}

/// Remove sqz's hook from `.gemini/settings.json`, as [`remove_claude_global_hook`] does.
pub fn remove_sqz_from_gemini_settings(project_dir: &Path) -> Result<Option<(PathBuf, bool)>> {
    let path = project_dir.join(".gemini").join("settings.json");
    if !path.exists() {
        return Ok(None);
    }
    let text = std::fs::read_to_string(&path)
        .map_err(|e| crate::error::SqzError::Other(format!("read {}: {e}", path.display())))?;
    if text.trim().is_empty() {
        return Ok(Some((path, false)));
    }
    let mut root: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        crate::error::SqzError::Other(format!(
            "{} is not plain JSON ({e}); remove the sqz hook by hand",
            path.display()
        ))
    })?;
    let Some(root_obj) = root.as_object_mut() else {
        return Ok(Some((path, false)));
    };
    let Some(hooks) = root_obj.get_mut("hooks").and_then(|h| h.as_object_mut()) else {
        return Ok(Some((path, false)));
    };
    let Some(arr) = hooks.get_mut("BeforeTool").and_then(|v| v.as_array_mut()) else {
        return Ok(Some((path, false)));
    };
    if !remove_sqz_hook_commands(arr, "hook gemini") {
        return Ok(Some((path, false)));
    }
    if arr.is_empty() {
        hooks.remove("BeforeTool");
        if hooks.is_empty() {
            root_obj.remove("hooks");
        }
    }
    if root_obj.is_empty() {
        std::fs::remove_file(&path).map_err(|e| {
            crate::error::SqzError::Other(format!("remove {}: {e}", path.display()))
        })?;
        return Ok(Some((path, true)));
    }
    write_json_config(&path, &root, &text)?;
    Ok(Some((path, true)))
}

/// Rewrite a JSON config through a temp file, keeping its mode and its final newline.
fn write_json_config(path: &Path, value: &serde_json::Value, original: &str) -> Result<()> {
    let parent = path.parent().ok_or_else(|| {
        crate::error::SqzError::Other(format!("path {} has no parent directory", path.display()))
    })?;
    let tmp = tempfile::NamedTempFile::new_in(parent).map_err(|e| {
        crate::error::SqzError::Other(format!("create temp file in {}: {e}", parent.display()))
    })?;
    let mut serialized = serde_json::to_string_pretty(value)
        .map_err(|e| crate::error::SqzError::Other(format!("serialize {}: {e}", path.display())))?;
    if original.ends_with('\n') {
        serialized.push('\n');
    }
    std::fs::write(tmp.path(), serialized).map_err(|e| {
        crate::error::SqzError::Other(format!("write to temp file {}: {e}", tmp.path().display()))
    })?;
    if let Ok(meta) = std::fs::metadata(path) {
        let _ = std::fs::set_permissions(tmp.path(), meta.permissions());
    }
    tmp.persist(path).map_err(|e| {
        crate::error::SqzError::Other(format!(
            "rename temp file into place at {}: {e}",
            path.display()
        ))
    })?;
    Ok(())
}

// ── Helpers ───────────────────────────────────────────────────────────────

/// Extract the base command name from a full command string.
fn extract_base_command(cmd: &str) -> &str {
    cmd.split_whitespace()
        .next()
        .unwrap_or("unknown")
        .rsplit('/')
        .next()
        .unwrap_or("unknown")
}

/// Escape a string for embedding as the contents of a double-quoted JSON
/// string value (per RFC 8259). Also valid for embedding in a double-quoted
/// JavaScript/TypeScript string literal — JS string-escape rules for the
/// characters that appear in filesystem paths (`\`, `"`, control chars) are
/// a strict subset of JSON's.
///
/// Needed because hook configs embed the sqz executable path into JSON/TS
/// files via `format!`. On Windows, `current_exe()` returns
/// `C:\Users\...\sqz.exe` — the raw backslashes produce invalid JSON that
/// Claude/Cursor/Gemini fail to parse. See issue #2.
pub(crate) fn json_escape_string_value(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\x08' => out.push_str("\\b"),
            '\x0c' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                // Other control chars: use \u00XX escape
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out
}

/// Shell-escape a string for use in an environment variable assignment.
fn shell_escape(s: &str) -> String {
    if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.') {
        s.to_string()
    } else {
        format!("'{}'", s.replace('\'', "'\\''"))
    }
}

/// What a hook returns when it leaves the tool call alone. Copilot needs a
/// JSON object on every path.
fn passthrough(platform: HookPlatform, input: &str) -> String {
    match platform {
        HookPlatform::Copilot => "{}".to_string(),
        _ => input.to_string(),
    }
}

/// Background, async or detached shell calls, under each client's name
/// for the flag.
fn runs_in_background(parsed: &serde_json::Value) -> bool {
    let Some(args) = parsed
        .get("tool_input")
        .or_else(|| parsed.get("toolArgs"))
        .or_else(|| parsed.get("args"))
    else {
        return false;
    };
    ["run_in_background", "is_background", "background", "async", "detach"]
        .iter()
        .any(|k| args.get(k).and_then(|v| v.as_bool()) == Some(true))
        || args.get("mode").and_then(|v| v.as_str()) == Some("async")
}

/// Allow rules `sqz init` adds to Claude Code settings so the two parts the
/// ungrouped rewrite adds never need approval of their own. Neither runs
/// anything: one sets a shell option, the other reads stdin.
pub const CLAUDE_ALLOW_RULES: [&str; 2] = ["Bash(set -o pipefail)", "Bash(sqz compress --cmd *)"];

/// Claude Code checks permissions against the rewritten command, so a
/// rewrite must not make an allowed command prompt. Outside bypass mode
/// that holds only for the ungrouped form, and only once the user has
/// allowed its extra parts; grouped commands are judged too complex to
/// match any rule. Everything else is left alone.
fn claude_rewrite(
    parsed: &serde_json::Value,
    command: &str,
    is_powershell: bool,
    settings: &[PathBuf],
    shell: crate::shell_scan::Shell,
) -> Option<String> {
    let bypass = parsed.get("permission_mode").and_then(|v| v.as_str()) == Some("bypassPermissions");
    if is_powershell {
        if !bypass || is_interactive_command(command) || has_shell_operators(command) {
            return None;
        }
        return Some(crate::exit_marker::powershell_rewrite(command, &shell_escape(command)));
    }
    if crate::shell_scan::flat(command).is_some() {
        let cmds = crate::shell_scan::flat_for(command, shell)?;
        return (bypass || claude_rules_installed(settings))
            .then(|| crate::exit_marker::posix_flat_rewrite(command, &cmds));
    }
    if bypass {
        return crate::shell_scan::plan(command).ok().map(|plan| posix_rewrite_plan(&plan));
    }
    None
}

/// A successful Bash result the Claude Code PostToolUse hook may shrink.
#[derive(Debug, Clone, PartialEq)]
pub struct PostToolUseTarget {
    /// The tool's result object. A replacement must keep its shape, so
    /// only `stdout` and `stderr` should change.
    pub response: serde_json::Map<String, serde_json::Value>,
    /// The stats and formatter label for its output.
    pub label: String,
}

/// Decide whether a Claude Code PostToolUse payload is worth compressing:
/// a Bash call the PreToolUse hook didn't already pipe through sqz, with
/// text output that Claude Code hasn't truncated. Claude Code only runs
/// PostToolUse after a command exits 0; a failure goes to
/// PostToolUseFailure, which can't replace output.
pub fn claude_post_tool_use_target(input: &str) -> Option<PostToolUseTarget> {
    let parsed: serde_json::Value = serde_json::from_str(input).ok()?;
    if parsed.get("hook_event_name").and_then(|v| v.as_str()) != Some("PostToolUse")
        || parsed.get("tool_name").and_then(|v| v.as_str()) != Some("Bash")
        || runs_in_background(&parsed)
    {
        return None;
    }
    let command = parsed.pointer("/tool_input/command")?.as_str()?;
    if command.contains("sqz compress")
        || crate::shell_scan::plan(command) == Err(crate::shell_scan::Skip::AlreadySqz)
    {
        return None;
    }
    let response = parsed.get("tool_response")?.as_object()?.clone();
    let flag = |k: &str| response.get(k).and_then(|v| v.as_bool()) == Some(true);
    if flag("isImage") || flag("interrupted") {
        return None;
    }
    // Past this many characters Claude Code has already cut the output and
    // shows only a preview, so a smaller replacement changes nothing.
    let limit = std::env::var("BASH_MAX_OUTPUT_LENGTH")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(30_000);
    let long = |k: &str| {
        response
            .get(k)
            .and_then(|v| v.as_str())
            .is_some_and(|s| s.chars().count() >= limit)
    };
    if response.get("stdout").and_then(|v| v.as_str()).is_none() || long("stdout") || long("stderr") {
        return None;
    }
    Some(PostToolUseTarget { response, label: post_tool_use_label(command) })
}

/// Whether sqz's Claude Code hooks, as `sqz init` installs them, compress a
/// Bash command's output in a default-mode session: the PreToolUse rewrite
/// takes it, or it exits 0 and the PostToolUse hook does. Followers and
/// background jobs never finish with output to replace.
pub fn claude_hooks_compress(command: &str, failed: bool) -> bool {
    use crate::shell_scan::{flat_for, plan, Shell, Skip};
    if command.contains("sqz compress") {
        return false;
    }
    match plan(command) {
        Err(Skip::AlreadySqz) => false,
        _ if flat_for(command, Shell::from_env()).is_some() => true,
        Err(Skip::LongRunning | Skip::Background) => false,
        _ => !failed,
    }
}

/// One command's label when only one command in the list has output worth
/// compressing, so its formatter can run; the generic `sh:` label otherwise.
fn post_tool_use_label(command: &str) -> String {
    if let Some(cmds) = crate::shell_scan::flat(command) {
        let mut labels = cmds.into_iter().filter_map(|c| c.label);
        if let (Some(only), None) = (labels.next(), labels.next()) {
            return only;
        }
    }
    list_label(command)
}

/// The settings files Claude Code reads allow rules from, managed policy
/// aside: the user file, then the project's shared and local files.
fn claude_settings_files(parsed: &serde_json::Value) -> Vec<PathBuf> {
    let mut files = Vec::new();
    let user = std::env::var_os("CLAUDE_CONFIG_DIR")
        .map(PathBuf::from)
        .or_else(|| dirs_next::home_dir().map(|h| h.join(".claude")));
    if let Some(dir) = user {
        files.push(dir.join("settings.json"));
    }
    let project = std::env::var_os("CLAUDE_PROJECT_DIR")
        .map(PathBuf::from)
        .or_else(|| parsed.get("cwd").and_then(|v| v.as_str()).map(PathBuf::from));
    if let Some(dir) = project {
        files.push(dir.join(".claude").join("settings.json"));
        files.push(dir.join(".claude").join("settings.local.json"));
    }
    files
}

/// Whether the allow rules across `files` cover both parts the ungrouped
/// rewrite adds.
fn claude_rules_installed(files: &[PathBuf]) -> bool {
    let (mut pipefail, mut compress) = (false, false);
    for file in files {
        let Ok(text) = std::fs::read_to_string(file) else { continue };
        let Ok(root) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
        let Some(rules) = root.pointer("/permissions/allow").and_then(|a| a.as_array()) else {
            continue;
        };
        for rule in rules.iter().filter_map(|r| r.as_str()) {
            pipefail |= bash_rule_allows(rule, "set -o pipefail");
            compress |= bash_rule_allows(rule, "sqz compress --cmd ls");
        }
    }
    pipefail && compress
}

/// Claude Code's matching for the rule shapes that could cover `command`:
/// bare `Bash`, an exact command, or one trailing wildcard (`x *`, `x:*`
/// and `x*`). Anything else counts as not covering it.
fn bash_rule_allows(rule: &str, command: &str) -> bool {
    let rule = rule.trim();
    if rule == "Bash" {
        return true;
    }
    let Some(spec) = rule.strip_prefix("Bash(").and_then(|r| r.strip_suffix(')')) else {
        return false;
    };
    if let Some(prefix) = spec.strip_suffix(":*").or_else(|| spec.strip_suffix(" *")) {
        if prefix.contains('*') {
            return false;
        }
        return command == prefix
            || command.strip_prefix(prefix).is_some_and(|rest| rest.starts_with(' '));
    }
    match spec.strip_suffix('*') {
        Some(prefix) if !prefix.contains('*') => command.starts_with(prefix),
        Some(_) => false,
        None => spec == command,
    }
}

/// The POSIX rewrite for a command `shell_scan` accepted.
fn posix_rewrite_plan(plan: &crate::shell_scan::Plan<'_>) -> String {
    let grouped = if plan.simple {
        // The full command is the label so subcommand formatters
        // (`git status`, `cargo test`) dispatch.
        let cmd = plan.body.trim();
        let label = cmd.strip_suffix(" 2>&1").map_or(cmd, str::trim_end);
        crate::exit_marker::posix_rewrite(cmd, &shell_escape(label))
    } else {
        crate::exit_marker::posix_rewrite_list(plan.body, &shell_escape(&list_label(plan.body)))
    };
    if plan.prefix.is_empty() {
        grouped
    } else {
        format!("{} {grouped}", plan.prefix)
    }
}

/// Label for a list or pipeline. The `sh:` prefix keeps per-command
/// formatters off output that is partial or comes from several commands.
fn list_label(body: &str) -> String {
    let first = body.trim().lines().next().unwrap_or("");
    let label = format!("sh: {}", first.split_whitespace().collect::<Vec<_>>().join(" "));
    if label.chars().count() > 100 {
        format!("{}…", label.chars().take(99).collect::<String>())
    } else {
        label
    }
}

/// Check if a command contains shell operators that would break piping.
/// Commands with these operators are passed through uncompressed rather
/// than risk incorrect behavior.
pub(crate) fn has_shell_operators(cmd: &str) -> bool {
    // Check for operators that would cause the pipe to only capture
    // the last command in a chain
    cmd.contains("&&")
        || cmd.contains("||")
        || cmd.contains(';')
        || cmd.contains('>')
        || cmd.contains('<')
        || cmd.contains('|') // already has a pipe
        || cmd.contains('&') && !cmd.contains("&&") // background &
        || cmd.contains("<<")  // heredoc
        || cmd.contains("$(")  // command substitution
        || cmd.contains('`')   // backtick substitution
}

/// Check if a command is interactive or long-running (should not be intercepted).
fn is_interactive_command(cmd: &str) -> bool {
    let base = extract_base_command(cmd);
    matches!(
        base,
        "vim" | "vi" | "nano" | "emacs" | "less" | "more" | "top" | "htop"
        | "ssh" | "python" | "python3" | "node" | "irb" | "ghci"
        | "psql" | "mysql" | "sqlite3" | "mongo" | "redis-cli"
    ) || cmd.contains("--watch")
        || cmd.contains("-w ")
        || cmd.ends_with(" -w")
        || cmd.contains("run dev")
        || cmd.contains("run start")
        || cmd.contains("run serve")
}

// ── Tests ─────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_copilot_hook_rewrites_bash_with_modified_args() {
        let input = r#"{"sessionId":"s","timestamp":1,"cwd":"/x","toolName":"bash","toolArgs":{"command":"git log -20","timeoutSec":30}}"#;
        let result = process_hook_copilot(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        // An "allow" would skip Copilot's own approval prompt.
        assert!(parsed.get("permissionDecision").is_none(), "{parsed}");
        let args = &parsed["modifiedArgs"];
        assert!(args["command"].as_str().unwrap().contains("sqz compress"));
        assert_eq!(args["timeoutSec"], 30, "sibling toolArgs fields carried over");
    }

    #[test]
    fn test_copilot_hook_reads_tool_args_given_as_a_string() {
        let input = serde_json::json!({
            "toolName": "bash",
            "toolArgs": r#"{"command":"git log -20","timeoutSec":30}"#,
        })
        .to_string();
        let out = process_hook_copilot(&input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        let args = &parsed["modifiedArgs"];
        assert!(args["command"].as_str().unwrap().contains("sqz compress"), "{parsed}");
        assert_eq!(args["timeoutSec"], 30, "{parsed}");
        let background = serde_json::json!({
            "toolName": "bash",
            "toolArgs": r#"{"command":"cargo build","mode":"async"}"#,
        })
        .to_string();
        assert_eq!(process_hook_copilot(&background).unwrap(), "{}");
    }

    #[test]
    fn test_copilot_hook_passes_non_shell_through() {
        let input = r#"{"sessionId":"s","timestamp":1,"cwd":"/x","toolName":"view","toolArgs":{"path":"a.rs"}}"#;
        let result = process_hook_copilot(input).unwrap();
        assert_eq!(result, "{}", "non-shell tools fall through with empty object");
    }

    #[test]
    fn test_copilot_hook_skips_risky_shell_operators() {
        // Copilot keeps one shell per session, so state changes must not
        // move into a subshell.
        for command in [
            "source .venv/bin/activate && pytest",
            "npm run build &",
            "for f in a b; do last=$f; done",
        ] {
            let input = serde_json::json!({"toolName": "bash", "toolArgs": {"command": command}}).to_string();
            assert_eq!(process_hook_copilot(&input).unwrap(), "{}", "{command}");
        }
    }

    #[test]
    fn test_claude_updated_input_preserves_sibling_fields() {
        // Claude Code's updatedInput replaces the whole input object, so
        // run_in_background / timeout / description must survive the rewrite.
        let input = r#"{"tool_name":"Bash","permission_mode":"bypassPermissions","tool_input":{"command":"cargo test","run_in_background":false,"timeout":120000,"description":"Run tests"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let updated = &parsed["hookSpecificOutput"]["updatedInput"];
        assert!(updated["command"].as_str().unwrap().contains("sqz compress"));
        assert_eq!(updated["run_in_background"], false);
        assert_eq!(updated["timeout"], 120000);
        assert_eq!(updated["description"], "Run tests");
    }

    fn rewritten(input: &str) -> Option<String> {
        let out: serde_json::Value = serde_json::from_str(&process_hook(input).unwrap()).unwrap();
        out.pointer("/hookSpecificOutput/updatedInput/command")
            .and_then(|c| c.as_str())
            .map(str::to_string)
    }

    /// A Claude Code Bash call in bypass mode, where the rewrite doesn't
    /// depend on the allow rules in this machine's settings files.
    fn bash(command: &str) -> String {
        serde_json::json!({
            "tool_name": "Bash",
            "permission_mode": "bypassPermissions",
            "tool_input": {"command": command}
        })
        .to_string()
    }

    fn claude_default(command: &str, settings: &[PathBuf]) -> Option<String> {
        claude_default_in(command, settings, crate::shell_scan::Shell::Zsh)
    }

    fn claude_default_in(
        command: &str,
        settings: &[PathBuf],
        shell: crate::shell_scan::Shell,
    ) -> Option<String> {
        let parsed = serde_json::json!({
            "tool_name": "Bash",
            "permission_mode": "default",
            "tool_input": {"command": command}
        });
        claude_rewrite(&parsed, command, false, settings, shell)
    }

    fn settings_with_rules(dir: &Path, rules: &[&str]) -> PathBuf {
        let path = dir.join("settings.json");
        std::fs::write(&path, serde_json::json!({"permissions": {"allow": rules}}).to_string())
            .unwrap();
        path
    }

    #[test]
    fn claude_default_mode_rewrites_only_with_the_allow_rules() {
        let dir = tempfile::tempdir().unwrap();
        let none = dir.path().join("missing.json");
        assert_eq!(claude_default("git status", &[none.clone()]), None);

        let partial = settings_with_rules(dir.path(), &["Bash(sqz compress --cmd *)"]);
        assert_eq!(claude_default("git status", &[partial]), None, "pipefail rule missing");

        let full = settings_with_rules(dir.path(), &CLAUDE_ALLOW_RULES);
        assert_eq!(
            claude_default("git status", &[none, full.clone()]).as_deref(),
            Some("set -o pipefail; git status 2>&1 | sqz compress --cmd 'git status'")
        );
        // Grouping is judged too complex for any allow rule to match, so
        // pipelines are left alone outside bypass mode.
        assert_eq!(claude_default("git log | head -5", &[full.clone()]), None);
        assert_eq!(claude_default("for f in *; do wc -l $f; done", &[full]), None);
    }

    #[test]
    fn claude_default_mode_keeps_builtins_in_the_shell() {
        let dir = tempfile::tempdir().unwrap();
        let rules = settings_with_rules(dir.path(), &CLAUDE_ALLOW_RULES);
        assert_eq!(
            claude_default("cd sub && export CI=1 && cargo test", &[rules]).as_deref(),
            Some("set -o pipefail; cd sub && export CI=1 && cargo test 2>&1 | sqz compress --cmd 'cargo test'")
        );
    }

    #[test]
    fn claude_flat_form_stops_where_the_shell_would() {
        use crate::shell_scan::Shell;
        let dir = tempfile::tempdir().unwrap();
        let rules = [settings_with_rules(dir.path(), &CLAUDE_ALLOW_RULES)];
        for shell in [Shell::Bash, Shell::Zsh] {
            assert_eq!(claude_default_in("ls ${X:?unset}; echo next", &rules, shell), None);
            assert_eq!(claude_default_in("ls $((1/0)) || echo next", &rules, shell), None);
            assert_eq!(
                claude_default_in("ls ${X:?unset} && echo next", &rules, shell).as_deref(),
                Some("set -o pipefail; ls ${X:?unset} 2>&1 | sqz compress --cmd ls && echo next")
            );
        }
        assert_eq!(claude_default_in("ls *.rs; echo next", &rules, Shell::Zsh), None);
        assert!(claude_default_in("ls *.rs; echo next", &rules, Shell::Bash).is_some());
        let parsed = serde_json::json!({"permission_mode": "bypassPermissions"});
        for shell in [Shell::Bash, Shell::Zsh] {
            for command in ["ls ${X:?unset}; echo next", "ls $((1/0))\necho next"] {
                assert_eq!(claude_rewrite(&parsed, command, false, &[], shell), None, "{command:?}");
            }
        }
    }

    #[test]
    fn claude_powershell_is_rewritten_only_in_bypass_mode() {
        let zsh = crate::shell_scan::Shell::Zsh;
        let parsed = serde_json::json!({"tool_name": "PowerShell", "permission_mode": "default"});
        assert_eq!(claude_rewrite(&parsed, "Get-ChildItem", true, &[], zsh), None);
        let parsed = serde_json::json!({"tool_name": "PowerShell", "permission_mode": "bypassPermissions"});
        assert!(claude_rewrite(&parsed, "Get-ChildItem", true, &[], zsh).is_some());
    }

    #[test]
    fn bash_rule_matching() {
        for (rule, command, expected) in [
            ("Bash", "set -o pipefail", true),
            ("Bash(*)", "set -o pipefail", true),
            ("Bash(set -o pipefail)", "set -o pipefail", true),
            ("Bash(set -o pipefail)", "set -o pipefail -x", false),
            ("Bash(set *)", "set -o pipefail", true),
            ("Bash(set:*)", "set -o pipefail", true),
            ("Bash(sqz compress --cmd *)", "sqz compress --cmd ls", true),
            ("Bash(sqz *)", "sqz compress --cmd ls", true),
            ("Bash(sqz*)", "sqz compress --cmd ls", true),
            ("Bash(sq *)", "sqz compress --cmd ls", false),
            ("Bash(* --cmd ls)", "sqz compress --cmd ls", false),
            ("Read(./x)", "sqz compress --cmd ls", false),
        ] {
            assert_eq!(bash_rule_allows(rule, command), expected, "{rule} vs {command}");
        }
    }

    #[test]
    fn crlf_copies_of_current_files_are_current() {
        use crate::kiro_integration::SteeringState;
        let dir = tempfile::tempdir().unwrap();
        let crlf = |s: String| s.replace('\n', "\r\n");
        let write = |name: &str, text: String| {
            let path = dir.path().join(name);
            std::fs::write(&path, text).unwrap();
            path
        };

        let cursor = write("sqz.mdc", crlf(sqz_rules_content("Cursor", "/opt/sqz")));
        assert_eq!(sqz_rules_state(&cursor, "Cursor"), SteeringState::Current);
        let legacy = write("old.mdc", crlf(format!("{LEGACY_CURSOR_FRONTMATTER}alwaysApply: true\n---\nold\n")));
        assert_eq!(sqz_rules_state(&legacy, "Cursor"), SteeringState::Stale);
        let kiro = write("kiro.md", crlf(crate::kiro_integration::kiro_steering_content("/opt/sqz")));
        assert_eq!(crate::kiro_integration::kiro_steering_state(&kiro, false), SteeringState::Current);
        let block = crate::codex_integration::agents_md_guidance_block("/opt/sqz");
        let agents = write("AGENTS.md", crlf(format!("# Mine\n\n{block}")));
        assert_eq!(crate::codex_integration::agents_md_guidance_state(&agents), SteeringState::Current);
        let claude_md = write("CLAUDE.md", crlf(crate::claude_md_integration::claude_md_guidance_block("/opt/sqz")));
        assert_eq!(crate::claude_md_integration::claude_md_guidance_state(dir.path()), SteeringState::Current);
        assert!(!crate::claude_md_integration::claude_md_block_outdated(dir.path(), "/opt/sqz"));
        let before = std::fs::read(&claude_md).unwrap();
        assert!(!crate::claude_md_integration::install_claude_md_guidance(dir.path(), "/opt/sqz").unwrap());
        assert_eq!(std::fs::read(&claude_md).unwrap(), before);
    }

    #[test]
    fn stale_claude_settings_are_detected_and_refreshed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let bin = dir.path().join("sqz");
        std::fs::write(&bin, "").unwrap();
        let bin = bin.to_string_lossy().to_string();
        // What a 1.9.0 install wrote, plus one of the user's own hooks.
        let old = serde_json::json!({"hooks": {
            "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": format!("{bin} hook claude")}]}],
            "PostToolUse": [{"matcher": "Edit", "hooks": [{"type": "command", "command": "prettier --write"}]}],
        }});
        std::fs::write(&path, old.to_string()).unwrap();
        assert!(claude_settings_stale(&path));

        assert!(refresh_claude_settings(&path, "/fallback/sqz").unwrap());
        assert!(!claude_settings_stale(&path));
        let v: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let post = v["hooks"]["PostToolUse"].as_array().unwrap();
        assert_eq!(post.len(), 2, "the user's own PostToolUse hook stays: {post:?}");
        assert_eq!(
            v["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
            format!("{bin} hook claude"),
            "keeps the binary the hook already used"
        );

        std::fs::write(&path, r#"{"permissions":{}}"#).unwrap();
        assert!(!claude_settings_stale(&path), "no sqz hook, nothing to refresh");
    }

    #[test]
    fn background_calls_pass_through() {
        for input in [
            r#"{"tool_name":"Bash","tool_input":{"command":"cargo build","run_in_background":true}}"#,
            r#"{"tool_name":"run_shell_command","tool_input":{"command":"cargo build","is_background":true}}"#,
            r#"{"toolName":"bash","toolArgs":{"command":"cargo build","mode":"async"}}"#,
        ] {
            assert_eq!(rewritten(input), None, "{input}");
        }
    }

    #[test]
    fn lists_and_pipelines_are_grouped_with_a_generic_label() {
        let cmd = rewritten(&bash("cargo test 2>&1 | tail -30")).unwrap();
        assert_eq!(
            cmd,
            "{ ( cargo test 2>&1 | tail -30\n); printf '\\n__SQZ_EXIT_%d__\\n' \"$?\"; } 2>&1 | sqz compress --cmd 'sh: cargo test 2>&1 | tail -30'"
        );
        // A trailing comment no longer swallows the closing brace.
        let cmd = rewritten(&bash("ls | head # list")).unwrap();
        assert!(cmd.starts_with("{ ( ls | head # list\n); printf"), "{cmd}");
        // Without a pipe nothing needs grouping, and the comment stays last.
        let cmd = rewritten(&bash("ls # list")).unwrap();
        assert_eq!(cmd, "set -o pipefail; ls 2>&1 | sqz compress --cmd ls # list");
    }

    #[test]
    fn leading_cd_runs_outside_the_group() {
        let cmd = rewritten(&bash("cd sqz_engine && cargo test 2>&1 | tail -5")).unwrap();
        assert_eq!(
            cmd,
            "cd sqz_engine && { (  cargo test 2>&1 | tail -5\n); printf '\\n__SQZ_EXIT_%d__\\n' \"$?\"; } 2>&1 | sqz compress --cmd 'sh: cargo test 2>&1 | tail -5'"
        );
        let cmd = rewritten(&bash("cd sqz_engine && cargo test 2>&1")).unwrap();
        assert_eq!(
            cmd,
            "set -o pipefail; cd sqz_engine && cargo test 2>&1 | sqz compress --cmd 'cargo test'"
        );
    }

    #[test]
    fn state_changes_pipe_only_the_commands_around_them() {
        assert_eq!(
            rewritten(&bash("export X=1 && make")).as_deref(),
            Some("set -o pipefail; export X=1 && make 2>&1 | sqz compress --cmd make")
        );
        assert_eq!(
            rewritten(&bash("make && cd build")).as_deref(),
            Some("set -o pipefail; make 2>&1 | sqz compress --cmd make && cd build")
        );
    }

    #[test]
    fn followers_background_jobs_and_sqz_pass_through() {
        for command in ["tail -f app.log", "make &", "git log | sqz compress", "cd x && npm run dev"] {
            assert_eq!(rewritten(&bash(command)), None, "{command}");
        }
    }

    #[test]
    fn test_process_hook_rewrites_bash_command() {
        // Use the official Claude Code input format: tool_name + tool_input
        let input = bash("git status");
        let result = process_hook(&input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        // Claude Code format: hookSpecificOutput with updatedInput
        let hook_output = &parsed["hookSpecificOutput"];
        assert_eq!(hook_output["hookEventName"].as_str().unwrap(), "PreToolUse");
        // "allow" would skip the permission prompt for the command.
        assert!(hook_output.get("permissionDecision").is_none(), "{hook_output}");
        assert!(hook_output.get("permissionDecisionReason").is_none(), "{hook_output}");
        // updatedInput for Claude Code (camelCase)
        let cmd = hook_output["updatedInput"]["command"].as_str().unwrap();
        assert!(cmd.contains("sqz compress"), "should pipe through sqz: {cmd}");
        assert!(cmd.contains("git status"), "should preserve original command: {cmd}");
        // Issue #10: the label is now passed as `--cmd NAME`, not as a
        // `SQZ_CMD=NAME` prefix (sh-specific, broken on PowerShell/cmd.exe).
        assert!(
            cmd.contains("--cmd 'git status'"),
            "should pass the full command as --cmd so subcommand formatters dispatch: {cmd}"
        );
        assert!(
            !cmd.contains("SQZ_CMD="),
            "new rewrites must not emit the legacy sh-style env prefix: {cmd}"
        );
        // Claude Code format should NOT have top-level decision/permission/continue
        assert!(parsed.get("decision").is_none(), "Claude Code format should not have top-level decision");
        assert!(parsed.get("permission").is_none(), "Claude Code format should not have top-level permission");
        assert!(parsed.get("continue").is_none(), "Claude Code format should not have top-level continue");
    }

    #[test]
    fn test_process_hook_passes_through_non_bash() {
        let input = r#"{"tool_name":"Read","tool_input":{"file_path":"file.txt"}}"#;
        let result = process_hook(input).unwrap();
        assert_eq!(result, input, "non-bash tools should pass through unchanged");
    }

    #[test]
    fn test_process_hook_rewrites_powershell_command() {
        let input = r#"{"tool_name":"PowerShell","permission_mode":"bypassPermissions","tool_input":{"command":"Get-Content big.log"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let cmd = parsed["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .expect("PowerShell tool calls should be rewritten");
        assert!(
            cmd.contains("Get-Content big.log"),
            "should preserve original PowerShell command: {cmd}"
        );
        assert!(
            cmd.contains("sqz compress"),
            "should pipe through sqz compress: {cmd}"
        );
        assert!(
            cmd.contains("--cmd 'Get-Content big.log'"),
            "should pass full command via --cmd: {cmd}"
        );
    }

    #[test]
    fn test_process_hook_rewrites_pwsh_command() {
        let input = r#"{"tool_name":"pwsh","permission_mode":"bypassPermissions","tool_input":{"command":"ls"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed["hookSpecificOutput"]["updatedInput"]["command"].is_string(),
            "pwsh tool calls should be rewritten"
        );
    }

    #[test]
    fn bash_rewrite_carries_exit_status_trailer() {
        let input = r#"{"tool_name":"run_shell_command","tool_input":{"command":"cargo test"}}"#;
        let result = process_hook_gemini(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let cmd = parsed["hookSpecificOutput"]["tool_input"]["command"]
            .as_str()
            .unwrap();
        assert_eq!(
            cmd,
            "{ ( cargo test\n); printf '\\n__SQZ_EXIT_%d__\\n' \"$?\"; } 2>&1 | sqz compress --cmd 'cargo test'",
            "POSIX rewrite must send the command's exit status through the pipe"
        );
        // Claude Code gets the ungrouped form, where pipefail carries it.
        let cmd = rewritten(&bash("cargo test")).unwrap();
        assert_eq!(cmd, "set -o pipefail; cargo test 2>&1 | sqz compress --cmd 'cargo test'");
    }

    #[test]
    fn powershell_rewrite_uses_lastexitcode_not_printf() {
        let input = r#"{"tool_name":"PowerShell","permission_mode":"bypassPermissions","tool_input":{"command":"cargo test"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let cmd = parsed["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .unwrap();
        assert!(cmd.contains("$LASTEXITCODE"), "PowerShell form uses $LASTEXITCODE: {cmd}");
        assert!(cmd.contains("__SQZ_EXIT_"), "PowerShell form emits the trailer: {cmd}");
        assert!(!cmd.contains("printf"), "printf is not valid PowerShell: {cmd}");
    }

    #[test]
    fn exit_trailer_rewrite_is_not_rewrapped() {
        // Feed the hook its own output — the anti-rewrap guard must catch
        // the new brace-group form (it contains `sqz compress --cmd`).
        let first = process_hook(&bash("git log")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&first).unwrap();
        let rewritten = parsed["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .unwrap();
        let second_input = serde_json::json!({
            "tool_name": "Bash",
            "tool_input": { "command": rewritten }
        })
        .to_string();
        let second = process_hook(&second_input).unwrap();
        assert_eq!(
            second, second_input,
            "already-rewritten commands must pass through unchanged"
        );
    }

    #[test]
    fn test_process_hook_skips_sqz_commands() {
        let input = r#"{"tool_name":"Bash","tool_input":{"command":"sqz stats"}}"#;
        let result = process_hook(input).unwrap();
        assert_eq!(result, input, "sqz commands should not be double-wrapped");
    }

    #[test]
    fn test_process_hook_skips_interactive() {
        let input = r#"{"tool_name":"Bash","tool_input":{"command":"vim file.txt"}}"#;
        let result = process_hook(input).unwrap();
        assert_eq!(result, input, "interactive commands should pass through");
    }

    #[test]
    fn test_process_hook_skips_watch_mode() {
        let input = r#"{"tool_name":"Bash","tool_input":{"command":"npm run dev --watch"}}"#;
        let result = process_hook(input).unwrap();
        assert_eq!(result, input, "watch mode should pass through");
    }

    #[test]
    fn test_process_hook_empty_command() {
        let input = r#"{"tool_name":"Bash","tool_input":{"command":""}}"#;
        let result = process_hook(input).unwrap();
        assert_eq!(result, input);
    }

    #[test]
    fn test_process_hook_gemini_format() {
        // Gemini CLI uses tool_name + tool_input (same field names as Claude Code)
        let input = r#"{"tool_name":"run_shell_command","tool_input":{"command":"git log"}}"#;
        let result = process_hook_gemini(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(parsed.get("decision").is_none(), "the policy engine decides: {parsed}");
        // Gemini format: hookSpecificOutput.tool_input.command (NOT updatedInput)
        let cmd = parsed["hookSpecificOutput"]["tool_input"]["command"].as_str().unwrap();
        assert!(cmd.contains("sqz compress"), "should pipe through sqz: {cmd}");
        // Should NOT have Claude Code fields
        assert!(parsed.get("hookSpecificOutput").unwrap().get("updatedInput").is_none(),
            "Gemini format should not have updatedInput");
        assert!(parsed.get("hookSpecificOutput").unwrap().get("permissionDecision").is_none(),
            "Gemini format should not have permissionDecision");
    }

    #[test]
    fn gemini_tool_input_keeps_every_argument() {
        // The scheduler replaces the call's arguments with tool_input.
        let input = r#"{"tool_name":"run_shell_command","tool_input":{"command":"git log","dir_path":"sub","description":"log"}}"#;
        let parsed: serde_json::Value =
            serde_json::from_str(&process_hook_gemini(input).unwrap()).unwrap();
        let args = &parsed["hookSpecificOutput"]["tool_input"];
        assert_eq!(args["dir_path"], "sub");
        assert_eq!(args["description"], "log");
        assert!(args["command"].as_str().unwrap().contains("sqz compress"));
    }

    #[test]
    fn test_process_hook_legacy_format() {
        // Test backward compatibility with older toolName/toolCall format
        let input = r#"{"toolName":"Bash","permission_mode":"bypassPermissions","toolCall":{"command":"git status"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let cmd = parsed["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap();
        assert!(cmd.contains("sqz compress"), "legacy format should still work: {cmd}");
    }

    #[test]
    fn test_process_hook_cursor_format() {
        // Any answer to a Cursor permission hook is a decision, so there is none.
        for input in [
            r#"{"tool_name":"Shell","tool_input":{"command":"git status"},"conversation_id":"abc"}"#,
            r#"{"hook_event_name":"beforeShellExecution","command":"git status","cwd":"/p"}"#,
            r#"{"hook_event_name":"preToolUse","tool_name":"Shell","tool_input":{"command":"git status"}}"#,
            r#"{"tool_name":"Read","tool_input":{"file_path":"file.txt"}}"#,
            r#"{"tool_name":"Shell","tool_input":{"command":"sqz stats"}}"#,
            "not json",
        ] {
            assert!(process_hook_cursor(input).is_err(), "{input}");
            assert!(process_hook_for_platform(input, HookPlatform::Cursor).is_err(), "{input}");
        }
    }

    #[test]
    fn test_process_hook_windsurf_format() {
        // Windsurf uses agent_action_name + tool_info.command_line
        let input = r#"{"agent_action_name":"pre_run_command","tool_info":{"command_line":"cargo test","cwd":"/project"}}"#;
        let result = process_hook_windsurf(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        // Windsurf uses Claude Code format as best-effort
        let cmd = parsed["hookSpecificOutput"]["updatedInput"]["command"].as_str().unwrap();
        assert!(cmd.contains("sqz compress"), "windsurf format should work: {cmd}");
        assert!(cmd.contains("cargo test"));
        // Issue #10: label is passed as `--cmd`, not `SQZ_CMD=` prefix.
        assert!(
            cmd.contains("--cmd 'cargo test'"),
            "full command must be passed via --cmd flag: {cmd}"
        );
        assert!(!cmd.contains("SQZ_CMD="), "must not emit legacy env prefix: {cmd}");
    }

    #[test]
    fn test_process_hook_invalid_json() {
        let result = process_hook("not json");
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_base_command() {
        assert_eq!(extract_base_command("git status"), "git");
        assert_eq!(extract_base_command("/usr/bin/git log"), "git");
        assert_eq!(extract_base_command("cargo test --release"), "cargo");
    }

    #[test]
    fn test_is_interactive_command() {
        assert!(is_interactive_command("vim file.txt"));
        assert!(is_interactive_command("npm run dev --watch"));
        assert!(is_interactive_command("python3"));
        assert!(!is_interactive_command("git status"));
        assert!(!is_interactive_command("cargo test"));
    }

    // ── Issue #10: Windows shell compatibility ────────────────────────────

    /// The rewritten command must use shell-neutral syntax so it works
    /// in PowerShell and cmd.exe on Windows, not just POSIX shells.
    ///
    /// The old form `SQZ_CMD=val cmd` is sh-specific: PowerShell parses
    /// `SQZ_CMD=val` as a command name (CommandNotFoundException), and
    /// cmd.exe does the same. OpenCode Desktop on Windows routes the
    /// bash tool through PowerShell (or cmd.exe when $SHELL is unset),
    /// so the old form produced zero compression and a spurious error
    /// dialog.
    ///
    /// Reported in issue #10. The fix: pass the label as `--cmd NAME`,
    /// a normal CLI argument that every shell accepts.
    #[test]
    fn issue_10_rewrite_is_shell_neutral() {
        let input = bash("dotnet build NewNeonCheckers3.sln");
        let result = process_hook(&input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let cmd = parsed["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .unwrap();

        // Must use the --cmd flag form, carrying the full command.
        assert!(
            cmd.contains("--cmd 'dotnet build NewNeonCheckers3.sln'"),
            "issue #10: rewrite must pass label via --cmd, got: {cmd}"
        );
        // Must NOT use the sh-specific inline-env-var form.
        assert!(
            !cmd.contains("SQZ_CMD="),
            "issue #10: rewrite must NOT emit `SQZ_CMD=` prefix \
             (broken in PowerShell and cmd.exe), got: {cmd}"
        );
        // Reporter's original command must still be intact.
        assert!(
            cmd.contains("dotnet build NewNeonCheckers3.sln"),
            "original command must be preserved verbatim: {cmd}"
        );
        // And the pipe to sqz must be there.
        assert!(cmd.contains("| sqz compress"), "must pipe through sqz: {cmd}");
    }

    /// The already-wrapped guard must recognise the new `--cmd` form so
    /// that a command the hook has already rewritten doesn't get
    /// wrapped again (causing `… | sqz compress --cmd X 2>&1 | sqz
    /// compress --cmd sqz` chains).
    ///
    /// This is the runaway-prefix bug from issue #5 rephrased for the
    /// new emission form.
    #[test]
    fn issue_10_already_wrapped_command_passes_through() {
        let input = r#"{"tool_name":"Bash","tool_input":{"command":"git status 2>&1 | sqz compress --cmd git"}}"#;
        let result = process_hook(input).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        // The hook must leave an already-wrapped command alone.
        // (When the guard short-circuits we return the input verbatim.)
        assert_eq!(
            result, input,
            "already-wrapped command must pass through unchanged; \
             otherwise each pass accumulates another `| sqz compress` tail"
        );
        // And explicitly verify the non-rewritten `command` is still the
        // original, so someone reading the hook response doesn't think
        // we silently re-wrapped.
        let _ = parsed; // suppress "unused" in case of future assertion adds
    }

    #[test]
    fn test_generate_hook_configs() {
        let configs = generate_hook_configs("sqz");
        assert!(configs.len() >= 5, "should generate configs for multiple tools (including OpenCode)");
        assert!(configs.iter().any(|c| c.tool_name == "Claude Code"));
        assert!(configs.iter().any(|c| c.tool_name == "Cursor"));
        assert!(configs.iter().any(|c| c.tool_name == "OpenCode"));
        // Windsurf, Cline, and Cursor should generate rules files, not hook configs
        // (none of the three support transparent command rewriting via hooks).
        let windsurf = configs.iter().find(|c| c.tool_name == "Windsurf").unwrap();
        assert_eq!(windsurf.config_path, PathBuf::from(".windsurf/rules/sqz.md"),
            "Windsurf should use the .windsurf/rules/ directory (legacy .windsurfrules is deprecated)");
        let cline = configs.iter().find(|c| c.tool_name == "Cline").unwrap();
        assert_eq!(cline.config_path, PathBuf::from(".clinerules"),
            "Cline should use .clinerules, not .clinerules/hooks/PreToolUse");
        // Cursor — empirically verified (forum/Cupcake/GitButler docs +
        // live cursor-agent trace) that beforeShellExecution cannot rewrite
        // commands. Use the modern .cursor/rules/*.mdc format.
        let cursor = configs.iter().find(|c| c.tool_name == "Cursor").unwrap();
        assert_eq!(cursor.config_path, PathBuf::from(".cursor/rules/sqz.mdc"),
            "Cursor should use .cursor/rules/sqz.mdc (modern rules), not \
             .cursor/hooks.json (non-functional) or .cursorrules (legacy)");
        assert!(cursor.config_content.starts_with("---"),
            "Cursor rule should start with YAML frontmatter");
        assert!(cursor.config_content.contains("alwaysApply: true"),
            "Cursor rule should use alwaysApply: true so the guidance loads \
             for every agent interaction");
        assert!(cursor.config_content.contains("sqz"),
            "Cursor rule body should mention sqz");
    }

    #[test]
    fn test_claude_config_includes_precompact_hook() {
        // The PreCompact hook is what keeps sqz's dedup refs from dangling
        // after Claude Code auto-compacts. Without this entry, cached refs
        // can point at content the LLM no longer has in context.
        // Documented at docs.anthropic.com/en/docs/claude-code/hooks-guide.
        let configs = generate_hook_configs("sqz");
        let claude = configs.iter().find(|c| c.tool_name == "Claude Code").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&claude.config_content)
            .expect("Claude Code config must be valid JSON");

        let precompact = parsed["hooks"]["PreCompact"]
            .as_array()
            .expect("PreCompact hook array must be present");
        assert!(
            !precompact.is_empty(),
            "PreCompact must have at least one registered hook"
        );

        let cmd = precompact[0]["hooks"][0]["command"]
            .as_str()
            .expect("command field must be a string");
        assert!(
            cmd.ends_with(" hook precompact"),
            "PreCompact hook should invoke `sqz hook precompact`; got: {cmd}"
        );
    }

    // ── Issue #2: Windows path escaping in hook configs ───────────────

    #[test]
    fn test_json_escape_string_value() {
        // Plain ASCII: unchanged
        assert_eq!(json_escape_string_value("sqz"), "sqz");
        assert_eq!(json_escape_string_value("/usr/local/bin/sqz"), "/usr/local/bin/sqz");
        // Backslash: escaped
        assert_eq!(json_escape_string_value(r"C:\Users\Alice\sqz.exe"),
                   r"C:\\Users\\Alice\\sqz.exe");
        // Double quote: escaped
        assert_eq!(json_escape_string_value(r#"path with "quotes""#),
                   r#"path with \"quotes\""#);
        // Control chars
        assert_eq!(json_escape_string_value("a\nb\tc"), r"a\nb\tc");
    }

    #[test]
    fn test_windows_path_produces_valid_json_for_claude() {
        // Issue #2 repro: on Windows, current_exe() returns a path with
        // backslashes. Without escaping, the generated JSON is invalid.
        let windows_path = r"C:\Users\SqzUser\.cargo\bin\sqz.exe";
        let configs = generate_hook_configs(windows_path);

        let claude = configs.iter().find(|c| c.tool_name == "Claude Code")
            .expect("Claude config should be generated");
        let parsed: serde_json::Value = serde_json::from_str(&claude.config_content)
            .expect("Claude hook config must be valid JSON on Windows paths");

        // Verify the command was written with the original path (not lossy-transformed).
        let cmd = parsed["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
            .as_str()
            .expect("command field must be a string");
        assert!(cmd.contains(windows_path),
            "command '{cmd}' must contain the original Windows path '{windows_path}'");
    }

    #[test]
    fn test_windows_path_in_cursor_rules_file() {
        // Cursor's config is now .cursor/rules/sqz.mdc (markdown), not JSON.
        // Markdown doesn't escape backslashes — the user reads this rule
        // through the agent and needs to see the raw path so commands are
        // pasteable. See test_rules_files_use_raw_path_for_readability for
        // the same property on Windsurf/Cline.
        let windows_path = r"C:\Users\SqzUser\.cargo\bin\sqz.exe";
        let configs = generate_hook_configs(windows_path);

        let cursor = configs.iter().find(|c| c.tool_name == "Cursor").unwrap();
        assert_eq!(cursor.config_path, PathBuf::from(".cursor/rules/sqz.mdc"));
        assert!(cursor.config_content.contains(windows_path),
            "Cursor rule must contain the raw (unescaped) path so users can \
             copy-paste the shown commands — got:\n{}", cursor.config_content);
        assert!(!cursor.config_content.contains(r"C:\\Users"),
            "Cursor rule must NOT double-escape backslashes in markdown — \
             got:\n{}", cursor.config_content);
    }

    #[test]
    fn test_windows_path_produces_valid_json_for_gemini() {
        let windows_path = r"C:\Users\SqzUser\.cargo\bin\sqz.exe";
        let configs = generate_hook_configs(windows_path);

        let gemini = configs.iter().find(|c| c.tool_name == "Gemini CLI").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&gemini.config_content)
            .expect("Gemini hook config must be valid JSON on Windows paths");
        let cmd = parsed["hooks"]["BeforeTool"][0]["hooks"][0]["command"].as_str().unwrap();
        assert!(cmd.contains(windows_path));
    }

    #[test]
    fn test_rules_files_use_raw_path_for_readability() {
        // The .windsurfrules / .clinerules / .cursor/rules/sqz.mdc files are
        // markdown for humans. Backslashes should NOT be doubled there — the
        // user needs to copy-paste the command into their shell.
        let windows_path = r"C:\Users\SqzUser\.cargo\bin\sqz.exe";
        let configs = generate_hook_configs(windows_path);

        for tool in &["Windsurf", "Cline", "Cursor"] {
            let cfg = configs.iter().find(|c| &c.tool_name == tool).unwrap();
            assert!(cfg.config_content.contains(windows_path),
                "{tool} rules file must contain the raw (unescaped) path — got:\n{}",
                cfg.config_content);
            assert!(!cfg.config_content.contains(r"C:\\Users"),
                "{tool} rules file must NOT double-escape backslashes — got:\n{}",
                cfg.config_content);
        }
    }

    #[test]
    fn test_unix_path_still_works() {
        // Regression: make sure the escape path doesn't mangle Unix paths
        // (which have no backslashes to escape).
        let unix_path = "/usr/local/bin/sqz";
        let configs = generate_hook_configs(unix_path);

        let claude = configs.iter().find(|c| c.tool_name == "Claude Code").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&claude.config_content)
            .expect("Unix path should produce valid JSON");
        let cmd = parsed["hooks"]["PreToolUse"][0]["hooks"][0]["command"].as_str().unwrap();
        assert_eq!(cmd, "/usr/local/bin/sqz hook claude");
    }

    #[test]
    fn test_shell_escape_simple() {
        assert_eq!(shell_escape("git"), "git");
        assert_eq!(shell_escape("cargo-test"), "cargo-test");
    }

    #[test]
    fn test_shell_escape_special_chars() {
        assert_eq!(shell_escape("git log --oneline"), "'git log --oneline'");
    }

    fn install_in(project: &Path, home: &Path, sqz: &str) -> Vec<String> {
        install_tool_hooks_at(project, sqz, InstallScope::Project, &ToolFilter::All, Some(home))
    }

    #[test]
    fn user_level_files_go_to_the_given_home() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(home.path().join(".copilot")).unwrap();
        install_in(dir.path(), home.path(), "/opt/sqz");
        for rel in [
            ".claude.json",
            ".codex/config.toml",
            ".config/zed/settings.json",
            ".config/opencode/plugins/sqz.ts",
            ".copilot/hooks/sqz.json",
        ] {
            assert!(home.path().join(rel).exists(), "{rel}");
        }
        let copilot = std::fs::read_to_string(home.path().join(".copilot/hooks/sqz.json")).unwrap();
        assert!(copilot.contains("/opt/sqz hook copilot"));

        let global = tempfile::tempdir().unwrap();
        let filter = ToolFilter::All;
        install_tool_hooks_at(dir.path(), "/opt/sqz", InstallScope::Global, &filter, Some(global.path()));
        for rel in [".claude/settings.json", ".kiro/steering/sqz.md", ".kiro/settings/mcp.json"] {
            assert!(global.path().join(rel).exists(), "{rel}");
        }
    }

    #[test]
    fn test_install_tool_hooks_creates_files() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let installed = install_in(dir.path(), home.path(), "sqz");
        // Should install at least some hooks
        assert!(!installed.is_empty(), "should install at least one hook config");
        // Verify files were created. Copilot CLI installs at user scope
        // (~/.copilot or $COPILOT_HOME), not under the project dir, so its
        // placeholder config_path is not checked here.
        for name in &installed {
            if name == "Copilot CLI" {
                continue;
            }
            let configs = generate_hook_configs("sqz");
            let config = configs.iter().find(|c| &c.tool_name == name).unwrap();
            let path = dir.path().join(&config.config_path);
            assert!(path.exists(), "hook config should exist: {}", path.display());
        }
    }

    #[test]
    fn test_install_tool_hooks_does_not_overwrite() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        // First install
        install_in(dir.path(), home.path(), "sqz");
        // Write a custom file to one of the paths. It is deliberately NOT
        // valid JSON: the Claude Code merge path refuses to touch files it
        // can't parse, and every other tool's config is skip-if-exists.
        let custom_path = dir.path().join(".claude/settings.local.json");
        std::fs::write(&custom_path, "custom content").unwrap();
        // Second install must leave the unparseable file alone.
        install_in(dir.path(), home.path(), "sqz");
        let content = std::fs::read_to_string(&custom_path).unwrap();
        assert_eq!(content, "custom content", "should not overwrite existing config");
    }

    /// Regression for the issue #26 leftover: a project-scope settings file
    /// from a pre-PowerShell install (matcher "Bash", old binary path) must
    /// be upgraded in place when `sqz init` runs again — while every key
    /// the user added themselves survives untouched. The old behavior was
    /// skip-if-exists, which left Windows installs on the stale matcher
    /// forever.
    #[test]
    fn test_reinit_upgrades_stale_project_scope_matcher() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join(".claude").join("settings.local.json");
        std::fs::create_dir_all(settings_path.parent().unwrap()).unwrap();

        // A pre-issue-#26 install: Bash-only matcher, stale binary path,
        // plus keys the user added by hand.
        let stale = serde_json::json!({
            "permissions": { "allow": ["Bash(ls:*)"] },
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Bash",
                        "hooks": [{ "type": "command", "command": "/old/path/sqz hook claude" }]
                    },
                    {
                        "matcher": "Edit",
                        "hooks": [{ "type": "command", "command": "my-linter --check" }]
                    }
                ]
            }
        });
        std::fs::write(&settings_path, serde_json::to_string_pretty(&stale).unwrap()).unwrap();

        let home = tempfile::tempdir().unwrap();
        install_in(dir.path(), home.path(), "/new/path/sqz");

        let content = std::fs::read_to_string(&settings_path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        // sqz's entry: matcher upgraded, binary path refreshed, no duplicate.
        let pre = parsed["hooks"]["PreToolUse"].as_array().unwrap();
        let sqz_entries: Vec<_> = pre
            .iter()
            .filter(|e| {
                e["hooks"][0]["command"]
                    .as_str()
                    .is_some_and(|c| c.contains("hook claude"))
            })
            .collect();
        assert_eq!(sqz_entries.len(), 1, "exactly one sqz PreToolUse entry: {content}");
        assert_eq!(
            sqz_entries[0]["matcher"].as_str().unwrap(),
            "Bash|PowerShell",
            "stale Bash-only matcher must be upgraded"
        );
        assert!(
            sqz_entries[0]["hooks"][0]["command"]
                .as_str()
                .unwrap()
                .contains("/new/path/sqz"),
            "binary path must be refreshed"
        );

        // The user's own entries survive.
        assert!(
            pre.iter().any(|e| e["matcher"] == "Edit"),
            "user's non-sqz PreToolUse entry must be preserved"
        );
        assert_eq!(
            parsed["permissions"]["allow"][0].as_str().unwrap(),
            "Bash(ls:*)",
            "user's permissions must be preserved"
        );

        // The other two sqz hooks got added too (full heal, not partial).
        assert!(parsed["hooks"]["PreCompact"].is_array());
        assert!(parsed["hooks"]["SessionStart"].is_array());
    }

    #[test]
    fn test_windsurf_installs_to_rules_directory() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert!(dir.path().join(".windsurf/rules/sqz.md").exists());
        assert!(!dir.path().join(".windsurfrules").exists());
    }

    fn legacy_rules(sqz: &str) -> String {
        format!(
            "# sqz \u{2014} Token-Optimized CLI Output\n\n```bash\ngit status        git status 2>&1 | {sqz} compress\n```\n\nUse these when you genuinely need raw data. The default compressed\npath is still what you want for most output.\n"
        )
    }

    #[test]
    fn test_windsurf_migrates_legacy_sqz_rules_file() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".windsurfrules"), legacy_rules("sqz")).unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert!(dir.path().join(".windsurf/rules/sqz.md").exists());
        assert!(!dir.path().join(".windsurfrules").exists(), "legacy file migrated");
    }

    #[test]
    fn test_windsurf_migration_keeps_user_rules_after_the_sqz_text() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let legacy = dir.path().join(".windsurfrules");
        std::fs::write(&legacy, format!("{}\n## Team rules\n\nUse tabs.\n", legacy_rules("sqz"))).unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert!(dir.path().join(".windsurf/rules/sqz.md").exists());
        assert_eq!(std::fs::read_to_string(&legacy).unwrap(), "## Team rules\n\nUse tabs.\n");
    }

    #[test]
    fn test_windsurf_leaves_user_legacy_rules_alone() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".windsurfrules"), "my own rules\n").unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert!(dir.path().join(".windsurf/rules/sqz.md").exists());
        assert_eq!(
            std::fs::read_to_string(dir.path().join(".windsurfrules")).unwrap(),
            "my own rules\n"
        );
    }

    #[test]
    fn test_cline_installs_into_rules_directory_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".clinerules")).unwrap();
        std::fs::write(dir.path().join(".clinerules/mine.md"), "user rule\n").unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert!(dir.path().join(".clinerules/sqz.md").exists());
        assert!(dir.path().join(".clinerules/mine.md").exists());
    }

    #[test]
    fn test_cline_single_file_untouched_when_user_authored() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".clinerules"), "user rules\n").unwrap();
        install_in(dir.path(), home.path(), "sqz");
        assert_eq!(
            std::fs::read_to_string(dir.path().join(".clinerules")).unwrap(),
            "user rules\n"
        );
    }

    /// Re-running init on an already-current project file is a no-op.
    #[test]
    fn test_reinit_is_idempotent_at_project_scope() {
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        install_in(dir.path(), home.path(), "/usr/bin/sqz");
        let settings_path = dir.path().join(".claude").join("settings.local.json");
        let first = std::fs::read_to_string(&settings_path).unwrap();

        install_in(dir.path(), home.path(), "/usr/bin/sqz");
        let second = std::fs::read_to_string(&settings_path).unwrap();

        let a: serde_json::Value = serde_json::from_str(&first).unwrap();
        let b: serde_json::Value = serde_json::from_str(&second).unwrap();
        assert_eq!(a, b, "second init must not change project settings");
        // No duplicated sqz entries.
        assert_eq!(b["hooks"]["PreToolUse"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn init_refreshes_old_sqz_rules_in_place() {
        let dir = tempfile::tempdir().unwrap();
        let filter = ToolFilter::Only(vec!["cursor".into(), "windsurf".into(), "cline".into()]);
        let old_cursor = "---\ndescription: sqz \u{2014} Token-Optimized CLI Output\nalwaysApply: true\n---\n\n# sqz \u{2014} Token-Optimized CLI Output\n\ngit status        git status 2>&1 | /old/sqz compress\n";
        std::fs::create_dir_all(dir.path().join(".cursor/rules")).unwrap();
        std::fs::write(dir.path().join(".cursor/rules/sqz.mdc"), old_cursor).unwrap();
        std::fs::write(dir.path().join(".clinerules"), legacy_rules("/old/sqz")).unwrap();

        let installed =
            install_tool_hooks_scoped_filtered(dir.path(), "/new/sqz", InstallScope::Project, &filter);
        assert_eq!(installed, vec!["Cursor", "Windsurf", "Cline"]);
        for (tool, rel) in [
            ("Cursor", ".cursor/rules/sqz.mdc"),
            ("Windsurf", ".windsurf/rules/sqz.md"),
            ("Cline", ".clinerules"),
        ] {
            let content = std::fs::read_to_string(dir.path().join(rel)).unwrap();
            assert_eq!(content, sqz_rules_content(tool, "/new/sqz"), "{tool}");
            assert!(!content.contains('%') && !content.contains('\u{2014}'), "{tool}");
        }
        assert!(
            install_tool_hooks_scoped_filtered(dir.path(), "/new/sqz", InstallScope::Project, &filter)
                .is_empty()
        );
    }

    #[test]
    fn init_leaves_user_written_rules_alone() {
        let dir = tempfile::tempdir().unwrap();
        let cursor = dir.path().join(".cursor/rules/sqz.mdc");
        std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
        std::fs::write(&cursor, "my own rule\n").unwrap();
        let filter = ToolFilter::Only(vec!["cursor".into()]);
        assert!(
            install_tool_hooks_scoped_filtered(dir.path(), "/new/sqz", InstallScope::Project, &filter)
                .is_empty()
        );
        assert_eq!(std::fs::read_to_string(&cursor).unwrap(), "my own rule\n");
    }

    #[test]
    fn rules_refresh_keeps_the_binary_the_old_text_points_at() {
        use crate::kiro_integration::SteeringState;
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("sqz");
        std::fs::write(&bin, "").unwrap();
        let bin = bin.to_string_lossy().to_string();
        let path = dir.path().join("sqz.md");
        std::fs::write(
            &path,
            format!("# sqz \u{2014} Token-Optimized CLI Output\n\ngit status        git status 2>&1 | {bin} compress\n"),
        )
        .unwrap();

        assert_eq!(sqz_rules_state(&path, "Windsurf"), SteeringState::Stale);
        assert!(refresh_sqz_rules(&path, "Windsurf", "/fallback/sqz").unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), sqz_rules_content("Windsurf", &bin));
        assert_eq!(sqz_rules_state(&path, "Windsurf"), SteeringState::Current);
        assert!(!refresh_sqz_rules(&path, "Windsurf", "/fallback/sqz").unwrap());

        std::fs::write(&path, "my own rules\n").unwrap();
        assert_eq!(sqz_rules_state(&path, "Windsurf"), SteeringState::UserAuthored);
        assert!(!refresh_sqz_rules(&path, "Windsurf", "/fallback/sqz").unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "my own rules\n");
    }

    #[test]
    fn cline_rules_keep_the_user_rules_after_them() {
        use crate::kiro_integration::SteeringState;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".clinerules");
        let filter = ToolFilter::Only(vec!["cline".into()]);
        let install = |sqz: &str| {
            install_tool_hooks_scoped_filtered(dir.path(), sqz, InstallScope::Project, &filter)
        };
        let mine = "\n## Team rules\n\nUse tabs.\n";
        std::fs::write(&path, format!("{}{mine}", legacy_rules("/old/sqz"))).unwrap();

        assert_eq!(sqz_rules_state(&path, "Cline"), SteeringState::Stale);
        assert_eq!(install("/new/sqz"), vec!["Cline"]);
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("{}{mine}", sqz_rules_content("Cline", "/new/sqz"))
        );
        assert_eq!(sqz_rules_state(&path, "Cline"), SteeringState::Current);
        assert!(install("/new/sqz").is_empty());

        assert_eq!(install("/other/sqz"), vec!["Cline"]);
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("{}{mine}", sqz_rules_content("Cline", "/other/sqz"))
        );

        assert!(remove_sqz_rules(&path).unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "## Team rules\n\nUse tabs.\n");
        assert!(!has_sqz_rules(&path));
    }

    #[test]
    fn cline_refresh_keeps_the_old_binary_and_the_user_rules() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("sqz");
        std::fs::write(&bin, "").unwrap();
        let bin = bin.to_string_lossy().to_string();
        let path = dir.path().join(".clinerules");
        let v2_ending = "and commands with shell operators. If sqz is\nnot on PATH, run commands normally.\n";
        let old = legacy_rules(&bin).replace(
            "Use these when you genuinely need raw data. The default compressed\npath is still what you want for most output.\n",
            v2_ending,
        );
        std::fs::write(&path, format!("{old}\nUse tabs.\n")).unwrap();

        assert!(refresh_sqz_rules(&path, "Cline", "/fallback/sqz").unwrap());
        let block = sqz_rules_content("Cline", &bin);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), format!("{block}\nUse tabs.\n"));
        assert!(!refresh_sqz_rules(&path, "Cline", "/fallback/sqz").unwrap());

        std::fs::write(&path, format!("{}\nUse tabs.\n", block.replace("sqz_recall", "recall"))).unwrap();
        assert!(refresh_sqz_rules(&path, "Cline", "/fallback/sqz").unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), format!("{block}\nUse tabs.\n"));
    }

    #[test]
    fn cline_rules_without_a_known_end_are_left_alone() {
        use crate::kiro_integration::SteeringState;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".clinerules");
        let edited = "# sqz \u{2014} Token-Optimized CLI Output\n\nPipe output through sqz.\n\n## Team rules\n";
        std::fs::write(&path, edited).unwrap();
        let filter = ToolFilter::Only(vec!["cline".into()]);

        assert_eq!(sqz_rules_state(&path, "Cline"), SteeringState::UserAuthored);
        assert!(
            install_tool_hooks_scoped_filtered(dir.path(), "/new/sqz", InstallScope::Project, &filter)
                .is_empty()
        );
        assert!(!refresh_sqz_rules(&path, "Cline", "/fallback/sqz").unwrap());
        assert!(!remove_sqz_rules(&path).unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), edited);
    }
}

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

    #[test]
    fn global_install_creates_fresh_settings_json() {
        let tmp = tempfile::tempdir().unwrap();
        let changed = install_claude_global_at("/usr/local/bin/sqz", Some(tmp.path())).unwrap();
        assert!(changed, "first install should report a change");

        let path = tmp.path().join(".claude").join("settings.json");
        assert!(path.exists(), "user settings.json should be created");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        // All three hook entries should be present.
        let pre = &parsed["hooks"]["PreToolUse"];
        assert!(pre.is_array(), "PreToolUse should be an array");
        assert_eq!(pre.as_array().unwrap().len(), 1);
        let cmd = pre[0]["hooks"][0]["command"].as_str().unwrap();
        assert!(
            cmd.contains("/usr/local/bin/sqz"),
            "hook command should use the passed sqz_path, got: {cmd}"
        );
        assert!(cmd.contains("hook claude"));

        let precompact = &parsed["hooks"]["PreCompact"];
        assert!(precompact.is_array());
        let precompact_cmd = precompact[0]["hooks"][0]["command"].as_str().unwrap();
        assert!(precompact_cmd.contains("hook precompact"));

        let session = &parsed["hooks"]["SessionStart"];
        assert!(session.is_array());
        assert_eq!(
            session[0]["matcher"].as_str().unwrap(),
            "compact",
            "SessionStart should only match /compact resume"
        );
    }

    #[test]
    fn global_install_preserves_existing_user_config() {
        let tmp = tempfile::tempdir().unwrap();
        let settings = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(settings.parent().unwrap()).unwrap();

        let existing = serde_json::json!({
            "permissions": {
                "allow": ["Bash(npm test *)"],
                "deny":  ["Read(./.env)"]
            },
            "env": { "FOO": "bar" },
            "statusLine": {
                "type": "command",
                "command": "~/.claude/statusline.sh"
            },
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Edit",
                        "hooks": [
                            {
                                "type": "command",
                                "command": "~/.claude/hooks/format-on-edit.sh"
                            }
                        ]
                    }
                ]
            }
        });
        std::fs::write(&settings, serde_json::to_string_pretty(&existing).unwrap()).unwrap();

        let changed = install_claude_global_at("/usr/local/bin/sqz", Some(tmp.path())).unwrap();
        assert!(changed, "install should report a change on new hook");

        let content = std::fs::read_to_string(&settings).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        // User's permissions survived.
        assert_eq!(
            parsed["permissions"]["allow"][0].as_str().unwrap(),
            "Bash(npm test *)"
        );
        assert_eq!(
            parsed["permissions"]["deny"][0].as_str().unwrap(),
            "Read(./.env)"
        );
        // User's env block survived.
        assert_eq!(parsed["env"]["FOO"].as_str().unwrap(), "bar");
        // User's statusLine survived.
        assert_eq!(
            parsed["statusLine"]["command"].as_str().unwrap(),
            "~/.claude/statusline.sh"
        );

        // PreToolUse should now contain BOTH the user's format-on-edit
        // hook and sqz's Bash hook — our install appends, not replaces.
        let pre = parsed["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre.len(), 2, "expected user's hook + sqz's hook, got: {pre:?}");
        let matchers: Vec<&str> = pre
            .iter()
            .map(|e| e["matcher"].as_str().unwrap_or(""))
            .collect();
        assert!(matchers.contains(&"Edit"), "user's Edit hook must survive");
        assert!(
            matchers.contains(&"Bash|PowerShell"),
            "sqz shell hook must be present (Bash|PowerShell matcher covers Windows CC, issue #26)"
        );
    }

    #[test]
    fn global_install_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(install_claude_global_at("sqz", Some(tmp.path())).unwrap());
        assert!(
            !install_claude_global_at("sqz", Some(tmp.path())).unwrap(),
            "second install with identical args should report no change"
        );

        let path = tmp.path().join(".claude").join("settings.json");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        for event in &["PreToolUse", "PreCompact", "SessionStart"] {
            let arr = parsed["hooks"][event].as_array().unwrap();
            assert_eq!(
                arr.len(),
                1,
                "{event} must have exactly one sqz entry after 2 installs, got {arr:?}"
            );
        }
    }

    /// Regression for issue #21: on Windows, `sqz_path` contains `.exe`
    /// so the stored command is `C:\...\sqz.exe hook claude`. The old
    /// sentinel was `"sqz hook claude"` which is NOT a substring of
    /// `"sqz.exe hook claude"` — causing every re-run to append a
    /// duplicate instead of replacing. The fix uses `"hook claude"` as
    /// the sentinel which matches regardless of `.exe`.
    #[test]
    fn global_install_is_idempotent_with_exe_path() {
        let tmp = tempfile::tempdir().unwrap();
        let exe_path = r"C:\Users\user\.cargo\bin\sqz.exe";
        assert!(install_claude_global_at(exe_path, Some(tmp.path())).unwrap());
        assert!(
            !install_claude_global_at(exe_path, Some(tmp.path())).unwrap(),
            "second install with .exe path should report no change (issue #21)"
        );

        let path = tmp.path().join(".claude").join("settings.json");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        for event in &["PreToolUse", "PreCompact", "SessionStart"] {
            let arr = parsed["hooks"][event].as_array().unwrap();
            assert_eq!(
                arr.len(),
                1,
                "{event} must have exactly one entry after 2 installs with .exe path, got {arr:?}"
            );
        }
    }

    #[test]
    fn global_install_upgrades_stale_sqz_hook_in_place() {
        let tmp = tempfile::tempdir().unwrap();
        install_claude_global_at("/old/path/sqz", Some(tmp.path())).unwrap();
        let changed = install_claude_global_at("/new/path/sqz", Some(tmp.path())).unwrap();
        assert!(changed, "different sqz_path must be seen as a change");

        let path = tmp.path().join(".claude").join("settings.json");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let pre = parsed["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre.len(), 1, "stale sqz entry must be replaced, not duplicated");
        let cmd = pre[0]["hooks"][0]["command"].as_str().unwrap();
        assert!(cmd.contains("/new/path/sqz"));
        assert!(!cmd.contains("/old/path/sqz"));
    }

    #[test]
    fn global_uninstall_removes_sqz_and_preserves_the_rest() {
        let tmp = tempfile::tempdir().unwrap();
        let settings = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
        std::fs::write(
            &settings,
            serde_json::json!({
                "permissions": { "allow": ["Bash(git status)"] },
                "hooks": {
                    "PreToolUse": [
                        {
                            "matcher": "Edit",
                            "hooks": [
                                { "type": "command", "command": "~/format.sh" }
                            ]
                        }
                    ]
                }
            })
            .to_string(),
        )
        .unwrap();

        install_claude_global_at("/usr/local/bin/sqz", Some(tmp.path())).unwrap();
        let result = remove_claude_global_hook_at(Some(tmp.path())).unwrap().unwrap();
        assert_eq!(result.0, settings);
        assert!(result.1, "should report that the file was modified");

        assert!(settings.exists(), "settings.json should be preserved");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();

        assert_eq!(
            parsed["permissions"]["allow"][0].as_str().unwrap(),
            "Bash(git status)"
        );

        let pre = parsed["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre.len(), 1, "only the user's Edit hook should remain");
        assert_eq!(pre[0]["matcher"].as_str().unwrap(), "Edit");

        assert!(parsed["hooks"].get("PreCompact").is_none());
        assert!(parsed["hooks"].get("SessionStart").is_none());
    }

    #[test]
    fn global_uninstall_deletes_settings_json_if_it_was_sqz_only() {
        let tmp = tempfile::tempdir().unwrap();
        install_claude_global_at("sqz", Some(tmp.path())).unwrap();
        let path = tmp.path().join(".claude").join("settings.json");
        assert!(path.exists(), "precondition: install created the file");

        let result = remove_claude_global_hook_at(Some(tmp.path())).unwrap().unwrap();
        assert!(result.1);
        assert!(!path.exists(), "sqz-only settings.json should be removed on uninstall");
    }

    #[test]
    fn only_commands_that_run_sqz_count_as_sqz_hooks() {
        for (command, args) in [
            ("sqz hook claude", "hook claude"),
            ("/usr/local/bin/sqz hook claude-post", "hook claude-post"),
            (r"C:\Users\me\.cargo\bin\sqz.exe hook precompact", "hook precompact"),
            ("C:/Users/Jane Doe/.cargo/bin/sqz.EXE resume", "resume"),
            (r"C:\Users\Jane Doe\.cargo\bin\sqz.exe hook claude", "hook claude"),
            ("/Users/Jane Doe/bin/sqz resume", "resume"),
            ("~/.cargo/bin/sqz hook claude", "hook claude"),
            ("\"/opt/sqz\" hook claude", "hook claude"),
            ("'/opt/my tools (x86)/sqz' hook claude-post", "hook claude-post"),
        ] {
            assert!(sqz_command_binary(command, args).is_some(), "{command}");
        }
        for (command, args) in [
            ("/usr/local/bin/on-resume.sh", "resume"),
            ("~/bin/save-notes --hook precompact", "hook precompact"),
            ("~/bin/audit-hook claude", "hook claude"),
            ("echo hi && /usr/bin/sqz hook claude", "hook claude"),
            ("nice -n 5 sqz hook claude", "hook claude"),
            ("/usr/bin/time /opt/sqz hook claude", "hook claude"),
            ("/usr/bin/env SQZ_NO_DEDUP=1 /opt/sqz hook claude", "hook claude"),
            ("/usr/bin/nice -n 5 /opt/sqz hook claude", "hook claude"),
            ("/usr/bin/time ~/bin/sqz hook claude", "hook claude"),
            ("sqz hook claude --verbose", "hook claude"),
            ("notsqz hook claude", "hook claude"),
            ("sqz hook claude-post", "hook claude"),
            ("\"/opt/sqz hook claude", "hook claude"),
            ("\"$HOME/bin/sqz\" hook claude", "hook claude"),
            ("\"/opt/notsqz\" hook claude", "hook claude"),
        ] {
            assert!(sqz_command_binary(command, args).is_none(), "{command}");
        }
    }

    #[test]
    fn legacy_hook_files_lose_only_sqz_hooks() {
        let project = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let write = |root: &Path, rel: &str, text: &str| {
            let path = root.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, text).unwrap();
            path
        };
        let p = project.path();
        let cursor = write(
            p,
            ".cursor/hooks.json",
            r#"{"version":1,"hooks":{"beforeShellExecution":[{"command":"/opt/sqz hook cursor"},{"command":"./audit.sh"}]}}"#,
        );
        let windsurf = write(p, ".windsurf/hooks.json", r#"{"hooks":{"pre_run_command":[{"command":"/opt/sqz hook windsurf"}]}}"#);
        let cline = write(
            p,
            ".cline/hooks.json",
            r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"sqz hook cline"}]}]}}"#,
        );
        let script = write(p, ".clinerules/hooks/PreToolUse", &LEGACY_CLINE_SCRIPT.replace('\n', "\r\n"));
        let user_cursor = write(
            home.path(),
            ".cursor/hooks.json",
            r#"{"version":1,"hooks":{"preToolUse":[{"command":"C:/tools/sqz.exe hook cursor","matcher":"Shell"}]}}"#,
        );

        let all = vec![cursor.clone(), windsurf.clone(), cline.clone(), script.clone(), user_cursor.clone()];
        assert_eq!(legacy_sqz_hook_files_at(p, Some(home.path())), all);
        assert_eq!(
            remove_legacy_sqz_hooks_at(p, Some(home.path())).unwrap(),
            vec![(cursor.clone(), false), (windsurf, true), (cline, true), (script.clone(), true), (user_cursor, true)]
        );
        let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap();
        assert_eq!(v, serde_json::json!({"version": 1, "hooks": {"beforeShellExecution": [{"command": "./audit.sh"}]}}));
        assert!(legacy_sqz_hook_files_at(p, Some(home.path())).is_empty());

        write(p, ".clinerules/hooks/PreToolUse", &LEGACY_CLINE_SCRIPT.replace("exit 0", "exit 1"));
        assert!(legacy_sqz_hook_files_at(p, Some(home.path())).is_empty(), "an edited script is the user's");
    }

    #[test]
    fn hook_binaries_are_read_from_every_hook_file_kind() {
        let dir = tempfile::tempdir().unwrap();
        let settings = dir.path().join("settings.json");
        std::fs::write(&settings, claude_settings_content("/opt/sqz")).unwrap();
        assert_eq!(sqz_hook_binaries(&settings), vec!["/opt/sqz"]);
        let copilot = dir.path().join("sqz.json");
        std::fs::write(&copilot, copilot_hook_content("C:\\tools\\sqz.exe")).unwrap();
        assert_eq!(sqz_hook_binaries(&copilot), vec!["C:\\tools\\sqz.exe"]);
        let plugin = dir.path().join("sqz.ts");
        std::fs::write(&plugin, crate::opencode_plugin::generate_opencode_plugin("/gone/sqz")).unwrap();
        assert_eq!(sqz_hook_binaries(&plugin), vec!["/gone/sqz"]);
        let user = dir.path().join("user.json");
        std::fs::write(
            &user,
            r#"{"hooks":{"PreCompact":[{"hooks":[{"command":"~/bin/save-notes --hook precompact"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"command":"/usr/bin/time /opt/sqz hook claude"}]}]}}"#,
        )
        .unwrap();
        assert!(sqz_hook_binaries(&user).is_empty());
    }

    #[test]
    fn refresh_never_points_a_hook_at_a_missing_binary() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        let old = r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"/gone/sqz hook claude"}]}]}}"#;
        std::fs::write(&path, old).unwrap();
        assert!(refresh_claude_settings(&path, "/also-gone/sqz").is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), old);
    }

    #[test]
    fn hook_binaries_resolve_to_files_without_running_them() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("my tools").join("sqz");
        std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
        std::fs::write(&bin, "").unwrap();
        let shown = bin.to_string_lossy().to_string();
        assert_eq!(resolve_sqz_binary(&shown), Some(bin.clone()));
        assert_eq!(resolve_sqz_binary(&format!("\"{shown}\"")), Some(bin.clone()));
        assert_eq!(resolve_sqz_binary(&format!("{shown}-gone")), None);
        assert_eq!(resolve_sqz_binary("sqz-not-on-any-path-xyz"), None);
    }

    #[test]
    fn user_hooks_that_look_like_sqz_ones_are_kept() {
        let tmp = tempfile::tempdir().unwrap();
        let settings = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
        let cmd = |c: &str| serde_json::json!({"type": "command", "command": c});
        let user = serde_json::json!({
            "hooks": {
                "SessionStart": [
                    {"matcher": "resume", "hooks": [cmd("/usr/local/bin/on-resume.sh")]},
                    {"matcher": "startup", "hooks": [cmd("echo user-startup")]}
                ],
                "PreCompact": [{"hooks": [cmd("~/bin/save-notes --hook precompact")]}],
                "PreToolUse": [{"matcher": "Bash", "hooks": [
                    cmd("~/bin/audit-hook claude"),
                    cmd("/usr/bin/env SQZ_NO_DEDUP=1 /opt/sqz hook claude")
                ]}]
            }
        });
        let text = serde_json::to_string_pretty(&user).unwrap();
        std::fs::write(&settings, &text).unwrap();
        let read = || -> serde_json::Value {
            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap()
        };

        assert_eq!(remove_claude_global_hook_at(Some(tmp.path())).unwrap(), Some((settings.clone(), false)));
        assert_eq!(std::fs::read_to_string(&settings).unwrap(), text);

        assert!(install_claude_global_at("/opt/sqz", Some(tmp.path())).unwrap());
        assert!(!install_claude_global_at("/opt/sqz", Some(tmp.path())).unwrap());
        let installed = read();
        for (event, user_count) in [("SessionStart", 2), ("PreCompact", 1), ("PreToolUse", 1)] {
            let arr = installed["hooks"][event].as_array().unwrap();
            assert_eq!(arr.len(), user_count + 1, "{event}: {arr:?}");
            assert_eq!(arr[..user_count], user["hooks"][event].as_array().unwrap()[..], "{event}");
        }

        let mut shared = installed.clone();
        shared["hooks"]["PreToolUse"][1]["hooks"]
            .as_array_mut()
            .unwrap()
            .push(cmd("echo also-mine"));
        std::fs::write(&settings, serde_json::to_string_pretty(&shared).unwrap()).unwrap();
        assert!(remove_claude_global_hook_at(Some(tmp.path())).unwrap().unwrap().1);
        let mut expected = user.clone();
        expected["hooks"]["PreToolUse"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::json!({"matcher": "Bash|PowerShell", "hooks": [cmd("echo also-mine")]}));
        assert_eq!(read(), expected);
    }

    #[test]
    fn project_install_leaves_claude_hooks_to_the_user_level_ones() {
        let home = tempfile::tempdir().unwrap();
        let project = tempfile::tempdir().unwrap();
        install_claude_global_at("/opt/sqz", Some(home.path())).unwrap();
        let filter = ToolFilter::Only(vec!["claudecode".to_string()]);
        let installed =
            install_tool_hooks_at(project.path(), "/opt/sqz", InstallScope::Project, &filter, Some(home.path()));
        assert_eq!(installed, vec!["Claude Code"]);
        assert!(!project.path().join(".claude").join("settings.local.json").exists());
        assert!(project.path().join("CLAUDE.md").exists());
    }

    #[test]
    fn duplicate_project_hooks_go_and_permissions_stay() {
        let project = tempfile::tempdir().unwrap();
        let local = project.path().join(".claude").join("settings.local.json");
        std::fs::create_dir_all(local.parent().unwrap()).unwrap();
        std::fs::write(&local, claude_settings_content("/opt/sqz")).unwrap();
        assert!(claude_settings_have_sqz_hooks(&local));
        assert!(remove_claude_project_hooks_only(project.path()).unwrap().unwrap().1);
        let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&local).unwrap()).unwrap();
        assert_eq!(v, serde_json::json!({"permissions": {"allow": CLAUDE_ALLOW_RULES}}));
        assert!(!claude_settings_have_sqz_hooks(&local));

        let hook = r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"sqz hook claude"}]}]}}"#;
        std::fs::write(&local, hook).unwrap();
        assert!(remove_claude_project_hooks_only(project.path()).unwrap().unwrap().1);
        assert!(!local.exists());
    }

    #[test]
    fn settings_rewrites_keep_the_final_newline_and_mode() {
        let tmp = tempfile::tempdir().unwrap();
        let settings = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
        let text = "{\n  \"theme\": \"dark\"\n}\n";
        std::fs::write(&settings, text).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&settings, std::fs::Permissions::from_mode(0o644)).unwrap();
        }

        assert!(install_claude_global_at("/opt/sqz", Some(tmp.path())).unwrap());
        assert!(std::fs::read_to_string(&settings).unwrap().ends_with("}\n"));
        assert!(remove_claude_global_hook_at(Some(tmp.path())).unwrap().unwrap().1);
        assert_eq!(std::fs::read_to_string(&settings).unwrap(), text);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&settings).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o644);
        }
    }

    #[test]
    fn global_uninstall_on_missing_file_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(
            remove_claude_global_hook_at(Some(tmp.path())).unwrap().is_none(),
            "missing file should return None, not error"
        );
    }

    #[test]
    fn global_uninstall_refuses_to_touch_unparseable_file() {
        let tmp = tempfile::tempdir().unwrap();
        let settings = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
        std::fs::write(&settings, "{ invalid json because").unwrap();

        assert!(
            remove_claude_global_hook_at(Some(tmp.path())).is_err(),
            "bad JSON must surface as an error"
        );

        let after = std::fs::read_to_string(&settings).unwrap();
        assert_eq!(after, "{ invalid json because");
    }
}

#[cfg(test)]
mod issue_11_tool_filter_tests {
    //! Regression tests for issue #11 (@shochdoerfer): let the user
    //! choose for which agent sqz init creates configs.
    //!
    //! Every assertion here pins a behaviour the filter should have.
    //! If any one of these flips, users are either getting configs for
    //! tools they asked to skip OR getting no config for tools they
    //! explicitly asked for — both are issue #11 regressions.

    use super::*;

    #[test]
    fn canonicalize_collapses_common_aliases() {
        // Each row: list of aliases a user might type, followed by the
        // canonical form they should all normalise to.
        for aliases in &[
            (vec!["Claude Code", "claude-code", "claude", "CLAUDE", "ClaudeCode"], "claudecode"),
            (vec!["Cursor", "cursor", "CURSOR"], "cursor"),
            (vec!["Windsurf", "WINDSURF"], "windsurf"),
            // Cline is also marketed as "Roo Code" — sqz treats them
            // as one integration (same .clinerules file) so the
            // aliases must collapse.
            (vec!["Cline", "cline", "Roo", "roo-code", "RooCode"], "cline"),
            (vec!["Gemini CLI", "gemini-cli", "gemini", "GEMINI"], "gemini"),
            (vec!["OpenCode", "open-code", "opencode", "OPENCODE"], "opencode"),
            (vec!["Codex", "codex"], "codex"),
        ] {
            for alias in &aliases.0 {
                assert_eq!(
                    canonicalize_tool_name(alias),
                    aliases.1,
                    "alias '{}' must canonicalise to '{}'",
                    alias,
                    aliases.1
                );
            }
        }
    }

    #[test]
    fn canonicalize_leaves_unknown_names_unchanged_but_normalised() {
        // Unknown names fall through — we don't guess. The caller
        // (parse_tool_list) is responsible for turning unknown values
        // into user-facing errors; canonicalize itself just
        // normalises case, whitespace, and hyphens/underscores.
        assert_eq!(canonicalize_tool_name("unknown-tool"), "unknowntool");
        assert_eq!(canonicalize_tool_name("Some Thing"), "something");
    }

    #[test]
    fn parse_tool_list_accepts_comma_separated_with_whitespace() {
        // Typical shell invocation: `--only opencode,codex` or
        // `--only "opencode, codex"` — both should work.
        let names = parse_tool_list("opencode,codex").unwrap();
        assert_eq!(names, vec!["opencode", "codex"]);

        let names = parse_tool_list(" opencode ,  codex ").unwrap();
        assert_eq!(names, vec!["opencode", "codex"]);

        // Single entry.
        let names = parse_tool_list("opencode").unwrap();
        assert_eq!(names, vec!["opencode"]);

        // Alias with hyphen.
        let names = parse_tool_list("claude-code").unwrap();
        assert_eq!(names, vec!["claudecode"]);
    }

    #[test]
    fn parse_tool_list_dedupes_repeated_entries() {
        // `--only opencode,opencode` shouldn't produce two "opencode"
        // entries that the filter then matches twice. Harmless today
        // but tomorrow someone could code `filter.allow.len()` against
        // it and silently count wrong.
        let names = parse_tool_list("opencode,opencode").unwrap();
        assert_eq!(names, vec!["opencode"]);

        // Same name via different aliases still dedupes because they
        // canonicalise to the same string.
        let names = parse_tool_list("Claude Code, claude, claude-code").unwrap();
        assert_eq!(names, vec!["claudecode"]);
    }

    #[test]
    fn parse_tool_list_rejects_unknown_names_with_helpful_error() {
        // This is the critical failure path: a typo in --only must
        // fail, not silently drop. Otherwise the user runs `sqz init
        // --only opncode` (typo), sees "OK" with nothing installed,
        // and spends 20 minutes figuring out why. The error message
        // must list valid options verbatim so they can spot their
        // typo.
        let err = parse_tool_list("opncode").unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unknown agent name 'opncode'"),
            "error must quote the bad input: {msg}"
        );
        assert!(msg.contains("opencode"), "error must list valid options: {msg}");
        assert!(msg.contains("cursor"), "error must list valid options: {msg}");
    }

    #[test]
    fn parse_tool_list_rejects_one_bad_entry_in_a_list() {
        // `--only opencode,xyz` — fail the whole list, don't just drop
        // xyz. User either typed a typo they need to see, or they
        // don't understand the vocabulary — in both cases pretending
        // the input was valid hurts them.
        let err = parse_tool_list("opencode,xyz").unwrap_err();
        assert!(err.to_string().contains("xyz"));
    }

    #[test]
    fn parse_tool_list_empty_and_whitespace_return_empty_vec() {
        // `--only ""` and `--only "   "` produce an empty filter —
        // semantically "install nothing" rather than "install all".
        // cmd_init surfaces this as ToolFilter::Only(empty) which
        // skips every config file but still installs the shell hook
        // and preset.
        assert_eq!(parse_tool_list("").unwrap(), Vec::<String>::new());
        assert_eq!(parse_tool_list("   ").unwrap(), Vec::<String>::new());
        assert_eq!(parse_tool_list(" , , ").unwrap(), Vec::<String>::new());
    }

    #[test]
    fn tool_filter_all_includes_every_supported_tool() {
        let filter = ToolFilter::All;
        for tool in SUPPORTED_TOOL_NAMES {
            assert!(
                filter.includes(tool),
                "default filter must include {tool}"
            );
        }
    }

    #[test]
    fn tool_filter_only_opencode_excludes_everything_else() {
        // The exact scenario from issue #11.
        let filter = ToolFilter::Only(vec!["opencode".to_string()]);
        assert!(filter.includes("OpenCode"));
        // Every other supported tool is rejected.
        for tool in SUPPORTED_TOOL_NAMES {
            if *tool == "OpenCode" {
                continue;
            }
            assert!(
                !filter.includes(tool),
                "--only opencode must not include {tool}"
            );
        }
    }

    #[test]
    fn tool_filter_only_multi_tool_includes_exactly_those() {
        let filter = ToolFilter::Only(vec!["opencode".to_string(), "codex".to_string()]);
        assert!(filter.includes("OpenCode"));
        assert!(filter.includes("Codex"));
        // Everything else: excluded.
        assert!(!filter.includes("Claude Code"));
        assert!(!filter.includes("Cursor"));
        assert!(!filter.includes("Windsurf"));
        assert!(!filter.includes("Cline"));
        assert!(!filter.includes("Gemini CLI"));
    }

    #[test]
    fn tool_filter_skip_inverts_the_set() {
        // `--skip cursor,windsurf` means "install everything except
        // those two." Opposite of --only.
        let filter = ToolFilter::Skip(vec!["cursor".to_string(), "windsurf".to_string()]);
        assert!(!filter.includes("Cursor"));
        assert!(!filter.includes("Windsurf"));
        // Everything else stays on.
        assert!(filter.includes("Claude Code"));
        assert!(filter.includes("Cline"));
        assert!(filter.includes("Gemini CLI"));
        assert!(filter.includes("OpenCode"));
        assert!(filter.includes("Codex"));
    }

    #[test]
    fn tool_filter_only_empty_excludes_everything() {
        // Edge: `--only ""` → empty filter → nothing passes. This is
        // semantically "install no AI-tool configs, just the shell
        // hook and preset." Surprising if the user typed it by
        // accident, but consistent — the plan output will show only
        // shell/preset lines and the user can abort.
        let filter = ToolFilter::Only(vec![]);
        for tool in SUPPORTED_TOOL_NAMES {
            assert!(
                !filter.includes(tool),
                "empty --only must exclude every tool, got {tool}"
            );
        }
    }

    #[test]
    fn tool_filter_only_accepts_display_name_or_canonical() {
        // The filter lives in the engine; callers pass the
        // display-name strings ("Claude Code", "Gemini CLI") straight
        // from generate_hook_configs. But filter entries come from
        // the CLI via parse_tool_list, which canonicalises. Both
        // sides must line up — assert the cross-path works.
        let filter = ToolFilter::Only(vec!["claudecode".to_string()]);
        assert!(filter.includes("Claude Code"));
        assert!(!filter.includes("Cursor"));

        let filter = ToolFilter::Only(vec!["gemini".to_string()]);
        assert!(filter.includes("Gemini CLI"));
    }

    #[test]
    fn supported_tool_names_matches_generate_hook_configs_exactly() {
        // Invariant: the SUPPORTED_TOOL_NAMES constant (used in error
        // messages, docs, tests) must match the tool_name fields the
        // config generator actually emits. If someone adds a new tool
        // config but forgets to add its name to the constant, this
        // test fails loudly.
        let configs = generate_hook_configs("sqz");
        let emitted: std::collections::HashSet<&str> =
            configs.iter().map(|c| c.tool_name.as_str()).collect();
        let declared: std::collections::HashSet<&str> =
            SUPPORTED_TOOL_NAMES.iter().copied().collect();
        assert_eq!(
            emitted, declared,
            "SUPPORTED_TOOL_NAMES must equal the set of tool_name values \
             from generate_hook_configs. emitted={:?}, declared={:?}",
            emitted, declared
        );
    }

    #[test]
    fn filtered_install_only_opencode_writes_only_opencode_files() {
        // End-to-end: exercise install_tool_hooks_scoped_filtered
        // against a tempdir and assert that only OpenCode's files
        // appear. This is the single most important regression for
        // issue #11: no Cursor rules, no Windsurf rules, no Cline
        // rules, no Gemini settings, no AGENTS.md, no .claude/.
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let filter = ToolFilter::Only(vec!["opencode".to_string()]);
        let _installed = install_tool_hooks_at(
            dir.path(),
            "sqz",
            InstallScope::Project,
            &filter,
            Some(home.path()),
        );

        // OpenCode SHOULD be there.
        assert!(
            dir.path().join("opencode.json").exists(),
            "OpenCode config must be written when --only opencode is used"
        );

        // None of the other agents' files should exist.
        for (path, tool) in &[
            (".claude/settings.local.json", "Claude Code"),
            (".cursor/rules/sqz.mdc", "Cursor"),
            (".windsurfrules", "Windsurf"),
            (".clinerules", "Cline"),
            (".gemini/settings.json", "Gemini CLI"),
            ("AGENTS.md", "Codex"),
        ] {
            assert!(
                !dir.path().join(path).exists(),
                "filter rejected {tool} but the installer still wrote {path}"
            );
        }
    }

    #[test]
    fn filtered_install_skip_cursor_omits_only_cursor() {
        // Symmetric: --skip cursor should leave everything else intact.
        let dir = tempfile::tempdir().unwrap();
        let home = tempfile::tempdir().unwrap();
        let filter = ToolFilter::Skip(vec!["cursor".to_string()]);
        let _installed = install_tool_hooks_at(
            dir.path(),
            "sqz",
            InstallScope::Project,
            &filter,
            Some(home.path()),
        );

        // Cursor rules must NOT exist.
        assert!(
            !dir.path().join(".cursor/rules/sqz.mdc").exists(),
            "skip cursor: .cursor/rules/sqz.mdc must not be written"
        );
        // Windsurf and Cline rules SHOULD still exist.
        assert!(
            dir.path().join(".windsurf/rules/sqz.md").exists(),
            "skip cursor should not skip windsurf"
        );
        assert!(
            dir.path().join(".clinerules").exists(),
            "skip cursor should not skip cline"
        );
    }
}

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

    #[test]
    fn ci_hook_content_is_valid_v1_config() {
        let parsed: serde_json::Value =
            serde_json::from_str(&ci_hook_content()).expect("CI hook must be valid JSON");
        assert_eq!(parsed["version"], 1);
        let session_start = parsed["hooks"]["sessionStart"].as_array().unwrap();
        assert!(session_start[0]["bash"]
            .as_str()
            .unwrap()
            .contains("install.sh"));
        let pre = parsed["hooks"]["preToolUse"].as_array().unwrap();
        let bash = pre[0]["bash"].as_str().unwrap();
        assert!(bash.contains("hook copilot"));
        // Fail-closed platform: every branch must end in output, never
        // a bare non-zero exit.
        assert!(bash.ends_with("echo '{}'"));
        assert_eq!(pre[0]["matcher"], "bash|powershell");
    }

    #[test]
    fn install_ci_hook_creates_then_noops() {
        let dir = tempfile::tempdir().unwrap();
        assert!(install_ci_hook(dir.path()).unwrap());
        let path = ci_hooks_path(dir.path());
        assert!(path.exists());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), ci_hook_content());
        // Second run: unchanged content, no rewrite reported.
        assert!(!install_ci_hook(dir.path()).unwrap());
    }

    #[test]
    fn install_ci_hook_refreshes_stale_sqz_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = ci_hooks_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, r#"{"version":1,"hooks":{"preToolUse":[{"bash":"sqz hook copilot"}]}}"#).unwrap();
        assert!(install_ci_hook(dir.path()).unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), ci_hook_content());
    }

    #[test]
    fn install_ci_hook_leaves_user_file_alone() {
        let dir = tempfile::tempdir().unwrap();
        let path = ci_hooks_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, r#"{"version":1,"hooks":{}}"#).unwrap();
        assert!(!install_ci_hook(dir.path()).unwrap());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            r#"{"version":1,"hooks":{}}"#
        );
    }

    #[test]
    fn remove_ci_hook_only_removes_sqz_authored() {
        let dir = tempfile::tempdir().unwrap();
        // Missing file: no-op.
        assert!(!remove_ci_hook(dir.path()).unwrap());
        // sqz-authored: removed.
        install_ci_hook(dir.path()).unwrap();
        assert!(remove_ci_hook(dir.path()).unwrap());
        assert!(!ci_hooks_path(dir.path()).exists());
        // User-owned: left alone.
        let path = ci_hooks_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "{}").unwrap();
        assert!(!remove_ci_hook(dir.path()).unwrap());
        assert!(path.exists());
    }

    fn read_json(path: &Path) -> serde_json::Value {
        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
    }

    #[test]
    fn claude_install_adds_the_post_hook_and_allow_rules_once() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join(".claude").join("settings.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, r#"{"permissions":{"allow":["Bash(npm test)"],"deny":["Bash(rm *)"]}}"#)
            .unwrap();
        assert!(install_claude_global_at("/usr/local/bin/sqz", Some(tmp.path())).unwrap());
        let v = read_json(&path);
        assert_eq!(
            v["permissions"]["allow"],
            serde_json::json!(["Bash(npm test)", "Bash(set -o pipefail)", "Bash(sqz compress --cmd *)"])
        );
        assert_eq!(v["permissions"]["deny"], serde_json::json!(["Bash(rm *)"]));
        assert_eq!(v["hooks"]["PostToolUse"][0]["matcher"], "Bash");
        assert_eq!(
            v["hooks"]["PostToolUse"][0]["hooks"][0]["command"],
            "/usr/local/bin/sqz hook claude-post"
        );
        assert!(claude_rules_installed(&[path.clone()]));
        assert!(!install_claude_global_at("/usr/local/bin/sqz", Some(tmp.path())).unwrap());

        let (_, changed) = remove_claude_global_hook_at(Some(tmp.path())).unwrap().unwrap();
        assert!(changed);
        assert_eq!(
            read_json(&path),
            serde_json::json!({"permissions": {"allow": ["Bash(npm test)"], "deny": ["Bash(rm *)"]}})
        );
    }

    #[test]
    fn gemini_merge_and_removal_touch_only_sqz_entries() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".gemini").join("settings.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let mine = serde_json::json!({"matcher": "write_file", "hooks": [{"type": "command", "command": "lint"}]});
        let settings = serde_json::json!({"theme": "x", "hooks": {"BeforeTool": [mine, gemini_hook_entry("/old/sqz")]}});
        std::fs::write(&path, settings.to_string()).unwrap();

        assert!(gemini_settings_has_sqz(&path));
        assert!(gemini_settings_needs_update(&path, "/new/sqz").unwrap());
        assert!(merge_sqz_gemini_hook(&path, "/new/sqz").unwrap());
        assert!(!gemini_settings_needs_update(&path, "/new/sqz").unwrap());
        assert!(!merge_sqz_gemini_hook(&path, "/new/sqz").unwrap());
        assert_eq!(
            read_json(&path)["hooks"]["BeforeTool"],
            serde_json::json!([mine, gemini_hook_entry("/new/sqz")])
        );

        let (_, changed) = remove_sqz_from_gemini_settings(dir.path()).unwrap().unwrap();
        assert!(changed);
        assert_eq!(
            read_json(&path),
            serde_json::json!({"theme": "x", "hooks": {"BeforeTool": [mine]}})
        );
        assert!(!gemini_settings_has_sqz(&path));
        assert_eq!(remove_sqz_from_gemini_settings(dir.path()).unwrap(), Some((path.clone(), false)));

        std::fs::write(&path, "{\n  // comment\n  \"theme\": \"x\"\n}\n").unwrap();
        assert!(gemini_settings_needs_update(&path, "/new/sqz").is_err());
        assert!(!merge_sqz_gemini_hook(&path, "/new/sqz").unwrap_or(false));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\n  // comment\n  \"theme\": \"x\"\n}\n");
    }

    #[test]
    fn fresh_project_settings_carry_the_rules_and_post_hook() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.local.json");
        std::fs::write(&path, claude_settings_content("/usr/bin/sqz")).unwrap();
        assert!(claude_rules_installed(&[path.clone()]));
        assert_eq!(
            read_json(&path)["hooks"]["PostToolUse"][0]["hooks"][0]["command"],
            "/usr/bin/sqz hook claude-post"
        );
        assert!(!claude_project_settings_needs_update(&path, "/usr/bin/sqz").unwrap());

        // A file from before the rules existed needs the update.
        let mut old = read_json(&path);
        old.as_object_mut().unwrap().remove("permissions");
        std::fs::write(&path, old.to_string()).unwrap();
        assert!(claude_settings_stale(&path));
        assert!(claude_project_settings_needs_update(&path, "/usr/bin/sqz").unwrap());
        assert!(merge_sqz_hooks_into_settings(&path, "/usr/bin/sqz").unwrap());
        assert!(!claude_settings_stale(&path));
    }

    #[test]
    fn project_uninstall_keeps_permissions_claude_saved() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".claude").join("settings.local.json");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, claude_settings_content("/usr/bin/sqz")).unwrap();
        // "Yes, and don't ask again" lands in the same file.
        let mut v = read_json(&path);
        v["permissions"]["allow"].as_array_mut().unwrap().push(serde_json::json!("Bash(make)"));
        std::fs::write(&path, v.to_string()).unwrap();

        let (_, changed) = remove_claude_project_hook(dir.path()).unwrap().unwrap();
        assert!(changed);
        assert_eq!(read_json(&path), serde_json::json!({"permissions": {"allow": ["Bash(make)"]}}));

        // A file holding only sqz's entries goes away entirely.
        std::fs::write(&path, claude_settings_content("/usr/bin/sqz")).unwrap();
        remove_claude_project_hook(dir.path()).unwrap();
        assert!(!path.exists());
        assert!(remove_claude_project_hook(dir.path()).unwrap().is_none());
    }

    fn post(command: &str, response: serde_json::Value) -> String {
        serde_json::json!({
            "hook_event_name": "PostToolUse",
            "tool_name": "Bash",
            "tool_input": {"command": command},
            "tool_response": response,
        })
        .to_string()
    }

    #[test]
    fn post_tool_use_picks_successful_bash_output_sqz_never_saw() {
        let ok = serde_json::json!({"stdout": "out", "stderr": "", "interrupted": false, "isImage": false});
        let t = claude_post_tool_use_target(&post("cargo test | tail -5", ok.clone())).unwrap();
        assert_eq!(t.label, "sh: cargo test | tail -5");
        assert_eq!(serde_json::Value::Object(t.response), ok);
        // One command with output: its formatter can run.
        let t = claude_post_tool_use_target(&post("cd a && cargo test", ok.clone())).unwrap();
        assert_eq!(t.label, "cargo test");

        let skipped = [
            post("set -o pipefail; ls 2>&1 | sqz compress --cmd ls", ok.clone()),
            post("sqz stats", ok.clone()),
            post("ls", serde_json::json!({"stdout": "x", "isImage": true})),
            post("ls", serde_json::json!({"stdout": "x", "interrupted": true})),
            post("ls", serde_json::json!({"content": "x"})),
            post("ls", serde_json::json!({"stdout": "a".repeat(30_000), "stderr": ""})),
            serde_json::json!({"hook_event_name": "PreToolUse", "tool_name": "Bash",
                "tool_input": {"command": "ls"}, "tool_response": ok}).to_string(),
            serde_json::json!({"hook_event_name": "PostToolUse", "tool_name": "Read",
                "tool_input": {"file_path": "/x"}, "tool_response": ok}).to_string(),
            serde_json::json!({"hook_event_name": "PostToolUse", "tool_name": "Bash",
                "tool_input": {"command": "make", "run_in_background": true}, "tool_response": ok}).to_string(),
            "not json".to_string(),
        ];
        for input in skipped {
            assert_eq!(claude_post_tool_use_target(&input), None, "{input}");
        }
    }
}