tokenix 0.67.0

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

use regex::Regex;
use rust_embed::Embed;
use serde::Deserialize;

mod blocks;
mod regex_lint;
mod trust;
pub use blocks::BlockCap;
pub use regex_lint::regex_issues;
pub use trust::{repo_input_hashes, repo_inputs_trusted, set_repo_inputs_trust};

#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct MatchOutput {
    pub pattern: String,
    pub message: String,
    /// Guard: when set, the short-circuit to `message` is skipped if the output
    /// also matches this regex. Prevents masking errors/warnings that appear
    /// alongside a success marker (e.g. "total size is" present, but so is "error").
    #[serde(default)]
    pub unless: Option<String>,
}

/// See `FilterDef::uniform_success`.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct UniformSuccess {
    /// The per-item pass shape every significant line must match.
    pub pattern: String,
    /// Summary to emit. `{n}` is replaced with the number of matched items,
    /// so the agent gets a real count instead of a bare "all clear".
    pub message: String,
    /// Lines to ignore entirely when deciding uniformity (banners, totals).
    #[serde(default)]
    pub ignore_lines: Vec<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct FilterDef {
    #[allow(dead_code)]
    pub description: Option<String>,
    pub match_command: String,
    /// When set, this filter is skipped (candidate falls through to the next
    /// filter or raw passthrough) if the matched candidate ALSO matches this
    /// regex. Use for commands where certain flags mean the agent already
    /// bounded its own output (e.g. `Get-Content -Tail`) and further
    /// compression would be redundant or could clip output the agent
    /// explicitly asked for. Only sees the matched segment/candidate text,
    /// not cross-segment context (e.g. a stripped-off pipe target).
    #[serde(default)]
    pub skip_when_matches: Option<String>,
    /// When true, a `max_lines`/`head_lines`/`tail_lines`/`truncate_lines_at`
    /// cut that actually drops content appends a `[... N ... ]` marker, so
    /// the agent knows it saw a partial view. Off by default — most bundled
    /// filters compress noise the agent doesn't need to know was cut; opt in
    /// per-filter where a silent cut could mislead (e.g. full-file reads).
    #[serde(default)]
    pub notify_on_truncate: bool,
    #[serde(default)]
    pub strip_ansi: bool,
    #[serde(default)]
    pub strip_lines_matching: Vec<String>,
    #[serde(default)]
    pub keep_lines_matching: Vec<String>,
    pub max_lines: Option<usize>,
    pub head_lines: Option<usize>,
    pub tail_lines: Option<usize>,
    pub on_empty: Option<String>,
    /// When the filter reduces *non-empty* command output to nothing — usually an
    /// unexpected output shape the keep/extract rules don't recognize (e.g.
    /// `git log --oneline` against a filter tuned for the full log format) — emit a
    /// bounded, ANSI-stripped view of the real output instead of `on_empty`.
    /// Opt-in so summary filters (cargo test all-pass → "ok") keep their behavior;
    /// only format-specific filters that would otherwise report a *false* "nothing
    /// here" (git-log, git-diff) set it.
    #[serde(default)]
    pub passthrough_when_emptied: bool,
    #[serde(default)]
    pub match_output: Vec<MatchOutput>,
    /// Whole-run success assertion for tools that report **per item**
    /// (`PASS - policy`, `ok 1 - test`, `[200] url`, `file is valid`).
    ///
    /// `match_output` is the wrong tool for those: it fires when *some* line
    /// matches, so a run where item 3 failed would still be reported as
    /// success. This collapses only when EVERY significant line matches the
    /// pass shape and at least one did — a single dissenting line (a failure,
    /// a warning, an unrecognized shape) leaves the normal pipeline in charge.
    /// That makes the summary a claim about the run, not about one line.
    pub uniform_success: Option<UniformSuccess>,
    pub truncate_lines_at: Option<usize>,
    #[serde(default)]
    #[allow(dead_code)]
    pub filter_stderr: bool,

    /// Regex replacement rules: each entry is [pattern, replacement].
    /// Applied after line filtering, before sizing. Enables custom transformations
    /// like shortening paths, normalizing timestamps, etc.
    #[serde(default)]
    pub replace_patterns: Vec<[String; 2]>,

    /// Extract only content between start/end markers (inclusive).
    /// Useful for pulling out specific sections like test failures, error blocks, etc.
    #[serde(default)]
    pub extract_sections: Vec<ExtractSection>,

    /// Keyword filter: keep only lines that share a term with a query.
    /// Keeps lines that share a keyword with the query.
    #[serde(default)]
    pub semantic_filter: Option<SemanticFilterDef>,

    /// Deduplicate similar blocks (not just exact lines).
    /// Groups consecutive blocks by structural similarity.
    #[serde(default)]
    pub deduplicate_blocks: Option<DeduplicateBlocksDef>,

    /// Intelligent JSON summarization beyond simple compaction.
    /// Extracts key fields, summarizes arrays, preserves structure.
    #[serde(default)]
    pub summarize_json: Option<SummarizeJsonDef>,

    /// Hard token budget: truncate intelligently to stay under token limit.
    /// Prioritizes head/tail/errors/semantic relevance.
    pub token_budget: Option<usize>,

    /// Failure policy applied when the run wrapper observed a nonzero exit:
    /// "passthrough" emits the raw output untouched; "tail:N" emits the last
    /// N raw lines. Unset = normal filtering (success sentinels are still
    /// suppressed on failure — see `apply_filter_with_exit`).
    #[serde(default)]
    pub on_failure: Option<String>,

    /// Lines matching any of these regexes survive every sizing cut
    /// (max/head/tail), even beyond the line budget — for verdict lines that
    /// must never be clipped (error summaries, totals).
    #[serde(default)]
    pub priority_lines: Vec<String>,

    /// Per-category caps: keep only the first `max` lines matching `pattern`,
    /// replacing the overflow with a single count marker. Bounds repetitive
    /// classes independently (e.g. 20 errors + 5 warnings) instead of a flat
    /// positional cut that may spend the whole budget on one class.
    #[serde(default)]
    pub category_caps: Vec<CategoryCap>,
    /// Keep only the first `max_lines` of each block opened by `start` (see
    /// `blocks::BlockCap`). Runs before `strip_lines_matching`.
    #[serde(default)]
    pub block_caps: Vec<BlockCap>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct CategoryCap {
    pub pattern: String,
    pub max: usize,
}

#[derive(Debug, Deserialize, Clone)]
pub struct ExtractSection {
    pub start_pattern: String,
    pub end_pattern: String,
    #[serde(default)]
    pub include_markers: bool,
    #[serde(default)]
    pub max_matches: Option<usize>,
    /// Lines kept per matched section (markers included); the rest collapse
    /// into one `[... N lines omitted ...]` marker for that section.
    #[serde(default)]
    pub max_lines: Option<usize>,
    /// A start line inside an open section begins the next section instead of
    /// being content of the current one — for records that are delimited only
    /// by their own header (`commit …`). Off: consecutive `npm ERR!` lines are
    /// one section.
    #[serde(default)]
    pub split_on_start: bool,
}

#[derive(Debug, Deserialize, Clone)]
pub struct SemanticFilterDef {
    /// Query to score relevance against (e.g., "error", "test failure", "build output")
    pub query: String,
    /// Ignored (relevance is keyword overlap); kept so old filter files still parse.
    #[allow(dead_code)]
    #[serde(default = "default_semantic_threshold")]
    pub threshold: f32,
    /// Always keep lines matching these patterns regardless of score
    #[serde(default)]
    pub always_keep: Vec<String>,
    /// Ignored; kept so old filter files still parse.
    #[allow(dead_code)]
    pub model: Option<String>,
}

fn default_semantic_threshold() -> f32 {
    0.3
}

#[derive(Debug, Deserialize, Clone)]
pub struct DeduplicateBlocksDef {
    /// Minimum lines per block to consider for deduplication
    #[serde(default = "default_min_block_lines")]
    pub min_block_lines: usize,
    /// Similarity threshold for block comparison (0.0-1.0)
    #[serde(default = "default_block_similarity")]
    pub similarity: f32,
    /// Regex to identify block boundaries (default: blank line)
    #[serde(default)]
    pub block_delimiter: Option<String>,
}

fn default_min_block_lines() -> usize {
    3
}

fn default_block_similarity() -> f32 {
    0.8
}

#[derive(Debug, Deserialize, Clone)]
pub struct SummarizeJsonDef {
    /// Max array elements to show before summarizing
    #[serde(default = "default_max_array_items")]
    pub max_array_items: usize,
    /// Max object depth to traverse
    #[serde(default = "default_max_depth")]
    pub max_depth: usize,
    /// Fields to always include (dot notation for nested)
    #[serde(default)]
    pub always_include: Vec<String>,
    /// Fields to exclude
    #[serde(default)]
    pub exclude: Vec<String>,
}

fn default_max_array_items() -> usize {
    10
}

fn default_max_depth() -> usize {
    3
}

#[derive(Debug, Deserialize)]
struct FilterFile {
    #[serde(default)]
    filters: HashMap<String, FilterDef>,
}

pub struct ActiveFilter {
    pub name: String,
    pub source: &'static str,
    pub filter: FilterDef,
}

#[derive(Embed)]
#[folder = "assets/filters"]
#[include = "*.toml"]
// Rebuild trigger for new filters
struct BundledFilters;

pub fn filters_dir() -> PathBuf {
    crate::store::global_dir()
        .unwrap_or_else(|| PathBuf::from(".tokenix"))
        .join("filters")
}

/// Content up to the first `[[tests.…]]` block. Golden cases are ~60% of the
/// bytes in the bundled corpus and are never needed to *use* a filter, so the
/// loader lexes only the head. Returns `None` when there is no test block.
fn filter_defs_head(content: &str) -> Option<&str> {
    let mut offset = 0usize;
    for line in content.split_inclusive('\n') {
        let t = line.trim_start();
        if t.starts_with("[[tests") || t.starts_with("[tests") {
            return Some(&content[..offset]);
        }
        offset += line.len();
    }
    None
}

/// Number of `[filters.x]` tables declared anywhere in the file. Used to detect
/// a head slice that cut before a later declaration; a line scan is enough
/// because a `[filters.` at line start is always a table header in TOML.
fn count_filter_tables(content: &str) -> usize {
    content
        .lines()
        .filter(|l| l.trim_start().starts_with("[filters."))
        .count()
}

fn parse_filter_file_named(content: &str) -> Vec<(String, FilterDef)> {
    // Fast path: parse only the definitions. Falls through to the full parse
    // when the head does not parse (a multi-line value containing a `[[tests`
    // line), yields nothing, or — the silent case — declares FEWER filters
    // than the whole file, which means the cut landed before a later
    // `[filters.x]` table and would have dropped it without any error.
    if let Some(head) = filter_defs_head(content) {
        if let Ok(f) = toml::from_str::<FilterFile>(head) {
            // Enforce the guard the comment above promises. A `[filters.x]` table
            // declared *after* a `[[tests]]` block leaves the head slice parsing
            // cleanly while silently dropping `x`, so compare declaration counts
            // first — a line scan, not a second full TOML parse, to keep the
            // hot path cheap.
            if !f.filters.is_empty() && count_filter_tables(content) == f.filters.len() {
                return f.filters.into_iter().collect();
            }
        }
    }
    match toml::from_str::<FilterFile>(content) {
        Ok(f) => f.filters.into_iter().collect(),
        Err(e) => {
            // Fail loudly: FilterDef rejects unknown fields, so a typo'd key
            // must surface instead of silently disabling the whole file.
            eprintln!("tokenix: skipping invalid filter file: {e}");
            Vec::new()
        }
    }
}

pub fn load_user_filters() -> Vec<FilterDef> {
    load_user_filters_named()
        .into_iter()
        .map(|(_, f)| f)
        .collect()
}

pub fn load_user_filters_named() -> Vec<(String, FilterDef)> {
    let dir = filters_dir();
    if !dir.exists() {
        return vec![];
    }
    let mut result = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("toml") {
                if let Ok(content) = std::fs::read_to_string(&path) {
                    result.extend(parse_filter_file_named(&content));
                }
            }
        }
    }
    result
}

/// This repo's `.tokenix/filters` directory.
pub fn local_filters_dir() -> PathBuf {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    crate::store::find_project_root(&cwd)
        .join(".tokenix")
        .join("filters")
}

pub fn load_local_filters_named() -> Vec<(String, FilterDef)> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let root = crate::store::find_project_root(&cwd);
    let dir = root.join(".tokenix").join("filters");
    if !dir.exists() {
        return vec![];
    }
    // Trust gate: silently skip untrusted repo-local filters in the hot path
    // (a warning here would leak into every filtered command's stderr).
    // `tokenix trust` reports the pending state interactively.
    if !repo_inputs_trusted(&root) {
        return vec![];
    }
    let mut result = Vec::new();
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("toml") {
                if let Ok(content) = std::fs::read_to_string(&path) {
                    result.extend(parse_filter_file_named(&content));
                }
            }
        }
    }
    result
}

pub fn load_local_filters() -> Vec<FilterDef> {
    load_local_filters_named()
        .into_iter()
        .map(|(_, f)| f)
        .collect()
}

pub fn load_bundled_filters() -> Vec<FilterDef> {
    load_bundled_filters_named()
        .into_iter()
        .map(|(_, f)| f)
        .collect()
}

pub fn load_bundled_filters_named() -> Vec<(String, FilterDef)> {
    BundledFilters::iter()
        .filter_map(|name| {
            let file = BundledFilters::get(&name)?;
            let content = std::str::from_utf8(file.data.as_ref()).ok()?;
            Some(parse_filter_file_named(content))
        })
        .flatten()
        .collect()
}

/// Prefilters of every `match_command` in one filter file, read straight off
/// the raw TOML text. `None` means "cannot be prefiltered" (a pattern shape
/// this cheap scan does not recognize) and the file is always parsed.
///
/// The scan only ever produces a *shorter* literal than the parsed pattern
/// would (escapes stop it early), so it can add work but never skip a file
/// that would have matched.
fn scan_bundled_anchors(content: &str) -> Option<Vec<Prefilter>> {
    let mut anchors = Vec::new();
    let mut headers = 0usize;
    for line in content.lines() {
        let t = line.trim_start();
        if t.starts_with("[[tests") || t.starts_with("[tests") {
            break; // golden cases live after the filter definitions
        }
        if t.starts_with("[filters.") {
            headers += 1;
            continue;
        }
        let Some(rest) = t.strip_prefix("match_command") else {
            continue;
        };
        let rest = rest.trim_start().strip_prefix('=')?.trim_start();
        let quote = rest.chars().next()?;
        if quote != '"' && quote != '\'' {
            return None; // multi-line/exotic string: fall back to parsing
        }
        let body = &rest[quote.len_utf8()..];
        if quote == '\'' {
            // Literal string: no escapes to undo.
            anchors.push(prefilter_for(&body[..body.find('\'')?])?);
            continue;
        }
        let end = {
            let mut prev_escape = false;
            let mut found = None;
            for (i, c) in body.char_indices() {
                if prev_escape {
                    prev_escape = false;
                    continue;
                }
                match c {
                    '\\' => prev_escape = true,
                    '"' => {
                        found = Some(i);
                        break;
                    }
                    _ => {}
                }
            }
            found?
        };
        // Basic string: undo the escapes a regex actually uses. Any other
        // escape is left as-is, which can only stop the literal run earlier.
        let unescaped = body[..end].replace("\\\\", "\\").replace("\\\"", "\"");
        anchors.push(prefilter_for(&unescaped)?);
    }
    // Every `[filters.x]` block must have contributed exactly one prefilter,
    // otherwise the scan missed a pattern and the file must be parsed.
    (headers > 0 && anchors.len() == headers).then_some(anchors)
}

fn any_allows(anchors: &Option<Vec<Prefilter>>, candidates: &[String]) -> bool {
    match anchors {
        None => true,
        Some(anchors) => anchors
            .iter()
            .any(|a| candidates.iter().any(|c| a.allows(c))),
    }
}

/// One user filter file as recorded in the on-disk prefilter index. `mtime`
/// and `len` are the validity stamp: any drift rebuilds the whole index.
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
struct UserFilterEntry {
    file: String,
    /// Nanoseconds since the epoch — see `user_filter_stats`.
    mtime: u128,
    len: u64,
    /// `None` = pattern shape the scanner cannot prefilter; always parsed.
    prefilters: Option<Vec<Prefilter>>,
}

fn user_filter_index_path(dir: &std::path::Path) -> PathBuf {
    dir.join(".prefilter-index.json")
}

/// `(name, mtime, len)` for every `*.toml` in the user filter dir, sorted by
/// name. One directory scan, no file reads.
///
/// `mtime` is nanoseconds, not seconds: two edits inside the same second that
/// keep the byte length identical (a one-character pattern fix) would leave a
/// second-resolution stamp unchanged, and the filter would silently keep
/// matching by its stale prefilter.
fn user_filter_stats(dir: &std::path::Path) -> Vec<(String, u128, u64)> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return vec![];
    };
    let mut stats: Vec<(String, u128, u64)> = entries
        .flatten()
        .filter_map(|e| {
            let path = e.path();
            if path.extension().and_then(|x| x.to_str()) != Some("toml") {
                return None;
            }
            let name = path.file_name()?.to_str()?.to_string();
            let meta = e.metadata().ok()?;
            let mtime = meta
                .modified()
                .ok()?
                .duration_since(std::time::UNIX_EPOCH)
                .ok()?
                .as_nanos();
            Some((name, mtime, meta.len()))
        })
        .collect();
    stats.sort();
    stats
}

/// Prefilter index for the user filter dir, rebuilt whenever the directory
/// listing drifts from what was recorded (added/removed/edited file).
///
/// Validity is decided from metadata only — reading every file is exactly the
/// cost this index exists to avoid. Residual limitation: two writes that keep
/// the byte length identical *and* land inside the same filesystem timestamp
/// tick (~15 ms on Windows) are indistinguishable. The blast radius is bounded
/// to a **missed** match — the `FilterDef` itself is always re-parsed from disk
/// for entries the prefilter admits, so a stale entry can cost compression but
/// can never apply the wrong filter to a command.
fn user_filter_index(dir: &std::path::Path) -> Vec<UserFilterEntry> {
    let stats = user_filter_stats(dir);
    let cached: Vec<UserFilterEntry> = std::fs::read_to_string(user_filter_index_path(dir))
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default();
    let matches_disk = cached.len() == stats.len()
        && cached
            .iter()
            .zip(&stats)
            .all(|(c, (name, mtime, len))| c.file == *name && c.mtime == *mtime && c.len == *len);
    if matches_disk {
        return cached;
    }

    use rayon::prelude::*;
    let rebuilt: Vec<UserFilterEntry> = stats
        .par_iter()
        .map(|(name, mtime, len)| UserFilterEntry {
            file: name.clone(),
            mtime: *mtime,
            len: *len,
            prefilters: std::fs::read_to_string(dir.join(name))
                .ok()
                .and_then(|c| scan_bundled_anchors(&c)),
        })
        .collect();
    if let Ok(json) = serde_json::to_string(&rebuilt) {
        let path = user_filter_index_path(dir);
        // Per-process temp name: parallel hooks otherwise write the SAME temp
        // file concurrently and rename an interleaved, corrupt index into
        // place. (A corrupt index self-heals via the rebuild path, but it
        // makes every hook pay the rebuild until someone wins the race.)
        let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
        // Best effort: a failed write only costs the next run a rebuild.
        if std::fs::write(&tmp, json).is_ok() && std::fs::rename(&tmp, &path).is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
    }
    rebuilt
}

/// User filters (`~/.tokenix/filters`) that can match `candidates`.
///
/// A user with hundreds of generated filters otherwise pays ~15 ms of file
/// I/O on every hook call just to discover that one of them matches. The
/// index keeps the per-file prefilters on disk, so a hook only opens the
/// files that can actually match.
fn load_user_filters_matching(candidates: &[String]) -> Vec<FilterDef> {
    let dir = filters_dir();
    if !dir.exists() {
        return vec![];
    }
    use rayon::prelude::*;
    user_filter_index(&dir)
        .par_iter()
        .filter(|e| any_allows(&e.prefilters, candidates))
        .filter_map(|e| {
            let content = std::fs::read_to_string(dir.join(&e.file)).ok()?;
            Some(parse_filter_file_named(&content))
        })
        .flatten()
        .map(|(_, f)| f)
        .collect()
}

/// Bundled files indexed by their prefilters, built once per process.
fn bundled_anchor_index() -> &'static [(String, Option<Vec<Prefilter>>)] {
    use std::sync::OnceLock;
    static INDEX: OnceLock<Vec<(String, Option<Vec<Prefilter>>)>> = OnceLock::new();
    INDEX.get_or_init(|| {
        BundledFilters::iter()
            .filter_map(|name| {
                let file = BundledFilters::get(&name)?;
                let content = std::str::from_utf8(file.data.as_ref()).ok()?;
                Some((name.to_string(), scan_bundled_anchors(content)))
            })
            .collect()
    })
}

/// Bundled filters whose file can possibly match one of `candidates`.
///
/// Parsing all 528 bundled TOML files costs ~29 ms; a hook process only ever
/// needs the handful whose literals appear in the command it was handed. The
/// prefilter is the same necessary condition `find_filter` applies per
/// pattern, so the surviving set contains every filter the full load would
/// have matched.
fn load_bundled_filters_matching(candidates: &[String]) -> Vec<FilterDef> {
    bundled_anchor_index()
        .iter()
        .filter(|(_, anchors)| any_allows(anchors, candidates))
        .filter_map(|(name, _)| {
            let file = BundledFilters::get(name)?;
            let content = std::str::from_utf8(file.data.as_ref()).ok()?;
            Some(parse_filter_file_named(content))
        })
        .flatten()
        .map(|(_, f)| f)
        .collect()
}

/// Local + user filters (always parsed — a handful of files) plus only the
/// bundled filters that can match `cmd`. Drop-in replacement for
/// `load_all_filters()` on the single-command hot path (hook rewrite,
/// `tokenix run`), where the full bundled set is never needed.
/// Filters that can match `cmd`, kept in their source groups:
/// `[local, user, bundled]`. `find_filter` resolves collisions by pattern
/// length, which alone would let a long bundled pattern beat a user filter that
/// was meant to override it — so precedence has to live in the grouping.
pub fn load_filter_groups_for_command(cmd: &str) -> Vec<Vec<FilterDef>> {
    let candidates = prioritized_candidates(cmd);
    vec![
        load_local_filters(),
        load_user_filters_matching(&candidates),
        load_bundled_filters_matching(&candidates),
    ]
}

/// First group (local > user > bundled) that yields a match wins; within a
/// group the longest — most specific — `match_command` still wins.
pub fn find_filter_ranked<'a>(cmd: &str, groups: &'a [Vec<FilterDef>]) -> Option<&'a FilterDef> {
    groups.iter().find_map(|g| find_filter(cmd, g))
}

/// First embedded `[[tests.<name>]].input` of one filter file, keyed by filter
/// name.
fn samples_in(content: &str) -> HashMap<String, String> {
    #[derive(Deserialize)]
    struct SampleCase {
        input: String,
    }
    #[derive(Deserialize)]
    struct TestsOnly {
        #[serde(default)]
        tests: HashMap<String, Vec<SampleCase>>,
    }
    let mut map = HashMap::new();
    if let Ok(parsed) = toml::from_str::<TestsOnly>(content) {
        for (fname, cases) in parsed.tests {
            if let Some(first) = cases.into_iter().next() {
                map.entry(fname).or_insert(first.input);
            }
        }
    }
    map
}

/// Representative sample output per filter name, used by the shell's preview
/// (input → `apply_filter` → output).
///
/// Covers user and project filters too, not just bundled ones: a filter the
/// user just generated carries its own `[[tests]]` and would otherwise show
/// "no embedded sample" in the one place built to inspect it. Local overrides
/// user overrides bundled, matching filter precedence.
pub fn sample_inputs() -> HashMap<String, String> {
    let mut map = HashMap::new();
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let root = crate::store::find_project_root(&cwd);
    // Untrusted repo-local files are not just skipped as filters — their
    // samples must not be shown either, or a cloned repo could put its own
    // text in the preview pane under a bundled filter's name.
    let mut dirs = vec![filters_dir()];
    if repo_inputs_trusted(&root) {
        dirs.insert(0, local_filters_dir());
    }
    for dir in dirs {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("toml") {
                continue;
            }
            if let Ok(content) = std::fs::read_to_string(&path) {
                for (name, input) in samples_in(&content) {
                    map.entry(name).or_insert(input);
                }
            }
        }
    }
    for name in BundledFilters::iter() {
        let Some(file) = BundledFilters::get(&name) else {
            continue;
        };
        let Ok(content) = std::str::from_utf8(file.data.as_ref()) else {
            continue;
        };
        for (name, input) in samples_in(content) {
            map.entry(name).or_insert(input);
        }
    }
    map
}

/// Bundled-filter inventory for `tokenix doctor`: total embedded golden test
/// cases across every bundled filter file.
pub fn bundled_test_case_count() -> usize {
    #[derive(Deserialize)]
    struct TestsOnly {
        #[serde(default)]
        tests: HashMap<String, Vec<toml::Value>>,
    }
    let mut count = 0;
    for name in BundledFilters::iter() {
        let Some(file) = BundledFilters::get(&name) else {
            continue;
        };
        let Ok(content) = std::str::from_utf8(file.data.as_ref()) else {
            continue;
        };
        if let Ok(parsed) = toml::from_str::<TestsOnly>(content) {
            count += parsed.tests.values().map(|v| v.len()).sum::<usize>();
        }
    }
    count
}

pub fn load_active_filters() -> Vec<ActiveFilter> {
    let mut result: Vec<ActiveFilter> = load_local_filters_named()
        .into_iter()
        .map(|(name, filter)| ActiveFilter {
            name,
            source: "local",
            filter,
        })
        .collect();
    result.extend(
        load_user_filters_named()
            .into_iter()
            .map(|(name, filter)| ActiveFilter {
                name,
                source: "user",
                filter,
            }),
    );
    result.extend(
        load_bundled_filters_named()
            .into_iter()
            .map(|(name, filter)| ActiveFilter {
                name,
                source: "bundled",
                filter,
            }),
    );
    result
}

/// Returns local filters (highest priority), then user filters, then bundled filters as fallback.
pub fn load_all_filters() -> Vec<FilterDef> {
    let mut all = load_local_filters();
    all.extend(load_user_filters());
    all.extend(load_bundled_filters());
    all
}

/// Notes on a filter's `semantic_filter`: `model` and `threshold` no longer do
/// anything (relevance is keyword overlap), and a line with no query term is
/// dropped unless `always_keep` matches it. Used by `tokenix doctor`.
pub fn semantic_filter_issues(f: &FilterDef) -> Vec<String> {
    let Some(sem) = &f.semantic_filter else {
        return Vec::new();
    };
    let mut issues = Vec::new();
    if sem.model.is_some() {
        issues.push("semantic_filter.model is ignored (embeddings were removed)".to_string());
    }
    if sem.threshold != default_semantic_threshold() {
        issues.push("semantic_filter.threshold is ignored (keyword overlap only)".to_string());
    }
    if sem.always_keep.is_empty() {
        issues.push(
            "semantic_filter drops lines sharing no query term; add always_keep for failure markers"
                .to_string(),
        );
    }
    issues
}

/// Message for a pattern that failed to compile. Bundled filters can never hit
/// this path (`every_bundled_filter_regex_compiles` gates the corpus in CI), so
/// in practice the pattern always came from a user or repo-local filter file —
/// point at the one command that inventories those (`tokenix doctor`, via
/// `regex_issues`) instead of just naming the pattern, or the only way to find
/// which file it came from is grepping every `*.toml` under `~/.tokenix/filters`
/// and `<repo>/.tokenix/filters` by hand.
fn invalid_regex_warning(pattern: &str, err: &regex::Error) -> String {
    format!(
        "tokenix: ignoring invalid filter regex {pattern:?}: {err} \
         (run `tokenix doctor` to see which filter file this is in)"
    )
}

/// Process-wide compiled-regex cache. The hook is a short-lived process that
/// evaluates hundreds of `match_command` patterns against a handful of
/// candidate strings — each pattern must compile at most once per process,
/// not once per (pattern × candidate) pair.
fn cached_regex(pattern: &str) -> Option<Regex> {
    use std::sync::{OnceLock, RwLock};
    static CACHE: OnceLock<RwLock<HashMap<String, Option<Regex>>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| RwLock::new(HashMap::new()));
    if let Some(hit) = cache.read().ok().and_then(|c| c.get(pattern).cloned()) {
        return hit;
    }
    let compiled = match Regex::new(pattern) {
        Ok(re) => Some(re),
        Err(e) => {
            // Warn once per pattern (the cache makes this idempotent). A typo'd
            // regex used to make the filter silently no-op with no diagnostic
            // anywhere — the file loaded "successfully" and simply never worked.
            eprintln!("{}", invalid_regex_warning(pattern, &e));
            None
        }
    };
    if let Ok(mut c) = cache.write() {
        c.insert(pattern.to_string(), compiled.clone());
    }
    compiled
}

/// Length of the leading run of characters that are literal in a regex.
/// `.` and `+` are metacharacters and must end the run — `^go.mod` matches
/// `goXmod`, so treating the `.` as literal would let the prefilter reject a
/// real match.
fn literal_run(s: &str) -> usize {
    s.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-')))
        .unwrap_or(s.len())
}

/// True when `pattern` has a top-level `|` alternation — a `|` outside any
/// group or character class, and not escaped.
///
/// This is what makes a leading-literal prefilter unsound: in
/// `^Select-String\b|\|\s*Select-String\b` only the FIRST branch is anchored,
/// so `Get-Content x | Select-String ERROR` is a real match that does not
/// start with the literal. No single literal is necessary for such a pattern.
fn has_top_level_alternation(pattern: &str) -> bool {
    let (mut depth, mut in_class, mut escaped) = (0i32, false, false);
    for c in pattern.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        match c {
            '\\' => escaped = true,
            '[' if !in_class => in_class = true,
            ']' if in_class => in_class = false,
            '(' if !in_class => depth += 1,
            ')' if !in_class => depth -= 1,
            '|' if !in_class && depth <= 0 => return true,
            _ => {}
        }
    }
    false
}

/// Literal start-anchor of a pattern (`^cargo\s+test` → `cargo`) when the
/// pattern begins with `^` followed by a plain literal. Cheap NECESSARY
/// condition: a candidate that doesn't start with the literal can never match
/// the anchored regex, so its compilation is skipped entirely.
fn literal_anchor(pattern: &str) -> Option<&str> {
    let rest = pattern.strip_prefix('^')?;
    let end = literal_run(rest);
    (end >= 2).then(|| &rest[..end])
}

/// A cheap necessary condition for a pattern to match a candidate. Evaluating
/// it costs a substring scan; failing it skips a regex compilation (~100 µs
/// cold), which is what a short-lived hook process spends most of its time on.
#[derive(Debug, Clone, PartialEq, Deserialize, serde::Serialize)]
enum Prefilter {
    /// Anchored pattern: the candidate must start with this literal.
    StartsWith(String),
    /// Unanchored but mandatory literal: the candidate must contain it.
    /// `bool` = case-insensitive (pattern carries a leading `(?i)`).
    Contains(String, bool),
}

impl Prefilter {
    fn allows(&self, candidate: &str) -> bool {
        match self {
            Prefilter::StartsWith(lit) => candidate.starts_with(lit.as_str()),
            Prefilter::Contains(lit, false) => candidate.contains(lit.as_str()),
            Prefilter::Contains(lit, true) => candidate.to_lowercase().contains(lit.as_str()),
        }
    }
}

/// First literal that every match of `pattern` must contain, for the shapes
/// this repo's filters actually use: a leading `\b`, an optional group
/// (`^(npx\s+)?eslint`), and `(?i)` flags. Everything else returns `None` and
/// is evaluated by compiling the regex — the prefilter may only skip work.
fn prefilter_for(pattern: &str) -> Option<Prefilter> {
    // Checked once, up front: with a top-level alternation no single literal
    // is mandatory, so neither the anchor nor the contains form is sound.
    if has_top_level_alternation(pattern) {
        return None;
    }
    if let Some(anchor) = literal_anchor(pattern) {
        return Some(Prefilter::StartsWith(anchor.to_string()));
    }
    let mut s = pattern;
    let mut ci = false;
    if let Some(rest) = s.strip_prefix("(?i)") {
        ci = true;
        s = rest;
    }
    // Walk past zero-width assertions and optional groups: none of them can
    // consume the mandatory literal that follows.
    loop {
        if let Some(r) = s.strip_prefix('^') {
            s = r;
        } else if let Some(r) = s.strip_prefix("\\b") {
            s = r;
        } else if s.starts_with('(') {
            let close = s.find(')')?;
            if s[1..close].contains('(') {
                return None; // nested group: out of scope for this scanner
            }
            // Only an OPTIONAL group can be skipped; a mandatory one (an
            // alternation) means no single literal is guaranteed, so bail.
            s = s[close + 1..].strip_prefix('?')?;
        } else {
            break;
        }
    }
    let end = literal_run(s);
    let mut lit = &s[..end];
    // A quantifier right after the run makes its last character optional.
    if matches!(s[end..].chars().next(), Some('?') | Some('*') | Some('{')) {
        lit = &lit[..lit.len().saturating_sub(1)];
    }
    (lit.len() >= 3).then(|| {
        Prefilter::Contains(
            if ci {
                lit.to_lowercase()
            } else {
                lit.to_string()
            },
            ci,
        )
    })
}

/// Candidate strings a command is matched against, most specific first:
/// per-segment (last segment first, effective form then raw), then the whole
/// compound command. Shared by `find_filter` and the lazy bundled loader so
/// both see exactly the same candidate set.
fn prioritized_candidates(cmd: &str) -> Vec<String> {
    let shell_body = unwrap_shell_runner(cmd);
    let base = shell_body.as_deref().unwrap_or(cmd);
    let segments = split_on_operators(base);

    let mut candidates = Vec::new();

    // 1. Segment-level candidates: last segment first
    for segment in segments.iter().rev() {
        let effective = get_effective_command(segment);
        push_unique(&mut candidates, &effective);
        push_unique(&mut candidates, segment);
    }

    // 2. Full compound candidates
    let effective_full = get_effective_command(cmd);
    push_unique(&mut candidates, &effective_full);
    if let Some(body) = &shell_body {
        let effective_body = get_effective_command(body);
        push_unique(&mut candidates, &effective_body);
        push_unique(&mut candidates, body);
    }
    push_unique(&mut candidates, cmd);
    candidates
}

pub fn find_filter<'a>(cmd: &str, filters: &'a [FilterDef]) -> Option<&'a FilterDef> {
    let effective = get_effective_command(cmd);
    let tokens = tokenize_command(&effective);

    // 1. Help flags bypass: let raw help outputs pass through unfiltered
    let has_help = tokens.iter().any(|t| {
        let t_lower = t.to_lowercase();
        t == "-h"
            || t == "-help"
            || t_lower == "--help"
            || t == "/h"
            || t == "/?"
            || t_lower == "help"
            || t_lower.starts_with("--help-")
            || t_lower.starts_with("-help-")
    });
    if has_help {
        return None;
    }

    // 2. Version flags bypass: version output is short and shouldn't be masked as success.
    // Lowercase `-v` is treated as a version flag only for tools where it actually queries version
    // (e.g. git, node, docker, npm), to avoid falsely bypassing verbose runs (e.g. cargo, pytest, python).
    let mut has_version = false;
    for (i, t) in tokens.iter().enumerate() {
        let t_lower = t.to_lowercase();
        if t_lower == "--version" || t_lower == "version" {
            has_version = true;
            break;
        }
        if t == "-V" {
            has_version = true;
            break;
        }
        if t == "-v" && i > 0 {
            let prev_tool = std::path::Path::new(&tokens[i - 1])
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap_or(&tokens[i - 1])
                .to_lowercase();
            let prev_tool = prev_tool.strip_suffix(".exe").unwrap_or(&prev_tool);
            if matches!(
                prev_tool,
                "git" | "node" | "docker" | "npm" | "npx" | "pnpm" | "yarn" | "bun"
            ) {
                has_version = true;
                break;
            }
        }
    }
    if !has_version && !tokens.is_empty() && (tokens[0] == "version" || tokens[0] == "--version") {
        has_version = true;
    }

    if has_version && tokens.len() <= 3 {
        return None;
    }

    // 3. Debug/verbose flags bypass: keep troubleshooting logs intact
    let has_debug_or_verbose = tokens.iter().any(|t| {
        let t_lower = t.to_lowercase();
        t == "-vv"
            || t == "-vvv"
            || t_lower == "--debug"
            || t_lower == "--verbose"
            || t_lower == "--trace"
            || t_lower.starts_with("--log-level=debug")
            || t_lower.starts_with("--log-level=trace")
    });
    if has_debug_or_verbose {
        return None;
    }

    // 4. YAML check to prevent breaking YAML outputs
    let has_yaml = tokens.iter().any(|t| {
        let t_lower = t.to_lowercase();
        t_lower == "--yaml" || t_lower == "-o=yaml" || t_lower == "yaml"
    }) || effective.contains("-o yaml")
        || effective.contains("--format yaml")
        || effective.contains("--format=yaml");
    if has_yaml {
        return None;
    }

    // 5. JSON check to prevent breaking JSON outputs unless explicitly handled by the filter
    let has_json = tokens.iter().enumerate().any(|(i, t)| {
        let t_lower = t.to_lowercase();
        if t_lower == "--json" || t_lower == "-o=json" || t_lower == "json" {
            true
        } else if t == "-j" {
            if i > 0 {
                let prev_tool = std::path::Path::new(&tokens[i - 1])
                    .file_name()
                    .and_then(|f| f.to_str())
                    .unwrap_or(&tokens[i - 1])
                    .to_lowercase();
                let prev_tool = prev_tool.strip_suffix(".exe").unwrap_or(&prev_tool);
                !matches!(
                    prev_tool,
                    "cargo" | "make" | "ninja" | "cmake" | "mvn" | "gradle" | "build"
                )
            } else {
                true
            }
        } else {
            false
        }
    }) || effective.contains("-o json")
        || effective.contains("--format json")
        || effective.contains("--format=json")
        || effective.contains("--message-format=json")
        || effective.contains("--message-format json");

    let prioritized_candidates = prioritized_candidates(cmd);

    // Find the first filter that matches any prioritized candidate, resolving collisions
    // by picking the one with the longest (most specific) match_command pattern.
    for candidate in &prioritized_candidates {
        let mut best_match: Option<&'a FilterDef> = None;
        let mut max_len = 0;

        for f in filters {
            // Hot-path prefilter: skip compiling patterns whose mandatory
            // literal can't match this candidate (the common case — one
            // command vs hundreds of tool-anchored patterns).
            if let Some(pf) = prefilter_for(&f.match_command) {
                if !pf.allows(candidate) {
                    continue;
                }
            }
            if let Some(re) = cached_regex(&f.match_command) {
                if re.is_match(candidate) {
                    // JSON bypass: if command asks for JSON output, but filter does not support summarizing JSON, bypass
                    if has_json && f.summarize_json.is_none() {
                        continue;
                    }
                    // Per-filter skip: candidate matches a form the filter opts out of
                    // (e.g. already-bounded reads via -Tail, or piped into another command).
                    if let Some(skip) = &f.skip_when_matches {
                        if let Some(skip_re) = cached_regex(skip) {
                            if skip_re.is_match(candidate) {
                                continue;
                            }
                        }
                    }
                    let pattern_len = f.match_command.len();
                    if pattern_len > max_len {
                        max_len = pattern_len;
                        best_match = Some(f);
                    }
                }
            }
        }
        if let Some(f) = best_match {
            return Some(f);
        }
    }
    None
}

pub fn tokenize_command(command: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut escaping = false;

    for c in command.trim().chars() {
        if escaping {
            current.push(c);
            escaping = false;
            continue;
        }

        if c == '\\' {
            escaping = true;
            continue;
        }

        if let Some(q) = quote {
            if c == q {
                quote = None;
            } else {
                current.push(c);
            }
            continue;
        }

        if c == '\'' || c == '"' {
            quote = Some(c);
            continue;
        }

        if c.is_whitespace() {
            if !current.is_empty() {
                tokens.push(current);
                current = String::new();
            }
            continue;
        }

        current.push(c);
    }

    if escaping {
        current.push('\\');
    }

    if !current.is_empty() {
        tokens.push(current);
    }

    tokens
}

pub fn unwrap_shell_runner(cmd: &str) -> Option<String> {
    let argv = tokenize_command(cmd);
    if argv.is_empty() {
        return None;
    }

    let first = &argv[0];
    let first_path = std::path::Path::new(first);
    let launcher_name = first_path
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(first)
        .to_lowercase();
    let launcher_name_no_ext = launcher_name.strip_suffix(".exe").unwrap_or(&launcher_name);

    let is_shell = matches!(
        launcher_name_no_ext,
        "bash"
            | "sh"
            | "zsh"
            | "fish"
            | "dash"
            | "ksh"
            | "mksh"
            | "ash"
            | "csh"
            | "tcsh"
            | "cmd"
            | "powershell"
            | "pwsh"
    );

    if !is_shell {
        return None;
    }

    for i in 1..(argv.len().saturating_sub(1)) {
        let arg = &argv[i];
        let is_command_flag = if launcher_name_no_ext == "cmd" {
            arg.eq_ignore_ascii_case("/c") || arg.eq_ignore_ascii_case("-c")
        } else if launcher_name_no_ext == "powershell" || launcher_name_no_ext == "pwsh" {
            arg.eq_ignore_ascii_case("-c")
                || arg.eq_ignore_ascii_case("-command")
                || arg.eq_ignore_ascii_case("--command")
        } else {
            arg.starts_with('-') && arg.contains('c')
        };

        if is_command_flag {
            return Some(argv[i + 1].trim().to_string());
        }
    }

    None
}

fn is_env_assignment(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return false;
    }
    if !bytes[0].is_ascii_alphabetic() && bytes[0] != b'_' {
        return false;
    }
    let mut i = 1;
    while i < bytes.len() {
        if bytes[i] == b'=' {
            return i > 0;
        }
        if !bytes[i].is_ascii_alphanumeric() && bytes[i] != b'_' {
            return false;
        }
        i += 1;
    }
    false
}

fn strip_leading_env_assignments(argv: &[String]) -> Vec<String> {
    let mut index = 0;
    while index < argv.len() && is_env_assignment(&argv[index]) {
        index += 1;
    }

    if index < argv.len() {
        let cmd_path = std::path::Path::new(&argv[index]);
        let cmd_name = cmd_path
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or(&argv[index]);
        if cmd_name == "env" || cmd_name == "cross-env" {
            index += 1;
            while index < argv.len() {
                let arg = &argv[index];
                if arg == "--" {
                    index += 1;
                    break;
                }
                if is_env_assignment(arg) {
                    index += 1;
                    continue;
                }
                if arg == "-i" || arg == "-0" || arg == "--ignore-environment" || arg == "--debug" {
                    index += 1;
                    continue;
                }
                if arg == "-u"
                    || arg == "--unset"
                    || arg == "-C"
                    || arg == "--chdir"
                    || arg == "-S"
                    || arg == "--split-string"
                {
                    index += 2;
                    continue;
                }
                if arg.starts_with("--unset=")
                    || arg.starts_with("--chdir=")
                    || arg.starts_with("--split-string=")
                {
                    index += 1;
                    continue;
                }
                break;
            }
        }
    }

    argv[index..].to_vec()
}

/// Strip known Unix command-timing / resource-limit wrappers that prefix the
/// real command without altering its behaviour for filter-matching purposes:
///
/// - `timeout [OPTS] DURATION CMD`  (GNU coreutils)
/// - `time CMD`
/// - `nice [-n N] CMD`
/// - `ionice [-c C] [-n N] [-t] CMD`
///
/// Each wrapper is peeled in a loop so stacked prefixes like
/// `timeout 30 nice -n 10 pnpm run test` resolve to `pnpm run test`.
fn strip_leading_wrappers(argv: &[String]) -> Vec<String> {
    let mut index = 0;

    loop {
        if index >= argv.len() {
            break;
        }
        let name_raw = std::path::Path::new(&argv[index])
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or(&argv[index])
            .to_lowercase();
        let name = name_raw.strip_suffix(".exe").unwrap_or(&name_raw);

        match name {
            // `& CMD` — PowerShell call operator
            "&" => {
                index += 1;
            }
            // `time CMD` — single token prefix
            "time" => {
                index += 1;
            }
            // `nice [-n N | --adjustment[=]N] CMD`
            "nice" => {
                index += 1;
                if index < argv.len() {
                    let a = &argv[index];
                    if a == "-n" || a == "--adjustment" {
                        index += 2;
                    } else if a.starts_with("--adjustment=") {
                        index += 1;
                    }
                }
            }
            // `ionice [-c C] [-n N] [-t] CMD`
            "ionice" => {
                index += 1;
                while index < argv.len() {
                    let a = &argv[index];
                    if (a == "-c" || a == "-n") && index + 1 < argv.len() {
                        index += 2;
                    } else if a == "-t" {
                        index += 1;
                    } else {
                        break;
                    }
                }
            }
            // `timeout [OPTS] DURATION CMD`
            // Options: --foreground, --preserve-status, --verbose, -k DUR, -s SIG
            "timeout" => {
                index += 1;
                let mut found_duration = false;
                while index < argv.len() {
                    let a = &argv[index];
                    if matches!(
                        a.as_str(),
                        "--foreground" | "--preserve-status" | "--verbose"
                    ) {
                        index += 1;
                        continue;
                    }
                    if (a == "-k" || a == "--kill-after" || a == "-s" || a == "--signal")
                        && index + 1 < argv.len()
                    {
                        index += 2;
                        continue;
                    }
                    if a.starts_with("--kill-after=") || a.starts_with("--signal=") {
                        index += 1;
                        continue;
                    }
                    if a.starts_with('-') {
                        index += 1;
                        continue;
                    }
                    // First non-option argument is the DURATION — skip it.
                    index += 1;
                    found_duration = true;
                    break;
                }
                if !found_duration {
                    // Malformed `timeout` invocation — stop peeling.
                    break;
                }
            }
            _ => break,
        }
    }

    argv[index..].to_vec()
}

/// Drop a leading package-runner prefix so the inner tool's filter matches:
/// `uv run pytest` -> `pytest`, `python -m ruff check` -> `ruff check`,
/// `bunx biome check` -> `biome check`, `npx tsc` -> `tsc`,
/// `pnpm exec eslint` / `pnpm dlx`/`yarn dlx`/`bun x`/`deno run`/`deno task`.
/// Returns the tail after the runner, or the input unchanged.
fn strip_package_runner(argv: &[String]) -> &[String] {
    if argv.is_empty() {
        return argv;
    }
    let t0 = std::path::Path::new(&argv[0])
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(&argv[0])
        .to_lowercase();
    let t0 = t0.strip_suffix(".exe").unwrap_or(&t0);

    let mut start_idx = 0;

    // 1. Detect the runner and set the start index after the runner tokens
    if matches!(t0, "npx" | "bunx" | "uvx") && argv.len() > 1 {
        start_idx = 1;
    } else if argv.len() > 2 {
        let t1 = argv[1].as_str();
        let pair = (t0, t1);
        if matches!(
            pair,
            ("uv", "run")
                | ("pnpm", "exec")
                | ("pnpm", "dlx")
                | ("yarn", "dlx")
                | ("bun", "x")
                | ("deno", "run")
                | ("deno", "task")
                | ("bundle", "exec")
        ) || (matches!(t0, "python" | "python3" | "py") && t1 == "-m")
        {
            start_idx = 2;
        }
    }

    if start_idx == 0 {
        return argv;
    }

    // 2. Skip any options/flags belonging to the runner itself (e.g. npx --no-install, uv run --with requests)
    let mut idx = start_idx;
    while idx < argv.len() {
        let arg = &argv[idx];
        if arg.starts_with('-') {
            if arg == "--" {
                idx += 1;
                break; // double dash indicates end of runner options
            }
            if (arg == "-p" || arg == "--package" || arg == "--with" || arg == "--import")
                && idx + 1 < argv.len()
            {
                idx += 2;
            } else {
                idx += 1;
            }
        } else {
            break;
        }
    }

    if idx < argv.len() {
        &argv[idx..]
    } else {
        &argv[start_idx..] // fallback
    }
}

/// Drop tool-global options that sit *between* a subcommand tool and its
/// subcommand, so a filter anchored on `^git\s+add` still matches
/// `git -C /repo -c user.name=x add .`. Without this, idiomatic invocations
/// like `git -C dir`, `kubectl -n ns`, `docker -H host` or `cargo +nightly`
/// bypass every subcommand filter and ship raw output.
///
/// Returns the tool name followed by the first non-option token onward, e.g.
/// `["git", "-C", "dir", "add", "."]` -> `["git", "add", "."]`. Tools not in
/// the recognized set are returned unchanged.
fn strip_subcommand_global_opts(argv: &[String]) -> Vec<String> {
    if argv.is_empty() {
        return Vec::new();
    }
    let tool = std::path::Path::new(&argv[0])
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(&argv[0])
        .to_lowercase();
    let tool = tool.strip_suffix(".exe").unwrap_or(&tool);

    // (flags taking a following value, boolean flags)
    let (valued, boolean): (&[&str], &[&str]) = match tool {
        "git" => (
            &[
                "-C",
                "-c",
                "--git-dir",
                "--work-tree",
                "--exec-path",
                "--namespace",
                "--super-prefix",
            ],
            &[
                "-p",
                "-P",
                "--paginate",
                "--no-pager",
                "--bare",
                "--no-replace-objects",
                "--literal-pathspecs",
                "--glob-pathspecs",
                "--noglob-pathspecs",
                "--icase-pathspecs",
                "--no-optional-locks",
            ],
        ),
        "kubectl" => (
            &[
                "-n",
                "--namespace",
                "--context",
                "--kubeconfig",
                "-s",
                "--server",
                "--token",
                "--as",
                "--as-group",
                "--cluster",
                "--user",
                "--cache-dir",
                "--request-timeout",
                "--client-certificate",
                "--client-key",
                "--certificate-authority",
                "--tls-server-name",
            ],
            &["--insecure-skip-tls-verify"],
        ),
        "docker" => (
            &[
                "-H",
                "--host",
                "--context",
                "--config",
                "-l",
                "--log-level",
                "--tlscacert",
                "--tlscert",
                "--tlskey",
            ],
            &["-D", "--debug", "--tls", "--tlsverify"],
        ),
        "terraform" | "tofu" => (&["-chdir"], &[]),
        "cargo" => (&[], &[]),
        "pnpm" => (
            &[
                "-C",
                "--dir",
                "--filter",
                "--reporter",
                "--store-dir",
                "--virtual-store-dir",
                "--loglevel",
            ],
            &[
                "-w",
                "--workspace",
                "-r",
                "--recursive",
                "--prod",
                "-D",
                "--dev",
                "--no-optional",
                "--frozen-lockfile",
                "--silent",
                "-s",
            ],
        ),
        "bun" => (
            &[
                "--cwd",
                "-c",
                "--config",
                "--filter",
                "-p",
                "--port",
                "--env-file",
                "--profile",
            ],
            &[
                "--watch",
                "--hot",
                "--smol",
                "--no-buffer",
                "-v",
                "--version",
            ],
        ),
        _ => return argv.to_vec(),
    };

    let mut i = 1;
    while i < argv.len() {
        let a = &argv[i];
        // `cargo +nightly test`
        if tool == "cargo" && a.starts_with('+') {
            i += 1;
            continue;
        }
        if a.starts_with("--") {
            if a.contains('=') {
                i += 1; // --opt=value
                continue;
            }
            if valued.contains(&a.as_str()) {
                i += if i + 1 < argv.len() { 2 } else { 1 }; // --opt value
                continue;
            }
            if boolean.contains(&a.as_str()) {
                i += 1;
                continue;
            }
            break;
        } else if a.len() >= 2 && a.starts_with('-') {
            if let Some((key, _)) = a.split_once('=') {
                if valued.contains(&key) {
                    i += 1; // -opt=value
                    continue;
                }
            }
            if valued.contains(&a.as_str()) {
                i += if i + 1 < argv.len() { 2 } else { 1 }; // -C dir
                continue;
            }
            if boolean.contains(&a.as_str()) {
                i += 1;
                continue;
            }
            break;
        } else {
            break; // subcommand reached
        }
    }

    if i == 1 {
        return argv.to_vec();
    }
    let mut out = Vec::with_capacity(1 + argv.len() - i);
    out.push(argv[0].clone());
    out.extend_from_slice(&argv[i..]);
    out
}

fn strip_cd_and_operators(mut argv: &[String]) -> &[String] {
    for _ in 0..8 {
        if argv.is_empty() {
            break;
        }
        let first = &argv[0];
        if first == "cd"
            || first == "pushd"
            || first.eq_ignore_ascii_case("set-location")
            || first == "sl"
        {
            if argv.len() >= 2 && (argv[1] == "&&" || argv[1] == ";") {
                argv = &argv[2..];
                continue;
            }
            if argv.len() >= 3 && (argv[2] == "&&" || argv[2] == ";") {
                argv = &argv[3..];
                continue;
            }
            // `cd /app; cmd` tokenizes the `;` glued to the directory.
            if argv.len() >= 3 && argv[1].ends_with(';') {
                argv = &argv[2..];
                continue;
            }
        }
        break;
    }
    argv
}

pub fn get_effective_command(cmd: &str) -> String {
    let mut current = cmd.trim().to_string();

    for _ in 0..16 {
        let unwrapped = unwrap_shell_runner(&current);
        if let Some(inner) = unwrapped {
            current = inner;
            continue;
        }

        let tokens = tokenize_command(&current);
        if tokens.is_empty() {
            break;
        }

        let stripped_env = strip_leading_env_assignments(&tokens);
        let stripped_wrappers = strip_leading_wrappers(&stripped_env);
        let stripped_cd = strip_cd_and_operators(&stripped_wrappers);
        let stripped_runner = strip_package_runner(stripped_cd);
        let stripped_opts = strip_subcommand_global_opts(stripped_runner);

        if stripped_opts.len() == tokens.len() {
            break;
        }

        current = stripped_opts.join(" ");
    }

    current
}

/// True when `cmd` contains a top-level `;`, `&&`, or `||` (quote- and
/// escape-aware) — the operators that run independent commands whose raw
/// stdout gets concatenated into one blob, as opposed to `|`, which chains
/// commands into the single stream the last stage produces.
pub(crate) fn has_sequential_operator(cmd: &str) -> bool {
    let mut quote: Option<char> = None;
    let mut escaping = false;
    let chars: Vec<char> = cmd.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if escaping {
            escaping = false;
            i += 1;
            continue;
        }
        if c == '\\' {
            escaping = true;
            i += 1;
            continue;
        }
        if let Some(q) = quote {
            if c == q {
                quote = None;
            }
            i += 1;
            continue;
        }
        if c == '\'' || c == '"' {
            quote = Some(c);
            i += 1;
            continue;
        }
        if c == ';' {
            return true;
        }
        let next = chars.get(i + 1).copied();
        if (c == '&' && next == Some('&')) || (c == '|' && next == Some('|')) {
            return true;
        }
        i += 1;
    }
    false
}

/// True when `f.match_command` matches `cmd` (or its effective form) taken as
/// a whole, as opposed to matching only because one inner `;`/`&&`/`||`
/// segment happens to look like the filter's target. Used to tell "this
/// filter really is what the compound command is running" from "this filter
/// just resolved off a tail segment".
pub(crate) fn filter_matches_whole_command(cmd: &str, match_command: &str) -> bool {
    let effective = get_effective_command(cmd);
    // `is_match` is a prefix match: `^git\s+log\b` would accept `git log -3 && echo done`.
    if has_sequential_operator(&effective) {
        return false;
    }
    let Some(re) = cached_regex(match_command) else {
        return false;
    };
    re.is_match(cmd) || re.is_match(&effective)
}

/// Split a shell command into segments on the operators `&&`, `||`, `;` and the
/// pipe `|`, quote- and escape-aware. Operators are recognized regardless of
/// surrounding whitespace, so `a;b` and `a ; b` segment identically.
/// Quoted operators (e.g. `echo "a;b"`) are left intact.
pub fn split_on_operators(cmd: &str) -> Vec<String> {
    let mut segments = Vec::new();
    let mut current = String::new();
    let mut quote: Option<char> = None;
    let mut escaping = false;

    let chars: Vec<char> = cmd.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];

        if escaping {
            current.push(c);
            escaping = false;
            i += 1;
            continue;
        }
        if c == '\\' {
            current.push(c);
            escaping = true;
            i += 1;
            continue;
        }
        if let Some(q) = quote {
            current.push(c);
            if c == q {
                quote = None;
            }
            i += 1;
            continue;
        }
        if c == '\'' || c == '"' {
            quote = Some(c);
            current.push(c);
            i += 1;
            continue;
        }

        let next = chars.get(i + 1).copied();
        // Two-char operators `&&` / `||` first, so the trailing `|` of `||`
        // is not mistaken for a pipe split.
        if (c == '&' && next == Some('&')) || (c == '|' && next == Some('|')) {
            push_segment(&mut segments, &mut current);
            i += 2;
            continue;
        }
        if c == ';' || c == '|' {
            push_segment(&mut segments, &mut current);
            i += 1;
            continue;
        }

        current.push(c);
        i += 1;
    }
    push_segment(&mut segments, &mut current);
    segments
}

fn push_segment(segments: &mut Vec<String>, current: &mut String) {
    let trimmed = current.trim();
    if !trimmed.is_empty() {
        segments.push(trimmed.to_string());
    }
    current.clear();
}

fn push_unique(candidates: &mut Vec<String>, candidate: &str) {
    let trimmed = candidate.trim();
    if !trimmed.is_empty() && !candidates.iter().any(|c| c == trimmed) {
        candidates.push(trimmed.to_string());
    }
}

#[cfg(test)]
pub fn derive_command_candidates(cmd: &str) -> Vec<String> {
    let mut candidates = Vec::new();

    push_unique(&mut candidates, cmd);

    let shell_body = unwrap_shell_runner(cmd);
    if let Some(body) = &shell_body {
        push_unique(&mut candidates, body);
    }

    push_unique(&mut candidates, &get_effective_command(cmd));

    // Operator-aware segmentation: split compound commands and add
    // each segment plus its effective form, so a filter anchored on its base
    // command matches regardless of position or spacing — e.g. `cd x;gitleaks`,
    // `npm i && gitleaks`, or `producer | gitleaks`.
    let mut bases = vec![cmd.to_string()];
    if let Some(body) = shell_body {
        bases.push(body);
    }
    for base in &bases {
        for segment in split_on_operators(base) {
            let effective = get_effective_command(&segment);
            push_unique(&mut candidates, &segment);
            push_unique(&mut candidates, &effective);
        }
    }

    candidates
}

/// Final safety net: a filter must never make the output more expensive than
/// the raw it replaces (a short raw beaten by a longer success message or an
/// omission notice). Byte length is a cheap, monotone proxy for tokens here.
/// Genuinely empty raw is exempt so `on_empty` sentinels still fire for
/// commands that print nothing.
/// `Some(summary)` when every significant line of `output` matches the pass
/// shape and at least one did. `None` means the run is not uniform — a single
/// dissenting line is enough — and the normal pipeline must handle it.
fn uniform_summary(output: &str, cfg: &UniformSuccess) -> Option<String> {
    let pass = cached_regex(&cfg.pattern)?;
    let ignore: Vec<Regex> = cfg
        .ignore_lines
        .iter()
        .filter_map(|p| cached_regex(p))
        .collect();
    let mut matched = 0usize;
    for line in output.lines() {
        if line.trim().is_empty() || ignore.iter().any(|re| re.is_match(line)) {
            continue;
        }
        if !pass.is_match(line) {
            return None;
        }
        matched += 1;
    }
    (matched > 0).then(|| cfg.message.replace("{n}", &matched.to_string()))
}

fn never_worse(raw: &str, filtered: String) -> String {
    let raw_trim = raw.trim_end();
    if !raw_trim.is_empty() && filtered.len() > raw_trim.len() {
        return raw_trim.to_string();
    }
    filtered
}

pub fn apply_filter(output: &str, f: &FilterDef) -> String {
    apply_filter_with_exit(output, f, None)
}

/// `exit_ok = Some(false)` means the run wrapper observed a nonzero exit.
/// On failure: the filter's `on_failure` policy ("passthrough" | "tail:N")
/// takes over if set; otherwise normal filtering runs but success sentinels
/// (`match_output` messages, `on_empty`) are suppressed — text heuristics
/// alone miss failing commands with quiet or unusual output.
pub fn apply_filter_with_exit(output: &str, f: &FilterDef, exit_ok: Option<bool>) -> String {
    // Every path below splits with `.lines()` and rejoins with "\n", which
    // launders CRLF into LF. On Windows that hands the agent a copy whose line
    // endings differ from disk on every line — fatal if it later quotes them
    // into an exact-match edit. Detect once here, restore once on the way out.
    let eol = crate::compress::dominant_eol(output);
    crate::compress::restore_eol(apply_filter_with_exit_inner(output, f, exit_ok), eol)
}

fn apply_filter_with_exit_inner(output: &str, f: &FilterDef, exit_ok: Option<bool>) -> String {
    let failed = exit_ok == Some(false);
    if failed {
        if let Some(policy) = &f.on_failure {
            if policy == "passthrough" {
                return output.trim_end().to_string();
            }
            if let Some(n) = policy
                .strip_prefix("tail:")
                .and_then(|n| n.parse::<usize>().ok())
            {
                let lines: Vec<&str> = output.trim_end().lines().collect();
                let start = lines.len().saturating_sub(n);
                return lines[start..].join("\n");
            }
        }
    }

    // match_output short-circuits before any other transformation. These are
    // success sentinels by convention — never fire them on a known failure, and
    // never on output carrying a generic failure signal either: `unless` is
    // opt-in and only 30 of the bundled filters declare one, so it cannot be the
    // only thing standing between a failed run and a "success" sentinel.
    let signals_failure = failed || output_has_failure_signal(output);
    if !signals_failure {
        for mo in &f.match_output {
            if let Some(re) = cached_regex(&mo.pattern) {
                if re.is_match(output) {
                    // `unless` guard: do not short-circuit when the output also matches
                    // this pattern, so errors/warnings are never masked as success.
                    // Fails closed — an unparseable `unless` skips the sentinel
                    // rather than silently dropping the guard.
                    if let Some(unless) = &mo.unless {
                        match cached_regex(unless) {
                            Some(u) if u.is_match(output) => continue,
                            None => continue,
                            Some(_) => {}
                        }
                    }
                    return never_worse(output, mo.message.clone());
                }
            }
        }
    }

    let s = if f.strip_ansi {
        crate::compress::strip_ansi(output)
    } else {
        output.to_string()
    };

    // Whole-run success: every significant line agrees, so the summary is a
    // statement about the run. Evaluated on the ANSI-stripped text (these
    // tools colorize their per-item lines) and suppressed on a known failure
    // like every other success sentinel.
    if !signals_failure {
        if let Some(uniform) = &f.uniform_success {
            if let Some(msg) = uniform_summary(&s, uniform) {
                return never_worse(output, msg);
            }
        }
    }

    let mut lines: Vec<String> = s.lines().map(|l| l.to_string()).collect();

    if !f.block_caps.is_empty() {
        lines = blocks::apply_block_caps(lines, &f.block_caps);
    }

    if !f.strip_lines_matching.is_empty() {
        let patterns: Vec<Regex> = f
            .strip_lines_matching
            .iter()
            .filter_map(|p| cached_regex(p))
            .collect();
        lines.retain(|l| !patterns.iter().any(|re| re.is_match(l)));
    }

    if !f.keep_lines_matching.is_empty() {
        let patterns: Vec<Regex> = f
            .keep_lines_matching
            .iter()
            .filter_map(|p| cached_regex(p))
            .collect();
        lines.retain(|l| patterns.iter().any(|re| re.is_match(l)));
    }

    // NEW: extract_sections - extract content between markers
    if !f.extract_sections.is_empty() {
        lines = apply_extract_sections(lines, &f.extract_sections);
    }

    // NEW: replace_patterns - regex replacements
    if !f.replace_patterns.is_empty() {
        lines = apply_replace_patterns(lines, &f.replace_patterns);
    }

    // category_caps - bound repetitive line classes independently
    if !f.category_caps.is_empty() {
        lines = apply_category_caps(lines, &f.category_caps);
    }

    // NEW: deduplicate_blocks - structural deduplication
    if let Some(dedup) = &f.deduplicate_blocks {
        lines = apply_deduplicate_blocks(lines, dedup);
    }

    // semantic_filter - keyword-overlap relevance filtering
    if let Some(semantic) = &f.semantic_filter {
        lines = apply_semantic_filter(lines, semantic);
    }

    // NEW: summarize_json - intelligent JSON summarization
    if let Some(summarize) = &f.summarize_json {
        lines = apply_summarize_json(lines, summarize);
    }

    let (mut lines, omitted_by_sizing) = apply_sizing(lines, f);
    if f.notify_on_truncate && omitted_by_sizing > 0 {
        lines.push(format!(
            "[... {omitted_by_sizing} lines omitted (line limit) ...]"
        ));
    }

    // NEW: token_budget - hard token limit with smart truncation
    let mut result = if let Some(max_len) = f.truncate_lines_at {
        let mut truncated_line_count = 0usize;
        let joined = lines
            .iter()
            .map(|l| {
                let t = truncate_at_char_boundary(l, max_len);
                if t.len() < l.len() {
                    truncated_line_count += 1;
                }
                t
            })
            .collect::<Vec<_>>()
            .join("\n");
        if f.notify_on_truncate && truncated_line_count > 0 {
            format!(
                "{joined}\n[... {truncated_line_count} line(s) truncated to {max_len} chars ...]"
            )
        } else {
            joined
        }
    } else {
        lines.join("\n")
    };

    if let Some(budget) = f.token_budget {
        result = apply_token_budget(&result, budget);
    }

    if result.trim().is_empty() {
        // Fall back to a bounded view of the real output (instead of `on_empty`)
        // when filtering emptied a non-empty output AND either:
        //  - the filter opted in via `passthrough_when_emptied`, or
        //  - the original output carries a generic failure signal that the
        //    per-tool keep/strip rules didn't recognize. Without this guard a
        //    failed build/test/deploy whose error text doesn't match the
        //    tool's native error format would be masked as the success
        //    `on_empty` message — the same "never mask errors" rule the
        //    `match_output.unless` guard enforces.
        // Not gated on `on_empty`: a filter whose keep/strip rules swallowed the
        // error text leaves the agent with nothing at all, which is the same
        // masking failure the sentinel guard exists to prevent.
        let masks_failure = failed || output_has_failure_signal(output);
        if !output.trim().is_empty() && (f.passthrough_when_emptied || masks_failure) {
            let cap = f.max_lines.unwrap_or(40);
            let fallback: Vec<String> = s
                .lines()
                .take(cap)
                .map(|l| match f.truncate_lines_at {
                    Some(n) => truncate_at_char_boundary(l, n).to_string(),
                    None => l.to_string(),
                })
                .collect();
            let fb_text = fallback.join("\n");
            return never_worse(
                output,
                match f.token_budget {
                    Some(budget) => apply_token_budget(&fb_text, budget),
                    None => fb_text,
                },
            );
        }
        if let Some(msg) = &f.on_empty {
            // A failed command must never earn the success sentinel, even
            // when it printed nothing — the empty result stands on its own.
            if !failed {
                return never_worse(output, msg.clone());
            }
        }
    }
    never_worse(output, result)
}

/// Strict detection of an unambiguous command-failure signal in raw output.
/// Used as a safety net so a filter never reports its success `on_empty`
/// message for output that actually describes a failure. Patterns are
/// deliberately anchored/cased to avoid tripping on benign mentions like
/// "0 errors", "no failures", or "error: 0".
fn output_has_failure_signal(output: &str) -> bool {
    use std::sync::OnceLock;
    static FAILURE: OnceLock<Regex> = OnceLock::new();
    let re = FAILURE.get_or_init(|| {
        Regex::new(
            // `^\S*:\s*(?i:error|fatal|panic):` catches the two dominant Unix
            // diagnostic shapes the line-start alternatives miss because a
            // prefix comes first: `cppcheck: error: unrecognized option` and
            // `main.c:3:5: error: expected ';'`. Without it a filter whose
            // keep-rules don't recognise a tool's own error format empties the
            // output and earns the success `on_empty` sentinel — and on the
            // PostToolUse path there is no exit code to fall back on.
            r"(?m)^\s*(?:(?i:error|fatal|panic|panicked|exception|stderr|err)\b|FAILED\b|FAIL\b|---\s*FAIL\b|Traceback \(most recent call last\)|Unhandled exception|Exception in thread\b)|^\S*:\s*(?i:error|fatal|panic):|\b(?i:failed with exit code|exited with status|exited with code|exit status|exit code|exit)\b\s*[:=]?\s*[1-9]\d*|\b(?:SIGSEGV|SIGABRT|SIGILL|SIGBUS|AssertionError|NullPointerException|Segmentation fault|(?i:Command failed|command not found|failed to compile))\b|\[(?i:error|fatal|panic|failed|fail)\]|level=(?i:error|fatal|panic)|\b(?i:err)(?:!|:)"
        )
        .expect("failure-signal regex compiles")
    });
    re.is_match(output)
}

/// Keep only the lines inside the configured sections.
///
/// Two invariants worth stating because both were once violated: surviving
/// lines are emitted in **source order**, not grouped per section (a Docker
/// build's trailing `ERROR: failed to solve` must not precede the frames that
/// explain it), and a section left **unclosed** at end of output is kept
/// regardless of `include_markers` — output that stops mid-section is exactly
/// the output of a command that died.
fn apply_extract_sections(lines: Vec<String>, sections: &[ExtractSection]) -> Vec<String> {
    let mut kept: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
    // Index of the last kept line of a capped section → lines dropped after it.
    let mut omitted: HashMap<usize, usize> = HashMap::new();
    let content = lines.join("\n");

    for section in sections {
        let start_re = match cached_regex(&section.start_pattern) {
            Some(r) => r,
            None => continue,
        };
        let end_re = match cached_regex(&section.end_pattern) {
            Some(r) => r,
            None => continue,
        };

        let mut matches = 0;
        let max_matches = section.max_matches.unwrap_or(usize::MAX);

        let mut in_section = false;
        let mut section_lines: Vec<usize> = Vec::new();
        let mut flush = |section_lines: &mut Vec<usize>| {
            let cap = section.max_lines.unwrap_or(usize::MAX).max(1);
            if section_lines.len() > cap {
                omitted.insert(section_lines[cap - 1], section_lines.len() - cap);
                section_lines.truncate(cap);
            }
            kept.extend(section_lines.drain(..));
        };

        for (i, line) in content.lines().enumerate() {
            let start_match = start_re.is_match(line);
            let end_match = end_re.is_match(line);

            if section.split_on_start && start_match && in_section && !end_match {
                flush(&mut section_lines);
                matches += 1;
                in_section = false;
                if matches >= max_matches {
                    break;
                }
            }

            if start_match && !in_section {
                in_section = true;
                if section.include_markers {
                    section_lines.push(i);
                }
                continue;
            }

            if in_section {
                if section.include_markers || !end_match {
                    section_lines.push(i);
                }
                if end_match {
                    flush(&mut section_lines);
                    matches += 1;
                    in_section = false;
                    if matches >= max_matches {
                        break;
                    }
                }
            }
        }

        // An unclosed section means the output ended inside it — a build that
        // was killed, a log that was truncated. Keep it either way.
        if in_section {
            flush(&mut section_lines);
        }
    }

    if kept.is_empty() {
        return lines;
    }
    let mut out = Vec::with_capacity(kept.len() + omitted.len());
    for i in kept {
        if let Some(line) = lines.get(i) {
            out.push(line.clone());
        }
        if let Some(n) = omitted.get(&i) {
            out.push(format!("    [... {n} lines omitted ...]"));
        }
    }
    out
}

fn apply_replace_patterns(lines: Vec<String>, patterns: &[[String; 2]]) -> Vec<String> {
    // Compile once per pattern, not once per (pattern × line).
    let compiled: Vec<(Regex, &str)> = patterns
        .iter()
        .filter_map(|[pattern, replacement]| {
            cached_regex(pattern).map(|re| (re, replacement.as_str()))
        })
        .collect();
    if compiled.is_empty() {
        return lines;
    }
    lines
        .into_iter()
        .map(|mut line| {
            for (re, replacement) in &compiled {
                line = re.replace_all(&line, *replacement).to_string();
            }
            line
        })
        .collect()
}

fn apply_deduplicate_blocks(lines: Vec<String>, dedup: &DeduplicateBlocksDef) -> Vec<String> {
    let delimiter = dedup.block_delimiter.as_deref().unwrap_or(r"^\s*$");
    let delim_re = match cached_regex(delimiter) {
        Some(r) => r,
        None => return lines,
    };

    // Every block is kept; `eligible` only decides whether a block may be
    // *collapsed* into a "similar block(s) omitted" marker. Dropping the
    // short ones outright — as this did — deletes exactly the lines that are
    // short because they stand alone, e.g. a lone `fatal: bad revision` above
    // an otherwise repetitive log, with no marker to say anything was lost.
    let mut blocks: Vec<(Vec<String>, bool)> = Vec::new();
    let mut current_block: Vec<String> = Vec::new();

    for line in &lines {
        if delim_re.is_match(line) && !current_block.is_empty() {
            let eligible = current_block.len() >= dedup.min_block_lines;
            blocks.push((std::mem::take(&mut current_block), eligible));
        } else {
            current_block.push(line.clone());
        }
    }
    if !current_block.is_empty() {
        let eligible = current_block.len() >= dedup.min_block_lines;
        blocks.push((current_block, eligible));
    }

    if blocks.iter().filter(|(_, eligible)| *eligible).count() < 2 {
        return lines;
    }

    let mut result = Vec::new();
    let mut i = 0;
    while i < blocks.len() {
        let (block, eligible) = &blocks[i];
        result.extend(block.iter().cloned());

        // Check next blocks for similarity
        let mut j = i + 1;
        let mut similar_count = 0;
        while *eligible && j < blocks.len() {
            let (candidate, candidate_eligible) = &blocks[j];
            if *candidate_eligible && blocks_similar(block, candidate, dedup.similarity) {
                similar_count += 1;
                j += 1;
            } else {
                break;
            }
        }

        if similar_count > 0 {
            result.push(format!(
                "[... {} similar block(s) omitted ...]",
                similar_count
            ));
            i = j;
        } else {
            i += 1;
        }
    }

    result
}

fn blocks_similar(a: &[String], b: &[String], threshold: f32) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let matches = a.iter().zip(b.iter()).filter(|(x, y)| x == y).count();
    (matches as f32 / a.len() as f32) >= threshold
}

fn apply_semantic_filter(lines: Vec<String>, semantic: &SemanticFilterDef) -> Vec<String> {
    let query_terms: Vec<&str> = semantic.query.split_whitespace().collect();
    let always_keep_patterns: Vec<Regex> = semantic
        .always_keep
        .iter()
        .filter_map(|p| cached_regex(p))
        .collect();

    lines
        .into_iter()
        .filter(|line| {
            if always_keep_patterns.iter().any(|re| re.is_match(line)) {
                return true;
            }
            // Simple keyword overlap as proxy for semantic relevance
            let line_lower = line.to_lowercase();
            query_terms
                .iter()
                .any(|term| line_lower.contains(&term.to_lowercase()))
        })
        .collect()
}

fn apply_summarize_json(lines: Vec<String>, summarize: &SummarizeJsonDef) -> Vec<String> {
    let content = lines.join("\n");
    let trimmed = content.trim();

    if !(trimmed.starts_with('{') || trimmed.starts_with('[')) {
        return lines;
    }

    let Ok(mut value) = serde_json::from_str::<serde_json::Value>(trimmed) else {
        return lines;
    };

    summarize_json_value(&mut value, summarize, 0, "");

    let result = serde_json::to_string_pretty(&value).unwrap_or(content);
    result.lines().map(|l| l.to_string()).collect()
}

/// `parent` is the dotted path of the enclosing object (empty at the root), so
/// `always_include`/`exclude` can address nested fields the way the field docs
/// promise (`outer.inner`). Keying on the recursion depth instead produced
/// paths like `1.inner`, which no configured value could ever match.
fn summarize_json_value(
    value: &mut serde_json::Value,
    summarize: &SummarizeJsonDef,
    depth: usize,
    parent: &str,
) {
    if depth >= summarize.max_depth {
        return;
    }
    let path_of = |k: &str| {
        if parent.is_empty() {
            k.to_string()
        } else {
            format!("{parent}.{k}")
        }
    };

    match value {
        serde_json::Value::Object(map) => {
            let keys_to_remove: Vec<String> = map
                .keys()
                .filter(|k| {
                    let full = path_of(k);
                    summarize
                        .exclude
                        .iter()
                        .any(|ex| k.as_str() == ex.as_str() || &full == ex)
                })
                .cloned()
                .collect();
            for k in keys_to_remove {
                map.remove(&k);
            }

            for (k, v) in map.iter_mut() {
                let full_path = path_of(k);
                if summarize
                    .always_include
                    .iter()
                    .any(|inc| inc == &full_path || inc == k)
                {
                    continue;
                }
                summarize_json_value(v, summarize, depth + 1, &full_path);
            }
        }
        serde_json::Value::Array(arr) => {
            if arr.len() > summarize.max_array_items {
                let shown = arr.drain(summarize.max_array_items..).collect::<Vec<_>>();
                let count = shown.len();
                arr.push(serde_json::Value::String(format!(
                    "... {} more item(s) omitted ...",
                    count
                )));
            }
            for item in arr.iter_mut() {
                summarize_json_value(item, summarize, depth + 1, parent);
            }
        }
        _ => {}
    }
}

fn apply_token_budget(text: &str, budget: usize) -> String {
    let tokens = crate::chunker::count_tokens(text);
    if tokens <= budget {
        return text.to_string();
    }

    let lines: Vec<&str> = text.lines().collect();
    if lines.is_empty() {
        return text.to_string();
    }

    // Priority order: errors/warnings > head > tail > middle
    let mut priority_lines = Vec::new();
    let mut other_lines = Vec::new();

    for (i, line) in lines.iter().enumerate() {
        let t = line.trim();
        let is_high_priority = t.starts_with("error")
            || t.starts_with("warning")
            || t.starts_with("FAIL")
            || t.starts_with("panic")
            || t.contains("error[")
            || t.contains("warning[")
            || i < lines.len() / 4
            || i >= lines.len() * 3 / 4;
        if is_high_priority {
            priority_lines.push((i, *line));
        } else {
            other_lines.push((i, *line));
        }
    }

    // Priority decides *what survives*, never *what order it is read in*: a
    // stack trace whose middle frames are emitted after the final verdict is
    // worse than one that is simply shorter. Keep the source index and restore
    // it before joining.
    let mut kept: Vec<(usize, &str)> = Vec::new();
    let mut used = 0usize;

    for (i, line) in priority_lines {
        let line_tokens = crate::chunker::count_tokens(line);
        if used + line_tokens > budget {
            break;
        }
        kept.push((i, line));
        used += line_tokens;
    }

    // Fill remaining budget with other lines (prefer head/tail)
    for (i, line) in other_lines {
        let line_tokens = crate::chunker::count_tokens(line);
        if used + line_tokens > budget {
            break;
        }
        kept.push((i, line));
        used += line_tokens;
    }

    kept.sort_by_key(|(i, _)| *i);
    let mut result: Vec<String> = kept.into_iter().map(|(_, l)| l.to_string()).collect();

    if result.len() < lines.len() {
        result.push(format!(
            "[... {} lines omitted to fit token budget {} ...]",
            lines.len() - result.len(),
            budget
        ));
    }

    result.join("\n")
}

/// Truncate `s` to at most `max_bytes`, backing off to the nearest char
/// boundary so we never slice through a multi-byte UTF-8 sequence (which would
/// panic). Returns a borrowed slice — no allocation.
fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Keep only the first `max` lines per category; overflow collapses into one
/// count marker placed right after the category's last kept line. The first
/// matching cap owns a line, so overlapping patterns don't double-count.
fn apply_category_caps(lines: Vec<String>, caps: &[CategoryCap]) -> Vec<String> {
    let compiled: Vec<(Regex, usize)> = caps
        .iter()
        .filter_map(|c| cached_regex(&c.pattern).map(|re| (re, c.max)))
        .collect();
    if compiled.is_empty() {
        return lines;
    }
    let mut kept = vec![0usize; compiled.len()];
    let mut dropped = vec![0usize; compiled.len()];
    let mut marker_pos = vec![0usize; compiled.len()];
    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    for line in lines {
        if let Some(ci) = compiled.iter().position(|(re, _)| re.is_match(&line)) {
            if kept[ci] < compiled[ci].1 {
                kept[ci] += 1;
                out.push(line);
                marker_pos[ci] = out.len();
            } else {
                dropped[ci] += 1;
            }
            continue;
        }
        out.push(line);
    }
    // Insert markers from the highest position down so earlier insertions
    // don't shift later ones.
    let mut markers: Vec<(usize, String)> = dropped
        .iter()
        .enumerate()
        .filter(|(_, d)| **d > 0)
        .map(|(ci, d)| {
            (
                marker_pos[ci],
                format!("[... {d} more similar line(s) omitted ...]"),
            )
        })
        .collect();
    markers.sort_by_key(|b| std::cmp::Reverse(b.0));
    for (pos, text) in markers {
        out.insert(pos.min(out.len()), text);
    }
    out
}

fn apply_sizing(lines: Vec<String>, f: &FilterDef) -> (Vec<String>, usize) {
    let original_len = lines.len();
    let n = lines.len();

    // Positional keep mask for the configured window.
    let mut keep = vec![true; n];
    let head_tail_combo = matches!((f.head_lines, f.tail_lines), (Some(h), Some(t)) if n > h + t);
    match (f.head_lines, f.tail_lines) {
        // head+tail together form a first+last window: header/context at the
        // top, verdict/summary at the bottom. The omitted middle gets an
        // explicit inline marker so the agent never sees a silent seam, and
        // is excluded from the returned count so notify_on_truncate does not
        // append a second, misplaced notice.
        (Some(head), Some(tail)) if n > head + tail => {
            for k in keep.iter_mut().take(n - tail).skip(head) {
                *k = false;
            }
        }
        // Both set but the output already fits the window — keep everything.
        (Some(_), Some(_)) => {}
        (Some(head), None) => {
            for k in keep.iter_mut().skip(head) {
                *k = false;
            }
        }
        (None, Some(tail)) => {
            for k in keep.iter_mut().take(n.saturating_sub(tail)) {
                *k = false;
            }
        }
        (None, None) => {
            if let Some(max) = f.max_lines {
                for k in keep.iter_mut().skip(max) {
                    *k = false;
                }
            }
        }
    }

    // Priority rescue: lines matching any priority regex survive the cut.
    if !f.priority_lines.is_empty() {
        let priority: Vec<Regex> = f
            .priority_lines
            .iter()
            .filter_map(|p| cached_regex(p))
            .collect();
        if !priority.is_empty() {
            for (i, line) in lines.iter().enumerate() {
                if !keep[i] && priority.iter().any(|re| re.is_match(line)) {
                    keep[i] = true;
                }
            }
        }
    }

    let dropped = keep.iter().filter(|k| !**k).count();
    if dropped == 0 {
        return (lines, 0);
    }

    let mut result: Vec<String> = Vec::with_capacity(n - dropped + 1);
    let mut marker_inserted = false;
    for (i, line) in lines.into_iter().enumerate() {
        if keep[i] {
            result.push(line);
        } else if head_tail_combo && !marker_inserted {
            result.push(format!("[... {dropped} lines omitted ...]"));
            marker_inserted = true;
        }
    }
    let omitted = if head_tail_combo {
        0
    } else {
        original_len - result.len()
    };
    (result, omitted)
}

/// Generate the TOML prompt to send to an AI CLI for filter creation.
pub fn build_filter_prompt(command: &str, sample_output: &str) -> String {
    format!(
        r#"Generate a tokenix TOML filter for the command `{command}`.

TOML filter schema (all fields optional except match_command):
```
[filters.<slug>]
description = "human-readable purpose"
match_command = "^regex_to_match_full_command_line"
strip_ansi = true          # remove ANSI color codes
strip_lines_matching = ["^pattern1", "^pattern2"]  # drop noisy lines
keep_lines_matching = ["error", "warning"]          # keep only signal lines
match_output = [           # short-circuit: if output matches pattern, return message
  {{ pattern = "already installed", message = "ok (already installed)" }},
  # optional `unless`: skip the short-circuit if output also matches it (avoids masking errors)
  {{ pattern = "Build complete!", message = "ok (build complete)", unless = "warning:|error:" }},
]
max_lines = 50             # truncate to N lines
head_lines = 30            # keep first N lines
tail_lines = 10            # keep last N lines
truncate_lines_at = 120    # truncate individual lines at N chars
on_empty = "command: ok"   # message when filter produces empty output

# ADVANCED (extended filtering capabilities):
replace_patterns = [       # regex replacements: [[pattern, replacement], ...]
  ["\\d+\\.\\d+s", "<duration>"],
  ["/home/[^/]+/", "~/"],
]
extract_sections = [       # extract content between markers
  {{ start_pattern = "---- FAILURES ----", end_pattern = "^\\s*$", include_markers = true, max_matches = 3 }},
  # records delimited only by their own header: each start line opens a new
  # section; keep 4 lines of each, the rest collapse into a count marker
  {{ start_pattern = "^commit ", end_pattern = "[^\\s\\S]", include_markers = true, split_on_start = true, max_lines = 4 }},
]
block_caps = [             # keep the first N lines of each block opened by `start`
  {{ start = "^warning: ", end = "^(\\s*$|[A-Za-z])", max_lines = 2 }},
]
filter_stderr = true       # also filter stderr (compilers write diagnostics there)
semantic_filter = {{       # keep lines sharing a keyword with `query`
  query = "test failure error panic",
  always_keep = ["^error\\[", "^FAIL"]
}}
deduplicate_blocks = {{    # structural block deduplication
  min_block_lines = 3,
  similarity = 0.8,
  block_delimiter = "^\\s*$"
}}
summarize_json = {{        # intelligent JSON summarization
  max_array_items = 10,
  max_depth = 3,
  always_include = ["packages", "workspace_members"],
  exclude = ["manifest", "dependencies"]
}}
token_budget = 2000        # hard token limit with smart truncation
```

Rules:
- Use strip_lines_matching to drop boilerplate (progress, verbose info)
- Use keep_lines_matching only if output has a clear signal/noise separation
- Use match_output for commands that succeed silently or with a predictable summary line
- Set on_empty when the command normally succeeds silently
- Use replace_patterns to normalize paths, timestamps, IDs, etc.
- Use extract_sections to pull out failure blocks, error sections, etc.
- Use semantic_filter to keep only lines sharing a keyword with a query
- Use deduplicate_blocks for repetitive output (test runs, build steps)
- Use summarize_json for large JSON (cargo metadata, API responses)
- Use token_budget as a hard cap with priority-based truncation
- match_command must be a valid Rust regex matching `{command}` or its typical invocations
- Return ONLY valid TOML, no markdown code fences, no explanations

Sample output from `{command} --help` (or similar):
---
{sample_output}
---

TOML filter:"#
    )
}

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

    /// An invalid filter regex (e.g. a look-ahead the `regex` crate rejects)
    /// must not vanish with just the bare parse error: the warning has to name
    /// the escape hatch (`tokenix doctor`), or an agent facing the raw stderr
    /// has no way to find which of the hundreds of possible filter files it
    /// came from — see `invalid_regex_warning`'s doc comment.
    #[test]
    fn invalid_regex_warning_points_at_doctor() {
        // Built at runtime, not passed as a literal: a literal invalid pattern
        // trips clippy's own `invalid_regex` lint, which is the point of this
        // test — the pattern is deliberately one the `regex` crate rejects.
        let pattern: String = ["[a-z]{2,3}", "(?=x)"].concat();
        let err = Regex::new(&pattern).unwrap_err();
        let msg = invalid_regex_warning(&pattern, &err);
        assert!(
            msg.contains("tokenix doctor"),
            "warning must point to the remediation command: {msg:?}"
        );
        assert!(
            msg.contains("[a-z]{2,3}(?=x)"),
            "warning must still name the offending pattern: {msg:?}"
        );
    }

    #[test]
    fn test_load_local_filters() {
        let temp_dir = std::env::current_dir()
            .unwrap()
            .join(".tokenix")
            .join("filters");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let toml_path = temp_dir.join("test_local_cmd.toml");
        std::fs::write(
            &toml_path,
            r#"
[filters.test_local_cmd]
description = "test local"
match_command = "^test_local_cmd$"
on_empty = "empty filter output"
"#,
        )
        .unwrap();

        // Trust gate: repo-local filters are skipped until `tokenix trust`.
        let root = crate::store::find_project_root(&std::env::current_dir().unwrap());
        let _ = set_repo_inputs_trust(&root, false);
        assert!(
            load_local_filters().is_empty(),
            "untrusted repo-local filters must not load"
        );

        set_repo_inputs_trust(&root, true).unwrap();
        let local_filters = load_local_filters();
        assert!(!local_filters.is_empty());
        let found = find_filter("test_local_cmd", &local_filters);
        assert!(found.is_some());
        let filter = found.unwrap();
        assert_eq!(filter.on_empty.as_deref(), Some("empty filter output"));

        // Editing a trusted file revokes trust (hash mismatch).
        std::fs::write(
            &toml_path,
            "[filters.test_local_cmd]\nmatch_command = \"^x$\"\n",
        )
        .unwrap();
        assert!(
            load_local_filters().is_empty(),
            "edited filter file must fail the trust check until re-trusted"
        );

        // Clean up
        let _ = set_repo_inputs_trust(&root, false);
        let _ = std::fs::remove_file(&toml_path);
        let _ = std::fs::remove_dir_all(
            std::env::current_dir()
                .unwrap()
                .join(".tokenix")
                .join("filters"),
        );
    }

    #[test]
    fn test_tokenize_command() {
        assert_eq!(tokenize_command("cargo test"), vec!["cargo", "test"]);
        assert_eq!(
            tokenize_command("echo \"hello world\""),
            vec!["echo", "hello world"]
        );
        assert_eq!(
            tokenize_command("env CI=true cargo test"),
            vec!["env", "CI=true", "cargo", "test"]
        );
    }

    #[test]
    fn test_unwrap_shell_runner() {
        assert_eq!(
            unwrap_shell_runner("bash -c 'cargo test'"),
            Some("cargo test".to_string())
        );
        assert_eq!(
            unwrap_shell_runner("powershell -Command \"cargo test\""),
            Some("cargo test".to_string())
        );
        assert_eq!(
            unwrap_shell_runner("cmd.exe /c \"cargo test\""),
            Some("cargo test".to_string())
        );
        assert_eq!(unwrap_shell_runner("cargo test"), None);
    }

    #[test]
    fn test_get_effective_command() {
        assert_eq!(
            get_effective_command("cd /app && CI=true cargo test"),
            "cargo test"
        );
        assert_eq!(
            get_effective_command("bash -c 'cd /app && CI=true env cargo test'"),
            "cargo test"
        );
        assert_eq!(
            get_effective_command("env CI=true cargo test"),
            "cargo test"
        );
        // timeout wrapper
        assert_eq!(
            get_effective_command("timeout 180 pnpm run test"),
            "pnpm run test"
        );
        assert_eq!(
            get_effective_command("timeout -k 10 180 pnpm run test"),
            "pnpm run test"
        );
        assert_eq!(
            get_effective_command("timeout --foreground 60s cargo test --quiet"),
            "cargo test --quiet"
        );
        // time wrapper
        assert_eq!(
            get_effective_command("time pnpm run build"),
            "pnpm run build"
        );
        // nice wrapper
        assert_eq!(get_effective_command("nice -n 10 make all"), "make all");
        // stacked: timeout + nice
        assert_eq!(
            get_effective_command("timeout 30 nice -n 5 pnpm run test"),
            "pnpm run test"
        );
        // pnpm / bun workspaces filters
        assert_eq!(
            get_effective_command("pnpm --filter @mika/desktop test"),
            "pnpm test"
        );
        assert_eq!(
            get_effective_command("bun --cwd /app run build"),
            "bun run build"
        );
        // pnpm -s (silent) short flag
        assert_eq!(get_effective_command("pnpm -s lint"), "pnpm lint");
        assert_eq!(get_effective_command("pnpm -s typecheck"), "pnpm typecheck");
        // PowerShell Set-Location / sl
        assert_eq!(
            get_effective_command("Set-Location /app && cargo test"),
            "cargo test"
        );
        assert_eq!(get_effective_command("sl /app; cargo test"), "cargo test");
    }

    #[test]
    fn test_derive_command_candidates() {
        let cmd = "bash -c 'cd /app && cargo test'";
        let candidates = derive_command_candidates(cmd);
        assert!(candidates.contains(&"bash -c 'cd /app && cargo test'".to_string()));
        assert!(candidates.contains(&"cd /app && cargo test".to_string()));
        assert!(candidates.contains(&"cargo test".to_string()));
    }

    #[test]
    fn scanned_anchor_never_overshoots_parsed_pattern() {
        // The lazy loader may only ever *under*-constrain: a scanned anchor must
        // be a prefix of the anchor the fully parsed pattern would produce, or
        // the file must be marked unprefilterable.
        for (name, anchors) in bundled_anchor_index() {
            let Some(anchors) = anchors else { continue };
            let file = BundledFilters::get(name).expect("embedded file");
            let content = std::str::from_utf8(file.data.as_ref()).expect("utf8");
            let parsed = parse_filter_file_named(content);
            assert_eq!(
                parsed.len(),
                anchors.len(),
                "{name}: scan found {} anchors for {} filters",
                anchors.len(),
                parsed.len()
            );
            for (_, def) in &parsed {
                let real = prefilter_for(&def.match_command);
                assert!(
                    real.as_ref().is_some_and(|r| anchors.contains(r)),
                    "{name}: scan lost the prefilter for {:?}",
                    def.match_command
                );
            }
        }
    }

    /// Command corpus used to homologate the prefilter: it must never reject a
    /// candidate the compiled regex would have matched.
    fn prefilter_probe_commands() -> Vec<String> {
        let mut cmds: Vec<String> = [
            "cargo test --quiet",
            "cargo build --release",
            "npm install",
            "npx eslint src/ --fix",
            "pnpm run build",
            "yarn dlx prettier --write .",
            "uv run pytest -x",
            "python -m ruff check .",
            "git status",
            "git -C /repo log --oneline",
            "docker compose up -d",
            "docker build -t app .",
            "kubectl -n prod get pods",
            "terraform plan",
            "Get-Content big.log",
            "Get-CimInstance Win32_Process",
            "sudo apt-get install curl",
            "sudo apk add curl",
            "bash -c 'cd /app && actionlint'",
            "npx cypress run --headless",
            "timeout 300 bats tests/",
            "gradlew build",
            "./mvnw -q verify",
            "cd web && npx astro build",
            "zzz_nonexistent --foo",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        // Every bundled filter contributes its own literal as a probe, so a
        // pattern shape nobody wrote a scenario for is still covered.
        for f in load_bundled_filters() {
            match prefilter_for(&f.match_command) {
                Some(Prefilter::StartsWith(lit)) => cmds.push(format!("{lit} --flag arg")),
                Some(Prefilter::Contains(lit, _)) => cmds.push(format!("npx {lit} --flag arg")),
                None => {}
            }
        }
        // Real invocations recorded in the corpus: these are the exact strings
        // the golden suite asserts `match_command` matches, so they are the
        // strongest available evidence that the prefilter admits real matches.
        for asset in BundledFilters::iter() {
            let Some(file) = BundledFilters::get(&asset) else {
                continue;
            };
            let Ok(content) = std::str::from_utf8(file.data.as_ref()) else {
                continue;
            };
            let Ok(parsed) = toml::from_str::<FilterTestFile>(content) else {
                continue;
            };
            for cases in parsed.tests.values() {
                cmds.extend(cases.iter().filter_map(|c| c.command.clone()));
            }
        }
        cmds
    }

    #[test]
    fn prefilter_never_rejects_a_real_match() {
        // The whole optimization rests on this: the prefilter is a NECESSARY
        // condition, so `regex matches` must imply `prefilter allows`.
        let commands = prefilter_probe_commands();
        let mut checked = 0usize;
        for f in load_bundled_filters()
            .iter()
            .chain(load_user_filters().iter())
        {
            let Some(pf) = prefilter_for(&f.match_command) else {
                continue;
            };
            let Some(re) = cached_regex(&f.match_command) else {
                continue;
            };
            for cmd in &commands {
                if re.is_match(cmd) {
                    assert!(
                        pf.allows(cmd),
                        "prefilter {pf:?} rejected {cmd:?} which {:?} matches",
                        f.match_command
                    );
                }
                checked += 1;
            }
        }
        assert!(checked > 100_000, "corpus too small: {checked} pairs");
    }

    #[test]
    fn head_slice_never_drops_a_filter_declared_after_a_fake_tests_marker() {
        // The head slice cuts at the first line starting with `[[tests`. If
        // that line lives inside a multi-line value, the cut lands before a
        // later `[filters.x]` table. What makes this safe is not a guard but
        // TOML itself: the cut always leaves the string unterminated, so the
        // head fails to parse and the full-file fallback runs. This test pins
        // that reasoning down — if the fast path ever starts accepting a
        // truncated head, it fails here instead of silently losing a filter.
        let content = "\
[filters.first]
match_command = \"^first\\\\b\"
on_empty = \"\"\"
sample text
[[tests.not-really]] this line is inside a string
\"\"\"

[filters.second]
match_command = \"^second\\\\b\"

[[tests.first]]
input = \"\"
expected = \"\"
";
        let parsed = parse_filter_file_named(content);
        let names: Vec<&str> = parsed.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            parsed.len(),
            2,
            "head slice dropped a filter; got {names:?}"
        );
    }

    #[test]
    fn user_filter_index_invalidates_on_same_length_edit() {
        // Regression: the index stamp was seconds + length. Fixing a pattern
        // without changing its byte length (`^alpha` -> `^bravo`) inside the
        // same second left the stamp identical, so the hook kept prefiltering
        // by the OLD pattern and the edited filter silently stopped matching.
        let dir = std::env::temp_dir().join(format!("tokenix-idx-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("temp dir");
        let file = dir.join("probe.toml");
        let toml_for = |cmd: &str| {
            format!("[filters.probe]\nmatch_command = \"^{cmd}\\\\b\"\nmax_lines = 10\n")
        };

        std::fs::write(&file, toml_for("alpha")).expect("write");
        let first = user_filter_index(&dir);
        let stamp_a = user_filter_stats(&dir)[0].1;

        // Same byte length, a realistic edit interval later — the case a
        // seconds-resolution stamp cannot see. The sleep clears the platform's
        // file-time tick (Windows updates file times on the ~15 ms system
        // clock tick, so sub-tick writes share a stamp on any resolution).
        std::thread::sleep(std::time::Duration::from_millis(25));
        std::fs::write(&file, toml_for("bravo")).expect("rewrite");
        let stamp_b = user_filter_stats(&dir)[0].1;
        let second = user_filter_index(&dir);
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(
            first[0].prefilters,
            Some(vec![Prefilter::StartsWith("alpha".into())])
        );
        // The whole cache rests on this: the stamp MUST distinguish two
        // consecutive same-length writes, or a filter edit is invisible to
        // every later hook. A failure here means the filesystem's timestamp
        // resolution is too coarse to validate the index by metadata.
        assert_ne!(
            stamp_a, stamp_b,
            "mtime stamp cannot distinguish two same-length writes"
        );
        assert_eq!(
            second[0].prefilters,
            Some(vec![Prefilter::StartsWith("bravo".into())]),
            "index served a stale prefilter after a same-length edit"
        );
    }

    #[test]
    fn piped_select_string_still_resolves_its_filter() {
        // `^Select-String\b|\|\s*Select-String\b` has a top-level alternation,
        // so only the FIRST branch is anchored. The leading-literal prefilter
        // used to demand that the candidate start with "Select-String", which
        // rejects the piped form the second branch exists for.
        //
        // In practice `split_on_operators` saved it: the segment candidate
        // `Select-String -Pattern ERROR` matches branch 1 on its own. So this
        // was a violated prefilter contract ("may only skip work, never change
        // results"), one candidate-derivation change away from becoming a real
        // miss — not a user-visible bug. This test pins the end-to-end shape;
        // `top_level_alternation_detection` pins the contract itself.
        let filters = load_bundled_filters();
        let cmd = "Get-Content log.txt | Select-String -Pattern ERROR";
        assert!(
            find_filter(cmd, &filters).is_some(),
            "piped Select-String must resolve a filter"
        );
    }

    #[test]
    fn top_level_alternation_detection() {
        assert!(has_top_level_alternation(r"^a\b|\|\s*a\b"));
        assert!(has_top_level_alternation("foo|bar"));
        // Alternation contained in a group is fine — the group is mandatory,
        // so the surrounding literal (if any) still applies.
        assert!(!has_top_level_alternation(r"^git\s+(add|rm)\b"));
        // `\|` is a literal pipe, `[|]` is a class member.
        assert!(!has_top_level_alternation(r"^grep\s+\|"));
        assert!(!has_top_level_alternation(r"^grep[|]x"));
    }

    #[test]
    fn uniform_success_is_a_claim_about_the_run_not_one_line() {
        // The reason `match_output` cannot express this: it fires on ANY
        // matching line, so a run where item 3 failed still reports success.
        let cfg = UniformSuccess {
            pattern: "^PASS - ".to_string(),
            message: "conftest: {n} policies passed".to_string(),
            ignore_lines: vec!["^Summary".to_string()],
        };

        let all_pass = "PASS - a.yaml - main\nPASS - b.yaml - main\nPASS - c.yaml - main\n";
        assert_eq!(
            uniform_summary(all_pass, &cfg).as_deref(),
            Some("conftest: 3 policies passed"),
            "a uniform run must collapse, with the real item count"
        );

        // One dissenting line is enough to disqualify the whole run.
        let mixed = "PASS - a.yaml - main\nFAIL - b.yaml - missing label\nPASS - c.yaml - main\n";
        assert_eq!(
            uniform_summary(mixed, &cfg),
            None,
            "a failed item must never be summarized as success"
        );

        // Unrecognized output is not a clean run either — this is what the 40
        // absence-based sentinels used to get wrong.
        assert_eq!(uniform_summary("some other tool output\n", &cfg), None);
        // Nothing to summarize is not success.
        assert_eq!(uniform_summary("\n  \n", &cfg), None);
        // Ignored lines don't count as items, but don't disqualify either.
        assert_eq!(
            uniform_summary("Summary: 1 checks\nPASS - a.yaml - main\n", &cfg).as_deref(),
            Some("conftest: 1 policies passed")
        );
    }

    #[test]
    fn prefilter_shapes() {
        assert_eq!(
            prefilter_for(r"^cargo\s+test"),
            Some(Prefilter::StartsWith("cargo".into()))
        );
        assert_eq!(
            prefilter_for(r"\bactionlint\b"),
            Some(Prefilter::Contains("actionlint".into(), false))
        );
        assert_eq!(
            prefilter_for(r"^(npx\s+)?eslint\b"),
            Some(Prefilter::Contains("eslint".into(), false))
        );
        assert_eq!(
            prefilter_for(r"(?i)^(get-ciminstance|gcim)\b"),
            None,
            "mandatory alternation cannot be reduced to one literal"
        );
        assert_eq!(
            prefilter_for(r"^(?:sudo\s+)?apk\s+(add|del)\b"),
            Some(Prefilter::Contains("apk".into(), false))
        );
        // `.` and `+` are metacharacters: the run must stop before them.
        assert_eq!(
            prefilter_for("^go.mod"),
            Some(Prefilter::StartsWith("go".into()))
        );
        // A quantified last character is optional and must be dropped.
        assert_eq!(
            prefilter_for(r"\bmake?\b"),
            Some(Prefilter::Contains("mak".into(), false))
        );
        // Too little literal left to be worth a scan.
        assert_eq!(prefilter_for(r"\bgo?\b"), None);
    }

    #[test]
    fn lazy_load_matches_full_load_for_commands() {
        let all = load_all_filters();
        let commands = [
            "cargo test --quiet",
            "npm install",
            "git status",
            "docker compose up -d",
            "cd /app && pnpm run build",
            "bash -c 'uv run pytest -q'",
            "kubectl -n prod get pods",
            "Get-Content big.log",
            "zzz_nonexistent --foo",
            "terraform plan",
        ];
        for cmd in commands.iter().map(|s| s.to_string()).chain(
            // Reuse the wide probe corpus so the lazy loader is homologated
            // against every bundled filter's own literal, not just scenarios.
            prefilter_probe_commands(),
        ) {
            let lazy = load_filter_groups_for_command(&cmd).concat();
            let full = find_filter(&cmd, &all).map(|f| f.match_command.clone());
            let subset = find_filter(&cmd, &lazy).map(|f| f.match_command.clone());
            assert_eq!(full, subset, "lazy load diverged for {cmd:?}");
        }
    }

    #[test]
    fn timeout_wrapper_included_in_candidates() {
        // Reported: `timeout 180 pnpm run test` must produce `pnpm run test`
        // as a candidate so filters keyed on `pnpm run test` match.
        let candidates = derive_command_candidates("timeout 180 pnpm run test");
        assert!(
            candidates.contains(&"pnpm run test".to_string()),
            "candidates: {candidates:?}"
        );
    }

    #[test]
    fn truncate_at_char_boundary_handles_multibyte() {
        // ASCII: exact byte cut
        assert_eq!(truncate_at_char_boundary("hello world", 5), "hello");
        // Shorter than limit: unchanged
        assert_eq!(truncate_at_char_boundary("hi", 10), "hi");
        // Multibyte: 'é' is 2 bytes — cutting at byte 4 lands mid-char, must back off
        let s = "café latte"; // 'é' occupies bytes 3..5
        let out = truncate_at_char_boundary(s, 4);
        assert!(s.starts_with(out));
        assert_eq!(out, "caf"); // backed off to char boundary, no panic
    }

    #[test]
    fn apply_filter_truncate_lines_at_no_panic_on_utf8() {
        let f = FilterDef {
            description: None,
            match_command: ".*".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: Some(4),
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        // Would panic with naive &l[..4] because 'é'/'ç' straddle the boundary.
        let out = apply_filter("café\nação\n", &f);
        assert_eq!(out, "caf\naç");
    }

    #[test]
    fn split_on_operators_handles_compound_commands() {
        // Spaced and unspaced operators segment identically.
        assert_eq!(
            split_on_operators("cd foo && gitleaks detect"),
            vec!["cd foo", "gitleaks detect"]
        );
        assert_eq!(
            split_on_operators("cd foo;gitleaks"),
            vec!["cd foo", "gitleaks"]
        );
        assert_eq!(split_on_operators("a || b"), vec!["a", "b"]);
        assert_eq!(
            split_on_operators("producer | gitleaks detect"),
            vec!["producer", "gitleaks detect"]
        );
        // Quoted operators are not split points.
        assert_eq!(
            split_on_operators(r#"echo "a;b" && x"#),
            vec![r#"echo "a;b""#, "x"]
        );
    }

    #[test]
    fn filter_matches_whole_command_rejects_compound_prefix_match() {
        // Regression: `^git\s+log\b` is start-anchored only. Against a
        // `&&`-chained compound command, `Regex::is_match` still reports
        // true because it matches the FIRST segment's prefix, not because
        // the filter is really "the whole command". That falsely told the
        // caller an allowlist filter could safely run over the entire
        // concatenated output of every chained sub-command.
        let compound = "git log --oneline -3 && echo marker-A";
        assert!(!filter_matches_whole_command(compound, r"^git\s+log\b"));

        // A genuinely single (non-compound) command still matches.
        let single = "git log --oneline -3";
        assert!(filter_matches_whole_command(single, r"^git\s+log\b"));

        // A `cd` prefix is not a second command: the effective command still matches.
        assert!(filter_matches_whole_command(
            "cd repo && git log --oneline -3",
            r"^git\s+log\b"
        ));
    }

    #[test]
    fn derive_candidates_segments_compound_commands() {
        let candidates = derive_command_candidates("cd foo;gitleaks detect --source .");
        assert!(
            candidates.iter().any(|c| c == "gitleaks detect --source ."),
            "expected a gitleaks segment candidate, got: {candidates:?}"
        );
    }

    #[test]
    fn find_filter_matches_command_after_cd_and_pipe() {
        let f = FilterDef {
            description: None,
            match_command: "^gitleaks\\b".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        let filters = [f];
        // Unspaced semicolon, cd prefix, and a pipe all resolve to the filter.
        assert!(find_filter("cd repo;gitleaks detect", &filters).is_some());
        assert!(find_filter("npm i && gitleaks detect", &filters).is_some());
        assert!(find_filter("cat x | gitleaks detect", &filters).is_some());
        // A bare argument named gitleaks must NOT match (anchored base command).
        assert!(find_filter("echo gitleaks", &filters).is_none());

        // Test pipeline segment prioritization: B takes priority over A in "A | B"
        let f_cat = FilterDef {
            description: None,
            match_command: "^cat\\b".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        let f_gitleaks = FilterDef {
            description: None,
            match_command: "^gitleaks\\b".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        let filters2 = [f_cat, f_gitleaks];
        let matched = find_filter("cat x | gitleaks detect", &filters2).unwrap();
        assert_eq!(matched.match_command, "^gitleaks\\b");
    }

    #[test]
    fn skip_when_matches_bypasses_already_bounded_reads() {
        let f = FilterDef {
            description: None,
            match_command: "^(Get-Content|gc)\\b".to_string(),
            skip_when_matches: Some("(?i)-Tail\\b|-TotalCount\\b|-Head\\b|-Raw\\b".to_string()),
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        let filters = [f];
        // Unbounded full dump: filter applies.
        assert!(find_filter("Get-Content large.log", &filters).is_some());
        // Agent already sliced its own read: filter steps aside.
        assert!(find_filter("Get-Content large.log -Tail 20", &filters).is_none());
        assert!(find_filter("Get-Content large.log -TotalCount 50", &filters).is_none());
    }

    #[test]
    fn strip_subcommand_global_opts_normalizes_tool_globals() {
        let eff = |c: &str| get_effective_command(c);
        // git global options before the subcommand are peeled away.
        assert_eq!(eff("git -C /repo add ."), "git add .");
        assert_eq!(eff("git -c user.name=x commit -m hi"), "git commit -m hi");
        assert_eq!(eff("git --git-dir=/r/.git -C /r status"), "git status");
        assert_eq!(eff("git --no-pager log --oneline"), "git log --oneline");
        // kubectl / docker / cargo share the same global-option bug class.
        assert_eq!(eff("kubectl -n prod get pods"), "kubectl get pods");
        assert_eq!(eff("docker -H tcp://h ps -a"), "docker ps -a");
        assert_eq!(eff("cargo +nightly test"), "cargo test");
        // terraform / tofu `-chdir=DIR` global flag precedes the subcommand.
        assert_eq!(eff("terraform -chdir=./infra apply"), "terraform apply");
        assert_eq!(eff("terraform -chdir ./infra apply"), "terraform apply");
        assert_eq!(
            eff("terraform -chdir=/a/b plan -out=p"),
            "terraform plan -out=p"
        );
        assert_eq!(eff("tofu -chdir=. init"), "tofu init");
        assert_eq!(eff("kubectl -n=prod get pods"), "kubectl get pods");
        // Subcommand-less or unknown tools are untouched.
        assert_eq!(eff("git status"), "git status");
        assert_eq!(eff("ls -la"), "ls -la");
        // Trailing valued options do not panic.
        assert_eq!(eff("git -C"), "git");
        assert_eq!(eff("git --git-dir"), "git");
    }

    #[test]
    fn strip_package_runner_exposes_inner_tool() {
        let eff = |c: &str| get_effective_command(c);
        assert_eq!(eff("uv run pytest tests/"), "pytest tests/");
        assert_eq!(eff("python -m ruff check ."), "ruff check .");
        assert_eq!(eff("python3 -m pytest"), "pytest");
        assert_eq!(eff("bunx biome check src"), "biome check src");
        assert_eq!(eff("npx tsc --noEmit"), "tsc --noEmit");
        assert_eq!(eff("pnpm exec eslint ."), "eslint .");
        assert_eq!(eff("pnpm dlx prettier -w ."), "prettier -w .");
        // Bare `pnpm build` is a script, not a runner — left untouched.
        assert_eq!(eff("pnpm build"), "pnpm build");
        // Composes with global-opt stripping: `uv run` then nothing to strip.
        assert_eq!(eff("npx kubectl -n ns get pods"), "kubectl get pods");
    }

    #[test]
    fn find_filter_matches_git_with_global_options() {
        let f = FilterDef {
            description: None,
            match_command: "^git\\s+add\\b".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        let filters = [f];
        assert!(find_filter("git -C /repo add .", &filters).is_some());
        assert!(find_filter("cd x && git -c k=v add -A", &filters).is_some());
    }

    #[test]
    fn bundled_filters_route_new_targets() {
        let filters = load_bundled_filters();
        let desc = |cmd: &str| {
            find_filter(cmd, &filters)
                .and_then(|f| f.description.clone())
                .unwrap_or_default()
                .to_lowercase()
        };
        // real-world command forms (global flags / cd prefix) must reach the new filters
        assert!(
            desc("git -C /repo add .").contains("line-ending"),
            "git add"
        );
        assert!(
            desc("cd repo && git commit -m x").contains("file-mode"),
            "git commit"
        );
        assert!(
            desc("pnpm --filter @x/y remove hono").contains("remove"),
            "pnpm remove"
        );
        assert!(
            desc("Get-CimInstance Win32_Service").contains("ciminstance"),
            "get-ciminstance"
        );
    }

    #[test]
    fn apply_filter_match_output_unless_guards_errors() {
        let f = FilterDef {
            description: None,
            match_command: ".*".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![MatchOutput {
                pattern: "total size is".to_string(),
                message: "ok (synced)".to_string(),
                unless: Some("error|failed".to_string()),
            }],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        };
        // Pattern present, no error → short-circuit to message
        assert_eq!(apply_filter("total size is 100\n", &f), "ok (synced)");
        // Pattern present AND error present → unless guard blocks short-circuit
        let out = apply_filter("rsync error\ntotal size is 100\n", &f);
        assert!(out.contains("error"), "error must not be masked: {out:?}");
    }

    /// Minimal `FilterDef` with everything off — scenario tests flip only the
    /// one field under test instead of repeating the full struct literal.
    #[test]
    fn head_fast_path_keeps_filter_declared_after_a_tests_block() {
        // Regression: the head slice cut at the first `[[tests` and returned
        // early, silently dropping `second`.
        let content = r#"
[filters.first]
match_command = "^first\\b"

[[tests.first]]
input = "x"
expect = "x"

[filters.second]
match_command = "^second\\b"
"#;
        let names: Vec<String> = parse_filter_file_named(content)
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        assert!(names.contains(&"second".to_string()), "got {names:?}");
    }

    #[test]
    fn match_output_does_not_mask_a_failing_run() {
        // Regression: the sentinel fired on any output containing the success
        // marker, with the opt-in `unless` as the only guard.
        let mut f = base_filter();
        f.match_output = vec![MatchOutput {
            pattern: "no leaks found".to_string(),
            message: "gitleaks: no leaks found".to_string(),
            unless: None,
        }];
        let failing = "no leaks found\nerror: failed to push some refs";
        let out = apply_filter(failing, &f);
        assert!(
            out.contains("error"),
            "failure text must survive, got {out:?}"
        );
    }

    #[test]
    fn unparseable_unless_fails_closed() {
        let mut f = base_filter();
        f.match_output = vec![MatchOutput {
            pattern: "done".to_string(),
            message: "ok".to_string(),
            unless: Some("(?i".to_string()), // never compiles
        }];
        let out = apply_filter("done", &f);
        assert_ne!(out, "ok", "a broken guard must not enable the sentinel");
    }

    fn base_filter() -> FilterDef {
        FilterDef {
            description: None,
            match_command: ".*".to_string(),
            skip_when_matches: None,
            notify_on_truncate: false,
            strip_ansi: false,
            strip_lines_matching: vec![],
            keep_lines_matching: vec![],
            max_lines: None,
            head_lines: None,
            tail_lines: None,
            on_empty: None,
            passthrough_when_emptied: false,
            match_output: vec![],
            truncate_lines_at: None,
            uniform_success: None,
            filter_stderr: false,
            replace_patterns: vec![],
            extract_sections: vec![],
            semantic_filter: None,
            deduplicate_blocks: None,
            summarize_json: None,
            token_budget: None,
            on_failure: None,
            priority_lines: vec![],
            category_caps: vec![],
            block_caps: vec![],
        }
    }

    #[test]
    fn apply_filter_strip_ansi_removes_color_codes() {
        let mut f = base_filter();
        f.strip_ansi = true;
        assert_eq!(
            apply_filter("\x1b[31merror\x1b[0m here\n", &f),
            "error here"
        );
    }

    #[test]
    fn apply_filter_strip_lines_matching_drops_noise() {
        let mut f = base_filter();
        f.strip_lines_matching = vec!["^DEBUG".to_string(), "^\\s*$".to_string()];
        let out = apply_filter("DEBUG init\nreal line\n\nDEBUG done\nkeep me\n", &f);
        assert_eq!(out, "real line\nkeep me");
    }

    #[test]
    fn apply_filter_keep_lines_matching_keeps_signal() {
        let mut f = base_filter();
        f.keep_lines_matching = vec!["warn|error".to_string()];
        let out = apply_filter("info: starting\nwarn: low disk\nok\nerror: boom\n", &f);
        assert_eq!(out, "warn: low disk\nerror: boom");
    }

    #[test]
    fn apply_filter_sizing_head_tail_max() {
        let input = "l1\nl2\nl3\nl4\nl5\n";
        let mut head = base_filter();
        head.head_lines = Some(2);
        assert_eq!(apply_filter(input, &head), "l1\nl2");

        let mut tail = base_filter();
        tail.tail_lines = Some(2);
        assert_eq!(apply_filter(input, &tail), "l4\nl5");

        let mut max = base_filter();
        max.max_lines = Some(3);
        assert_eq!(apply_filter(input, &max), "l1\nl2\nl3");

        // head+tail combine into a first+last window with an explicit middle
        // marker (rtk parity): header/context on top, verdict at the bottom.
        let long_input = (1..=40)
            .map(|i| format!("line number {i} with some payload text"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut both = base_filter();
        both.head_lines = Some(2);
        both.tail_lines = Some(2);
        let out = apply_filter(&long_input, &both);
        assert_eq!(
            out,
            "line number 1 with some payload text\n\
             line number 2 with some payload text\n\
             [... 36 lines omitted ...]\n\
             line number 39 with some payload text\n\
             line number 40 with some payload text"
        );

        // The middle marker replaces the notify_on_truncate end notice — no
        // double marker for the same cut.
        let mut both_notify = base_filter();
        both_notify.head_lines = Some(2);
        both_notify.tail_lines = Some(2);
        both_notify.notify_on_truncate = true;
        assert_eq!(apply_filter(&long_input, &both_notify), out);
    }

    #[test]
    fn apply_filter_never_worse_than_raw() {
        // A success message longer than the raw output reverts to the raw:
        // filtering must never cost more tokens than not filtering.
        let mut f = base_filter();
        f.match_output = vec![MatchOutput {
            pattern: "ok".to_string(),
            message: "everything completed successfully with no findings".to_string(),
            unless: None,
        }];
        assert_eq!(apply_filter("ok\n", &f), "ok");

        // Same guard for truncation notices on tiny outputs.
        let mut noisy = base_filter();
        noisy.max_lines = Some(1);
        noisy.notify_on_truncate = true;
        assert_eq!(apply_filter("a\nb\n", &noisy), "a\nb");

        // Genuinely empty raw is exempt so on_empty sentinels still fire.
        let mut empty = base_filter();
        empty.on_empty = Some("cmd: ok".to_string());
        assert_eq!(apply_filter("", &empty), "cmd: ok");
    }

    #[test]
    fn apply_filter_with_exit_failure_policies() {
        // on_failure = "passthrough": nonzero exit emits raw untouched.
        let mut f = base_filter();
        f.keep_lines_matching = vec!["^KEEP".to_string()];
        f.on_failure = Some("passthrough".to_string());
        let raw = "some context line\nanother detail line\nKEEP this one\n";
        assert_eq!(
            apply_filter_with_exit(raw, &f, Some(false)),
            "some context line\nanother detail line\nKEEP this one"
        );
        // Success (or unknown exit) still filters normally.
        assert_eq!(apply_filter_with_exit(raw, &f, Some(true)), "KEEP this one");
        assert_eq!(apply_filter_with_exit(raw, &f, None), "KEEP this one");

        // on_failure = "tail:N": last N raw lines.
        let mut t = base_filter();
        t.keep_lines_matching = vec!["^KEEP".to_string()];
        t.on_failure = Some("tail:2".to_string());
        assert_eq!(
            apply_filter_with_exit(raw, &t, Some(false)),
            "another detail line\nKEEP this one"
        );
    }

    #[test]
    fn apply_filter_with_exit_suppresses_success_sentinels() {
        // A success match_output must not fire on a known-failed command,
        // even when the output contains its success marker.
        let mut f = base_filter();
        f.match_output = vec![MatchOutput {
            pattern: "Build complete!".to_string(),
            message: "ok".to_string(),
            unless: None,
        }];
        let raw = "Build complete! (but the linker crashed afterwards)\n";
        assert_eq!(apply_filter_with_exit(raw, &f, Some(false)), raw.trim_end());

        // on_empty must not report success for a failed command: benign-looking
        // emptied output falls back to a bounded raw view instead.
        let mut e = base_filter();
        e.keep_lines_matching = vec!["^NEVER".to_string()];
        e.on_empty = Some("cmd: ok".to_string());
        let benign = "all tasks completed with warnings suppressed\n";
        assert_eq!(
            apply_filter_with_exit(benign, &e, Some(false)),
            benign.trim_end()
        );
        // And a failed command that printed nothing yields nothing — never the
        // success sentinel.
        assert_eq!(apply_filter_with_exit("", &e, Some(false)), "");
    }

    #[test]
    fn apply_filter_priority_lines_survive_sizing() {
        let mut f = base_filter();
        f.max_lines = Some(2);
        f.priority_lines = vec!["^error".to_string(), "^Summary:".to_string()];
        let input = (1..=6)
            .map(|i| format!("noise line number {i} with plenty of padding"))
            .collect::<Vec<_>>()
            .join("\n")
            + "\nerror: the thing that matters\nSummary: 1 failed\n";
        let out = apply_filter(&input, &f);
        assert_eq!(
            out,
            "noise line number 1 with plenty of padding\n\
             noise line number 2 with plenty of padding\n\
             error: the thing that matters\n\
             Summary: 1 failed"
        );
    }

    #[test]
    fn apply_filter_category_caps_bound_each_class() {
        let mut f = base_filter();
        f.category_caps = vec![CategoryCap {
            pattern: "^warning:".to_string(),
            max: 2,
        }];
        let input = "warning: first warning about a thing\n\
                     warning: second warning about a thing\n\
                     warning: third warning about a thing\n\
                     warning: fourth warning about a thing\n\
                     error: the actual problem to look at\n";
        let out = apply_filter(input, &f);
        assert_eq!(
            out,
            "warning: first warning about a thing\n\
             warning: second warning about a thing\n\
             [... 2 more similar line(s) omitted ...]\n\
             error: the actual problem to look at"
        );
    }

    #[test]
    fn filter_def_rejects_unknown_fields() {
        let toml = r#"
[filters.typo]
match_command = "^typo\\b"
keep_lines_matchin = ["oops"]
"#;
        assert!(
            toml::from_str::<FilterFile>(toml).is_err(),
            "typo'd field must fail loudly, not silently no-op"
        );
    }

    #[test]
    fn notify_on_truncate_is_opt_in_per_filter() {
        // Inputs are long enough that notice + kept lines stay cheaper than
        // raw, so the never_worse guard does not revert them.
        let input = (1..=9)
            .map(|i| format!("line {i} with enough payload to keep the notice cheaper"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut silent = base_filter();
        silent.max_lines = Some(2);
        assert!(!apply_filter(&input, &silent).contains("omitted"));

        let mut noisy = base_filter();
        noisy.max_lines = Some(2);
        noisy.notify_on_truncate = true;
        assert!(apply_filter(&input, &noisy).ends_with("[... 7 lines omitted (line limit) ...]"));

        let mut noisy_chars = base_filter();
        noisy_chars.truncate_lines_at = Some(24);
        noisy_chars.notify_on_truncate = true;
        let long_lines = format!(
            "café {0}\nação {0}\n",
            "is a rather long line with plenty of payload so the notice stays cheaper than raw"
        );
        assert!(apply_filter(&long_lines, &noisy_chars)
            .ends_with("[... 2 line(s) truncated to 24 chars ...]"));
    }

    #[test]
    fn apply_filter_replace_patterns_rewrites_lines() {
        let mut f = base_filter();
        f.replace_patterns = vec![
            ["\\d+\\.\\d+s".to_string(), "<dur>".to_string()],
            ["/home/[^/]+/".to_string(), "~/".to_string()],
        ];
        let out = apply_filter("built in 1.23s at /home/bob/app\n", &f);
        assert_eq!(out, "built in <dur> at ~/app");
    }

    #[test]
    fn apply_filter_extract_sections_between_markers() {
        let mut f = base_filter();
        f.extract_sections = vec![ExtractSection {
            start_pattern: "^START".to_string(),
            end_pattern: "^END".to_string(),
            include_markers: false,
            max_matches: None,
            max_lines: None,
            split_on_start: false,
        }];
        let out = apply_filter("noise\nSTART\na\nb\nEND\ntrailing\n", &f);
        assert_eq!(out, "a\nb");

        // include_markers keeps the boundary lines.
        f.extract_sections[0].include_markers = true;
        let out2 = apply_filter("noise\nSTART\na\nEND\n", &f);
        assert_eq!(out2, "START\na\nEND");
    }

    #[test]
    fn apply_filter_extract_sections_keeps_source_order_and_unclosed_tail() {
        // Two sections, configured in the opposite order to how they appear.
        // The verdict line must not be delivered before the evidence, and the
        // unclosed trailing section must survive even with include_markers off.
        let mut f = base_filter();
        f.extract_sections = vec![
            ExtractSection {
                start_pattern: "^ERROR".to_string(),
                end_pattern: "^NEVER_CLOSES".to_string(),
                include_markers: false,
                max_matches: None,
                max_lines: None,
                split_on_start: false,
            },
            ExtractSection {
                start_pattern: "^-----".to_string(),
                end_pattern: "^-----$".to_string(),
                include_markers: false,
                max_matches: None,
                max_lines: None,
                split_on_start: false,
            },
        ];
        let input =
            "noise\n-----\nframe one\nframe two\n-----\nERROR: failed to solve\ntail detail\n";
        let out = apply_filter(input, &f);
        let frame = out
            .find("frame one")
            .unwrap_or_else(|| panic!("frames kept: {out:?}"));
        let tail = out
            .find("tail detail")
            .unwrap_or_else(|| panic!("unclosed section kept: {out:?}"));
        assert!(
            frame < tail,
            "evidence must precede the trailing section: {out:?}"
        );
    }

    #[test]
    fn apply_filter_extract_sections_no_match_returns_original() {
        let mut f = base_filter();
        f.extract_sections = vec![ExtractSection {
            start_pattern: "^NEVER".to_string(),
            end_pattern: "^NOPE".to_string(),
            include_markers: false,
            max_matches: None,
            max_lines: None,
            split_on_start: false,
        }];
        // No marker present → falls back to the unmodified content.
        assert_eq!(apply_filter("just\ntwo lines\n", &f), "just\ntwo lines");
    }

    #[test]
    fn apply_filter_deduplicate_blocks_collapses_repeats() {
        let mut f = base_filter();
        f.deduplicate_blocks = Some(DeduplicateBlocksDef {
            min_block_lines: 3,
            similarity: 0.8,
            block_delimiter: None,
        });
        let block = "connection refused to upstream host\nretrying with backoff enabled\ngiving up after three attempts";
        let input = format!("{block}\n\n{block}\n\n{block}\n");
        let out = apply_filter(&input, &f);
        assert!(
            out.starts_with("connection refused to upstream host"),
            "first block kept: {out:?}"
        );
        assert!(
            out.contains("2 similar block(s) omitted"),
            "duplicates collapsed: {out:?}"
        );
    }

    #[test]
    fn apply_filter_deduplicate_blocks_keeps_short_blocks() {
        // A block shorter than `min_block_lines` is ineligible for collapsing,
        // not eligible for deletion. The lone line above a repetitive log is
        // usually the one that matters — a failure the agent must see.
        let mut f = base_filter();
        f.deduplicate_blocks = Some(DeduplicateBlocksDef {
            min_block_lines: 3,
            similarity: 0.8,
            block_delimiter: None,
        });
        let block = "connection refused to upstream host\nretrying with backoff enabled\ngiving up after three attempts";
        let input = format!("fatal: bad revision 'HEAD~99'\n\n{block}\n\n{block}\n");
        let out = apply_filter(&input, &f);
        assert!(
            out.contains("fatal: bad revision 'HEAD~99'"),
            "the one-line block must survive: {out:?}"
        );
        assert!(
            out.contains("1 similar block(s) omitted"),
            "eligible duplicates still collapse: {out:?}"
        );
    }

    #[test]
    fn apply_filter_token_budget_truncates_with_marker() {
        let mut f = base_filter();
        f.token_budget = Some(10);
        let mut input = String::from("error: critical failure\n");
        for i in 0..60 {
            input.push_str(&format!("filler line number {i} with words\n"));
        }
        let out = apply_filter(&input, &f);
        assert!(
            out.contains("omitted to fit token budget"),
            "expected truncation marker: {out:?}"
        );
        assert!(
            out.len() < input.len(),
            "budgeted output must be smaller than input"
        );
    }

    #[test]
    fn apply_filter_token_budget_keeps_source_order() {
        // A budget that drops *some* middle lines must still deliver the
        // survivors in the order the command printed them: an agent reading a
        // panic body after the "test result: FAILED" verdict misreads which
        // assertion failed.
        let mut f = base_filter();
        f.token_budget = Some(210);
        let mut input = String::new();
        for i in 0..40 {
            input.push_str(&format!("line {i:02} of the captured build output\n"));
        }
        let out = apply_filter(&input, &f);
        let kept: Vec<usize> = out
            .lines()
            .filter_map(|l| l.strip_prefix("line "))
            .filter_map(|l| l.get(..2))
            .filter_map(|n| n.parse::<usize>().ok())
            .collect();
        assert!(
            kept.len() > 4 && kept.len() < 40,
            "test needs a partial keep-set, got {kept:?}"
        );
        assert!(
            kept.windows(2).all(|w| w[0] < w[1]),
            "surviving lines must stay in source order: {kept:?}"
        );
    }

    #[test]
    fn apply_filter_on_empty_for_genuinely_empty_output() {
        let mut f = base_filter();
        f.on_empty = Some("cmd: ok".to_string());
        // Truly empty / whitespace-only command output → success sentinel.
        assert_eq!(apply_filter("", &f), "cmd: ok");
        assert_eq!(apply_filter("   \n\t\n", &f), "cmd: ok");
    }

    #[test]
    fn apply_filter_benign_emptied_output_keeps_on_empty() {
        // keep rules strip everything, output is benign (no failure signal):
        // the success `on_empty` must still fire — guard must not over-trigger.
        let mut f = base_filter();
        f.keep_lines_matching = vec!["^KEEP".to_string()];
        f.on_empty = Some("cmd: ok".to_string());
        assert_eq!(
            apply_filter("benign output line\nnothing notable here\n", &f),
            "cmd: ok"
        );
    }

    #[test]
    fn apply_filter_failure_signal_overrides_on_empty() {
        // Same filter, but the output is a failure whose format the keep rule
        // doesn't recognize → must passthrough the error, never "cmd: ok".
        let mut f = base_filter();
        f.keep_lines_matching = vec!["^KEEP".to_string()];
        f.on_empty = Some("cmd: ok".to_string());
        let out = apply_filter("ERROR: boom\nprocess exited with exit code 1\n", &f);
        assert_ne!(out, "cmd: ok", "failure must not be masked");
        assert!(out.contains("ERROR: boom"), "real error surfaced: {out:?}");
    }

    #[test]
    fn apply_filter_passthrough_when_emptied_opt_in() {
        // Opt-in passthrough surfaces real output even without a failure signal.
        let mut f = base_filter();
        f.keep_lines_matching = vec!["^KEEP".to_string()];
        f.on_empty = Some("no changes".to_string());
        f.passthrough_when_emptied = true;
        let out = apply_filter("abc123 some commit subject\n", &f);
        assert_ne!(out, "no changes");
        assert!(out.contains("abc123"), "real output shown: {out:?}");
    }

    #[test]
    fn apply_filter_match_output_short_circuits_without_unless() {
        let mut f = base_filter();
        f.match_output = vec![MatchOutput {
            pattern: "BUILD SUCCESSFUL".to_string(),
            message: "ok".to_string(),
            unless: None,
        }];
        // Short-circuits before any line filtering / sizing.
        assert_eq!(
            apply_filter("noise\nBUILD SUCCESSFUL in 2s\nmore noise\n", &f),
            "ok"
        );
    }

    #[test]
    fn literal_anchor_extracts_only_plain_prefixes() {
        assert_eq!(literal_anchor("^cargo\\s+test\\b"), Some("cargo"));
        assert_eq!(literal_anchor("^gt\\s+submit\\b"), Some("gt"));
        assert_eq!(literal_anchor("^dotnet\\s+build"), Some("dotnet"));
        // Groups, alternations, escapes and unanchored patterns must never
        // yield a prefix — they go through full regex evaluation.
        assert_eq!(literal_anchor("^(npx\\s+)?alex\\b"), None);
        assert_eq!(literal_anchor("^(Get-Content|gc)\\b"), None);
        assert_eq!(literal_anchor("\\b(?:phpunit|pest)\\b"), None);
        assert_eq!(literal_anchor("^\\.?/gradlew"), None);
        // Single-char anchors are too weak to be worth the skip.
        assert_eq!(literal_anchor("^x\\b"), None);
    }

    #[test]
    #[ignore = "manual benchmark: cargo test --release hook_lookup_bench -- --ignored --nocapture"]
    fn hook_lookup_bench() {
        let filters = load_bundled_filters();
        let commands = [
            "git status",
            "cargo test --quiet 2>&1 | Select-Object -Last 5",
            "cd /app && npm install --no-audit",
            "Get-Content src/main.rs",
            "some-unknown-tool --flag value",
        ];
        // Warm the compile cache the way a long-lived process would…
        for cmd in &commands {
            let _ = find_filter(cmd, &filters);
        }
        let iterations = 200;
        let start = std::time::Instant::now();
        for _ in 0..iterations {
            for cmd in &commands {
                let _ = find_filter(cmd, &filters);
            }
        }
        let per_call = start.elapsed() / (iterations * commands.len() as u32);
        println!(
            "find_filter warm per-call: {per_call:?} over {} filters",
            filters.len()
        );

        // …and measure the cold path (fresh process cost) as a single pass.
        let cold = std::time::Instant::now();
        let _ = find_filter("terraform plan -out tf.plan", &filters);
        println!("find_filter cold first-call: {:?}", cold.elapsed());
    }

    #[test]
    fn find_filter_picks_longest_matching_pattern() {
        let mut broad = base_filter();
        broad.match_command = "^git\\b".to_string();
        let mut specific = base_filter();
        specific.match_command = "^git\\s+status\\b".to_string();
        let filters = [broad, specific];
        let hit = find_filter("git status -s", &filters).unwrap();
        assert_eq!(
            hit.match_command, "^git\\s+status\\b",
            "most specific (longest) pattern wins"
        );
    }

    // --- Golden self-test: run every bundled filter's embedded [[tests.<name>]]
    // cases through the real apply_filter pipeline. Homologation guard so the
    // ~150 declared input→expected pairs can never silently drift.
    #[derive(Debug, Deserialize)]
    struct GoldenCase {
        #[serde(default)]
        name: Option<String>,
        #[serde(default)]
        command: Option<String>,
        input: String,
        expected: String,
    }

    #[derive(Debug, Deserialize)]
    struct FilterTestFile {
        #[serde(default)]
        filters: HashMap<String, FilterDef>,
        #[serde(default)]
        tests: HashMap<String, Vec<GoldenCase>>,
    }

    #[test]
    fn verbose_real_output_compresses_at_least_70pct() {
        // The corpus golden inputs are tiny fixtures; the headline 55% figure is
        // diluted by them. On the real use case — verbose, noisy command output —
        // the bundled filters must deliver heavy compression. Each pair is routed
        // through the real `find_filter` + `apply_filter` path, exactly like the
        // hook. Uses many command VARIANTS to also exercise filter resolution.
        use crate::chunker::count_tokens;
        let bundled = load_bundled_filters();

        // Realistic, verbose success output for common noisy commands. A clean
        // run is mostly progress/compile noise that collapses to a sentinel.
        let compiling = (0..30)
            .map(|i| format!("   Compiling crate_{i} v0.{i}.0"))
            .collect::<Vec<_>>()
            .join("\n");
        let cargo_build_out = format!(
            "    Updating crates.io index\n{compiling}\n    Finished dev [unoptimized + debuginfo] target(s) in 18.4s\n"
        );
        let cargo_test_out = format!(
            "{compiling}\n     Running unittests src/lib.rs\nrunning 42 tests\n{dots}\ntest result: ok. 42 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.31s\n",
            dots = (0..42)
                .map(|i| format!("test module::case_{i} ... ok"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        let npm_out = {
            let mut s = String::new();
            for i in 0..25 {
                s.push_str(&format!(
                    "npm WARN deprecated pkg_{i}@1.0.0: use pkg_{i}@2\n"
                ));
            }
            s.push_str("added 642 packages, and audited 643 packages in 12s\n");
            s.push_str("found 0 vulnerabilities\n");
            s
        };
        let pip_out = {
            let mut s = String::new();
            for i in 0..20 {
                s.push_str(&format!(
                    "Requirement already satisfied: dep_{i} in ./venv\n"
                ));
            }
            s.push_str("Successfully installed app-1.0.0\n");
            s
        };
        let pytest_out = format!(
            "============================= test session starts ==============================\nplatform linux -- Python 3.12.0, pytest-8.0.0\ncollected 88 items\n\n{}\n\n============================== 88 passed in 4.21s ==============================\n",
            (0..6).map(|_| "tests/test_x.py ................................").collect::<Vec<_>>().join("\n")
        );
        let docker_out = {
            let mut s = String::new();
            for i in 1..25 {
                s.push_str(&format!(
                    "#{i} [stage {i}/24] RUN build step {i}\n#{i} DONE 0.{i}s\n"
                ));
            }
            s.push_str("#25 exporting to image\n#25 naming to docker.io/library/app:latest DONE\n");
            s
        };
        let eslint_out = "No problems found in 240 files.\n".to_string();
        let git_pull_out = "remote: Enumerating objects: 1200, done.\nremote: Counting objects: 100% (1200/1200), done.\nremote: Compressing objects: 100% (600/600), done.\nremote: Total 1200 (delta 800), reused 1100 (delta 700)\nUnpacking objects: 100% (1200/1200), 2.40 MiB | 4.80 MiB/s, done.\nFrom github.com:org/repo\n   abc1234..def5678  main       -> origin/main\nUpdating abc1234..def5678\nFast-forward\n".to_string();

        let cases: Vec<(&str, &str)> = vec![
            ("cargo build --release", &cargo_build_out),
            ("timeout 600 cargo test --all", &cargo_test_out),
            ("env CI=1 npm install --no-fund", &npm_out),
            ("pip install -r requirements.txt", &pip_out),
            ("python -m pytest -q", &pytest_out),
            ("docker build -t app:latest .", &docker_out),
            ("npx eslint src/", &eslint_out),
            ("git pull --rebase origin main", &git_pull_out),
        ];

        let mut in_total = 0usize;
        let mut out_total = 0usize;
        let mut report: Vec<String> = Vec::new();
        for (cmd, sample) in &cases {
            let f = find_filter(cmd, &bundled)
                .unwrap_or_else(|| panic!("no bundled filter resolved for {cmd:?}"));
            let got = apply_filter(sample, f);
            let it = count_tokens(sample);
            let ot = count_tokens(&got);
            let pct = (it.saturating_sub(ot) as f64 / it as f64) * 100.0;
            report.push(format!("{cmd}: {it}->{ot} ({pct:.0}%)"));
            in_total += it;
            out_total += ot;
        }
        let agg = (in_total.saturating_sub(out_total) as f64 / in_total as f64) * 100.0;
        eprintln!(
            "verbose-economy: {in_total}->{out_total} tokens, {agg:.1}% saved\n  {}",
            report.join("\n  ")
        );
        assert!(
            agg >= 70.0,
            "verbose real output must compress >=70%, got {agg:.1}%\n{}",
            report.join("\n")
        );
    }

    #[test]
    fn match_command_resolves_many_invocation_variants() {
        // Homologation: a filter must survive the many shapes a command arrives
        // in — wrappers (timeout/env/nice), launchers (npx/uv run/python -m),
        // shell `-c`, tool global options, cd-prefixes, pipes and `&&` chains.
        let bundled = load_bundled_filters();
        let variants: &[(&str, &[&str])] = &[
            (
                "cargo build",
                &[
                    "cargo build",
                    "cargo build --release",
                    "timeout 300 cargo build",
                    "env RUSTFLAGS=-W cargo build -j 8",
                    "cargo +nightly build",
                    "cd crates/app && cargo build",
                    "bash -c 'cargo build --workspace'",
                    "nice -n 10 cargo build",
                ],
            ),
            (
                "pytest",
                &[
                    "pytest",
                    "pytest -q tests/",
                    "python -m pytest",
                    "python3 -m pytest tests/unit",
                    "uv run pytest -x",
                    "cd backend && pytest",
                ],
            ),
            (
                "eslint",
                &[
                    "eslint .",
                    "npx eslint src/ --fix",
                    "cd web && npx eslint .",
                ],
            ),
            (
                "kubectl get",
                &[
                    "kubectl get pods",
                    "kubectl -n prod get pods -o wide",
                    "kubectl --context staging get deploy",
                ],
            ),
            (
                "git status",
                &[
                    "git status",
                    "git status -s",
                    "git -C /repo status",
                    "git -c color.ui=always status",
                    "cd repo && git status",
                ],
            ),
            (
                "docker build",
                &[
                    "docker build -t x .",
                    "docker buildx build --platform linux/amd64 .",
                    "timeout 900 docker build .",
                ],
            ),
            (
                "npm install",
                &[
                    "npm install",
                    "npm i",
                    "npm install --save-dev typescript",
                    "cat .npmrc && npm install",
                ],
            ),
            // Newly added filters — verify their variants resolve too.
            (
                "npm ci",
                &["npm ci", "timeout 300 npm ci", "cd web && npm ci"],
            ),
            (
                "cargo bench",
                &[
                    "cargo bench",
                    "cargo bench --bench parse",
                    "cargo +nightly bench",
                ],
            ),
            ("cargo update", &["cargo update", "cargo update -p serde"]),
            (
                "pip list",
                &[
                    "pip list",
                    "pip freeze",
                    "python -m pip list",
                    "pip3 freeze",
                ],
            ),
            (
                "git cherry-pick",
                &[
                    "git cherry-pick abc123",
                    "git -C /repo cherry-pick --continue",
                ],
            ),
            (
                "dotnet run",
                &[
                    "dotnet run",
                    "dotnet run --project app",
                    "cd svc && dotnet run",
                ],
            ),
            (
                "prisma",
                &[
                    "prisma generate",
                    "npx prisma migrate dev",
                    "pnpm prisma db push",
                    "yarn prisma studio",
                    "bunx prisma generate",
                ],
            ),
            (
                "wrangler",
                &[
                    "wrangler deploy",
                    "npx wrangler deploy",
                    "pnpm wrangler pages deploy dist",
                    "yarn wrangler tail",
                ],
            ),
        ];
        let mut misses: Vec<String> = Vec::new();
        for (label, cmds) in variants {
            for cmd in *cmds {
                if find_filter(cmd, &bundled).is_none() {
                    misses.push(format!("[{label}] no filter for variant: {cmd:?}"));
                }
            }
        }
        assert!(
            misses.is_empty(),
            "{} command variant(s) failed to resolve a filter:\n{}",
            misses.len(),
            misses.join("\n")
        );
    }

    #[test]
    fn bundled_filters_pass_embedded_golden_tests() {
        let mut total = 0usize;
        let mut files_with_tests = 0usize;
        let mut failures: Vec<String> = Vec::new();

        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("bundled asset readable");
            let content = std::str::from_utf8(file.data.as_ref()).expect("filter is utf8");
            let parsed: FilterTestFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(e) => {
                    failures.push(format!("{asset}: TOML parse error: {e}"));
                    continue;
                }
            };
            if !parsed.tests.is_empty() {
                files_with_tests += 1;
            }
            for (fname, cases) in &parsed.tests {
                let Some(fdef) = parsed.filters.get(fname) else {
                    failures.push(format!(
                        "{asset}: [[tests.{fname}]] references undefined [filters.{fname}]"
                    ));
                    continue;
                };
                for (i, case) in cases.iter().enumerate() {
                    total += 1;
                    if let Some(command) = case.command.as_deref() {
                        let re = Regex::new(&fdef.match_command).unwrap_or_else(|e| {
                            panic!("{asset} [{fname}] invalid match_command: {e}")
                        });
                        assert!(
                            re.is_match(command),
                            "{asset} [{fname}] expected match_command to match {:?}",
                            command
                        );
                    }
                    let got = apply_filter(&case.input, fdef);
                    if got.trim_end() != case.expected.trim_end() {
                        let label = case.name.clone().unwrap_or_else(|| format!("#{i}"));
                        failures.push(format!(
                            "{asset} [{fname} / {label}]\n  expected: {:?}\n  got:      {:?}",
                            case.expected, got
                        ));
                    }
                }
            }
        }

        eprintln!(
            "golden: ran {total} embedded cases across {files_with_tests} bundled filter files"
        );
        assert!(
            failures.is_empty(),
            "{} bundled golden filter case(s) failed:\n\n{}",
            failures.len(),
            failures.join("\n\n")
        );
    }

    #[test]
    fn bundled_filters_require_minimum_tests() {
        let mut failures = Vec::new();
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("bundled asset readable");
            let content = std::str::from_utf8(file.data.as_ref()).expect("filter is utf8");
            let parsed: FilterTestFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(e) => {
                    failures.push(format!("{asset}: TOML parse error: {e}"));
                    continue;
                }
            };
            for fname in parsed.filters.keys() {
                match parsed.tests.get(fname) {
                    Some(cases) => {
                        if cases.len() < 2 {
                            failures.push(format!(
                                "{asset}: [filters.{fname}] has only {} test case(s), expected at least 2",
                                cases.len()
                            ));
                        }
                    }
                    None => {
                        failures.push(format!(
                            "{asset}: [filters.{fname}] has NO test cases defined"
                        ));
                    }
                }
            }
        }
        assert!(
            failures.is_empty(),
            "The following bundled filter(s) do not meet the minimum test requirement (>=2 golden cases):\n\n{}",
            failures.join("\n")
        );
    }

    #[test]
    #[ignore = "maintainer report; run with --ignored --nocapture"]
    fn report_sentinel_evidence_candidates() {
        // For each filter whose sentinel answers non-empty output, print the
        // fixture that proves it. The success marker for a `match_output`
        // (positive evidence) rule is almost always already in that text.
        let unknown = "unrecognized tool output line one\n\
                       some other shape the filter never saw\n\
                       third line of genuine output\n";
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("asset");
            let content = std::str::from_utf8(file.data.as_ref()).expect("utf8");
            let Ok(parsed) = toml::from_str::<FilterTestFile>(content) else {
                continue;
            };
            for (fname, fdef) in &parsed.filters {
                let Some(sentinel) = fdef.on_empty.as_deref() else {
                    continue;
                };
                if apply_filter(unknown, fdef).trim() != sentinel.trim() {
                    continue;
                }
                let Some(cases) = parsed.tests.get(fname) else {
                    continue;
                };
                for c in cases {
                    if !c.input.trim().is_empty() && c.expected.trim() == sentinel.trim() {
                        println!(
                            "@@@\t{fname}\t{asset}\t{}",
                            c.input.replace('\n', " ⏎ ").trim()
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn on_empty_sentinel_never_answers_unrecognized_output() {
        // Per-filter homologation of the "filters must only filter, never
        // invent responses" rule.
        //
        // An `on_empty` sentinel is legitimate in exactly two shapes:
        //  a) the tool's clean run really is empty (a silent linter) — the
        //     sentinel then answers *empty* output, and the filter must set
        //     `passthrough_when_emptied` so that NON-empty output it does not
        //     recognize is shown instead of being answered with a false "all
        //     clear";
        //  b) the filter deliberately collapses recognized verbose output into
        //     a summary — proven by a golden case whose non-empty input yields
        //     the sentinel.
        //
        // Anything else is a filter telling the agent a command succeeded when
        // it has no evidence of that.
        let unknown = "unrecognized tool output line one\n\
                       some other shape the filter never saw\n\
                       third line of genuine output\n";
        let mut offenders = Vec::new();
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("asset");
            let content = std::str::from_utf8(file.data.as_ref()).expect("utf8");
            let Ok(parsed) = toml::from_str::<FilterTestFile>(content) else {
                continue;
            };
            for (fname, fdef) in &parsed.filters {
                let Some(sentinel) = fdef.on_empty.as_deref() else {
                    continue;
                };
                if apply_filter(unknown, fdef).trim() != sentinel.trim() {
                    continue; // does not fabricate — nothing to prove
                }
                let summarizes = parsed.tests.get(fname).is_some_and(|cases| {
                    cases
                        .iter()
                        .any(|c| !c.input.trim().is_empty() && c.expected.trim() == sentinel.trim())
                });
                if !summarizes {
                    offenders.push(format!(
                        "{asset} [{fname}]: answers unrecognized output with {sentinel:?}; \
                         add `passthrough_when_emptied = true` (or a golden case proving it \
                         legitimately summarizes non-empty output)"
                    ));
                }
            }
        }
        assert!(
            offenders.is_empty(),
            "{} filter(s) fabricate a success sentinel over real output:\n{}",
            offenders.len(),
            offenders.join("\n")
        );
    }

    /// Per-filter homologation report (one TSV row per bundled filter):
    /// golden verdict, token economy, failure-path coverage, masking,
    /// inflation, sentinel shape and prefilter class.
    ///
    /// Ignored by default because it is a report, not an assertion — the
    /// invariants it surfaces are locked by the tests above. Run it with:
    /// `cargo test --release --bin tokenix homologate -- --ignored --nocapture`
    #[test]
    #[ignore = "maintainer report; run with --ignored --nocapture"]
    fn homologate_each_filter() {
        use crate::chunker::count_tokens;
        println!("FILTER\tASSET\tCASES\tGOLDEN\tRAW\tOUT\tSAVED%\tFAILCASE\tMASKS\tINFLATES\tON_EMPTY\tPASSTHRU\tPREFILTER\tFABRICATES\tSUMMARY");
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("asset");
            let content = std::str::from_utf8(file.data.as_ref()).expect("utf8");
            let parsed: FilterTestFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(e) => {
                    println!("?\t{asset}\tPARSE_ERROR\t{e}");
                    continue;
                }
            };
            for (fname, fdef) in &parsed.filters {
                let empty: Vec<GoldenCase> = Vec::new();
                let cases = parsed.tests.get(fname).unwrap_or(&empty);
                let (mut raw, mut out) = (0usize, 0usize);
                let (mut golden_ok, mut fail_case, mut masks, mut inflates) =
                    (true, false, false, false);
                for case in cases {
                    let got = apply_filter(&case.input, fdef);
                    if got.trim_end() != case.expected.trim_end() {
                        golden_ok = false;
                    }
                    raw += count_tokens(&case.input);
                    out += count_tokens(&got);
                    // `never_worse` only guards non-empty raw output: an
                    // `on_empty` sentinel replacing genuinely empty output is
                    // by design, not inflation.
                    let raw_trim = case.input.trim_end();
                    if !raw_trim.is_empty() && got.len() > raw_trim.len() {
                        inflates = true;
                    }
                    // A failure-path case: the raw input carries a failure
                    // signal. The filtered view must still carry one, or the
                    // agent is told a failed command succeeded.
                    if output_has_failure_signal(&case.input) {
                        fail_case = true;
                        if !output_has_failure_signal(&got) {
                            masks = true;
                        }
                    }
                }
                let pct = if raw > 0 {
                    100.0 * (raw.saturating_sub(out)) as f64 / raw as f64
                } else {
                    0.0
                };
                // The failure mode `passthrough_when_emptied` exists to stop:
                // real, non-empty output the filter does not recognize being
                // replaced by a fabricated success sentinel. Probe it with a
                // benign payload carrying no failure signal.
                let unknown = "unrecognized tool output line one\n\
                               some other shape the filter never saw\n\
                               third line of genuine output\n";
                let probe = apply_filter(unknown, fdef);
                let fabricates = fdef
                    .on_empty
                    .as_deref()
                    .is_some_and(|sentinel| probe.trim() == sentinel.trim());

                // Does any golden case reach the sentinel from NON-EMPTY input?
                // If not, the sentinel only ever answers a genuinely empty run
                // (a clean linter), and `passthrough_when_emptied` can be added
                // without changing a single documented behavior.
                let sentinel_from_nonempty = fdef.on_empty.as_deref().is_some_and(|sentinel| {
                    cases
                        .iter()
                        .any(|c| !c.input.trim().is_empty() && c.expected.trim() == sentinel.trim())
                });

                let pf = match prefilter_for(&fdef.match_command) {
                    Some(Prefilter::StartsWith(_)) => "anchor",
                    Some(Prefilter::Contains(_, _)) => "contains",
                    None => "none",
                };
                println!(
                    "{fname}\t{asset}\t{}\t{}\t{raw}\t{out}\t{pct:.0}\t{}\t{}\t{}\t{}\t{}\t{pf}\t{}\t{}",
                    cases.len(),
                    if golden_ok { "ok" } else { "FAIL" },
                    if fail_case { "yes" } else { "NO" },
                    if masks { "MASKS" } else { "-" },
                    if inflates { "INFLATES" } else { "-" },
                    if fdef.on_empty.is_some() { "on_empty" } else { "-" },
                    if fdef.passthrough_when_emptied { "pass" } else { "-" },
                    if fabricates { "FABRICATES" } else { "-" },
                    if sentinel_from_nonempty { "SUMMARY" } else { "-" },
                );
            }
        }
    }

    /// Iterate every bundled filter's embedded golden cases, applying the real
    /// pipeline. Yields `(asset, filter_name, input, filtered_output)`.
    fn for_each_golden_case<F: FnMut(&str, &str, &str, &str)>(mut visit: F) {
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).expect("bundled asset readable");
            let content = std::str::from_utf8(file.data.as_ref()).expect("utf8");
            let parsed: FilterTestFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(_) => continue,
            };
            for (fname, cases) in &parsed.tests {
                let Some(fdef) = parsed.filters.get(fname) else {
                    continue;
                };
                for case in cases {
                    let got = apply_filter(&case.input, fdef);
                    visit(&asset, fname, &case.input, &got);
                }
            }
        }
    }

    #[test]
    #[ignore]
    fn diag_per_filter_compression() {
        let mut rows: Vec<(String, usize, usize, f64)> = Vec::new();
        for_each_golden_case_grouped(|fname, it, ot| {
            let pct = if it > 0 {
                (it.saturating_sub(ot) as f64 / it as f64) * 100.0
            } else {
                0.0
            };
            rows.push((fname.to_string(), it, ot, pct));
        });
        // Lowest %-saved first; ties broken by biggest input (most waste left).
        rows.sort_by(|a, b| a.3.partial_cmp(&b.3).unwrap().then(b.1.cmp(&a.1)));
        let mut out = String::from("FILTER,IN_TOK,OUT_TOK,PCT_SAVED\n");
        for (n, it, ot, pct) in &rows {
            out.push_str(&format!("{n},{it},{ot},{pct:.0}\n"));
        }
        let path = std::env::temp_dir().join("tokenix_diag_compression.csv");
        std::fs::write(&path, out).unwrap();
        eprintln!("wrote {}", path.display());
    }

    /// Like `for_each_golden_case` but aggregates per filter: `(name, in_tok, out_tok)`.
    fn for_each_golden_case_grouped<F: FnMut(&str, usize, usize)>(mut visit: F) {
        use crate::chunker::count_tokens;
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).unwrap();
            let content = std::str::from_utf8(file.data.as_ref()).unwrap();
            let parsed: FilterTestFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(_) => continue,
            };
            for (fname, cases) in &parsed.tests {
                let Some(fdef) = parsed.filters.get(fname) else {
                    continue;
                };
                let mut it = 0usize;
                let mut ot = 0usize;
                for case in cases {
                    it += count_tokens(&case.input);
                    ot += count_tokens(&apply_filter(&case.input, fdef));
                }
                visit(fname, it, ot);
            }
        }
    }

    #[test]
    fn filters_never_inflate_output_tokens() {
        // Economy invariant: a filter must never produce MORE tokens than it was
        // given (a tiny slack covers short inputs replaced by a sentinel message
        // like "cmd: ok"). A filter that inflates output is a net token loss.
        use crate::chunker::count_tokens;
        const SLACK_TOKENS: usize = 8;
        let mut offenders: Vec<String> = Vec::new();
        for_each_golden_case(|asset, fname, input, got| {
            let in_tok = count_tokens(input);
            let out_tok = count_tokens(got);
            if out_tok > in_tok + SLACK_TOKENS {
                offenders.push(format!(
                    "{asset} [{fname}]: {in_tok} -> {out_tok} tokens (inflated)"
                ));
            }
        });
        assert!(
            offenders.is_empty(),
            "{} filter case(s) inflated output beyond slack:\n{}",
            offenders.len(),
            offenders.join("\n")
        );
    }

    #[test]
    fn filters_deliver_aggregate_token_savings() {
        // The whole point of the tool: across the bundled corpus' realistic
        // sample inputs, filtering must cut a large share of tokens. Guards
        // against a regression that quietly neuters compression (e.g. a broken
        // strip/keep stage) while individual golden equality still passes.
        use crate::chunker::count_tokens;
        let mut in_total = 0usize;
        let mut out_total = 0usize;
        let mut cases = 0usize;
        for_each_golden_case(|_, _, input, got| {
            in_total += count_tokens(input);
            out_total += count_tokens(got);
            cases += 1;
        });
        assert!(cases > 100, "expected the full corpus, saw {cases} cases");
        let saved = in_total.saturating_sub(out_total);
        let pct = (saved as f64 / in_total as f64) * 100.0;
        eprintln!("economy: {cases} cases, {in_total} -> {out_total} tokens, {pct:.1}% saved");
        assert!(out_total < in_total, "corpus must shrink, not grow");
        assert!(
            pct >= 40.0,
            "expected >=40% aggregate token savings across the corpus, got {pct:.1}%"
        );
    }

    #[test]
    fn output_has_failure_signal_strict() {
        // Positives: real failure output.
        assert!(output_has_failure_signal(
            "fatal: something went wrong\nERROR: build failed with exit code 1"
        ));
        assert!(output_has_failure_signal(
            "panic: runtime error: index out of range"
        ));
        assert!(output_has_failure_signal(
            "FAILED tests/test_foo.py::test_bar - AssertionError"
        ));
        assert!(output_has_failure_signal(
            "Traceback (most recent call last):\n  File \"x.py\""
        ));
        assert!(output_has_failure_signal("error: aborting due to 1 error"));

        // New Positives:
        assert!(output_has_failure_signal(
            "[ERROR] database connection failed"
        ));
        assert!(output_has_failure_signal(
            "2026-06-22T12:00:00Z [error] database down"
        ));
        assert!(output_has_failure_signal("npm ERR! code ELIFECYCLE"));
        assert!(output_has_failure_signal("yarn ERR: error Command failed"));
        assert!(output_has_failure_signal(
            "--- FAIL: TestExploreCodebase (0.05s)"
        ));
        assert!(output_has_failure_signal(
            "Segmentation fault (core dumped)"
        ));
        assert!(output_has_failure_signal("Process received signal SIGSEGV"));
        assert!(output_has_failure_signal(
            "java.lang.NullPointerException: object is null"
        ));
        assert!(output_has_failure_signal("exited with status: 1"));
        assert!(output_has_failure_signal("exit status 127"));
        assert!(output_has_failure_signal("Command failed with exit code 2"));
        assert!(output_has_failure_signal(
            "time=\"xxx\" level=error msg=\"db lost\""
        ));

        // Negatives: benign success summaries that merely mention error/fail.
        assert!(!output_has_failure_signal("test result: ok. 0 failed"));
        assert!(!output_has_failure_signal("0 errors, 0 warnings"));
        assert!(!output_has_failure_signal("no errors found"));
        assert!(!output_has_failure_signal("Compiling: 0 failures"));
        assert!(!output_has_failure_signal("exit status 0"));
        assert!(!output_has_failure_signal("exited with status: 0"));
        assert!(!output_has_failure_signal("warnings: 12"));

        // Prefixed diagnostics: the shape every Unix tool and every C/C++
        // compiler emits. These reach `on_empty` unguarded on the PostToolUse
        // path, which carries no exit code.
        assert!(output_has_failure_signal(
            "cppcheck: error: unrecognized command line option: \"--foo\".\n"
        ));
        assert!(output_has_failure_signal(
            "main.c:3:5: error: expected ';'\n"
        ));
        assert!(output_has_failure_signal("ld: fatal: symbol not found\n"));
        // Still not a failure: a warning with the same prefix shape.
        assert!(!output_has_failure_signal(
            "main.c:3:5: warning: unused variable 'x'\n"
        ));
    }

    #[test]
    fn post_hook_path_never_masks_a_prefixed_tool_error() {
        // Regression: `run_hook_post` compresses with an unknown exit status,
        // so the sentinel guard is the only thing between a failed command and
        // a fabricated "ok". A tool that reports its own errors in a format its
        // filter's keep-rules do not recognise used to come back as success.
        let out = crate::compress::compress_bash_output(
            "cppcheck --foo src/",
            "cppcheck: error: unrecognized command line option: \"--foo\".\n",
        );
        assert!(
            !out.contains("cppcheck: ok"),
            "failed command must not earn the success sentinel: {out:?}"
        );
        assert!(
            out.contains("unrecognized command line option"),
            "the real error must survive: {out:?}"
        );
    }

    #[test]
    fn bundled_filters_never_mask_generic_failure() {
        // Homologation guard: a generic command failure must never be reduced
        // to a filter's success `on_empty` message. Feeds each bundled filter
        // an unambiguous failure payload and asserts a failure marker survives.
        let payload = "fatal: the operation failed\nERROR: process exited with exit code 1\nFAILED";
        let survives = Regex::new(r"(?i)error|fail|fatal").unwrap();
        let mut masked: Vec<String> = Vec::new();
        for asset in BundledFilters::iter() {
            let file = BundledFilters::get(&asset).unwrap();
            let content = std::str::from_utf8(file.data.as_ref()).unwrap();
            let parsed: FilterFile = match toml::from_str(content) {
                Ok(p) => p,
                Err(_) => continue,
            };
            for (name, fdef) in &parsed.filters {
                let got = apply_filter(payload, fdef);
                if !survives.is_match(&got) {
                    masked.push(format!("{asset} [{name}] -> {:?}", got));
                }
            }
        }
        assert!(
            masked.is_empty(),
            "{} bundled filter(s) masked a generic failure as success:\n{}",
            masked.len(),
            masked.join("\n")
        );
    }

    #[test]
    fn test_gradlew_match() {
        let filters = load_bundled_filters();
        let f = find_filter("./gradlew", &filters);
        assert!(f.is_some(), "gradlew filter must be found for './gradlew'");
        // gradlew is an all-noise-success tool: an emptied benign output must
        // collapse to the on_empty sentinel (the engine's failure-signal guard
        // still passes real errors through), not resurrect raw noise.
        assert!(
            f.unwrap().on_empty.is_some(),
            "gradlew filter must report success via on_empty when filtering empties it"
        );
    }

    #[test]
    fn find_filter_parameter_scenarios() {
        let filters = [
            FilterDef {
                description: None,
                match_command: "^cargo\\s+test\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("cargo-test".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^docker\\s+build\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("docker-build".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^git\\s+diff\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("git-diff".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^git\\s+log\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("git-log".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^kubectl\\s+get\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("kubectl-get".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: Some(SummarizeJsonDef {
                    max_array_items: 10,
                    max_depth: 3,
                    always_include: vec![],
                    exclude: vec![],
                }),
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^pytest\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("pytest".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^git\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("git-broad".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^git\\s+branch\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("git-branch".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
            FilterDef {
                description: None,
                match_command: "^eslint\\b".to_string(),
                skip_when_matches: None,
                notify_on_truncate: false,
                strip_ansi: false,
                strip_lines_matching: vec![],
                keep_lines_matching: vec![],
                max_lines: None,
                head_lines: None,
                tail_lines: None,
                on_empty: Some("eslint".to_string()),
                passthrough_when_emptied: false,
                match_output: vec![],
                truncate_lines_at: None,
                uniform_success: None,
                filter_stderr: false,
                replace_patterns: vec![],
                extract_sections: vec![],
                semantic_filter: None,
                deduplicate_blocks: None,
                summarize_json: None,
                token_budget: None,
                on_failure: None,
                priority_lines: vec![],
                category_caps: vec![],
                block_caps: vec![],
            },
        ];

        let run =
            |cmd: &str| find_filter(cmd, &filters).map(|f| f.on_empty.as_ref().unwrap().as_str());

        // 120+ data-driven test cases validating parameters, wrappers, shell features, and bypass flags
        let static_cases = vec![
            // 1. Tool-specific basic matches
            ("cargo test", Some("cargo-test")),
            ("docker build", Some("docker-build")),
            ("git diff", Some("git-diff")),
            ("git log", Some("git-log")),
            ("kubectl get", Some("kubectl-get")),
            ("pytest", Some("pytest")),
            ("eslint", Some("eslint")),
            ("git branch", Some("git-branch")),
            // 2. Standard parameters & flags
            (
                "cargo test --workspace --all-features --jobs 4",
                Some("cargo-test"),
            ),
            ("cargo test -p my-package --lib", Some("cargo-test")),
            (
                "docker build -t image:latest -f Dockerfile .",
                Some("docker-build"),
            ),
            (
                "docker build --build-arg KEY=VAL --no-cache .",
                Some("docker-build"),
            ),
            (
                "git diff HEAD~1 HEAD --stat --compact-summary",
                Some("git-diff"),
            ),
            ("git diff main..feature --name-status", Some("git-diff")),
            (
                "git log -n 50 --oneline --graph --decorate",
                Some("git-log"),
            ),
            (
                "git log --author=\"Bob\" --since=\"1 week ago\"",
                Some("git-log"),
            ),
            (
                "kubectl get pods -n kube-system -o wide",
                Some("kubectl-get"),
            ),
            (
                "kubectl get services,deployments -l app=nginx",
                Some("kubectl-get"),
            ),
            (
                "pytest tests/test_auth.py -k \"login_successful\"",
                Some("pytest"),
            ),
            (
                "pytest -v --tb=short --cov=src --cov-report=html",
                Some("pytest"),
            ),
            ("eslint src/ --ext .ts,.tsx --fix", Some("eslint")),
            (
                "eslint --cache --resolve-plugins-relative-to .",
                Some("eslint"),
            ),
            // 3. Env vars & wrappers
            ("CI=true cargo test", Some("cargo-test")),
            ("NODE_ENV=test PORT=3000 pytest", Some("pytest")),
            ("cross-env CI=true pnpm exec eslint", Some("eslint")),
            ("time cargo test", Some("cargo-test")),
            ("nice cargo test", Some("cargo-test")),
            ("nice -n 10 cargo test", Some("cargo-test")),
            ("timeout 30s pytest", Some("pytest")),
            ("timeout --foreground 60s pytest", Some("pytest")),
            ("timeout -k 5 10 nice -n 19 pytest", Some("pytest")),
            (
                "CI=true timeout 30 nice -n 5 cargo test --quiet",
                Some("cargo-test"),
            ),
            // 4. Directory prefixes (cd / pushd)
            ("cd app && cargo test", Some("cargo-test")),
            ("cd app; cargo test", Some("cargo-test")),
            ("cd app || exit 1; cargo test", Some("cargo-test")),
            ("pushd app && pytest", Some("pytest")),
            ("cd /d C:\\Project && docker build .", Some("docker-build")),
            ("cd src && ENV=1 timeout 10 pytest -v", Some("pytest")),
            // 5. Global tool options with subcommand parameters
            ("git -C /src diff", Some("git-diff")),
            ("git --git-dir=/src/.git diff", Some("git-diff")),
            ("git -c core.autocrlf=input diff", Some("git-diff")),
            ("git --no-pager diff", Some("git-diff")),
            (
                "git -C /src -c k=v --no-pager diff --stat",
                Some("git-diff"),
            ),
            ("docker -H tcp://1.2.3.4:2376 build .", Some("docker-build")),
            ("docker --context default build .", Some("docker-build")),
            (
                "kubectl --kubeconfig=~/.kube/config get pods",
                Some("kubectl-get"),
            ),
            (
                "kubectl -n default --context=dev get pods",
                Some("kubectl-get"),
            ),
            // 6. Package runners
            ("npx eslint", Some("eslint")),
            ("npx --no-install eslint .", Some("eslint")),
            ("pnpm exec eslint", Some("eslint")),
            ("pnpm dlx eslint", Some("eslint")),
            ("bunx eslint", Some("eslint")),
            ("bun x eslint", Some("eslint")),
            ("yarn dlx eslint", Some("eslint")),
            ("uv run pytest", Some("pytest")),
            ("uvx pytest", Some("pytest")),
            ("python -m pytest", Some("pytest")),
            ("python3 -m pytest", Some("pytest")),
            ("python -m ruff check", None), // no ruff filter registered
            // 7. Shell runners
            ("bash -c \"cargo test\"", Some("cargo-test")),
            ("sh -c \"pytest\"", Some("pytest")),
            ("cmd.exe /c \"cargo test\"", Some("cargo-test")),
            ("powershell -Command \"cargo test\"", Some("cargo-test")),
            ("pwsh -Command \"pytest\"", Some("pytest")),
            ("& 'cargo test'", Some("cargo-test")),
            // 8. Help flag bypass variants
            ("cargo test --help", None),
            ("cargo test -h", None),
            ("cargo test help", None),
            ("cargo test /h", None),
            ("cargo test /?", None),
            ("cargo test --help-all", None),
            ("cargo test -help", None),
            ("git diff --help", None),
            ("git diff -h", None),
            ("git help diff", None),
            ("kubectl get --help", None),
            ("pytest -h", None),
            ("eslint --help", None),
            // 9. Version flag bypass variants
            ("node --version", None),
            ("node -v", None),
            ("python -V", None),
            ("python3 --version", None),
            ("git --version", None),
            ("git -v", None),
            ("docker --version", None),
            ("docker -v", None),
            ("kubectl version", None),
            // 10. Debug / Verbose bypass variants
            ("cargo test --debug", None),
            ("cargo test --verbose", None),
            ("cargo test --trace", None),
            ("cargo test -vv", None),
            ("cargo test -vvv", None),
            ("cargo test --log-level=debug", None),
            ("cargo test --log-level=trace", None),
            ("pytest --verbose", None),
            ("pytest -vv", None),
            ("git diff --verbose", None),
            ("docker build --debug", None),
            ("kubectl get pods --log-level=debug", None),
            // 11. YAML format bypass variants
            ("kubectl get pods --yaml", None),
            ("kubectl get pods -o yaml", None),
            ("kubectl get pods -o=yaml", None),
            ("kubectl get pods --format yaml", None),
            ("kubectl get pods --format=yaml", None),
            ("docker inspect --format yaml", None),
            // 12. JSON format bypass vs match
            ("cargo test --json", None),                // no JSON support
            ("cargo test -o json", None),               // no JSON support
            ("cargo test -o=json", None),               // no JSON support
            ("cargo test --message-format=json", None), // no JSON support
            ("pytest --json", None),                    // no JSON support
            ("kubectl get pods -o json", Some("kubectl-get")), // supported!
            ("kubectl get pods -o=json", Some("kubectl-get")), // supported!
            ("kubectl get pods --format=json", Some("kubectl-get")), // supported!
            // 13. Collision & specificity
            ("git branch", Some("git-branch")),
            ("git branch -a", Some("git-branch")),
            ("git checkout -b branch", Some("git-broad")), // git-checkout falls back to git-broad
            ("git status", Some("git-broad")),             // git-status falls back to git-broad
            ("git status -s", Some("git-broad")),
            // 14. Complex combined expressions
            (
                "NODE_ENV=production PORT=8080 timeout 30s npx eslint --fix --ext .ts .",
                Some("eslint"),
            ),
            (
                "cd /app && time nice -n 5 pnpm exec eslint --cache",
                Some("eslint"),
            ),
            ("git -C /repo -c k=v diff --stat --verbose", None), // verbose bypasses
            ("kubectl --kubeconfig=config get pods -o yaml", None), // yaml bypasses
            (
                "cd /app && npm install --no-audit | git log --oneline --help",
                None,
            ), // help bypasses
            // 15. More combined and edge cases
            ("git", Some("git-broad")),
            ("git -v diff", None), // version flag bypasses
            ("nice nice nice cargo test", Some("cargo-test")), // nested wrappers
            ("cd app && pushd src && time cargo test", Some("cargo-test")),
            ("npx npx eslint", Some("eslint")),
            ("npx pnpm exec eslint", Some("eslint")),
            ("bunx bunx eslint", Some("eslint")),
            ("timeout 10 timeout 10 pytest", Some("pytest")),
            ("pytest -v --tb=short --json", None),
            ("kubectl get pods -o json -n kube-system --help", None), // help takes priority over JSON support
            ("kubectl get pods -o yaml -n default", None),            // YAML bypass
            ("kubectl get pods -o=yaml --log-level=debug", None),     // debug and YAML bypass
            ("git log --oneline --json", None),                       // no JSON support
            ("eslint --fix --format json", None),                     // no JSON support
        ];

        let mut test_cases: Vec<(String, Option<&str>)> = static_cases
            .into_iter()
            .map(|(cmd, expected)| (cmd.to_string(), expected))
            .collect();

        // 16. Dynamic generated matrix of combinatorial match and bypass variations (4000+ cases)
        let prefixes = [
            "",
            "CI=true",
            "timeout 30s",
            "cd src &&",
            "CI=true nice -n 10 timeout 5",
        ];

        let runners = ["", "npx", "pnpm exec", "uv run"];

        let tools = [
            ("cargo test", vec!["", " --workspace"], "cargo-test"),
            ("git diff", vec!["", " --stat --cached"], "git-diff"),
            ("docker build", vec!["", " -t tag ."], "docker-build"),
            ("pytest", vec!["", " tests/test_auth.py"], "pytest"),
            ("eslint", vec!["", " --fix"], "eslint"),
            ("kubectl get", vec!["", " pods"], "kubectl-get"),
        ];

        let shell_wrappers = ["", "bash -c", "powershell -Command"];

        for prefix in &prefixes {
            for runner in &runners {
                for (tool, args_list, expected) in &tools {
                    for arg in args_list {
                        let mut cmd_parts = Vec::new();
                        if !prefix.is_empty() {
                            cmd_parts.push(*prefix);
                        }
                        if !runner.is_empty() {
                            cmd_parts.push(*runner);
                        }
                        cmd_parts.push(*tool);
                        if !arg.is_empty() {
                            cmd_parts.push(arg.trim());
                        }
                        let base_cmd = cmd_parts.join(" ");

                        // Base match
                        test_cases.push((base_cmd.clone(), Some(*expected)));

                        // Wrapped match
                        for wrapper in &shell_wrappers {
                            if !wrapper.is_empty() {
                                test_cases.push((
                                    format!("{} \"{}\"", wrapper, base_cmd),
                                    Some(*expected),
                                ));
                            }
                        }

                        // Bypass variations
                        let bypass_flags = [
                            "--help",
                            "-h",
                            "--verbose",
                            "--debug",
                            "-vv",
                            "--yaml",
                            "-o yaml",
                        ];

                        for flag in &bypass_flags {
                            let bypass_cmd = format!("{} {}", base_cmd, flag);
                            test_cases.push((bypass_cmd.clone(), None));

                            for wrapper in &shell_wrappers {
                                if !wrapper.is_empty() {
                                    test_cases
                                        .push((format!("{} \"{}\"", wrapper, bypass_cmd), None));
                                }
                            }
                        }

                        // JSON bypass test
                        let json_cmd = format!("{} --json", base_cmd);
                        let json_expected = if *expected == "kubectl-get" {
                            Some("kubectl-get")
                        } else {
                            None
                        };
                        test_cases.push((json_cmd.clone(), json_expected));

                        for wrapper in &shell_wrappers {
                            if !wrapper.is_empty() {
                                test_cases
                                    .push((format!("{} \"{}\"", wrapper, json_cmd), json_expected));
                            }
                        }
                    }
                }
            }
        }

        for (cmd, expected) in &test_cases {
            assert_eq!(
                run(cmd),
                *expected,
                "command resolution failed for: {:?}",
                cmd
            );
        }
    }
}