codewhale-tui 0.9.8

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

#[cfg(windows)]
use std::os::windows::io::AsRawHandle;
#[cfg(windows)]
use windows::Win32::Foundation::{CloseHandle, HANDLE};
#[cfg(windows)]
use windows::Win32::System::Diagnostics::ToolHelp::{
    CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
#[cfg(windows)]
use windows::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
    SetInformationJobObject, TerminateJobObject,
};
#[cfg(windows)]
use windows::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
#[cfg(windows)]
use windows::core::PCWSTR;

/// Context passed to hooks via environment variables
#[derive(Debug, Clone, Default)]
pub struct HookContext {
    /// Tool name (for ToolCallBefore/After)
    pub tool_name: Option<String>,
    /// Engine-assigned tool call id, so a `tool_call_before` record and the
    /// matching `tool_call_after` / `on_error` record can be correlated.
    pub tool_call_id: Option<String>,
    /// Tool arguments as JSON string
    pub tool_args: Option<String>,
    /// Tool result output (truncated)
    pub tool_result: Option<String>,
    /// Tool exit code if applicable.
    ///
    /// `i64` end-to-end: a Windows crash code such as `3221225477`
    /// (`0xC0000005`) is a real value `exec_shell` reports, and narrowing it
    /// to `i32` used to discard exactly the failures a hook most wants to see.
    pub tool_exit_code: Option<i64>,
    /// Whether tool succeeded
    pub tool_success: Option<bool>,
    /// Current mode
    pub mode: Option<String>,
    /// Previous mode (for `ModeChange`)
    pub previous_mode: Option<String>,
    /// Session ID
    pub session_id: Option<String>,
    /// User message content
    pub message: Option<String>,
    /// Error message (for `OnError`)
    pub error_message: Option<String>,
    /// Workspace path
    pub workspace: Option<PathBuf>,
    /// Current model name
    pub model: Option<String>,
    /// Total tokens used
    pub total_tokens: Option<u32>,
    /// Session cost in USD
    pub session_cost: Option<f64>,
}

impl HookContext {
    pub fn new() -> Self {
        Self::default()
    }

    #[allow(dead_code)] // Public builder API, used in tests
    pub fn with_tool_name(mut self, name: &str) -> Self {
        self.tool_name = Some(name.to_string());
        self
    }

    pub fn with_tool_call_id(mut self, id: &str) -> Self {
        self.tool_call_id = Some(id.to_string());
        self
    }

    #[allow(dead_code)] // Public builder API
    pub fn with_tool_args(mut self, args: &serde_json::Value) -> Self {
        self.tool_args = Some(truncate_env_value(
            &args.to_string(),
            HOOK_TOOL_ARGS_ENV_MAX_BYTES,
        ));
        self
    }

    #[allow(dead_code)] // Public builder API
    pub fn with_tool_result(mut self, result: &str, success: bool, exit_code: Option<i64>) -> Self {
        self.tool_result = Some(truncate_env_value(
            result,
            HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES,
        ));
        self.tool_success = Some(success);
        self.tool_exit_code = exit_code;
        self
    }

    #[allow(dead_code)] // Public builder API, used in tests
    pub fn with_mode(mut self, mode: &str) -> Self {
        self.mode = Some(mode.to_string());
        self
    }

    pub fn with_previous_mode(mut self, mode: &str) -> Self {
        self.previous_mode = Some(mode.to_string());
        self
    }

    #[allow(dead_code)] // Public builder API, used in tests
    pub fn with_workspace(mut self, path: PathBuf) -> Self {
        self.workspace = Some(path);
        self
    }

    pub fn with_model(mut self, model: &str) -> Self {
        self.model = Some(model.to_string());
        self
    }

    pub fn with_session_id(mut self, session_id: &str) -> Self {
        self.session_id = Some(session_id.to_string());
        self
    }

    #[allow(dead_code)] // Public builder API
    pub fn with_message(mut self, message: &str) -> Self {
        self.message = Some(message.to_string());
        self
    }

    #[allow(dead_code)] // Public builder API
    pub fn with_error(mut self, error: &str) -> Self {
        self.error_message = Some(truncate_env_value(error, HOOK_ERROR_CONTEXT_MAX_BYTES));
        self
    }

    pub fn with_tokens(mut self, tokens: u32) -> Self {
        self.total_tokens = Some(tokens);
        self
    }

    #[allow(dead_code)] // Public builder API
    pub fn with_cost(mut self, cost: f64) -> Self {
        self.session_cost = Some(cost);
        self
    }

    /// Clamp all observer-owned strings before the context is cloned into a
    /// bounded queue. Builders already apply these limits, but fields remain
    /// public for compatibility, so the submission boundary must defend
    /// itself against a directly-constructed context too.
    fn bounded_for_observer(mut self) -> Self {
        fn bound(value: &mut Option<String>, max_bytes: usize) {
            if let Some(raw) = value.take() {
                *value = Some(truncate_env_value(&raw, max_bytes));
            }
        }

        bound(&mut self.tool_name, HOOK_OBSERVER_METADATA_MAX_BYTES);
        bound(&mut self.tool_call_id, HOOK_OBSERVER_METADATA_MAX_BYTES);
        bound(&mut self.tool_args, HOOK_TOOL_ARGS_ENV_MAX_BYTES);
        bound(&mut self.tool_result, HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES);
        bound(&mut self.mode, HOOK_OBSERVER_METADATA_MAX_BYTES);
        bound(&mut self.previous_mode, HOOK_OBSERVER_METADATA_MAX_BYTES);
        bound(&mut self.session_id, HOOK_OBSERVER_METADATA_MAX_BYTES);
        bound(&mut self.message, HOOK_MESSAGE_CONTEXT_MAX_BYTES);
        bound(&mut self.error_message, HOOK_ERROR_CONTEXT_MAX_BYTES);
        bound(&mut self.model, HOOK_OBSERVER_METADATA_MAX_BYTES);
        if let Some(workspace) = self.workspace.take() {
            self.workspace = Some(PathBuf::from(truncate_env_value(
                &workspace.to_string_lossy(),
                HOOK_OBSERVER_METADATA_MAX_BYTES,
            )));
        }
        self
    }

    /// Convert to environment variables
    pub fn to_env_vars(&self) -> HashMap<String, String> {
        let mut env = HashMap::new();

        if let Some(ref name) = self.tool_name {
            env.insert("DEEPSEEK_TOOL_NAME".to_string(), name.clone());
        }
        if let Some(ref id) = self.tool_call_id {
            env.insert("DEEPSEEK_TOOL_CALL_ID".to_string(), id.clone());
        }
        if let Some(ref args) = self.tool_args {
            // Tool arguments can include whole patches or encoded payloads.
            // Keep the diagnostic environment surface bounded just like tool
            // results; hooks that need the canonical arguments already receive
            // the structured tool request at the engine boundary.
            env.insert(
                "DEEPSEEK_TOOL_ARGS".to_string(),
                truncate_env_value(args, HOOK_TOOL_ARGS_ENV_MAX_BYTES),
            );
        }
        if let Some(ref result) = self.tool_result {
            // Truncate result to 10KB to avoid environment variable size limits
            env.insert(
                "DEEPSEEK_TOOL_RESULT".to_string(),
                truncate_env_value(result, 10000),
            );
        }
        if let Some(code) = self.tool_exit_code {
            env.insert("DEEPSEEK_TOOL_EXIT_CODE".to_string(), code.to_string());
        }
        if let Some(success) = self.tool_success {
            env.insert("DEEPSEEK_TOOL_SUCCESS".to_string(), success.to_string());
        }
        if let Some(ref mode) = self.mode {
            env.insert("DEEPSEEK_MODE".to_string(), mode.clone());
        }
        if let Some(ref prev) = self.previous_mode {
            env.insert("DEEPSEEK_PREVIOUS_MODE".to_string(), prev.clone());
        }
        if let Some(ref session_id) = self.session_id {
            env.insert("DEEPSEEK_SESSION_ID".to_string(), session_id.clone());
        }
        if let Some(ref message) = self.message {
            // Truncate message to prevent env var issues
            env.insert(
                "DEEPSEEK_MESSAGE".to_string(),
                truncate_env_value(message, 5000),
            );
        }
        if let Some(ref error) = self.error_message {
            // Bounded like every other payload field: a tool failure message
            // can be the whole of a failed command's output, and an unbounded
            // env var is both an exec limit risk and an accidental transcript
            // copy in whatever the hook writes it to.
            env.insert(
                "DEEPSEEK_ERROR".to_string(),
                truncate_env_value(error, 5000),
            );
        }
        if let Some(ref ws) = self.workspace {
            env.insert("DEEPSEEK_WORKSPACE".to_string(), ws.display().to_string());
        }
        if let Some(ref model) = self.model {
            env.insert("DEEPSEEK_MODEL".to_string(), model.clone());
        }
        if let Some(tokens) = self.total_tokens {
            env.insert("DEEPSEEK_TOTAL_TOKENS".to_string(), tokens.to_string());
        }
        if let Some(cost) = self.session_cost {
            env.insert("DEEPSEEK_SESSION_COST".to_string(), format!("{cost:.6}"));
        }

        env
    }
}

/// Clamp a hook environment value to `max_bytes`, on a UTF-8 boundary, with a
/// visible marker so a hook can tell truncation from a short value.
fn truncate_env_value(value: &str, max_bytes: usize) -> String {
    if value.len() <= max_bytes {
        return value.to_string();
    }
    let safe_end = value
        .char_indices()
        .take_while(|(i, c)| *i + c.len_utf8() <= max_bytes)
        .last()
        .map_or(0, |(i, c)| i + c.len_utf8());
    format!("{}...[truncated]", &value[..safe_end])
}

/// Result of a hook execution
#[derive(Debug, Clone, Default)]
#[allow(dead_code)] // Fields are part of public API for hook consumers
pub struct HookResult {
    /// Hook name (if specified)
    pub name: Option<String>,
    /// Whether the hook succeeded.
    ///
    /// For a background hook this is `true` as soon as the bounded supervisor
    /// accepts the job: no child outcome has been observed yet. Check
    /// [`Self::background`] before reading this as "the command succeeded".
    pub success: bool,
    /// `true` when this result describes a background submission rather than
    /// a completed run. Background results always carry `exit_code: None`,
    /// empty `stdout`/`stderr`, and a duration that measures the spawn, not
    /// the command.
    pub background: bool,
    /// `true` when the hook behind this result declared
    /// `continue_on_error = false` and ran in the foreground.
    ///
    /// This travels with the *result*, not with the event, because it is the
    /// only way a steering call site can tell "the gate that actually matched
    /// this call could not answer" from "some other, unrelated strict hook for
    /// the same event exists in config". Background submissions are never
    /// strict: nothing is awaited, so there is no answer to withhold.
    pub strict: bool,
    /// Exit code from the hook command
    pub exit_code: Option<i32>,
    /// Standard output
    pub stdout: String,
    /// Standard error
    pub stderr: String,
    /// Time taken to execute
    pub duration: Duration,
    /// Error message if execution failed
    pub error: Option<String>,
}

impl HookResult {
    /// A result that carries an observed exit code, as opposed to a
    /// background submission or a spawn failure.
    ///
    /// Steering paths must gate on this: a background hook's `exit_code` is
    /// `None` because nothing was waited for, not because the command exited
    /// without a code.
    #[must_use]
    pub fn observed_exit_code(&self) -> Option<i32> {
        if self.background {
            return None;
        }
        self.exit_code
    }
}

/// Result of running mutable `message_submit` hooks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageSubmitOutcome {
    /// No hook changed the submitted text.
    Unchanged { warning: Option<String> },
    /// One or more hooks replaced the submitted text.
    Replaced {
        text: String,
        warning: Option<String>,
    },
    /// A hook intentionally blocked the submission.
    Blocked { reason: String },
}

impl MessageSubmitOutcome {
    pub fn unchanged() -> Self {
        Self::Unchanged { warning: None }
    }

    pub fn replaced(text: String) -> Self {
        Self::Replaced {
            text,
            warning: None,
        }
    }

    fn with_warning(self, warning: Option<String>) -> Self {
        match self {
            Self::Unchanged { .. } => Self::Unchanged { warning },
            Self::Replaced { text, .. } => Self::Replaced { text, warning },
            Self::Blocked { reason } => Self::Blocked { reason },
        }
    }

    pub fn warning(&self) -> Option<&str> {
        match self {
            Self::Unchanged { warning } | Self::Replaced { warning, .. } => warning.as_deref(),
            Self::Blocked { .. } => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum MessageSubmitStdout {
    Unchanged,
    Replaced(String),
    Invalid(String),
}

/// Maximum characters kept from one text field a `tool_call_before` hook
/// prints (`reason`, `additionalContext`).
///
/// Both fields end up somewhere unbounded output would be a real problem:
/// `reason` in a TUI denial line, `additionalContext` inside the tool result
/// that is sent to the model and counted against the context budget. A hook
/// that prints a megabyte gets a bounded, marked prefix instead.
pub(crate) const HOOK_TEXT_FIELD_MAX_CHARS: usize = 2_000;

/// Maximum characters of concatenated `additionalContext` appended to a single
/// tool result, across every hook that contributed to that one call.
pub(crate) const HOOK_CONTEXT_AGGREGATE_MAX_CHARS: usize = 8_000;

/// Largest tool-argument snapshot exported through `DEEPSEEK_TOOL_ARGS`.
const HOOK_TOOL_ARGS_ENV_MAX_BYTES: usize = 10_000;

/// Largest raw tool result retained in an observer job before enqueue.
const HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES: usize = 10_000;

/// Largest error retained in an observer job before enqueue.
const HOOK_ERROR_CONTEXT_MAX_BYTES: usize = 5_000;

/// Largest user/message preview retained in an observer job before enqueue.
const HOOK_MESSAGE_CONTEXT_MAX_BYTES: usize = 5_000;

/// Largest identifier or other diagnostic retained in an observer job.
const HOOK_OBSERVER_METADATA_MAX_BYTES: usize = 4_096;

/// Largest stdout or stderr prefix retained from one foreground hook. Reader
/// threads continue draining after this cap so a verbose child cannot fill its
/// pipe and deadlock before exit; only the in-memory receipt is clipped.
const HOOK_PIPE_CAPTURE_MAX_BYTES: usize = 64 * 1024;

/// Largest serialized `updatedInput` object accepted from a decision hook.
/// This is intentionally smaller than the pipe cap so the surrounding JSON
/// and other fields still have headroom.
const HOOK_UPDATED_INPUT_MAX_BYTES: usize = 32 * 1024;

/// Largest replacement message accepted from `message_submit`.
const HOOK_MESSAGE_REPLACEMENT_MAX_CHARS: usize = 32_000;

/// Hard ceiling for the complete serialized `message_submit` stdin document.
/// The text prefix is fitted beneath this boundary after bounded metadata has
/// been added, so JSON escaping cannot push a producer past the limit.
pub(crate) const HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES: usize = 32 * 1024;

/// Individual metadata fields in `message_submit` stdin are diagnostic only.
/// Bound them before fitting text so an unusual workspace/model value cannot
/// consume the entire payload budget.
const HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES: usize = 4 * 1024;

/// Largest turn error copied into a `turn_end` observer payload.
const HOOK_TURN_ERROR_MAX_CHARS: usize = 2_000;

/// Largest denial reason persisted into UI/model receipts.
const HOOK_DENIAL_RECEIPT_MAX_CHARS: usize = 240;

/// Bound and de-fang text a hook printed before it is shown or sent onward.
///
/// Control characters are removed (`\r`) or flattened to a space so hook
/// stdout cannot repaint the TUI with escape sequences or forge structure in
/// the model-facing transcript; `\n` and `\t` survive because a hook's context
/// is legitimately multi-line. Truncation carries a visible marker so a
/// consumer can tell a clipped value from a short one.
pub(crate) fn sanitize_hook_text(text: &str, max_chars: usize) -> String {
    let mut out = String::new();
    let mut kept = 0usize;
    let mut truncated = false;
    for ch in text.chars() {
        let mapped = match ch {
            '\n' | '\t' => ch,
            '\r' => continue,
            c if c.is_control() => ' ',
            c => c,
        };
        if kept == max_chars {
            truncated = true;
            break;
        }
        out.push(mapped);
        kept += 1;
    }
    if truncated {
        out.push_str("…[truncated]");
    }
    out
}

/// Longest hook/config name kept in a log line, a `/hooks` row, or a receipt.
///
/// Names are operator-supplied and otherwise unbounded: nothing stops a
/// `name` from being a megabyte of ANSI escapes, and it is echoed into the
/// TUI, the tracing stream, and the model-facing denial.
pub(crate) const HOOK_LABEL_MAX_CHARS: usize = 64;

/// [`sanitize_hook_text`], forced onto one line.
///
/// Labels and previews sit inside a formatted row, so an embedded newline or
/// tab would forge structure in the very listing that is supposed to describe
/// the hook. Everything else [`sanitize_hook_text`] does — control-character
/// removal and the marked truncation — still applies.
pub(crate) fn sanitize_hook_line(text: &str, max_chars: usize) -> String {
    sanitize_hook_text(text, max_chars)
        .chars()
        .map(|c| if c == '\n' || c == '\t' { ' ' } else { c })
        .collect()
}

/// The display label for a hook, from its optional operator-supplied `name`.
///
/// One line, bounded, control-free, and never empty — every surface that
/// prints a hook name (logs, `/hooks list`, config problems, no-verdict
/// receipts) goes through here so there is one answer to "what can a `name`
/// put on my screen".
pub(crate) fn sanitize_hook_label(name: Option<&str>) -> String {
    let cleaned = name
        .map(|name| sanitize_hook_line(name, HOOK_LABEL_MAX_CHARS))
        .unwrap_or_default();
    if cleaned.trim().is_empty() {
        "(unnamed)".to_string()
    } else {
        cleaned.trim().to_string()
    }
}

#[derive(Clone, Copy)]
enum PendingDenialRedaction {
    AuthorizationSchemeOrCredential,
    SecretValue,
    Command,
    Path,
}

/// Split a denial into whitespace-delimited fields while keeping quoted
/// values together. This makes `command="rm -rf"` and
/// `path='/private folder'` one redaction unit even though the value contains
/// spaces. Unterminated quotes are conservatively kept in the final field.
fn denial_fields(line: &str) -> Vec<String> {
    let mut fields = Vec::new();
    let mut current = String::new();
    let mut quote = None;
    for ch in line.chars() {
        match (quote, ch) {
            (None, '\'' | '"') => {
                quote = Some(ch);
                current.push(ch);
            }
            (Some(open), close) if open == close => {
                quote = None;
                current.push(ch);
            }
            (None, ch) if ch.is_whitespace() => {
                if !current.is_empty() {
                    fields.push(std::mem::take(&mut current));
                }
            }
            _ => current.push(ch),
        }
    }
    if !current.is_empty() {
        fields.push(current);
    }
    fields
}

fn denial_field_core(field: &str) -> &str {
    field.trim_matches(|ch: char| {
        matches!(
            ch,
            '\'' | '"' | '`' | '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';'
        )
    })
}

fn denial_sensitive_assignment(field: &str) -> Option<(&str, &str)> {
    let core = denial_field_core(field);
    let separator = core.find([':', '='])?;
    let key = denial_field_core(&core[..separator]);
    let value = denial_field_core(&core[separator + 1..]);
    Some((key, value))
}

fn normalized_denial_key(key: &str) -> String {
    denial_field_core(key)
        .chars()
        .map(|ch| match ch {
            '-' | '.' => '_',
            ch => ch.to_ascii_lowercase(),
        })
        .collect()
}

fn denial_key_is_secret(key: &str) -> bool {
    matches!(
        key,
        "token"
            | "secret"
            | "password"
            | "passwd"
            | "api_key"
            | "apikey"
            | "authorization"
            | "bearer"
    ) || key.ends_with("_api_key")
        || key.ends_with("_token")
        || key.ends_with("_secret")
}

/// Render an explicit hook denial without carrying raw process output into a
/// durable transcript. Structured reasons are useful operator copy, but they
/// still pass through a conservative redaction boundary: path-like tokens,
/// command-line flags, and common secret assignments are replaced rather than
/// persisted. Unstructured stdout/stderr never reaches this function.
pub(crate) fn sanitize_hook_denial_reason(reason: &str) -> String {
    let line = sanitize_hook_line(reason, HOOK_DENIAL_RECEIPT_MAX_CHARS);
    let mut redacted = Vec::new();
    let mut pending = None;
    for field in denial_fields(&line) {
        let core = denial_field_core(&field);
        let lower = core.to_ascii_lowercase();

        if matches!(core, "=" | ":") {
            continue;
        }

        if let Some(expected) = pending {
            match expected {
                PendingDenialRedaction::AuthorizationSchemeOrCredential => {
                    redacted.push("[secret]".to_string());
                    // Authorization uses `scheme credentials`. Treat the
                    // first field as a scheme even when it is proprietary;
                    // over-redacting one following field is safer than
                    // leaking a credential for a scheme we do not know.
                    pending = Some(PendingDenialRedaction::SecretValue);
                }
                PendingDenialRedaction::SecretValue => {
                    redacted.push("[secret]".to_string());
                    pending = None;
                }
                PendingDenialRedaction::Command => {
                    redacted.push("[command]".to_string());
                    pending = None;
                }
                PendingDenialRedaction::Path => {
                    redacted.push("[path]".to_string());
                    pending = None;
                }
            }
            continue;
        }

        if let Some((key, value)) = denial_sensitive_assignment(&field) {
            let key = normalized_denial_key(key);
            if denial_key_is_secret(&key) {
                redacted.push("[secret]".to_string());
                pending = if key == "authorization" && value.is_empty() {
                    Some(PendingDenialRedaction::AuthorizationSchemeOrCredential)
                } else if key == "authorization"
                    && !value.chars().any(char::is_whitespace)
                    && !value.contains(':')
                {
                    // A lone assignment value is normally the scheme
                    // (`Authorization=Digest <credential>`). Quoted values
                    // containing whitespace already include both pieces.
                    Some(PendingDenialRedaction::SecretValue)
                } else if value.is_empty() {
                    Some(PendingDenialRedaction::SecretValue)
                } else {
                    None
                };
                continue;
            }
            if matches!(
                key.as_str(),
                "path" | "file" | "directory" | "cwd" | "workspace"
            ) {
                redacted.push("[path]".to_string());
                pending = value.is_empty().then_some(PendingDenialRedaction::Path);
                continue;
            }
            if matches!(key.as_str(), "command" | "cmd" | "argv" | "executable") {
                redacted.push("[command]".to_string());
                pending = value.is_empty().then_some(PendingDenialRedaction::Command);
                continue;
            }
        }

        let secret_prefix = lower.starts_with("sk-")
            || lower.starts_with("ghp_")
            || lower.starts_with("github_pat_");
        let path_like = core.starts_with('/')
            || core.starts_with("~/")
            || core.starts_with("./")
            || core.starts_with("../")
            || core.contains('/')
            || core.contains('\\')
            || core
                .as_bytes()
                .get(1)
                .is_some_and(|separator| *separator == b':');
        let command_flag = core.starts_with('-');
        let label = lower.trim_end_matches([':', '=']);
        if matches!(label, "command" | "cmd" | "argv" | "executable") {
            redacted.push("[command]".to_string());
            pending = Some(PendingDenialRedaction::Command);
        } else if label == "authorization" {
            redacted.push("[secret]".to_string());
            pending = Some(PendingDenialRedaction::AuthorizationSchemeOrCredential);
        } else if matches!(label, "bearer" | "token" | "secret" | "password" | "passwd") {
            redacted.push("[secret]".to_string());
            pending = Some(PendingDenialRedaction::SecretValue);
        } else if matches!(label, "path" | "file" | "directory" | "cwd" | "workspace") {
            redacted.push("[path]".to_string());
            pending = Some(PendingDenialRedaction::Path);
        } else if secret_prefix {
            redacted.push("[secret]".to_string());
        } else if path_like {
            redacted.push("[path]".to_string());
        } else if command_flag {
            redacted.push("[argument]".to_string());
        } else {
            redacted.push(field);
        }
    }
    let rendered = sanitize_hook_line(&redacted.join(" "), HOOK_DENIAL_RECEIPT_MAX_CHARS);
    if rendered.is_empty() {
        "hook denied the action".to_string()
    } else {
        rendered
    }
}

/// Render a foreground hook's failure as a detail string that is safe to show.
///
/// The executor already writes generic errors, but this is the *boundary*, not
/// a restatement of that habit: only the shapes recognized here survive, and
/// each is re-rendered from parts rather than passed through. A future code
/// path that stuffs a command line, a resolved interpreter path, or hook
/// output into `HookResult::error` therefore cannot leak it into a receipt
/// merely by skipping the genericization at the producer — it degrades to the
/// catch-all instead, and the raw text is discarded.
pub(crate) fn generic_unavailable_detail(error: Option<&str>) -> String {
    const GENERIC: &str = "hook returned no verdict";
    let Some(error) = error else {
        return GENERIC.to_string();
    };
    if let Some(rest) = error.strip_prefix("Hook timed out after ") {
        let secs: String = rest.chars().take_while(char::is_ascii_digit).collect();
        return if secs.is_empty() {
            "hook timed out".to_string()
        } else {
            format!("hook timed out after {secs}s")
        };
    }
    if let Some(rest) = error.strip_prefix("hook process could not be started (") {
        // Only the `std::io::ErrorKind` debug name, and only if it really is
        // one: bare ASCII letters, nothing else.
        let kind: String = rest.chars().take_while(char::is_ascii_alphabetic).collect();
        return if kind.is_empty() {
            "hook process could not be started".to_string()
        } else {
            format!("hook process could not be started ({kind})")
        };
    }
    if error.starts_with("failed to contain hook process tree")
        || error.starts_with("failed to resume contained hook process")
    {
        return "hook process could not be contained".to_string();
    }
    if error.starts_with("hook executor did not run") {
        return "hook executor did not run".to_string();
    }
    if error.starts_with("Failed to submit background hook")
        || error.starts_with("background hook supervisor could not be started")
        || error.starts_with("background hook supervisor queue is full")
        || error.starts_with("background hook supervisor is unavailable")
    {
        return "hook could not be submitted".to_string();
    }
    if error.starts_with("Failed to wait for hook")
        || error.starts_with("hook could not be reaped")
        || error.starts_with("Failed to encode hook stdin")
        || error.starts_with("hook stdout reader could not be started")
        || error.starts_with("hook stderr reader could not be started")
        || error.starts_with("hook stdin writer could not be started")
        || error.starts_with("background hook process could not be started")
        || error.starts_with("background hook stdin writer could not be started")
        || error.starts_with("background hook setup")
    {
        return "hook did not complete cleanly".to_string();
    }
    tracing::debug!(target: "hooks", "hook failure had no recognized shape; reporting it generically");
    GENERIC.to_string()
}

/// [`sanitize_hook_text`], dropping the value entirely when nothing
/// meaningful survives.
fn sanitized_hook_field(text: &str) -> Option<String> {
    let cleaned = sanitize_hook_text(text, HOOK_TEXT_FIELD_MAX_CHARS);
    if cleaned.trim().is_empty() {
        None
    } else {
        Some(cleaned)
    }
}

/// Parsed stdout from a `tool_call_before` hook (#3026).
///
/// Hooks may emit a JSON decision on stdout:
/// `{"decision": "allow"|"deny"|"ask", "reason": "...",
///   "updatedInput": {...}, "additionalContext": "..."}`
/// Non-JSON or empty stdout → legacy passthrough (allow).
///
/// `reason` and `additional_context` are sanitized and bounded here, at the
/// only door hook stdout comes through, so no downstream consumer has to
/// remember to do it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolCallBeforeStdout {
    pub decision: Option<ToolCallDecision>,
    pub reason: Option<String>,
    pub updated_input: Option<serde_json::Value>,
    pub additional_context: Option<String>,
}

/// Decision a hook can return for a tool call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCallDecision {
    Allow,
    Deny,
    Ask,
}

pub(crate) fn parse_tool_call_before_stdout(stdout: &str) -> ToolCallBeforeStdout {
    let passthrough = ToolCallBeforeStdout {
        decision: None,
        reason: None,
        updated_input: None,
        additional_context: None,
    };
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return passthrough;
    }
    let value: serde_json::Value = match serde_json::from_str(trimmed) {
        Ok(v) => v,
        // Non-JSON stdout → legacy passthrough (allow).
        Err(_) => return passthrough,
    };
    let Some(obj) = value.as_object() else {
        tracing::warn!(
            "tool_call_before hook stdout is JSON but not an object; \
             ignoring it (legacy passthrough)"
        );
        return passthrough;
    };
    let decision = obj
        .get("decision")
        .and_then(|v| v.as_str())
        .and_then(|s| match s {
            "allow" => Some(ToolCallDecision::Allow),
            "deny" => Some(ToolCallDecision::Deny),
            "ask" => Some(ToolCallDecision::Ask),
            _ => {
                tracing::warn!(
                    "tool_call_before hook returned unrecognized decision \
                     (expected allow|deny|ask); treating as allow"
                );
                None
            }
        });
    let reason = obj
        .get("reason")
        .and_then(|v| v.as_str())
        .and_then(sanitized_hook_field);
    let updated_input = obj.get("updatedInput").cloned().filter(|v| {
        if !v.is_object() {
            tracing::warn!("tool_call_before hook updatedInput must be a JSON object; ignoring");
            return false;
        }
        let serialized_len = serde_json::to_vec(v).map_or(usize::MAX, |bytes| bytes.len());
        if serialized_len > HOOK_UPDATED_INPUT_MAX_BYTES {
            tracing::warn!(
                serialized_len,
                max_bytes = HOOK_UPDATED_INPUT_MAX_BYTES,
                "tool_call_before hook updatedInput exceeded the size limit; ignoring"
            );
            return false;
        }
        true
    });
    let additional_context = obj
        .get("additionalContext")
        .and_then(|v| v.as_str())
        .and_then(sanitized_hook_field);
    ToolCallBeforeStdout {
        decision,
        reason,
        updated_input,
        additional_context,
    }
}

/// Post-turn accumulated totals included in the `turn_end` observer payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TurnEndTotals {
    pub session_tokens: u32,
    pub conversation_tokens: u32,
    pub input_tokens: u32,
    pub output_tokens: u32,
}

/// Input used to build the structured `turn_end` observer payload.
pub struct TurnEndPayloadInput<'a> {
    pub context: &'a HookContext,
    pub created_at: DateTime<Utc>,
    pub model_backed: bool,
    pub provider: Option<&'a str>,
    pub billing_surface: Option<&'a str>,
    pub model: Option<&'a str>,
    pub turn_id: &'a str,
    pub status: &'a str,
    pub error: Option<&'a str>,
    pub duration: Duration,
    pub usage: &'a crate::models::Usage,
    pub totals: TurnEndTotals,
    pub tool_count: usize,
    pub queued_message_count: usize,
}

/// Owns the process tree created for one hook invocation.
///
/// Hooks run through a shell, so killing only the immediate `sh`/`cmd.exe`
/// child can leave the actual hook runtime alive. Unix hooks get their own
/// process group and Windows hooks are attached to a kill-on-close Job Object.
/// Dropping this guard after the shell exits also closes inherited stdout and
/// stderr pipes held by any lingering descendants.
struct HookProcessTree {
    #[cfg(unix)]
    pgid: libc::pid_t,
    #[cfg(windows)]
    job: WindowsHookJob,
}

impl HookProcessTree {
    fn attach(child: &Child) -> std::io::Result<Self> {
        #[cfg(unix)]
        {
            Ok(Self {
                pgid: child.id() as libc::pid_t,
            })
        }

        #[cfg(windows)]
        {
            Ok(Self {
                job: WindowsHookJob::attach(child)?,
            })
        }

        #[cfg(not(any(unix, windows)))]
        {
            Ok(Self {})
        }
    }

    fn terminate(&self, child: &mut Child) {
        #[cfg(unix)]
        {
            let result = unsafe { libc::kill(-self.pgid, libc::SIGKILL) };
            if result != 0 {
                let error = std::io::Error::last_os_error();
                if error.raw_os_error() != Some(libc::ESRCH) {
                    tracing::warn!(?error, "failed to terminate hook process group");
                    let _ = child.kill();
                }
            }
        }

        #[cfg(windows)]
        {
            let result = self
                .job
                .terminate()
                .or_else(|_| kill_windows_process_tree(child.id()));
            if let Err(error) = result {
                tracing::warn!(
                    ?error,
                    "failed to terminate hook process tree; killing immediate child"
                );
                let _ = child.kill();
            }
        }

        #[cfg(not(any(unix, windows)))]
        {
            let _ = child.kill();
        }
    }
}

impl Drop for HookProcessTree {
    fn drop(&mut self) {
        #[cfg(unix)]
        unsafe {
            // The shell may have exited while one of its descendants still
            // holds a captured pipe. Reaping the process group keeps hook
            // lifetimes bounded and lets the reader threads finish.
            let _ = libc::kill(-self.pgid, libc::SIGKILL);
        }
        // On Windows, dropping WindowsHookJob closes a Job Object configured
        // with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.
    }
}

#[cfg(windows)]
struct WindowsHookJob {
    handle: HANDLE,
}

#[cfg(windows)]
impl WindowsHookJob {
    fn attach(child: &Child) -> std::io::Result<Self> {
        let handle = unsafe { CreateJobObjectW(None, PCWSTR::null()).map_err(windows_io_error)? };
        let job = Self { handle };
        let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

        unsafe {
            SetInformationJobObject(
                job.handle,
                JobObjectExtendedLimitInformation,
                &limits as *const _ as *const core::ffi::c_void,
                std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
            )
            .map_err(windows_io_error)?;
            AssignProcessToJobObject(job.handle, HANDLE(child.as_raw_handle()))
                .map_err(windows_io_error)?;
        }
        Ok(job)
    }

    fn terminate(&self) -> std::io::Result<()> {
        unsafe { TerminateJobObject(self.handle, 1).map_err(windows_io_error) }
    }
}

#[cfg(windows)]
impl Drop for WindowsHookJob {
    fn drop(&mut self) {
        unsafe {
            let _ = CloseHandle(self.handle);
        }
    }
}

#[cfg(windows)]
fn windows_io_error(error: windows::core::Error) -> std::io::Error {
    std::io::Error::other(error)
}

#[cfg(windows)]
fn resume_windows_process(child: &Child) -> std::io::Result<()> {
    let snapshot =
        unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0).map_err(windows_io_error)? };
    let result = (|| {
        let mut entry = THREADENTRY32 {
            dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
            ..Default::default()
        };
        let mut next = unsafe { Thread32First(snapshot, &mut entry) };
        let mut resumed = 0usize;
        while next.is_ok() {
            if entry.th32OwnerProcessID == child.id() {
                let thread = unsafe {
                    OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID)
                        .map_err(windows_io_error)?
                };
                let resume_result = unsafe { ResumeThread(thread) };
                let close_result = unsafe { CloseHandle(thread).map_err(windows_io_error) };
                if resume_result == u32::MAX {
                    return Err(std::io::Error::last_os_error());
                }
                close_result?;
                resumed += 1;
            }
            next = unsafe { Thread32Next(snapshot, &mut entry) };
        }
        if resumed == 0 {
            return Err(std::io::Error::other(
                "suspended hook process had no resumable thread",
            ));
        }
        Ok(())
    })();
    let close_result = unsafe { CloseHandle(snapshot).map_err(windows_io_error) };
    result?;
    close_result
}

#[cfg(windows)]
fn kill_windows_process_tree(pid: u32) -> std::io::Result<()> {
    let mut command = Command::new("taskkill");
    crate::utils::suppress_console_window(&mut command);
    let pid = pid.to_string();
    let mut child = command
        .args(["/F", "/T", "/PID", pid.as_str()])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    let status = wait_for_helper_status(&mut child, WINDOWS_TASKKILL_TIMEOUT)?;
    if status.success() {
        Ok(())
    } else {
        Err(std::io::Error::other(format!(
            "taskkill exited with {status}"
        )))
    }
}

#[cfg(any(windows, test))]
fn wait_for_helper_status(
    child: &mut Child,
    timeout: Duration,
) -> std::io::Result<std::process::ExitStatus> {
    match child.wait_timeout(timeout)? {
        Some(status) => Ok(status),
        None => {
            let _ = kill_and_reap_immediate_child(child, HOOK_REAP_TIMEOUT);
            Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "hook helper did not finish within its timeout",
            ))
        }
    }
}

fn kill_and_reap_immediate_child(child: &mut Child, timeout: Duration) -> bool {
    let _ = child.kill();
    matches!(child.wait_timeout(timeout), Ok(Some(_)))
}

/// Spawn a contained hook child.
///
/// Errors returned here are deliberately free of the hook command, the
/// resolved interpreter path, and the OS message: the caller turns them into a
/// user-visible "hook could not answer" receipt, and on Windows a raw spawn
/// error echoes the whole command line back. The detail is logged instead.
fn spawn_hook_child(command: &mut Command) -> std::io::Result<(Child, HookProcessTree)> {
    let mut child = command.spawn()?;
    let process_tree = match HookProcessTree::attach(&child) {
        Ok(process_tree) => process_tree,
        Err(error) => {
            // Windows hooks are created suspended, so a containment failure
            // cannot race with a descendant spawn. Fail closed without ever
            // running the uncontained hook.
            let _ = kill_and_reap_immediate_child(&mut child, HOOK_REAP_TIMEOUT);
            tracing::warn!(target: "hooks", %error, "failed to contain hook process tree");
            return Err(std::io::Error::other("failed to contain hook process tree"));
        }
    };

    #[cfg(windows)]
    if let Err(error) = resume_windows_process(&child) {
        let _ = terminate_and_reap(None, &mut child, process_tree);
        tracing::warn!(target: "hooks", %error, "failed to resume contained hook process");
        return Err(std::io::Error::other(
            "failed to resume contained hook process",
        ));
    }

    Ok((child, process_tree))
}

/// A spawn failure rendered without the command, the path, or the OS message.
///
/// The error kind is the useful, non-identifying part (`NotFound`,
/// `PermissionDenied`, …); everything else is logged, not surfaced.
fn spawn_failure_message(error: &std::io::Error) -> String {
    format!("hook process could not be started ({:?})", error.kind())
}

const OBSERVER_DISPATCH_QUEUE_CAPACITY: usize = 32;
const OBSERVER_DISPATCH_WORKERS: usize = 2;

#[derive(Debug, Clone, Copy)]
enum ObserverDispatchFailure {
    Full,
    Disconnected,
}

/// Bounded, persistent submission path for observer-only events.
///
/// The terminal loop never creates a thread per event. Two long-lived workers
/// drain a fixed-capacity channel, and `try_send` makes saturation observable
/// without ever parking the caller.
#[derive(Clone)]
struct ObserverDispatcher {
    sender: Option<SyncSender<ObserverJob>>,
    #[cfg(test)]
    held_receiver: Option<Arc<Mutex<Receiver<ObserverJob>>>>,
}

impl fmt::Debug for ObserverDispatcher {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ObserverDispatcher")
            .field("available", &self.sender.is_some())
            .finish_non_exhaustive()
    }
}

impl ObserverDispatcher {
    fn new() -> Self {
        let (sender, receiver) = mpsc::sync_channel(OBSERVER_DISPATCH_QUEUE_CAPACITY);
        let receiver = Arc::new(Mutex::new(receiver));

        for worker_index in 0..OBSERVER_DISPATCH_WORKERS {
            let worker_receiver = Arc::clone(&receiver);
            let spawned = std::thread::Builder::new()
                .name(format!("hook-observer-{worker_index}"))
                .spawn(move || observer_worker_loop(worker_receiver));
            if let Err(error) = spawned {
                tracing::warn!(
                    target: "hooks",
                    worker_index,
                    error_kind = ?error.kind(),
                    "failed to start observer hook dispatcher"
                );
                // Dropping the only sender disconnects any workers that did
                // start. A partially-created pool is not presented as healthy.
                drop(sender);
                return Self {
                    sender: None,
                    #[cfg(test)]
                    held_receiver: None,
                };
            }
        }

        Self {
            sender: Some(sender),
            #[cfg(test)]
            held_receiver: None,
        }
    }

    fn submit(&self, event: HookEvent, job: ObserverJob) -> Result<(), String> {
        let Some(sender) = &self.sender else {
            return Err(observer_dispatch_failure_message(
                event,
                ObserverDispatchFailure::Disconnected,
            ));
        };
        match sender.try_send(job) {
            Ok(()) => Ok(()),
            Err(TrySendError::Full(_)) => Err(observer_dispatch_failure_message(
                event,
                ObserverDispatchFailure::Full,
            )),
            Err(TrySendError::Disconnected(_)) => Err(observer_dispatch_failure_message(
                event,
                ObserverDispatchFailure::Disconnected,
            )),
        }
    }
}

fn observer_dispatch_failure_message(event: HookEvent, failure: ObserverDispatchFailure) -> String {
    match failure {
        ObserverDispatchFailure::Full => format!(
            "{} observer hook queue is full; event was not submitted",
            event.as_str()
        ),
        ObserverDispatchFailure::Disconnected => format!(
            "{} observer hook dispatcher is unavailable; event was not submitted",
            event.as_str()
        ),
    }
}

enum ObserverJob {
    Environment {
        hooks: HookExecutor,
        event: HookEvent,
        context: HookContext,
    },
    Json {
        hooks: HookExecutor,
        event: HookEvent,
        context: HookContext,
        payload: serde_json::Value,
    },
}

impl ObserverJob {
    fn run(self) {
        match self {
            Self::Environment {
                hooks,
                event,
                context,
            } => {
                let _ = hooks.execute(event, &context);
            }
            Self::Json {
                hooks,
                event,
                context,
                payload,
            } => {
                let _ = hooks.execute_json_observer(event, &context, &payload);
            }
        }
    }
}

fn observer_worker_loop(receiver: Arc<Mutex<Receiver<ObserverJob>>>) {
    loop {
        let received = match receiver.lock() {
            Ok(receiver) => receiver.recv(),
            Err(_) => {
                tracing::warn!(target: "hooks", "observer hook dispatcher lock was poisoned");
                return;
            }
        };
        match received {
            Ok(job) => job.run(),
            Err(_) => return,
        }
    }
}

const BACKGROUND_SUPERVISOR_QUEUE_CAPACITY: usize = 32;
const BACKGROUND_SUPERVISOR_WORKERS: usize = 2;

#[derive(Debug, Clone, Copy)]
enum BackgroundSupervisorFailure {
    Full,
    Disconnected,
}

/// Bounded pool that owns background-child setup, timeout, tree kill, and
/// reap. Observer workers enqueue here instead of creating one detached
/// supervisor thread per invocation.
#[derive(Clone)]
struct BackgroundSupervisor {
    sender: Option<SyncSender<BackgroundHookJob>>,
    #[cfg(test)]
    held_receiver: Option<Arc<Mutex<Receiver<BackgroundHookJob>>>>,
}

impl fmt::Debug for BackgroundSupervisor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("BackgroundSupervisor")
            .field("available", &self.sender.is_some())
            .finish_non_exhaustive()
    }
}

impl BackgroundSupervisor {
    fn new() -> Self {
        let (sender, receiver) = mpsc::sync_channel(BACKGROUND_SUPERVISOR_QUEUE_CAPACITY);
        let receiver = Arc::new(Mutex::new(receiver));

        for worker_index in 0..BACKGROUND_SUPERVISOR_WORKERS {
            let worker_receiver = Arc::clone(&receiver);
            let spawned = std::thread::Builder::new()
                .name(format!("hook-supervisor-{worker_index}"))
                .spawn(move || background_supervisor_worker_loop(worker_receiver));
            if let Err(error) = spawned {
                tracing::warn!(
                    target: "hooks",
                    worker_index,
                    error_kind = ?error.kind(),
                    "failed to start background hook supervisor pool"
                );
                drop(sender);
                return Self {
                    sender: None,
                    #[cfg(test)]
                    held_receiver: None,
                };
            }
        }

        Self {
            sender: Some(sender),
            #[cfg(test)]
            held_receiver: None,
        }
    }

    fn submit(&self, job: BackgroundHookJob) -> Result<(), BackgroundSupervisorFailure> {
        let Some(sender) = &self.sender else {
            return Err(BackgroundSupervisorFailure::Disconnected);
        };
        match sender.try_send(job) {
            Ok(()) => Ok(()),
            Err(TrySendError::Full(_)) => Err(BackgroundSupervisorFailure::Full),
            Err(TrySendError::Disconnected(_)) => Err(BackgroundSupervisorFailure::Disconnected),
        }
    }
}

struct BackgroundHookJob {
    command: String,
    env: HashMap<String, String>,
    working_dir: PathBuf,
    stdin_bytes: Option<Vec<u8>>,
    label: String,
    timeout: Duration,
}

impl BackgroundHookJob {
    fn run(self) {
        let Self {
            command: command_text,
            env,
            working_dir,
            stdin_bytes,
            label,
            timeout,
        } = self;
        let timeout_secs = timeout.as_secs();
        let mut command = HookExecutor::build_shell_command(&command_text);
        command
            .current_dir(&working_dir)
            .envs(&env)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            // Always pipe stdin so dropping it delivers EOF through shell
            // wrappers even when there is no structured payload.
            .stdin(Stdio::piped());

        let (mut child, process_tree) = match spawn_hook_child(&mut command) {
            Ok(child) => child,
            Err(error) => {
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    error_kind = ?error.kind(),
                    "failed to start background hook"
                );
                return;
            }
        };

        let _stdin_writer = match (stdin_bytes, child.stdin.take()) {
            (Some(bytes), Some(stdin)) => match spawn_stdin_writer(stdin, bytes) {
                Ok(writer) => Some(writer),
                Err(error) => {
                    tracing::warn!(
                        target: "hooks",
                        hook = %label,
                        error_kind = ?error.kind(),
                        "failed to start background hook stdin writer"
                    );
                    terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
                    return;
                }
            },
            _ => None,
        };

        match child.wait_timeout(timeout) {
            Ok(Some(status)) => {
                if !status.success() {
                    tracing::warn!(
                        target: "hooks",
                        hook = %label,
                        exit_code = ?status.code(),
                        "background hook exited non-zero"
                    );
                }
            }
            Ok(None) => {
                let reaped = terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    timeout_secs,
                    reaped,
                    "background hook timed out; process tree killed"
                );
            }
            Err(error) => {
                terminate_and_reap(Some(label.as_str()), &mut child, process_tree);
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    ?error,
                    "failed to wait for background hook; process tree killed"
                );
            }
        }
    }
}

fn background_supervisor_worker_loop(receiver: Arc<Mutex<Receiver<BackgroundHookJob>>>) {
    loop {
        let received = match receiver.lock() {
            Ok(receiver) => receiver.recv(),
            Err(_) => {
                tracing::warn!(target: "hooks", "background supervisor lock was poisoned");
                return;
            }
        };
        match received {
            Ok(job) => job.run(),
            Err(_) => return,
        }
    }
}

/// Executor for running hooks
#[derive(Debug, Clone)]
pub struct HookExecutor {
    config: HooksConfig,
    default_working_dir: PathBuf,
    session_id: String,
    observer_dispatcher: ObserverDispatcher,
    background_supervisor: BackgroundSupervisor,
    #[cfg(test)]
    lose_message_submit_executor: bool,
}

impl HookExecutor {
    fn build_shell_command(command: &str) -> Command {
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt as _;
            let mut cmd = Command::new("cmd");
            const CREATE_SUSPENDED: u32 = 0x0000_0004;
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            cmd.creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW);
            // raw_arg: cmd.exe does not parse the CRT-style \" escapes that
            // Command::arg would insert, so pass the command line verbatim.
            cmd.arg("/C").raw_arg(command);
            cmd
        }
        #[cfg(not(windows))]
        {
            let mut cmd = Command::new("sh");
            cmd.arg("-c").arg(command);
            #[cfg(unix)]
            {
                use std::os::unix::process::CommandExt as _;
                cmd.process_group(0);
            }
            cmd
        }
    }

    /// Create a new `HookExecutor` with configuration.
    ///
    /// This mints the hook session identity for the whole TUI session. Call it
    /// **once per launch**; every later reload (workspace switch, trust
    /// onboarding) must go through [`Self::rebind`] so the id every hook has
    /// already seen stays valid. Regenerating it mid-session would break
    /// correlation for anything that grouped records by `DEEPSEEK_SESSION_ID`.
    pub fn new(config: HooksConfig, default_working_dir: PathBuf) -> Self {
        // Generate a session ID
        let session_id = format!("sess_{}", &uuid::Uuid::new_v4().to_string()[..8]);
        Self {
            config,
            default_working_dir,
            session_id,
            observer_dispatcher: ObserverDispatcher::new(),
            background_supervisor: BackgroundSupervisor::new(),
            #[cfg(test)]
            lose_message_submit_executor: false,
        }
    }

    /// Rebuild the executor with new configuration and working directory while
    /// preserving the session identity minted at launch.
    ///
    /// Used when the workspace changes or a trust decision makes project hooks
    /// eligible: the hook set may change, the session does not.
    #[must_use]
    pub fn rebind(&self, config: HooksConfig, default_working_dir: PathBuf) -> Self {
        Self {
            config,
            default_working_dir,
            session_id: self.session_id.clone(),
            observer_dispatcher: self.observer_dispatcher.clone(),
            background_supervisor: self.background_supervisor.clone(),
            #[cfg(test)]
            lose_message_submit_executor: self.lose_message_submit_executor,
        }
    }

    /// Create a disabled `HookExecutor` (no hooks will run)
    #[allow(dead_code)] // Used in tests and as convenience constructor
    pub fn disabled() -> Self {
        Self {
            config: HooksConfig {
                enabled: false,
                ..Default::default()
            },
            default_working_dir: PathBuf::from("."),
            session_id: String::new(),
            observer_dispatcher: ObserverDispatcher::new(),
            background_supervisor: BackgroundSupervisor::new(),
            #[cfg(test)]
            lose_message_submit_executor: false,
        }
    }

    /// Check if hooks are enabled
    #[allow(dead_code)] // Public API for hook system consumers
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the session ID
    /// Read-only access to the underlying configuration. Used by
    /// `/hooks` (#460 read-only MVP) so the user can list configured
    /// hooks without reaching for `cat ~/.deepseek/config.toml`.
    pub fn config(&self) -> &HooksConfig {
        &self.config
    }

    pub fn session_id(&self) -> &str {
        &self.session_id
    }

    /// Cheap pre-check: are there any enabled hooks for this event?
    /// Lets call sites avoid building a [`HookContext`] (which allocates
    /// for `workspace`, `model`, `session_id`, …) on every tool call
    /// when the user hasn't configured any hooks. The cost matters
    /// because `ToolCallBefore` / `ToolCallAfter` fire from
    /// `tool_routing.rs` on every tool dispatch (#455).
    #[must_use]
    pub fn has_hooks_for_event(&self, event: HookEvent) -> bool {
        self.config.enabled && self.config.hooks.iter().any(|h| h.event == event)
    }

    /// Check if there are any background hooks configured for a specific event.
    ///
    /// Background hooks fire and forget — their `exit_code` is always `None`,
    /// so they cannot deny tool calls. This is a known limitation; the check
    /// is used to warn operators when a `ToolCallBefore` hook is configured
    /// as background but expects to block a tool.
    #[must_use]
    pub fn has_background_hooks_for_event(&self, event: HookEvent) -> bool {
        if !self.config.enabled {
            return false;
        }
        self.config
            .hooks
            .iter()
            .any(|h| h.event == event && h.background)
    }

    /// Sanitized labels of the strict foreground gates that *would* run for
    /// this event and context.
    ///
    /// "Strict" is `continue_on_error = false` on a foreground hook: an
    /// operator instruction that the action must not proceed without this
    /// hook's answer. The caller collects these **before** dispatching the
    /// executor so it can still honor them if the execution itself is lost —
    /// a panicked or cancelled `spawn_blocking` returns no results at all, and
    /// an empty result set is indistinguishable from "every hook allowed it".
    ///
    /// Condition matching is the same predicate [`Self::execute`] uses, so
    /// this never names a hook that would not have run: a strict `write_file`
    /// gate has no say over an `exec_shell` call it never matched.
    #[must_use]
    pub fn matched_strict_gate_labels(
        &self,
        event: HookEvent,
        context: &HookContext,
    ) -> Vec<String> {
        if !self.config.enabled {
            return Vec::new();
        }
        self.config
            .hooks_for_event(event)
            .into_iter()
            .filter(|hook| {
                // A background hook is never awaited, so it is not a gate no
                // matter what `continue_on_error` says.
                let foreground = !hook.background || !hook.event.honors_background();
                foreground && !hook.continue_on_error && self.matches_condition(hook, context)
            })
            .map(|hook| sanitize_hook_label(hook.name.as_deref()))
            .collect()
    }

    /// Run configured `message_submit` hooks as a mutable submit pipeline.
    ///
    /// This is deliberately separate from [`Self::execute`]: most hook events
    /// are observer-only, while `message_submit` has a narrow stdout JSON
    /// contract that can replace or block the submitted text.
    pub fn execute_message_submit_transform(
        &self,
        context: &HookContext,
        original_text: &str,
    ) -> MessageSubmitOutcome {
        if !self.config.enabled {
            return MessageSubmitOutcome::unchanged();
        }

        let hooks = self.config.hooks_for_event(HookEvent::MessageSubmit);
        if hooks.is_empty() {
            return MessageSubmitOutcome::unchanged();
        }

        let mut current_text = original_text.to_string();
        let mut warning = None;

        for hook in hooks {
            let hook_context = context.clone().with_message(&current_text);
            if !self.matches_condition(hook, &hook_context) {
                continue;
            }

            let env_vars = hook_context.to_env_vars();
            let payload = message_submit_payload(&hook_context, &current_text);
            if hook.background {
                // A background `message_submit` hook cannot steer, but it must
                // still receive the documented stdin payload — the contract is
                // the same JSON, only the steering is dropped.
                let submitted = self.execute_background_with_stdin(hook, &env_vars, &payload);
                // Submission itself can fail (thread spawn refused, payload not
                // encodable). Discarding that silently is the one outcome an
                // operator cannot debug: the hook is configured, nothing runs,
                // and nothing says so. Still non-blocking — the submit proceeds.
                if !submitted.success {
                    tracing::warn!(
                        target: "hooks",
                        hook = %sanitize_hook_label(submitted.name.as_deref()),
                        event = "message_submit",
                        error = %generic_unavailable_detail(submitted.error.as_deref()),
                        "background message_submit hook was not submitted; it will not run"
                    );
                }
                continue;
            }

            let result = self.execute_sync_with_stdin(hook, &env_vars, &payload);

            if result.exit_code == Some(2) {
                return MessageSubmitOutcome::Blocked {
                    reason: message_submit_block_reason(
                        &result,
                        "message_submit hook blocked submission",
                    ),
                };
            }

            if !result.success {
                let label = sanitize_hook_label(result.name.as_deref());
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    event = "message_submit",
                    exit_code = ?result.exit_code,
                    duration_ms = result.duration.as_millis() as u64,
                    detail = %generic_unavailable_detail(result.error.as_deref()),
                    "message_submit hook failed"
                );

                if hook.continue_on_error {
                    warning = message_submit_continue_warning(&result).or(warning);
                    continue;
                }

                return MessageSubmitOutcome::Blocked {
                    reason: message_submit_block_reason(
                        &result,
                        "message_submit hook failed and blocked submission",
                    ),
                };
            }

            match parse_message_submit_stdout(&result.stdout) {
                MessageSubmitStdout::Unchanged => {}
                MessageSubmitStdout::Replaced(text) => {
                    current_text = text;
                }
                MessageSubmitStdout::Invalid(reason) => {
                    tracing::warn!(
                        target: "hooks",
                        hook = %sanitize_hook_label(result.name.as_deref()),
                        event = "message_submit",
                        reason = %reason,
                        "ignored invalid message_submit hook stdout"
                    );
                }
            }
        }

        if current_text == original_text {
            MessageSubmitOutcome::unchanged().with_warning(warning)
        } else {
            MessageSubmitOutcome::replaced(current_text).with_warning(warning)
        }
    }

    /// Dispatch-bound entry point for the mutable submit gate.
    ///
    /// Keeping this wrapper distinct gives the production dispatch path a
    /// deterministic test seam for a lost blocking task. Normal hook tests use
    /// [`Self::execute_message_submit_transform`] directly.
    pub(crate) fn execute_message_submit_transform_for_dispatch(
        &self,
        context: &HookContext,
        original_text: &str,
    ) -> MessageSubmitOutcome {
        #[cfg(test)]
        if self.lose_message_submit_executor {
            panic!("injected message_submit executor loss");
        }
        self.execute_message_submit_transform(context, original_text)
    }

    #[cfg(test)]
    pub(crate) fn inject_message_submit_executor_loss_for_test(&mut self) {
        self.lose_message_submit_executor = true;
    }

    #[cfg(test)]
    pub(crate) fn inject_observer_dispatch_full_for_test(&mut self) {
        let (sender, receiver) = mpsc::sync_channel(0);
        self.observer_dispatcher.sender = Some(sender);
        // Keep the receiver connected but deliberately leave no worker waiting
        // on it. The production `try_send` path therefore returns `Full`.
        self.observer_dispatcher.held_receiver = Some(Arc::new(Mutex::new(receiver)));
    }

    #[cfg(test)]
    pub(crate) fn inject_observer_dispatch_disconnect_for_test(&mut self) {
        let (sender, receiver) = mpsc::sync_channel(1);
        drop(receiver);
        self.observer_dispatcher.sender = Some(sender);
        self.observer_dispatcher.held_receiver = None;
    }

    #[cfg(test)]
    fn inject_background_supervisor_full_for_test(&mut self) {
        let (sender, receiver) = mpsc::sync_channel(0);
        self.background_supervisor.sender = Some(sender);
        self.background_supervisor.held_receiver = Some(Arc::new(Mutex::new(receiver)));
    }

    /// Run every `ShellEnv` hook for this context and merge their stdout
    /// (`KEY=VALUE\n` lines) into a single env-var map. Used by the
    /// `exec_shell` tool to inject ephemeral credentials, per-skill PATH
    /// adjustments, etc. (#456). Failures don't abort the shell call —
    /// the hook simply contributes no vars and a `tracing::warn!` lands.
    ///
    /// Each successful hook's keys (NOT values) are written to the audit
    /// log so a session can be reconciled later without leaking the
    /// secret material itself.
    pub fn collect_shell_env(&self, context: &HookContext) -> HashMap<String, String> {
        let mut merged: HashMap<String, String> = HashMap::new();
        if !self.config.enabled {
            return merged;
        }
        let hooks = self.config.hooks_for_event(HookEvent::ShellEnv);
        if hooks.is_empty() {
            return merged;
        }
        let env_vars = context.to_env_vars();
        for hook in hooks {
            if !self.matches_condition(hook, context) {
                continue;
            }
            // ShellEnv hooks must be synchronous — their stdout is the contract.
            let result = self.execute_sync(hook, &env_vars);
            if !result.success {
                tracing::warn!(
                    target: "hooks",
                    hook = %sanitize_hook_label(result.name.as_deref()),
                    event = "shell_env",
                    exit_code = ?result.exit_code,
                    detail = %generic_unavailable_detail(result.error.as_deref()),
                    "shell_env hook failed; contributing no env vars"
                );
                continue;
            }
            let parsed = parse_env_lines(&result.stdout);
            if parsed.is_empty() {
                continue;
            }
            // Audit-log the *keys* — never the values.
            crate::audit::log_sensitive_event(
                "shell_env_hook",
                serde_json::json!({
                    // Bounded and de-fanged like every other rendering of a
                    // hook name: an audit record is read by a person, often
                    // through `tail`, where a raw escape sequence still acts.
                    "hook": sanitize_hook_label(result.name.as_deref()),
                    "tool": context.tool_name,
                    "keys": parsed.keys().cloned().collect::<Vec<_>>(),
                }),
            );
            // Later hooks override earlier ones. Documented behavior.
            merged.extend(parsed);
        }
        merged
    }

    /// Execute all hooks for an event
    pub fn execute(&self, event: HookEvent, context: &HookContext) -> Vec<HookResult> {
        if !self.config.enabled {
            return Vec::new();
        }

        let hooks = self.config.hooks_for_event(event);
        if hooks.is_empty() {
            // Fast path: no hooks for this event → skip the
            // `context.to_env_vars()` HashMap allocation. With
            // `tool_call_before` / `tool_call_after` firing per-tool
            // (#455) this allocation would otherwise happen on every
            // tool dispatch even for users with zero hooks configured.
            return Vec::new();
        }
        let env_vars = context.to_env_vars();
        let mut results = Vec::new();

        for hook in hooks {
            if !self.matches_condition(hook, context) {
                continue;
            }

            let result = if hook.background {
                self.execute_background(hook, &env_vars)
            } else {
                self.execute_sync(hook, &env_vars)
            };

            // Log failures via tracing so operators tailing
            // `deepseek` with `RUST_LOG=warn` can see hook errors
            // without instrumenting each call site. Successful runs
            // log nothing (would be too noisy on per-tool events).
            if !result.success {
                let label = sanitize_hook_label(result.name.as_deref());
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    event = event.as_str(),
                    exit_code = ?result.exit_code,
                    duration_ms = result.duration.as_millis() as u64,
                    detail = %generic_unavailable_detail(result.error.as_deref()),
                    "hook failed"
                );
            }

            let should_continue = result.success || hook.continue_on_error;
            results.push(result);

            if !should_continue {
                break;
            }
        }

        results
    }

    /// Execute observer hooks with a structured JSON stdin payload.
    ///
    /// Unlike `message_submit`, stdout is deliberately ignored by callers:
    /// these hooks are lifecycle observers and cannot mutate or block the
    /// underlying action.
    pub fn execute_json_observer(
        &self,
        event: HookEvent,
        context: &HookContext,
        payload: &serde_json::Value,
    ) -> Vec<HookResult> {
        if !self.config.enabled {
            return Vec::new();
        }

        let hooks = self.config.hooks_for_event(event);
        if hooks.is_empty() {
            return Vec::new();
        }

        let env_vars = context.to_env_vars();
        let mut results = Vec::new();
        for hook in hooks {
            if !self.matches_condition(hook, context) {
                continue;
            }

            let result = if hook.background {
                self.execute_background_with_stdin(hook, &env_vars, payload)
            } else {
                self.execute_sync_with_stdin(hook, &env_vars, payload)
            };

            if !result.success {
                let label = sanitize_hook_label(result.name.as_deref());
                tracing::warn!(
                    target: "hooks",
                    hook = %label,
                    event = event.as_str(),
                    exit_code = ?result.exit_code,
                    duration_ms = result.duration.as_millis() as u64,
                    detail = %generic_unavailable_detail(result.error.as_deref()),
                    "observer hook failed"
                );
            }

            results.push(result);
        }

        results
    }

    /// Submit an observer event without waiting on foreground child processes
    /// from the caller's thread. The outer worker is fallible and the failure
    /// is returned to the UI; silently dropping a configured observer is not a
    /// truthful fire-and-forget contract.
    pub fn submit_observer(&self, event: HookEvent, context: HookContext) -> Result<(), String> {
        if !self.has_hooks_for_event(event) {
            return Ok(());
        }
        self.observer_dispatcher.submit(
            event,
            ObserverJob::Environment {
                hooks: self.clone(),
                event,
                context: context.bounded_for_observer(),
            },
        )
    }

    /// Structured-payload counterpart to [`Self::submit_observer`].
    pub fn submit_json_observer(
        &self,
        event: HookEvent,
        context: HookContext,
        payload: serde_json::Value,
    ) -> Result<(), String> {
        if !self.has_hooks_for_event(event) {
            return Ok(());
        }
        self.observer_dispatcher.submit(
            event,
            ObserverJob::Json {
                hooks: self.clone(),
                event,
                context: context.bounded_for_observer(),
                payload,
            },
        )
    }

    /// Check whether a tool name matches a condition pattern with `*` glob support.
    fn tool_name_matches_condition(tool_name: &str, pattern: &str) -> bool {
        if !pattern.contains('*') {
            return tool_name == pattern;
        }
        // Escape regex metacharacters except `*`, which becomes `.*`.
        let escaped = regex::escape(pattern);
        let regex_pattern = escaped.replace(r"\*", ".*");
        let anchored = format!("^{regex_pattern}$");
        regex::Regex::new(&anchored).is_ok_and(|re| re.is_match(tool_name))
    }

    /// Check if a hook's condition matches the context
    #[allow(clippy::only_used_in_recursion)]
    fn matches_condition(&self, hook: &Hook, context: &HookContext) -> bool {
        match &hook.condition {
            None | Some(HookCondition::Always) => true,
            Some(HookCondition::ToolName { name }) => {
                // #3026: Support `*` globs in tool_name conditions so
                // `mcp__*` matches all MCP tools.  Exact names keep working.
                context
                    .tool_name
                    .as_ref()
                    .is_some_and(|n| Self::tool_name_matches_condition(n, name))
            }
            Some(HookCondition::ToolCategory { category }) => {
                let tool_category = context
                    .tool_name
                    .as_deref()
                    .map(|name| tool_category_for(name, context.tool_args.as_deref()));
                tool_category.is_some_and(|c| c == category.as_str())
            }
            Some(HookCondition::Mode { mode }) => context
                .mode
                .as_ref()
                .is_some_and(|m| m.eq_ignore_ascii_case(mode)),
            Some(HookCondition::ExitCode { code }) => context.tool_exit_code == Some(*code),
            Some(HookCondition::All { conditions }) => conditions.iter().all(|c| {
                self.matches_condition(
                    &Hook {
                        condition: Some(c.clone()),
                        ..hook.clone()
                    },
                    context,
                )
            }),
            Some(HookCondition::Any { conditions }) => conditions.iter().any(|c| {
                self.matches_condition(
                    &Hook {
                        condition: Some(c.clone()),
                        ..hook.clone()
                    },
                    context,
                )
            }),
        }
    }

    /// Execute a hook synchronously
    fn execute_sync(&self, hook: &Hook, env_vars: &HashMap<String, String>) -> HookResult {
        self.execute_sync_inner(hook, env_vars, None)
    }

    /// Execute a hook synchronously with a structured JSON stdin payload.
    ///
    /// Used by mutable `message_submit` hooks. Existing observer hooks keep the
    /// stdin-less [`Self::execute_sync`] path so their behavior is unchanged.
    fn execute_sync_with_stdin(
        &self,
        hook: &Hook,
        env_vars: &HashMap<String, String>,
        stdin_json: &serde_json::Value,
    ) -> HookResult {
        self.execute_sync_inner(hook, env_vars, Some(stdin_json))
    }

    fn execute_sync_inner(
        &self,
        hook: &Hook,
        env_vars: &HashMap<String, String>,
        stdin_json: Option<&serde_json::Value>,
    ) -> HookResult {
        let started = Instant::now();
        let working_dir = self
            .config
            .working_dir
            .clone()
            .unwrap_or_else(|| self.default_working_dir.clone());

        let timeout_secs = self.effective_timeout_secs(hook);
        let timeout = Duration::from_secs(timeout_secs);
        // This path always runs the hook in the foreground and awaits it, so
        // `continue_on_error = false` is a live "do not proceed without my
        // answer" for whichever call this result belongs to.
        let strict = !hook.continue_on_error;

        let stdin_bytes = match stdin_json.map(serde_json::to_vec).transpose() {
            Ok(bytes) => bytes,
            Err(e) => {
                return HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some(format!("Failed to encode hook stdin: {e}")),
                };
            }
        };

        let mut command = Self::build_shell_command(&hook.command);
        command
            .current_dir(&working_dir)
            .envs(env_vars)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            // A closed pipe is a portable EOF signal through shell layers.
            // Windows cmd/PowerShell can reopen console input when handed
            // NUL, so Stdio::null() is not sufficient when the parent test or
            // terminal still owns a live stdin handle.
            .stdin(Stdio::piped());

        let (mut child, process_tree) = match spawn_hook_child(&mut command) {
            Ok(child) => child,
            Err(e) => {
                // Generic on purpose: this string reaches the deny receipt and
                // the TUI, and a spawn error can otherwise echo the resolved
                // command line or interpreter path back to the transcript.
                tracing::warn!(
                    target: "hooks",
                    hook = %sanitize_hook_label(hook.name.as_deref()),
                    error = %e,
                    "failed to start hook process"
                );
                return HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some(spawn_failure_message(&e)),
                };
            }
        };

        let stdout_reader = match child
            .stdout
            .take()
            .map(|pipe| spawn_pipe_reader(pipe, "hook-stdout-reader"))
            .transpose()
        {
            Ok(reader) => reader,
            Err(error) => {
                tracing::warn!(
                    target: "hooks",
                    hook = %sanitize_hook_label(hook.name.as_deref()),
                    error_kind = ?error.kind(),
                    "failed to start hook stdout reader"
                );
                terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
                return HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some("hook stdout reader could not be started".to_string()),
                };
            }
        };
        let stderr_reader = match child
            .stderr
            .take()
            .map(|pipe| spawn_pipe_reader(pipe, "hook-stderr-reader"))
            .transpose()
        {
            Ok(reader) => reader,
            Err(error) => {
                tracing::warn!(
                    target: "hooks",
                    hook = %sanitize_hook_label(hook.name.as_deref()),
                    error_kind = ?error.kind(),
                    "failed to start hook stderr reader"
                );
                terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
                let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                return HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some("hook stderr reader could not be started".to_string()),
                };
            }
        };
        let _stdin_writer = match (stdin_bytes, child.stdin.take()) {
            (Some(bytes), Some(stdin)) => match spawn_stdin_writer(stdin, bytes) {
                Ok(writer) => Some(writer),
                Err(error) => {
                    tracing::warn!(
                        target: "hooks",
                        hook = %sanitize_hook_label(hook.name.as_deref()),
                        error_kind = ?error.kind(),
                        "failed to start hook stdin writer"
                    );
                    terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
                    let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                    let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                    return HookResult {
                        name: hook.name.clone(),
                        background: false,
                        strict,
                        success: false,
                        exit_code: None,
                        stdout: String::new(),
                        stderr: String::new(),
                        duration: started.elapsed(),
                        error: Some("hook stdin writer could not be started".to_string()),
                    };
                }
            },
            _ => None,
        };

        match child.wait_timeout(timeout) {
            Ok(Some(status)) => {
                drop(process_tree);
                HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: status.success(),
                    exit_code: status.code(),
                    stdout: collect_reader(stdout_reader, HOOK_PIPE_DRAIN_TIMEOUT),
                    stderr: collect_reader(stderr_reader, HOOK_PIPE_DRAIN_TIMEOUT),
                    duration: started.elapsed(),
                    error: None,
                }
            }
            Ok(None) => {
                let reaped = terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
                let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some(if reaped {
                        format!("Hook timed out after {timeout_secs}s")
                    } else {
                        // The gate still did not answer, and now we also cannot
                        // prove the process is gone. Say the weaker thing.
                        "hook could not be reaped after its timeout".to_string()
                    }),
                }
            }
            Err(e) => {
                tracing::warn!(
                    target: "hooks",
                    hook = %sanitize_hook_label(hook.name.as_deref()),
                    error = %e,
                    "failed to wait for hook process"
                );
                terminate_and_reap(hook.name.as_deref(), &mut child, process_tree);
                let _ = collect_reader(stdout_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                let _ = collect_reader(stderr_reader, HOOK_PIPE_SHUTDOWN_TIMEOUT);
                HookResult {
                    name: hook.name.clone(),
                    background: false,
                    strict,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    // Generic on purpose, like the spawn path: an OS wait error
                    // can name the child and reaches the deny receipt.
                    error: Some("Failed to wait for hook".to_string()),
                }
            }
        }
    }

    /// Execute a hook in the background (non-blocking)
    fn execute_background(&self, hook: &Hook, env_vars: &HashMap<String, String>) -> HookResult {
        self.execute_background_inner(hook, env_vars, None)
    }

    fn execute_background_with_stdin(
        &self,
        hook: &Hook,
        env_vars: &HashMap<String, String>,
        stdin_json: &serde_json::Value,
    ) -> HookResult {
        self.execute_background_inner(hook, env_vars, Some(stdin_json))
    }

    fn execute_background_inner(
        &self,
        hook: &Hook,
        env_vars: &HashMap<String, String>,
        stdin_json: Option<&serde_json::Value>,
    ) -> HookResult {
        let started = Instant::now();
        let working_dir = self
            .config
            .working_dir
            .clone()
            .unwrap_or_else(|| self.default_working_dir.clone());

        let stdin_bytes = match stdin_json.map(serde_json::to_vec).transpose() {
            Ok(bytes) => bytes,
            Err(e) => {
                return HookResult {
                    name: hook.name.clone(),
                    background: true,
                    strict: false,
                    success: false,
                    exit_code: None,
                    stdout: String::new(),
                    stderr: String::new(),
                    duration: started.elapsed(),
                    error: Some(format!("Failed to encode hook stdin: {e}")),
                };
            }
        };
        let submission = self.background_supervisor.submit(BackgroundHookJob {
            command: hook.command.clone(),
            env: env_vars.clone(),
            working_dir,
            stdin_bytes,
            label: sanitize_hook_label(hook.name.as_deref()),
            timeout: Duration::from_secs(self.effective_timeout_secs(hook)),
        });

        // The result describes the bounded submission, not the run: no caller
        // can mistake "queued" for "exited 0".
        HookResult {
            name: hook.name.clone(),
            background: true,
            strict: false,
            success: submission.is_ok(),
            exit_code: None,
            stdout: String::new(),
            stderr: String::new(),
            duration: started.elapsed(),
            error: submission.err().map(|failure| match failure {
                BackgroundSupervisorFailure::Full => {
                    "background hook supervisor queue is full".to_string()
                }
                BackgroundSupervisorFailure::Disconnected => {
                    "background hook supervisor is unavailable".to_string()
                }
            }),
        }
    }

    /// The timeout actually applied to a hook, foreground or background.
    ///
    /// `[hooks].default_timeout_secs` *replaces* the per-hook value when set;
    /// that is the shipped behavior and is documented as such in
    /// `docs/HOOKS.md`.
    fn effective_timeout_secs(&self, hook: &Hook) -> u64 {
        self.config.effective_timeout_secs(hook)
    }
}

/// Classify a tool call for `condition = { type = "tool_category", … }`.
///
/// Categories are `shell`, `file_write`, `safe`, and `other`, as documented in
/// `docs/HOOKS.md`. This must be kept in step with the names the registry
/// actually registers: before 2026-08-04 the map knew only the retired
/// `exec_shell`/`write_file`/`read_file` spellings, so EVERY live call fell
/// through to `other` and a `tool_category` **deny** hook silently never
/// fired — the exact failure `docs/HOOKS.md` warns about ("a deny gate the
/// operator believes is armed").
///
/// `File`, `Git`, and `Run` are multi-action, so the action decides the
/// category: a `File` read is `safe` while a `File` write is `file_write`.
/// An unparseable or absent argument blob is treated as the tool's most
/// dangerous action, because a gate that cannot see the action must not
/// assume the harmless one.
fn tool_category_for(tool_name: &str, tool_args: Option<&str>) -> &'static str {
    let action = tool_args
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
        .and_then(|value| {
            value
                .get("action")
                .and_then(serde_json::Value::as_str)
                .map(str::to_ascii_lowercase)
        });

    match tool_name {
        // The shell surface. `exec_shell` is retired but kept here because
        // `shell.rs` still stamps it for the `shell_env` hook event.
        "bash" | "Bash" | "exec_shell" => "shell",
        // The lowercase primitives ship without an action envelope.
        "read" | "todo_write" => "safe",
        "write" | "edit" => "file_write",
        "File" | "file" => match action.as_deref() {
            Some("read" | "list" | "search_name" | "search_content") => "safe",
            // write/edit/patch, and the unknown-action case, are writes.
            _ => "file_write",
        },
        "apply_patch" => "file_write",
        "Git" | "git" => match action.as_deref() {
            // Every shipped Git action is read-only today; classify by action
            // anyway so adding a mutating one cannot silently inherit `safe`.
            Some("status" | "diff" | "log" | "show" | "blame") => "safe",
            _ => "other",
        },
        // `Run` executes test/verifier commands — closer to shell than safe.
        "Run" | "run" => "shell",
        _ => "other",
    }
}

const HOOK_PIPE_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
const HOOK_PIPE_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(250);
/// How long the timeout path waits for the killed child to be reaped.
///
/// The wait after a kill is *bounded* rather than unbounded: `child.wait()`
/// blocks forever if the kill did not take (a `SIGKILL`-immune uninterruptible
/// state on Unix, a `TerminateJobObject` that a protected process survived on
/// Windows), and that turned "this hook has a 30s budget" into a hung turn.
const HOOK_REAP_TIMEOUT: Duration = Duration::from_secs(2);
#[cfg(windows)]
const WINDOWS_TASKKILL_TIMEOUT: Duration = Duration::from_secs(2);

/// Kill the hook's process tree and wait, briefly, for the corpse.
///
/// Termination is best-effort by nature — the OS owns whether a kill lands.
/// What is guaranteed here is that *this* thread stops waiting: the
/// containment guard is dropped first (which re-signals the Unix process group
/// and closes the kill-on-close Windows Job Object), then the reap gets one
/// bounded window. Returns `false` when the child could not be confirmed dead,
/// so the caller can report the weaker claim instead of asserting cleanup.
fn terminate_and_reap(
    hook_name: Option<&str>,
    child: &mut Child,
    process_tree: HookProcessTree,
) -> bool {
    process_tree.terminate(child);
    // Drop before the wait, not after: on Windows this closes the Job Object
    // and is itself a kill, and on Unix it re-signals the group. Waiting first
    // would delay the very thing meant to make the wait short.
    drop(process_tree);
    match child.wait_timeout(HOOK_REAP_TIMEOUT) {
        Ok(Some(_)) => true,
        Ok(None) => {
            tracing::warn!(
                target: "hooks",
                hook = %sanitize_hook_label(hook_name),
                reap_timeout_secs = HOOK_REAP_TIMEOUT.as_secs(),
                "hook process did not exit after its tree was killed; abandoning the reap"
            );
            false
        }
        Err(error) => {
            tracing::warn!(
                target: "hooks",
                hook = %sanitize_hook_label(hook_name),
                %error,
                "failed to reap killed hook process"
            );
            false
        }
    }
}

fn spawn_pipe_reader(
    mut pipe: impl Read + Send + 'static,
    worker_name: &str,
) -> std::io::Result<Receiver<String>> {
    let (tx, rx) = mpsc::channel();
    std::thread::Builder::new()
        .name(worker_name.to_string())
        .spawn(move || {
            let mut retained = Vec::with_capacity(HOOK_PIPE_CAPTURE_MAX_BYTES.min(8 * 1024));
            let mut chunk = [0_u8; 8 * 1024];
            let mut truncated = false;
            loop {
                match pipe.read(&mut chunk) {
                    Ok(0) => break,
                    Ok(read) => {
                        let remaining = HOOK_PIPE_CAPTURE_MAX_BYTES.saturating_sub(retained.len());
                        let keep = remaining.min(read);
                        retained.extend_from_slice(&chunk[..keep]);
                        truncated |= keep < read;
                    }
                    Err(error) => {
                        tracing::warn!(target: "hooks", %error, "failed while draining hook pipe");
                        break;
                    }
                }
            }
            let mut output = String::from_utf8_lossy(&retained).into_owned();
            if truncated {
                output.push_str("…[truncated]");
            }
            let _ = tx.send(output);
        })
        .map(|_| rx)
}

fn collect_reader(reader: Option<Receiver<String>>, timeout: Duration) -> String {
    let Some(reader) = reader else {
        return String::new();
    };
    match reader.recv_timeout(timeout) {
        Ok(output) => output,
        Err(RecvTimeoutError::Timeout) => {
            tracing::warn!(
                ?timeout,
                "hook pipe reader did not finish after process cleanup"
            );
            String::new()
        }
        Err(RecvTimeoutError::Disconnected) => String::new(),
    }
}

fn spawn_stdin_writer(
    mut stdin: std::process::ChildStdin,
    mut bytes: Vec<u8>,
) -> std::io::Result<JoinHandle<()>> {
    std::thread::Builder::new()
        .name("hook-stdin-writer".to_string())
        .spawn(move || {
            bytes.push(b'\n');
            let _ = stdin.write_all(&bytes);
            let _ = stdin.flush();
        })
}

fn bounded_message_submit_metadata(value: Option<&str>, max_bytes: usize) -> Option<String> {
    value.map(|value| truncate_env_value(value, max_bytes))
}

fn build_message_submit_payload(
    context: &HookContext,
    text: &str,
    original_bytes: usize,
    truncated: bool,
    metadata_max_bytes: Option<usize>,
) -> serde_json::Value {
    let mut payload = json!({
        "event": HookEvent::MessageSubmit.as_str(),
        "text": text,
        "text_bytes": text.len(),
        "text_original_bytes": original_bytes,
        "text_truncated": truncated,
    });
    if let Some(max_bytes) = metadata_max_bytes {
        let object = payload
            .as_object_mut()
            .expect("message_submit payload is an object");
        object.insert(
            "session_id".to_string(),
            json!(bounded_message_submit_metadata(
                context.session_id.as_deref(),
                max_bytes
            )),
        );
        object.insert(
            "workspace".to_string(),
            json!(bounded_message_submit_metadata(
                context.workspace.as_ref().and_then(|path| path.to_str()),
                max_bytes
            )),
        );
        object.insert(
            "mode".to_string(),
            json!(bounded_message_submit_metadata(
                context.mode.as_deref(),
                max_bytes
            )),
        );
        object.insert(
            "model".to_string(),
            json!(bounded_message_submit_metadata(
                context.model.as_deref(),
                max_bytes
            )),
        );
        object.insert("total_tokens".to_string(), json!(context.total_tokens));
    }
    payload
}

fn encoded_message_submit_payload_fits(payload: &serde_json::Value) -> bool {
    serde_json::to_vec(payload)
        .is_ok_and(|bytes| bytes.len() <= HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES)
}

fn finalize_message_submit_payload(
    payload: serde_json::Value,
    original_bytes: usize,
) -> serde_json::Value {
    if encoded_message_submit_payload_fits(&payload) {
        return payload;
    }

    // Serialization of a `Value` is infallible in practice, but the size
    // boundary is security-sensitive. If an invariant above ever regresses,
    // discard all user text and diagnostics rather than handing an oversized
    // document to a hook process.
    tracing::error!(target: "hooks", "message_submit payload fitter exceeded its hard byte cap");
    let fail_closed = build_message_submit_payload(
        &HookContext::new(),
        "",
        original_bytes,
        original_bytes != 0,
        None,
    );
    assert!(
        encoded_message_submit_payload_fits(&fail_closed),
        "minimal message_submit payload must fit the hard byte cap"
    );
    fail_closed
}

/// Build the one canonical `message_submit` stdin document.
///
/// Every producer — immediate input, restored queue entries, merged steers,
/// and hook-to-hook replacements — crosses this serialization boundary. The
/// largest UTF-8-safe text prefix that keeps the *serialized JSON* within the
/// byte ceiling is retained, and explicit metadata tells the hook exactly
/// what was clipped.
pub(crate) fn message_submit_payload(context: &HookContext, text: &str) -> serde_json::Value {
    // Diagnostic metadata is useful but never allowed to crowd the actual
    // gate input out of the hard byte budget. Control-heavy strings can grow
    // sixfold when JSON-escaped, so try progressively smaller snapshots and
    // finally omit diagnostics altogether.
    let metadata_max_bytes = [
        Some(HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES),
        Some(1_024),
        Some(256),
        None,
    ]
    .into_iter()
    .find(|metadata_max_bytes| {
        encoded_message_submit_payload_fits(&build_message_submit_payload(
            context,
            "",
            text.len(),
            !text.is_empty(),
            *metadata_max_bytes,
        ))
    })
    .unwrap_or(None);

    if text.len() <= HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES {
        let complete =
            build_message_submit_payload(context, text, text.len(), false, metadata_max_bytes);
        if encoded_message_submit_payload_fits(&complete) {
            return finalize_message_submit_payload(complete, text.len());
        }
    }

    // No candidate can retain more raw bytes than the full JSON budget. Build
    // at most that many UTF-8 boundaries even if a restored queue entry is
    // unexpectedly enormous.
    let raw_prefix_cap = text.len().min(HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES);
    let mut utf8_ends = Vec::with_capacity(raw_prefix_cap.saturating_add(1));
    utf8_ends.push(0);
    utf8_ends.extend(
        text.char_indices()
            .map(|(index, ch)| index + ch.len_utf8())
            .take_while(|end| *end <= raw_prefix_cap),
    );

    let mut lower = 0usize;
    let mut upper = utf8_ends.len();
    while lower < upper {
        let middle = lower + (upper - lower) / 2;
        let end = utf8_ends[middle];
        let candidate = build_message_submit_payload(
            context,
            &text[..end],
            text.len(),
            true,
            metadata_max_bytes,
        );
        let fits = encoded_message_submit_payload_fits(&candidate);
        if fits {
            lower = middle + 1;
        } else {
            upper = middle;
        }
    }

    let retained_end = utf8_ends[lower.saturating_sub(1)];
    finalize_message_submit_payload(
        build_message_submit_payload(
            context,
            &text[..retained_end],
            text.len(),
            true,
            metadata_max_bytes,
        ),
        text.len(),
    )
}

pub fn turn_end_payload(input: TurnEndPayloadInput<'_>) -> serde_json::Value {
    let bounded_error = input
        .error
        .map(|error| sanitize_hook_text(error, HOOK_TURN_ERROR_MAX_CHARS));
    json!({
        "event": HookEvent::TurnEnd.as_str(),
        "session_id": input.context.session_id.as_deref(),
        "workspace": input.context.workspace.as_ref().map(|path| path.display().to_string()),
        "mode": input.context.mode.as_deref(),
        "created_at": input.created_at.to_rfc3339(),
        "model_backed": input.model_backed,
        "provider": input.provider,
        "billing_surface": input.billing_surface,
        "model": input.model.or(input.context.model.as_deref()),
        "turn_id": input.turn_id,
        "status": input.status,
        "error": bounded_error,
        "duration_ms": duration_ms_saturating(input.duration),
        "usage": {
            "input_tokens": input.usage.input_tokens,
            "output_tokens": input.usage.output_tokens,
            "prompt_cache_hit_tokens": input.usage.prompt_cache_hit_tokens,
            "prompt_cache_miss_tokens": input.usage.prompt_cache_miss_tokens,
            "prompt_cache_write_tokens": input.usage.prompt_cache_write_tokens,
            "reasoning_tokens": input.usage.reasoning_tokens,
            "reasoning_replay_tokens": input.usage.reasoning_replay_tokens,
        },
        "totals": {
            "session_tokens": input.totals.session_tokens,
            "conversation_tokens": input.totals.conversation_tokens,
            "input_tokens": input.totals.input_tokens,
            "output_tokens": input.totals.output_tokens,
        },
        "tool_count": input.tool_count,
        "queued_message_count": input.queued_message_count,
        "stop_hook_active": false,
    })
}

fn duration_ms_saturating(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

fn parse_message_submit_stdout(stdout: &str) -> MessageSubmitStdout {
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return MessageSubmitStdout::Unchanged;
    }

    let value: serde_json::Value = match serde_json::from_str(trimmed) {
        Ok(value) => value,
        Err(e) => return MessageSubmitStdout::Invalid(format!("invalid JSON: {e}")),
    };

    let Some(object) = value.as_object() else {
        return MessageSubmitStdout::Invalid("stdout JSON must be an object".to_string());
    };

    match object.get("text") {
        Some(serde_json::Value::String(text)) if !text.is_empty() => {
            if text.chars().count() > HOOK_MESSAGE_REPLACEMENT_MAX_CHARS {
                MessageSubmitStdout::Invalid(format!(
                    "stdout `text` field exceeds {HOOK_MESSAGE_REPLACEMENT_MAX_CHARS} characters"
                ))
            } else {
                MessageSubmitStdout::Replaced(text.clone())
            }
        }
        Some(serde_json::Value::String(_)) => {
            MessageSubmitStdout::Invalid("stdout `text` field must not be empty".to_string())
        }
        Some(_) => MessageSubmitStdout::Invalid("stdout `text` field must be a string".to_string()),
        None => MessageSubmitStdout::Unchanged,
    }
}

fn message_submit_continue_warning(result: &HookResult) -> Option<String> {
    message_submit_stdout_reason(&result.stdout)
        .or_else(|| {
            Some(generic_unavailable_detail(result.error.as_deref()))
                .filter(|detail| detail != "hook returned no verdict")
        })
        .or_else(|| {
            result
                .observed_exit_code()
                .map(|code| format!("message_submit hook exited with code {code}"))
        })
}

fn message_submit_block_reason(result: &HookResult, fallback: &str) -> String {
    if let Some(reason) = message_submit_stdout_reason(&result.stdout) {
        return reason;
    }
    let detail = generic_unavailable_detail(result.error.as_deref());
    if detail != "hook returned no verdict" {
        return detail;
    }
    fallback.to_string()
}

fn message_submit_stdout_reason(stdout: &str) -> Option<String> {
    let value: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
    value
        .get("reason")
        .and_then(serde_json::Value::as_str)
        .map(sanitize_hook_denial_reason)
}

/// Largest single `shell_env` value that is accepted, in bytes.
const SHELL_ENV_VALUE_MAX_BYTES: usize = 32 * 1024;
/// Largest total `shell_env` contribution from one hook, in bytes of
/// `KEY` + `VALUE`. Past this, later entries from that hook are dropped.
const SHELL_ENV_TOTAL_MAX_BYTES: usize = 256 * 1024;

/// Whether a parsed name is usable as an environment variable name.
///
/// `Command::env` **panics** on a key containing a NUL byte or `=`, and an
/// empty key is meaningless, so an entry that fails this check is dropped
/// rather than carried into `exec_shell`'s environment. A `shell_env` hook is
/// a normal process whose stdout can contain anything — including a NUL
/// straight out of a binary — and "the hook printed something odd" must never
/// become "Codewhale aborted the tool call".
fn is_valid_env_key(key: &str) -> bool {
    !key.is_empty()
        && !key.contains('=')
        && !key.chars().any(|c| c == '\0' || c.is_control() || c == ' ')
}

/// Parse `KEY=VALUE\n` lines from a `shell_env` hook's stdout into a map.
///
/// Tolerated: blank lines, leading whitespace, `#` comment lines (ignored),
/// `export KEY=VALUE` (the `export ` prefix is dropped), surrounding quotes
/// on the value. Lines without `=` are silently dropped — easier than
/// failing the whole hook for one stray line of human-friendly output.
/// Values are otherwise taken verbatim; we don't run them through a shell
/// for variable expansion to avoid surprises.
///
/// Rejected: entries whose key is unusable ([`is_valid_env_key`]), values
/// containing a NUL byte, values over [`SHELL_ENV_VALUE_MAX_BYTES`], and
/// anything past [`SHELL_ENV_TOTAL_MAX_BYTES`] of accumulated output. Each
/// drop is logged by key name only — never by value.
fn parse_env_lines(stdout: &str) -> HashMap<String, String> {
    let mut out: HashMap<String, String> = HashMap::new();
    let mut total_bytes = 0usize;
    for raw in stdout.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line.strip_prefix("export ").unwrap_or(line);
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        if !is_valid_env_key(key) {
            tracing::warn!(
                target: "hooks",
                "shell_env hook produced an unusable variable name; dropping the entry"
            );
            continue;
        }
        let value = value.trim();
        let stripped = value
            .strip_prefix('"')
            .and_then(|v| v.strip_suffix('"'))
            .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
            .unwrap_or(value);
        if stripped.contains('\0') {
            tracing::warn!(
                target: "hooks",
                key,
                "shell_env value contains a NUL byte; dropping the entry"
            );
            continue;
        }
        if stripped.len() > SHELL_ENV_VALUE_MAX_BYTES {
            tracing::warn!(
                target: "hooks",
                key,
                limit = SHELL_ENV_VALUE_MAX_BYTES,
                "shell_env value exceeds the per-value limit; dropping the entry"
            );
            continue;
        }
        let entry_bytes = key.len() + stripped.len();
        if total_bytes.saturating_add(entry_bytes) > SHELL_ENV_TOTAL_MAX_BYTES {
            tracing::warn!(
                target: "hooks",
                key,
                limit = SHELL_ENV_TOTAL_MAX_BYTES,
                "shell_env output exceeds the total limit; dropping the remaining entries"
            );
            break;
        }
        total_bytes += entry_bytes;
        out.insert(key.to_string(), stripped.to_string());
    }
    out
}

// === Unit Tests ===

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{EnvVarGuard, lock_test_env};
    use std::collections::HashMap;
    use std::path::{Path, PathBuf};

    fn trust_workspace_for_project_hooks(workspace: &Path, config_path: &Path) -> EnvVarGuard {
        let guard = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path);
        crate::config::save_workspace_trust(workspace).expect("save workspace trust");
        guard
    }

    #[test]
    fn config_types_are_available_from_config_module() {
        let hook = crate::hooks::config::Hook::new(
            crate::hooks::config::HookEvent::SessionStart,
            "echo ready",
        );
        let config = crate::hooks::config::HooksConfig {
            enabled: true,
            hooks: vec![hook],
            ..Default::default()
        };

        let hooks = config.hooks_for_event(crate::hooks::config::HookEvent::SessionStart);

        assert_eq!(hooks.len(), 1);
    }

    #[test]
    fn executor_type_is_available_from_executor_module() {
        let executor = crate::hooks::executor::HookExecutor::disabled();

        assert!(!executor.is_enabled());
    }

    /// #456 — `parse_env_lines` covers the formats users actually emit from
    /// shell hooks: bare `KEY=VAL`, `export KEY=VAL`, quoted values, comments,
    /// blank lines. Lines without `=` are dropped; values are taken verbatim
    /// (no shell expansion).
    #[test]
    fn parse_env_lines_handles_realistic_hook_output() {
        let stdout = r#"
# Aux comment line, ignored
AWS_ACCESS_KEY_ID=AKIAEXAMPLE
export GITHUB_TOKEN=ghp_examplevalue
QUOTED="value with spaces"
SINGLE='also valid'

= empty key dropped
NOEQUAL line dropped
"#;
        let parsed = super::parse_env_lines(stdout);
        assert_eq!(
            parsed.get("AWS_ACCESS_KEY_ID"),
            Some(&"AKIAEXAMPLE".to_string())
        );
        assert_eq!(
            parsed.get("GITHUB_TOKEN"),
            Some(&"ghp_examplevalue".to_string())
        );
        assert_eq!(parsed.get("QUOTED"), Some(&"value with spaces".to_string()));
        assert_eq!(parsed.get("SINGLE"), Some(&"also valid".to_string()));
        assert!(!parsed.contains_key(""));
        assert!(!parsed.contains_key("NOEQUAL line dropped"));
        // 4 valid entries above; nothing else.
        assert_eq!(parsed.len(), 4);
    }

    /// #456 — empty stdout (or only blank/comments) yields an empty map.
    #[test]
    fn parse_env_lines_empty_when_no_assignments() {
        let parsed = super::parse_env_lines("# nothing\n\n  \n");
        assert!(parsed.is_empty());
    }

    #[test]
    fn parse_message_submit_stdout_replaces_text() {
        assert_eq!(
            super::parse_message_submit_stdout(r#"{"text":"changed"}"#),
            MessageSubmitStdout::Replaced("changed".to_string())
        );
    }

    #[test]
    fn parse_message_submit_stdout_empty_is_unchanged() {
        assert_eq!(
            super::parse_message_submit_stdout(" \n\t "),
            MessageSubmitStdout::Unchanged
        );
    }

    #[test]
    fn parse_message_submit_stdout_without_text_is_unchanged() {
        assert_eq!(
            super::parse_message_submit_stdout(r#"{"reason":"only used for blocks"}"#),
            MessageSubmitStdout::Unchanged
        );
    }

    #[test]
    fn message_submit_payload_is_byte_bounded_after_json_escaping() {
        let original = "用户\"\\\n".repeat(20_000);
        let payload = super::message_submit_payload(
            &HookContext::new()
                .with_session_id("sess_test")
                .with_model("model"),
            &original,
        );
        let encoded = serde_json::to_vec(&payload).expect("serialize bounded payload");

        assert!(
            encoded.len() <= super::HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES,
            "serialized payload was {} bytes",
            encoded.len()
        );
        assert_eq!(payload["text_truncated"], true);
        assert_eq!(payload["text_original_bytes"], original.len());
        let retained = payload["text"].as_str().expect("text string");
        assert_eq!(payload["text_bytes"], retained.len());
        assert!(original.starts_with(retained));
        assert!(std::str::from_utf8(retained.as_bytes()).is_ok());
    }

    #[test]
    fn message_submit_payload_omits_hostile_diagnostics_before_exceeding_cap() {
        let hostile = "\u{0}\u{1}\u{1f}\"\\".repeat(8_000);
        let original = "\u{0}\"\\用户".repeat(20_000);
        let context = HookContext::new()
            .with_session_id(&hostile)
            .with_workspace(PathBuf::from(&hostile))
            .with_mode(&hostile)
            .with_model(&hostile);
        let payload = super::message_submit_payload(&context, &original);
        let encoded = serde_json::to_vec(&payload).expect("serialize hostile payload");

        assert!(
            encoded.len() <= super::HOOK_MESSAGE_SUBMIT_PAYLOAD_MAX_BYTES,
            "serialized payload was {} bytes",
            encoded.len()
        );
        assert_eq!(payload["text_truncated"], true);
        assert_eq!(payload["text_original_bytes"], original.len());
        assert!(original.starts_with(payload["text"].as_str().expect("text")));

        for key in ["session_id", "workspace", "mode", "model"] {
            if let Some(value) = payload.get(key).and_then(serde_json::Value::as_str) {
                assert!(
                    value.len() <= super::HOOK_MESSAGE_SUBMIT_METADATA_MAX_BYTES + 16,
                    "{key} was not bounded before serialization"
                );
            }
        }
    }

    #[test]
    fn short_message_submit_payload_carries_explicit_untruncated_metadata() {
        let payload = super::message_submit_payload(&HookContext::new(), "hello 用户");
        assert_eq!(payload["text"], "hello 用户");
        assert_eq!(payload["text_bytes"], "hello 用户".len());
        assert_eq!(payload["text_original_bytes"], "hello 用户".len());
        assert_eq!(payload["text_truncated"], false);
    }

    #[test]
    fn parse_message_submit_stdout_rejects_malformed_json() {
        assert!(matches!(
            super::parse_message_submit_stdout("not json"),
            MessageSubmitStdout::Invalid(_)
        ));
    }

    #[test]
    fn parse_message_submit_stdout_rejects_non_string_text() {
        assert!(matches!(
            super::parse_message_submit_stdout(r#"{"text":123}"#),
            MessageSubmitStdout::Invalid(_)
        ));
    }

    #[test]
    fn parse_message_submit_stdout_rejects_empty_text() {
        assert_eq!(
            super::parse_message_submit_stdout(r#"{"text":""}"#),
            MessageSubmitStdout::Invalid("stdout `text` field must not be empty".to_string())
        );
    }

    #[test]
    fn parse_message_submit_stdout_rejects_non_object_json() {
        assert!(matches!(
            super::parse_message_submit_stdout(r#"["not", "an", "object"]"#),
            MessageSubmitStdout::Invalid(_)
        ));
        assert!(matches!(
            super::parse_message_submit_stdout(r#""not an object""#),
            MessageSubmitStdout::Invalid(_)
        ));
    }

    #[test]
    fn test_hook_event_as_str() {
        assert_eq!(HookEvent::SessionStart.as_str(), "session_start");
        assert_eq!(HookEvent::ToolCallAfter.as_str(), "tool_call_after");
        assert_eq!(HookEvent::ModeChange.as_str(), "mode_change");
        assert_eq!(HookEvent::TurnEnd.as_str(), "turn_end");
        assert_eq!(HookEvent::SubagentSpawn.as_str(), "subagent_spawn");
        assert_eq!(HookEvent::SubagentComplete.as_str(), "subagent_complete");
    }

    #[test]
    fn turn_end_payload_contains_post_turn_observer_fields() {
        let context = HookContext::new()
            .with_session_id("sess_test")
            .with_workspace(PathBuf::from("/tmp/codewhale"))
            .with_mode("agent")
            .with_model("deepseek-v4")
            .with_tokens(125);
        let usage = crate::models::Usage {
            input_tokens: 40,
            output_tokens: 9,
            prompt_cache_hit_tokens: Some(10),
            prompt_cache_miss_tokens: Some(30),
            prompt_cache_write_tokens: None,
            reasoning_tokens: Some(4),
            reasoning_replay_tokens: Some(2),
            server_tool_use: None,
        };

        let payload = super::turn_end_payload(TurnEndPayloadInput {
            context: &context,
            created_at: "2026-07-12T10:30:00Z".parse().expect("timestamp"),
            model_backed: true,
            provider: Some("deepseek"),
            billing_surface: Some("test-payg"),
            model: Some("deepseek-v4-pro"),
            turn_id: "turn_123",
            status: "completed",
            error: None,
            duration: Duration::from_millis(321),
            usage: &usage,
            totals: TurnEndTotals {
                session_tokens: 125,
                conversation_tokens: 100,
                input_tokens: 100,
                output_tokens: 25,
            },
            tool_count: 2,
            queued_message_count: 1,
        });

        assert_eq!(payload["event"], "turn_end");
        assert_eq!(payload["session_id"], "sess_test");
        assert_eq!(payload["workspace"], "/tmp/codewhale");
        assert_eq!(payload["mode"], "agent");
        assert_eq!(payload["created_at"], "2026-07-12T10:30:00+00:00");
        assert_eq!(payload["model_backed"], true);
        assert_eq!(payload["provider"], "deepseek");
        assert_eq!(payload["billing_surface"], "test-payg");
        assert!(payload.get("base_url").is_none());
        assert_eq!(payload["model"], "deepseek-v4-pro");
        assert_eq!(payload["turn_id"], "turn_123");
        assert_eq!(payload["status"], "completed");
        assert_eq!(payload["error"], serde_json::Value::Null);
        assert_eq!(payload["duration_ms"], 321);
        assert_eq!(payload["usage"]["input_tokens"], 40);
        assert_eq!(payload["usage"]["output_tokens"], 9);
        assert_eq!(payload["usage"]["prompt_cache_hit_tokens"], 10);
        assert_eq!(payload["usage"]["prompt_cache_miss_tokens"], 30);
        assert_eq!(payload["usage"]["reasoning_tokens"], 4);
        assert_eq!(payload["usage"]["reasoning_replay_tokens"], 2);
        assert_eq!(payload["totals"]["session_tokens"], 125);
        assert_eq!(payload["totals"]["conversation_tokens"], 100);
        assert_eq!(payload["totals"]["input_tokens"], 100);
        assert_eq!(payload["totals"]["output_tokens"], 25);
        assert_eq!(payload["tool_count"], 2);
        assert_eq!(payload["queued_message_count"], 1);
        assert_eq!(payload["stop_hook_active"], false);
    }

    #[test]
    fn test_hook_context_to_env_vars() {
        let ctx = HookContext::new()
            .with_tool_name("exec_shell")
            .with_mode("agent")
            .with_workspace(PathBuf::from("/tmp"));

        let env = ctx.to_env_vars();

        assert_eq!(
            env.get("DEEPSEEK_TOOL_NAME"),
            Some(&"exec_shell".to_string())
        );
        assert_eq!(env.get("DEEPSEEK_MODE"), Some(&"agent".to_string()));
        assert_eq!(env.get("DEEPSEEK_WORKSPACE"), Some(&"/tmp".to_string()));
    }

    #[test]
    fn test_hook_condition_always() {
        let hook = Hook::new(HookEvent::SessionStart, "echo test");
        let executor = HookExecutor::disabled();
        let context = HookContext::new();

        assert!(executor.matches_condition(&hook, &context));
    }

    #[test]
    fn test_hook_condition_tool_name() {
        let hook = Hook::new(HookEvent::ToolCallBefore, "echo test").with_condition(
            HookCondition::ToolName {
                name: "exec_shell".to_string(),
            },
        );

        let executor = HookExecutor::disabled();

        let context_match = HookContext::new().with_tool_name("exec_shell");
        let context_no_match = HookContext::new().with_tool_name("write_file");

        assert!(executor.matches_condition(&hook, &context_match));
        assert!(!executor.matches_condition(&hook, &context_no_match));
    }

    #[test]
    fn test_hook_condition_mode() {
        let hook =
            Hook::new(HookEvent::ModeChange, "echo test").with_condition(HookCondition::Mode {
                mode: "agent".to_string(),
            });

        let executor = HookExecutor::disabled();

        let context_match = HookContext::new().with_mode("AGENT"); // Case insensitive
        let context_no_match = HookContext::new().with_mode("normal");

        assert!(executor.matches_condition(&hook, &context_match));
        assert!(!executor.matches_condition(&hook, &context_no_match));
    }

    #[test]
    fn test_hooks_config_for_event() {
        let config = HooksConfig {
            enabled: true,
            hooks: vec![
                Hook::new(HookEvent::SessionStart, "echo start"),
                Hook::new(HookEvent::SessionEnd, "echo end"),
                Hook::new(HookEvent::SessionStart, "echo start2"),
            ],
            ..Default::default()
        };

        let start_hooks = config.hooks_for_event(HookEvent::SessionStart);
        assert_eq!(start_hooks.len(), 2);

        let end_hooks = config.hooks_for_event(HookEvent::SessionEnd);
        assert_eq!(end_hooks.len(), 1);
    }

    #[test]
    fn test_hooks_config_disabled() {
        let config = HooksConfig {
            enabled: false,
            hooks: vec![Hook::new(HookEvent::SessionStart, "echo start")],
            ..Default::default()
        };

        let hooks = config.hooks_for_event(HookEvent::SessionStart);
        assert!(hooks.is_empty());
    }

    #[test]
    fn test_hook_builder() {
        let hook = Hook::new(HookEvent::ToolCallAfter, "notify.sh")
            .with_name("notify_tool")
            .with_timeout(60)
            .background()
            .with_condition(HookCondition::ToolCategory {
                category: "shell".to_string(),
            });

        assert_eq!(hook.name, Some("notify_tool".to_string()));
        assert_eq!(hook.timeout_secs, 60);
        assert!(hook.background);
        assert!(matches!(
            hook.condition,
            Some(HookCondition::ToolCategory { .. })
        ));
    }

    #[test]
    fn test_hook_timeout_enforced() {
        let command = if cfg!(windows) {
            "ping -n 3 127.0.0.1 > nul"
        } else {
            "sleep 2"
        };
        let hook = Hook::new(HookEvent::SessionStart, command).with_timeout(1);
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let env_vars = HashMap::new();

        let result = executor.execute_sync(&hook, &env_vars);
        assert!(!result.success);
        assert!(
            result
                .error
                .as_ref()
                .is_some_and(|e| e.contains("timed out"))
        );
    }

    #[test]
    fn observer_hook_receives_eof_instead_of_inheriting_terminal_stdin() {
        const INNER_ENV: &str = "CODEWHALE_TEST_HOOK_EOF_INNER";
        const TEST_NAME: &str =
            "hooks::tests::observer_hook_receives_eof_instead_of_inheriting_terminal_stdin";

        if std::env::var_os(INNER_ENV).is_some() {
            let dir = tempfile::tempdir().expect("tempdir");
            #[cfg(not(windows))]
            let command = write_hook_script(
                &dir,
                "read_to_eof.sh",
                r#"#!/bin/sh
payload=$(cat)
printf 'stdin-bytes=%s\n' "${#payload}"
"#,
            );
            #[cfg(windows)]
            let command = "powershell -NoProfile -Command \"$value = [Console]::In.ReadToEnd(); [Console]::Out.WriteLine(('stdin-bytes=' + $value.Length))\"".to_string();
            // A cold PowerShell process can take several seconds to start on a
            // contended Windows CI runner. Keep the hook timeout finite so the
            // regression still detects an inherited live stdin pipe, while
            // allowing enough startup time for the EOF assertion itself.
            let hook_timeout_secs = if cfg!(windows) { 10 } else { 2 };
            let hook =
                Hook::new(HookEvent::ToolCallBefore, &command).with_timeout(hook_timeout_secs);
            let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());

            let result = executor.execute_sync(&hook, &HashMap::new());
            assert!(result.success, "stdin-less hook should finish: {result:?}");
            assert_eq!(result.stdout.trim(), "stdin-bytes=0");
            return;
        }

        // Keep this subprocess's stdin pipe deliberately open. Before #4489,
        // the hook inherited that live pipe and blocked instead of receiving
        // EOF. The inner test can only finish when HookExecutor closes the
        // child's stdin write end.
        let mut child = Command::new(std::env::current_exe().expect("current test binary"))
            .args(["--exact", TEST_NAME, "--nocapture", "--test-threads=1"])
            .env(INNER_ENV, "1")
            .stdin(Stdio::piped())
            .spawn()
            .expect("spawn isolated hook EOF test");
        let held_open_stdin = child.stdin.take().expect("piped child stdin");
        // Leave headroom around the inner hook timeout so a cold Windows test
        // process can start, without weakening the held-open-pipe regression.
        let isolated_timeout_secs = if cfg!(windows) { 25 } else { 10 };
        let status = match child
            .wait_timeout(Duration::from_secs(isolated_timeout_secs))
            .expect("wait for isolated hook EOF test")
        {
            Some(status) => status,
            None => {
                let _ = child.kill();
                let _ = child.wait();
                panic!("isolated hook EOF test hung with parent stdin open");
            }
        };
        drop(held_open_stdin);
        assert!(status.success(), "isolated hook EOF test failed: {status}");
    }

    #[cfg(not(windows))]
    #[test]
    fn timed_out_hook_kills_descendant_process_group() {
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("descendant-survived");
        let command = write_hook_script(
            &dir,
            "spawn_descendant.sh",
            &format!(
                "#!/bin/sh\n(sleep 2; printf leaked > '{}') &\nsleep 5\n",
                marker.display()
            ),
        );
        let hook = Hook::new(HookEvent::ToolCallBefore, &command).with_timeout(1);
        let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());

        let result = executor.execute_sync(&hook, &HashMap::new());
        assert!(
            result
                .error
                .as_ref()
                .is_some_and(|error| error.contains("timed out")),
            "hook should time out: {result:?}"
        );
        std::thread::sleep(Duration::from_millis(1_500));
        assert!(
            !marker.exists(),
            "the timed-out hook's descendant escaped its process group"
        );
    }

    #[cfg(windows)]
    #[test]
    fn timed_out_hook_kills_windows_descendant_job() {
        let dir = tempfile::tempdir().expect("tempdir");
        let started = dir.path().join("descendant-started.txt");
        let survived = dir.path().join("descendant-survived.txt");
        let descendant = dir.path().join("descendant.cmd");
        std::fs::write(
            &descendant,
            "@echo off\r\necho started>descendant-started.txt\r\nping -n 5 127.0.0.1 > nul\r\necho survived>descendant-survived.txt\r\n",
        )
        .expect("write descendant script");
        let parent = dir.path().join("parent.cmd");
        std::fs::write(
            &parent,
            "@echo off\r\nstart \"\" /b cmd.exe /d /c descendant.cmd\r\n:wait_for_child\r\nif exist descendant-started.txt goto child_started\r\nping -n 2 127.0.0.1 > nul\r\ngoto wait_for_child\r\n:child_started\r\nping -n 10 127.0.0.1 > nul\r\n",
        )
        .expect("write parent script");
        let hook = Hook::new(HookEvent::ToolCallBefore, "call parent.cmd").with_timeout(3);
        let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());

        let result = executor.execute_sync(&hook, &HashMap::new());
        assert!(
            result
                .error
                .as_ref()
                .is_some_and(|error| error.contains("timed out")),
            "hook should time out: {result:?}"
        );
        assert!(
            started.exists(),
            "descendant never reached its start handshake"
        );
        std::thread::sleep(Duration::from_secs(5));
        assert!(
            !survived.exists(),
            "the timed-out hook's descendant escaped its Job Object"
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_stdin_write_does_not_deadlock_when_hook_writes_first() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = write_hook_script(
            &dir,
            "write_before_read.sh",
            r#"#!/bin/sh
dd if=/dev/zero bs=1024 count=256 2>/dev/null | tr '\000' x
dd if=/dev/zero bs=1024 count=256 2>/dev/null | tr '\000' e >&2
payload=$(cat)
printf '\ndone:%s\n' "${#payload}"
"#,
        );
        let hook = Hook::new(HookEvent::MessageSubmit, &command).with_timeout(5);
        let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());
        let env_vars = HashMap::new();
        let payload = json!({
            "event": "message_submit",
            "text": "x".repeat(256 * 1024),
        });

        let result = executor.execute_sync_with_stdin(&hook, &env_vars, &payload);

        assert!(result.success, "hook should complete: {result:?}");
        assert!(result.stdout.ends_with("…[truncated]"));
        assert!(result.stderr.ends_with("…[truncated]"));
        assert!(result.stdout.len() <= HOOK_PIPE_CAPTURE_MAX_BYTES + 16);
        assert!(result.stderr.len() <= HOOK_PIPE_CAPTURE_MAX_BYTES + 16);
    }

    #[test]
    fn test_executor_session_id() {
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));

        assert!(executor.session_id().starts_with("sess_"));
        assert_eq!(executor.session_id().len(), 13); // "sess_" + 8 chars
    }

    #[cfg(not(windows))]
    fn write_hook_script(dir: &tempfile::TempDir, name: &str, content: &str) -> String {
        let path = dir.path().join(name);
        std::fs::write(&path, content).expect("write hook script");
        format!("sh {}", path.display())
    }

    #[cfg(not(windows))]
    fn submit_context(dir: &tempfile::TempDir) -> HookContext {
        HookContext::new()
            .with_session_id("sess_test")
            .with_workspace(dir.path().to_path_buf())
            .with_mode("agent")
            .with_model("deepseek-test")
            .with_tokens(42)
    }

    #[cfg(not(windows))]
    #[test]
    fn json_observer_hook_receives_structured_stdin() {
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("payload.json");
        let command = write_hook_script(
            &dir,
            "capture_observer.sh",
            &format!(
                r#"#!/bin/sh
cat > "{}"
"#,
                out.display()
            ),
        );
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::SubagentSpawn, &command)],
                ..Default::default()
            },
            dir.path().to_path_buf(),
        );
        let payload = json!({
            "event": "subagent_spawn",
            "agent_id": "agent_123",
            "prompt_preview": "inspect this",
            "prompt_truncated": false,
        });

        let results = executor.execute_json_observer(
            HookEvent::SubagentSpawn,
            &submit_context(&dir),
            &payload,
        );

        assert_eq!(results.len(), 1);
        assert!(results[0].success);
        let captured: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(out).expect("payload written"))
                .expect("valid JSON payload");
        assert_eq!(captured["event"], "subagent_spawn");
        assert_eq!(captured["agent_id"], "agent_123");
        assert_eq!(captured["prompt_preview"], "inspect this");
        assert_eq!(captured["prompt_truncated"], false);
    }

    #[cfg(not(windows))]
    #[test]
    fn turn_end_observer_hook_receives_stdin_json_and_ignores_stdout_contract() {
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("turn_end.json");
        let command = write_hook_script(
            &dir,
            "capture_turn_end.sh",
            &format!(
                r#"#!/bin/sh
cat > "{}"
printf '%s\n' '{{"text":"stdout is not a mutation contract"}}'
"#,
                out.display()
            ),
        );
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::TurnEnd, &command)],
                ..Default::default()
            },
            dir.path().to_path_buf(),
        );
        let usage = crate::models::Usage {
            input_tokens: 12,
            output_tokens: 3,
            prompt_cache_hit_tokens: None,
            prompt_cache_miss_tokens: None,
            prompt_cache_write_tokens: None,
            reasoning_tokens: None,
            reasoning_replay_tokens: None,
            server_tool_use: None,
        };
        let context = submit_context(&dir).with_tokens(15);
        let payload = super::turn_end_payload(TurnEndPayloadInput {
            context: &context,
            created_at: "2026-07-12T10:30:00Z".parse().expect("timestamp"),
            model_backed: true,
            provider: Some("openai"),
            billing_surface: None,
            model: Some("gpt-5.5"),
            turn_id: "turn_observed",
            status: "completed",
            error: None,
            duration: Duration::from_millis(7),
            usage: &usage,
            totals: TurnEndTotals {
                session_tokens: 15,
                conversation_tokens: 15,
                input_tokens: 12,
                output_tokens: 3,
            },
            tool_count: 0,
            queued_message_count: 0,
        });

        let results = executor.execute_json_observer(HookEvent::TurnEnd, &context, &payload);

        assert_eq!(results.len(), 1);
        assert!(results[0].success);
        assert!(
            results[0]
                .stdout
                .contains("stdout is not a mutation contract"),
            "stdout is still captured for diagnostics"
        );
        let captured: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(out).expect("payload written"))
                .expect("valid JSON payload");
        assert_eq!(captured["event"], "turn_end");
        assert_eq!(captured["created_at"], "2026-07-12T10:30:00+00:00");
        assert_eq!(captured["provider"], "openai");
        assert_eq!(captured["model"], "gpt-5.5");
        assert_eq!(captured["turn_id"], "turn_observed");
        assert_eq!(captured["totals"]["input_tokens"], 12);
        assert_eq!(captured["totals"]["output_tokens"], 3);
    }

    #[cfg(not(windows))]
    #[test]
    fn json_observer_hook_failure_does_not_stop_later_hooks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("later-ran");
        let failing = write_hook_script(
            &dir,
            "failing_observer.sh",
            r#"#!/bin/sh
echo boom >&2
exit 1
"#,
        );
        let later = write_hook_script(
            &dir,
            "later_observer.sh",
            &format!(
                r#"#!/bin/sh
cat > "{}"
"#,
                marker.display()
            ),
        );
        let mut first = Hook::new(HookEvent::SubagentComplete, &failing);
        first.continue_on_error = false;
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![first, Hook::new(HookEvent::SubagentComplete, &later)],
                ..Default::default()
            },
            dir.path().to_path_buf(),
        );
        let payload = json!({
            "event": "subagent_complete",
            "agent_id": "agent_456",
            "status": "completed",
        });

        let results = executor.execute_json_observer(
            HookEvent::SubagentComplete,
            &submit_context(&dir),
            &payload,
        );

        assert_eq!(results.len(), 2);
        assert!(!results[0].success);
        assert!(results[1].success);
        assert!(
            marker.exists(),
            "observer failures must be warn-only and non-blocking"
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_transform_applies_hooks_in_order() {
        let dir = tempfile::tempdir().expect("tempdir");
        let first = write_hook_script(
            &dir,
            "first.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"first"}'
"#,
        );
        let second = write_hook_script(
            &dir,
            "second.sh",
            r#"#!/bin/sh
payload=$(cat)
case "$payload" in
  *'"text":"first"'*) printf '%s\n' '{"text":"first second"}' ;;
  *) printf '%s\n' '{"text":"wrong"}' ;;
esac
"#,
        );
        let config = HooksConfig {
            enabled: true,
            hooks: vec![
                Hook::new(HookEvent::MessageSubmit, &first),
                Hook::new(HookEvent::MessageSubmit, &second),
            ],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::replaced("first second".to_string())
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_transform_exit_two_blocks_submission() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = write_hook_script(
            &dir,
            "block.sh",
            r#"#!/bin/sh
printf '%s\n' '{"reason":"policy blocked this prompt"}'
exit 2
"#,
        );
        let config = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::MessageSubmit, &command)],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::Blocked {
                reason: "policy blocked this prompt".to_string()
            }
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn background_message_submit_hook_is_observer_only() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = write_hook_script(
            &dir,
            "background.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"ignored"}'
"#,
        );
        let config = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::MessageSubmit, &command).background()],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::unchanged()
        );
    }

    #[test]
    fn message_submit_transform_without_configured_hooks_is_unchanged() {
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));

        assert_eq!(
            executor.execute_message_submit_transform(&HookContext::new(), "original"),
            MessageSubmitOutcome::unchanged()
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_transform_skips_non_matching_condition() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = write_hook_script(
            &dir,
            "replace.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"should not apply"}'
"#,
        );
        let hook =
            Hook::new(HookEvent::MessageSubmit, &command).with_condition(HookCondition::Mode {
                mode: "plan".into(),
            });
        let config = HooksConfig {
            enabled: true,
            hooks: vec![hook],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::unchanged()
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_continue_on_error_true_keeps_text_and_runs_later_hooks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let failing = write_hook_script(
            &dir,
            "fail_continue.sh",
            r#"#!/bin/sh
printf '%s\n' 'soft failure' >&2
exit 9
"#,
        );
        let replacing = write_hook_script(
            &dir,
            "replace_after_failure.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"recovered"}'
"#,
        );
        let config = HooksConfig {
            enabled: true,
            hooks: vec![
                Hook::new(HookEvent::MessageSubmit, &failing),
                Hook::new(HookEvent::MessageSubmit, &replacing),
            ],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::replaced("recovered".to_string())
                .with_warning(Some("message_submit hook exited with code 9".to_string()))
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_timeout_continue_surfaces_warning_and_runs_later_hooks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let slow = write_hook_script(
            &dir,
            "slow_continue.sh",
            r#"#!/bin/sh
sleep 2
"#,
        );
        let replacing = write_hook_script(
            &dir,
            "replace_after_timeout.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"after timeout"}'
"#,
        );
        let mut slow_hook = Hook::new(HookEvent::MessageSubmit, &slow).with_timeout(1);
        slow_hook.continue_on_error = true;
        let config = HooksConfig {
            enabled: true,
            hooks: vec![slow_hook, Hook::new(HookEvent::MessageSubmit, &replacing)],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::replaced("after timeout".to_string())
                .with_warning(Some("hook timed out after 1s".to_string()))
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_invalid_stdout_keeps_text_and_runs_later_hooks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let invalid = write_hook_script(
            &dir,
            "invalid_stdout.sh",
            r#"#!/bin/sh
printf '%s\n' 'not json'
"#,
        );
        let replacing = write_hook_script(
            &dir,
            "replace_after_invalid.sh",
            r#"#!/bin/sh
printf '%s\n' '{"text":"valid later"}'
"#,
        );
        let config = HooksConfig {
            enabled: true,
            hooks: vec![
                Hook::new(HookEvent::MessageSubmit, &invalid),
                Hook::new(HookEvent::MessageSubmit, &replacing),
            ],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::replaced("valid later".to_string())
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn message_submit_continue_on_error_false_blocks_on_failure() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = write_hook_script(
            &dir,
            "fail.sh",
            r#"#!/bin/sh
printf '%s\n' 'hard failure' >&2
exit 7
"#,
        );
        let mut hook = Hook::new(HookEvent::MessageSubmit, &command);
        hook.continue_on_error = false;
        let config = HooksConfig {
            enabled: true,
            hooks: vec![hook],
            working_dir: Some(dir.path().to_path_buf()),
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, dir.path().to_path_buf());

        assert_eq!(
            executor.execute_message_submit_transform(&submit_context(&dir), "original"),
            MessageSubmitOutcome::Blocked {
                reason: "message_submit hook failed and blocked submission".to_string()
            }
        );
    }

    #[test]
    fn has_hooks_for_event_fast_path_returns_false_for_empty_config() {
        let executor = HookExecutor::disabled();
        // No hooks configured AT ALL — every event is a fast skip.
        for event in [
            HookEvent::SessionStart,
            HookEvent::SessionEnd,
            HookEvent::MessageSubmit,
            HookEvent::ToolCallBefore,
            HookEvent::ToolCallAfter,
            HookEvent::ModeChange,
            HookEvent::OnError,
            HookEvent::TurnEnd,
            HookEvent::SubagentSpawn,
            HookEvent::SubagentComplete,
        ] {
            assert!(
                !executor.has_hooks_for_event(event),
                "empty config must short-circuit for {event:?}"
            );
        }
    }

    #[test]
    fn has_hooks_for_event_returns_false_when_globally_disabled() {
        let config = HooksConfig {
            enabled: false,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo blocked")],
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, PathBuf::from("."));
        assert!(
            !executor.has_hooks_for_event(HookEvent::ToolCallBefore),
            "globally-disabled hooks must report no fires even when one is configured"
        );
    }

    #[test]
    fn has_hooks_for_event_distinguishes_event_types() {
        let config = HooksConfig {
            enabled: true,
            hooks: vec![
                Hook::new(HookEvent::SessionStart, "echo start"),
                Hook::new(HookEvent::ToolCallBefore, "echo before"),
            ],
            ..HooksConfig::default()
        };
        let executor = HookExecutor::new(config, PathBuf::from("."));
        // Configured events return true.
        assert!(executor.has_hooks_for_event(HookEvent::SessionStart));
        assert!(executor.has_hooks_for_event(HookEvent::ToolCallBefore));
        // Unconfigured events return false even when other events are present.
        assert!(!executor.has_hooks_for_event(HookEvent::ToolCallAfter));
        assert!(!executor.has_hooks_for_event(HookEvent::OnError));
        assert!(!executor.has_hooks_for_event(HookEvent::ModeChange));
    }

    // ── #3026: tool_call_before stdout decision contract ──────────────────

    #[test]
    fn tool_call_before_stdout_parses_deny_with_reason() {
        let parsed =
            parse_tool_call_before_stdout(r#"{"decision":"deny","reason":"blocked by policy"}"#);
        assert_eq!(parsed.decision, Some(ToolCallDecision::Deny));
        assert_eq!(parsed.reason.as_deref(), Some("blocked by policy"));
        assert!(parsed.updated_input.is_none());
        assert!(parsed.additional_context.is_none());
    }

    #[test]
    fn tool_call_before_stdout_parses_ask_and_allow() {
        let ask = parse_tool_call_before_stdout(r#"{"decision":"ask"}"#);
        assert_eq!(ask.decision, Some(ToolCallDecision::Ask));

        let allow = parse_tool_call_before_stdout(r#"{"decision":"allow"}"#);
        assert_eq!(allow.decision, Some(ToolCallDecision::Allow));
    }

    #[test]
    fn tool_call_before_stdout_parses_updated_input_object() {
        let parsed =
            parse_tool_call_before_stdout(r#"{"updatedInput":{"command":"ls -la","timeout":5}}"#);
        assert!(parsed.decision.is_none());
        assert_eq!(
            parsed.updated_input,
            Some(serde_json::json!({"command":"ls -la","timeout":5}))
        );
    }

    #[test]
    fn tool_call_before_stdout_rejects_non_object_updated_input() {
        let parsed = parse_tool_call_before_stdout(r#"{"updatedInput":"rm -rf /"}"#);
        assert!(
            parsed.updated_input.is_none(),
            "updatedInput must be a JSON object"
        );
        let parsed = parse_tool_call_before_stdout(r#"{"updatedInput":[1,2]}"#);
        assert!(parsed.updated_input.is_none());
    }

    #[test]
    fn tool_call_before_stdout_parses_additional_context() {
        let parsed =
            parse_tool_call_before_stdout(r#"{"additionalContext":"remember the style guide"}"#);
        assert_eq!(
            parsed.additional_context.as_deref(),
            Some("remember the style guide")
        );
    }

    #[test]
    fn tool_call_before_stdout_empty_and_non_json_are_passthrough() {
        for stdout in ["", "   \n  ", "ok, proceeding", "exit code zero"] {
            let parsed = parse_tool_call_before_stdout(stdout);
            assert!(parsed.decision.is_none(), "stdout {stdout:?}");
            assert!(parsed.reason.is_none());
            assert!(parsed.updated_input.is_none());
            assert!(parsed.additional_context.is_none());
        }
    }

    #[test]
    fn tool_call_before_stdout_json_without_decision_is_passthrough() {
        let parsed = parse_tool_call_before_stdout(r#"{"status":"fine"}"#);
        assert!(parsed.decision.is_none());
    }

    #[test]
    fn tool_call_before_stdout_non_object_json_is_passthrough() {
        for stdout in [r#""deny""#, "[1,2,3]", "42", "true"] {
            let parsed = parse_tool_call_before_stdout(stdout);
            assert!(parsed.decision.is_none(), "stdout {stdout:?}");
        }
    }

    #[test]
    fn tool_call_before_stdout_unknown_decision_treated_as_allow() {
        let parsed = parse_tool_call_before_stdout(r#"{"decision":"block"}"#);
        assert!(parsed.decision.is_none());
    }

    // ── #3026: glob matchers for tool_name conditions ──────────────────────

    #[test]
    fn tool_name_glob_matches_mcp_prefix() {
        assert!(HookExecutor::tool_name_matches_condition(
            "mcp__github__create_issue",
            "mcp__*"
        ));
        assert!(!HookExecutor::tool_name_matches_condition(
            "read_file",
            "mcp__*"
        ));
    }

    #[test]
    fn tool_name_exact_match_still_works() {
        assert!(HookExecutor::tool_name_matches_condition(
            "read_file",
            "read_file"
        ));
        assert!(!HookExecutor::tool_name_matches_condition(
            "read_files",
            "read_file"
        ));
    }

    #[test]
    fn tool_name_glob_escapes_regex_metacharacters() {
        // Without escaping, `.` would match any character.
        assert!(!HookExecutor::tool_name_matches_condition(
            "mcpXgithub",
            "mcp.git*"
        ));
        assert!(HookExecutor::tool_name_matches_condition(
            "mcp.github",
            "mcp.git*"
        ));
        // `+` and parens must be literal too.
        assert!(HookExecutor::tool_name_matches_condition(
            "weird+tool(name)",
            "weird+tool(*)"
        ));
    }

    #[test]
    fn tool_name_glob_supports_infix_and_suffix_positions() {
        assert!(HookExecutor::tool_name_matches_condition(
            "mcp__github__create_issue",
            "mcp__*__create_issue"
        ));
        assert!(HookExecutor::tool_name_matches_condition(
            "task_shell_start",
            "*_shell_start"
        ));
        assert!(!HookExecutor::tool_name_matches_condition(
            "task_shell_wait",
            "*_shell_start"
        ));
    }

    // ── #3026: project-local hooks ─────────────────────────────────────────

    #[test]
    fn load_with_project_missing_file_keeps_global() {
        let dir = tempfile::tempdir().expect("tempdir");
        let global = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
            ..HooksConfig::default()
        };

        let merged = HooksConfig::load_with_project(global.clone(), dir.path());
        assert_eq!(merged.hooks.len(), 1);
        assert_eq!(merged.hooks[0].command, "echo global");
    }

    #[test]
    fn load_with_project_appends_project_hooks_after_global() {
        let _lock = lock_test_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let config_path = dir.path().join("user-config.toml");
        let _config = trust_workspace_for_project_hooks(dir.path(), &config_path);
        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
        let project_dir = dir.path().join(".codewhale");
        std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
        std::fs::write(
            project_dir.join("hooks.toml"),
            r#"
[[hooks]]
event = "tool_call_before"
command = "echo project"
"#,
        )
        .expect("write hooks.toml");

        let global = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
            ..HooksConfig::default()
        };

        let merged = HooksConfig::load_with_project(global, dir.path());
        assert_eq!(merged.hooks.len(), 2);
        assert_eq!(
            merged.hooks[0].command, "echo global",
            "global hooks run first"
        );
        assert_eq!(
            merged.hooks[1].command, "echo project",
            "project hooks are appended after global"
        );
    }

    #[test]
    fn load_with_project_ignores_project_hooks_until_workspace_trusted() {
        let _lock = lock_test_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
        let project_dir = dir.path().join(".codewhale");
        std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
        std::fs::write(
            project_dir.join("hooks.toml"),
            r#"
[[hooks]]
event = "tool_call_before"
command = "echo project"
"#,
        )
        .expect("write hooks.toml");

        let global = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
            ..HooksConfig::default()
        };

        let merged = HooksConfig::load_with_project(global, dir.path());
        assert_eq!(merged.hooks.len(), 1);
        assert_eq!(merged.hooks[0].command, "echo global");
    }

    #[test]
    fn load_with_project_ignores_project_local_legacy_trust_marker() {
        let _lock = lock_test_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", dir.path().join("config.toml"));
        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
        let project_dir = dir.path().join(".codewhale");
        let legacy_trust_dir = dir.path().join(".deepseek");
        std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
        std::fs::create_dir_all(&legacy_trust_dir).expect("mkdir .deepseek");
        std::fs::write(legacy_trust_dir.join("trusted"), "").expect("write legacy trust marker");
        std::fs::write(
            project_dir.join("hooks.toml"),
            r#"
[[hooks]]
event = "tool_call_before"
command = "echo project"
"#,
        )
        .expect("write hooks.toml");

        let global = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
            ..HooksConfig::default()
        };

        let merged = HooksConfig::load_with_project(global, dir.path());
        assert_eq!(merged.hooks.len(), 1);
        assert_eq!(merged.hooks[0].command, "echo global");
    }

    #[test]
    fn load_with_project_malformed_file_falls_back_to_global() {
        let _lock = lock_test_env();
        let dir = tempfile::tempdir().expect("tempdir");
        let config_path = dir.path().join("user-config.toml");
        let _config = trust_workspace_for_project_hooks(dir.path(), &config_path);
        let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
        let project_dir = dir.path().join(".codewhale");
        std::fs::create_dir_all(&project_dir).expect("mkdir .codewhale");
        std::fs::write(project_dir.join("hooks.toml"), "this is [ not toml")
            .expect("write hooks.toml");

        let global = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::ToolCallBefore, "echo global")],
            ..HooksConfig::default()
        };

        let merged = HooksConfig::load_with_project(global, dir.path());
        assert_eq!(merged.hooks.len(), 1, "malformed project file is ignored");
        assert_eq!(merged.hooks[0].command, "echo global");
    }

    // === v0.9.2 hooks contract regression tests ===============================
    //
    // Each of these pins a claim that `docs/HOOKS.md` makes, so the docs cannot
    // drift ahead of the runtime again. All of them are provider-free: they
    // spawn `sh`, never a model.

    #[test]
    fn background_result_is_a_submission_not_an_observed_exit_code() {
        // `background` is the flag that keeps "queued" from reading as
        // "exited 0". Steering paths gate on `observed_exit_code`.
        let submitted = HookResult {
            background: true,
            success: true,
            exit_code: None,
            ..HookResult::default()
        };
        assert!(submitted.background);
        assert_eq!(submitted.observed_exit_code(), None);

        // A foreground deny still reads through.
        let denied = HookResult {
            background: false,
            success: false,
            exit_code: Some(2),
            ..HookResult::default()
        };
        assert_eq!(denied.observed_exit_code(), Some(2));

        // A foreground timeout has no exit code either, but it is *not* a
        // background submission — callers must be able to tell them apart.
        let timed_out = HookResult {
            background: false,
            success: false,
            exit_code: None,
            error: Some("Hook timed out after 1s".to_string()),
            ..HookResult::default()
        };
        assert!(!timed_out.background);
        assert_eq!(timed_out.observed_exit_code(), None);
    }

    #[test]
    fn default_timeout_secs_replaces_per_hook_timeout() {
        // Documented as-implemented: the global value overrides, it does not
        // merely fill in for hooks that omit one.
        let hook = Hook::new(HookEvent::SessionStart, "true").with_timeout(90);
        let overridden = HookExecutor::new(
            HooksConfig {
                default_timeout_secs: Some(5),
                ..HooksConfig::default()
            },
            PathBuf::from("."),
        );
        assert_eq!(overridden.effective_timeout_secs(&hook), 5);

        let per_hook = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        assert_eq!(per_hook.effective_timeout_secs(&hook), 90);
    }

    #[test]
    fn foreground_timeout_result_is_bounded_and_carries_no_payload() {
        // The timeout result must not leak the stdin payload, the environment,
        // or partial output back to the caller.
        let command = if cfg!(windows) {
            "ping -n 4 127.0.0.1 > nul"
        } else {
            "echo secret-stdout; sleep 5"
        };
        let hook = Hook::new(HookEvent::MessageSubmit, command).with_timeout(1);
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let payload = serde_json::json!({ "text": "super secret user text" });

        let result = executor.execute_sync_with_stdin(&hook, &HashMap::new(), &payload);

        assert!(!result.success);
        assert!(!result.background);
        assert_eq!(result.exit_code, None);
        assert!(result.stdout.is_empty(), "stdout leaked: {}", result.stdout);
        assert!(result.stderr.is_empty(), "stderr leaked: {}", result.stderr);
        let error = result.error.unwrap_or_default();
        assert!(error.contains("timed out"), "{error}");
        assert!(!error.contains("super secret"), "{error}");
    }

    #[cfg(unix)]
    #[test]
    fn background_hook_timeout_kills_and_reaps_its_process_tree() {
        // The claim under test: "There is no path on which a timed-out hook
        // keeps running." A background hook used to be waited on with an
        // unbounded `child.wait()`, so a runaway command outlived the session.
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("survived.txt");
        // The inner `sh -c ... &` is a grandchild: killing only the immediate
        // shell would leave it alive, so this also covers process-group kill.
        let command = format!(
            "sh -c 'sleep 4; echo survived > {}' & wait",
            marker.display()
        );
        let hook = Hook::new(HookEvent::SessionStart, &command).with_timeout(1);
        let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());

        let result = executor.execute_background(&hook, &HashMap::new());
        assert!(result.background, "background submission must be flagged");
        assert_eq!(result.observed_exit_code(), None);

        // Well past the hook's 1s budget, and past the 4s the command wanted.
        std::thread::sleep(Duration::from_secs(6));
        assert!(
            !marker.exists(),
            "background hook outlived its timeout and kept running"
        );
    }

    #[cfg(unix)]
    #[test]
    fn background_hook_receives_the_same_stdin_payload_as_foreground() {
        // Background changes scheduling, not the payload contract.
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("bg-stdin.json");
        let command = write_hook_script(
            &dir,
            "capture_bg_stdin.sh",
            &format!("#!/bin/sh\ncat > {}\n", out.display()),
        );
        let hook = Hook::new(HookEvent::MessageSubmit, &command)
            .with_name("bg")
            .background();
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![hook],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let context = submit_context(&dir);
        let outcome = executor.execute_message_submit_transform(&context, "hello world");
        // Background hooks cannot steer.
        assert_eq!(outcome, MessageSubmitOutcome::unchanged());

        // Give the submitted child time to land.
        for _ in 0..50 {
            if out.exists() {
                break;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        let raw = std::fs::read_to_string(&out).expect("background hook wrote no stdin payload");
        let payload: serde_json::Value = serde_json::from_str(raw.trim()).expect("valid JSON");
        assert_eq!(payload["event"], "message_submit");
        assert_eq!(payload["text"], "hello world");
        assert_eq!(payload["session_id"], "sess_test");
        assert_eq!(payload["mode"], "agent");
        assert_eq!(payload["model"], "deepseek-test");
        assert_eq!(payload["total_tokens"], 42);
    }

    #[cfg(unix)]
    #[test]
    fn background_hook_receives_the_documented_environment() {
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("bg-env.txt");
        let command = write_hook_script(
            &dir,
            "capture_bg_env.sh",
            &format!(
                "#!/bin/sh\nprintf '%s|%s|%s\\n' \"$DEEPSEEK_SESSION_ID\" \"$DEEPSEEK_MODE\" \
                 \"$DEEPSEEK_TOOL_NAME\" > {}\n",
                out.display()
            ),
        );
        let hook = Hook::new(HookEvent::ToolCallAfter, &command)
            .with_name("bg-env")
            .background();
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![hook],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let context = submit_context(&dir).with_tool_name("exec_shell");
        let results = executor.execute(HookEvent::ToolCallAfter, &context);
        assert_eq!(results.len(), 1);
        assert!(results[0].background);

        for _ in 0..50 {
            if out.exists() {
                break;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        let captured = std::fs::read_to_string(&out).expect("background hook wrote no env");
        assert_eq!(captured.trim(), "sess_test|agent|exec_shell");
    }

    #[test]
    fn session_id_is_stable_across_every_event_and_survives_a_rebind() {
        // One TUI session, one `DEEPSEEK_SESSION_ID`. This is what makes hook
        // records correlatable, so it is asserted over every event name.
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let session_id = executor.session_id().to_string();
        assert!(
            session_id.starts_with("sess_"),
            "unexpected session id shape: {session_id}"
        );

        for event in crate::hooks::ALL_HOOK_EVENTS {
            let context = HookContext::new()
                .with_session_id(executor.session_id())
                .with_tool_name(event.as_str());
            let env = context.to_env_vars();
            assert_eq!(
                env.get("DEEPSEEK_SESSION_ID"),
                Some(&session_id),
                "event `{}` reported a different session id",
                event.as_str()
            );
        }

        // A workspace switch or trust decision reloads the hook set. It must
        // not mint a new identity.
        let rebound = executor.rebind(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::SessionStart, "true")],
                ..HooksConfig::default()
            },
            PathBuf::from("/tmp"),
        );
        assert_eq!(rebound.session_id(), session_id);
        assert_eq!(rebound.config().hooks.len(), 1);

        // A genuinely new executor is a genuinely new session.
        let fresh = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        assert_ne!(fresh.session_id(), session_id);
    }

    #[test]
    fn exit_code_condition_matches_only_a_real_exit_code() {
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let hook = Hook::new(HookEvent::ToolCallAfter, "true")
            .with_condition(HookCondition::ExitCode { code: 1 });

        // No exit code reported at all: must not match. Notably it must not be
        // satisfied by the failure flag either.
        let no_code = HookContext::new()
            .with_tool_name("read_file")
            .with_tool_result("boom", false, None);
        assert!(!executor.matches_condition(&hook, &no_code));

        // A different exit code: no match.
        let other_code = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_result("boom", false, Some(127));
        assert!(!executor.matches_condition(&hook, &other_code));

        // The real thing.
        let exact = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_result("boom", false, Some(1));
        assert!(executor.matches_condition(&hook, &exact));

        // Exit code 0 on a successful call is a real code and matches a
        // `code = 0` predicate.
        let zero_hook = Hook::new(HookEvent::ToolCallAfter, "true")
            .with_condition(HookCondition::ExitCode { code: 0 });
        let zero = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_result("ok", true, Some(0));
        assert!(executor.matches_condition(&zero_hook, &zero));
        assert!(!executor.matches_condition(&zero_hook, &no_code));
    }

    #[test]
    fn tool_call_id_is_exported_for_correlation() {
        let env = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_call_id("call_abc123")
            .to_env_vars();
        assert_eq!(
            env.get("DEEPSEEK_TOOL_CALL_ID"),
            Some(&"call_abc123".to_string())
        );

        // Absent when unknown — never synthesized.
        let without = HookContext::new()
            .with_tool_name("exec_shell")
            .to_env_vars();
        assert!(!without.contains_key("DEEPSEEK_TOOL_CALL_ID"));
    }

    #[test]
    fn tool_exit_code_env_var_is_absent_when_the_tool_reported_none() {
        let with_code = HookContext::new()
            .with_tool_result("out", false, Some(3))
            .to_env_vars();
        assert_eq!(
            with_code.get("DEEPSEEK_TOOL_EXIT_CODE"),
            Some(&"3".to_string())
        );
        assert_eq!(
            with_code.get("DEEPSEEK_TOOL_SUCCESS"),
            Some(&"false".to_string())
        );

        let without_code = HookContext::new()
            .with_tool_result("out", false, None)
            .to_env_vars();
        assert!(!without_code.contains_key("DEEPSEEK_TOOL_EXIT_CODE"));
        assert_eq!(
            without_code.get("DEEPSEEK_TOOL_SUCCESS"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn payload_env_vars_are_bounded() {
        // Errors used to be the one unbounded field; a failed `exec_shell`
        // could push its whole output into `DEEPSEEK_ERROR`.
        let long = "x".repeat(20_000);
        let env = HookContext::new()
            .with_error(&long)
            .with_message(&long)
            .with_tool_result(&long, false, None)
            .to_env_vars();

        for key in ["DEEPSEEK_ERROR", "DEEPSEEK_MESSAGE", "DEEPSEEK_TOOL_RESULT"] {
            let value = env.get(key).unwrap_or_else(|| panic!("{key} missing"));
            assert!(value.len() < 20_000, "{key} was not truncated");
            assert!(value.ends_with("...[truncated]"), "{key} lost its marker");
        }
    }

    #[test]
    fn truncate_env_value_respects_utf8_boundaries() {
        // 4-byte characters straddling the cap must not panic or split.
        let value = "🐋".repeat(100);
        let truncated = super::truncate_env_value(&value, 10);
        assert!(truncated.ends_with("...[truncated]"));
        let head = truncated.trim_end_matches("...[truncated]");
        assert!(head.chars().all(|c| c == '🐋'));
        assert!(head.len() <= 12);
    }

    #[cfg(unix)]
    #[test]
    fn collect_shell_env_merges_later_hooks_over_earlier_ones() {
        // The documented merge: parsed verbatim, later hooks win, failures
        // contribute nothing and do not abort.
        let dir = tempfile::tempdir().expect("tempdir");
        let first = write_hook_script(
            &dir,
            "env_first.sh",
            "#!/bin/sh\necho SHARED=first\necho ONLY_FIRST=1\n",
        );
        let second = write_hook_script(
            &dir,
            "env_second.sh",
            "#!/bin/sh\necho SHARED=second\necho QUOTED=\"has spaces\"\n",
        );
        let failing = write_hook_script(&dir, "env_fail.sh", "#!/bin/sh\necho NEVER=1\nexit 1\n");

        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![
                    Hook::new(HookEvent::ShellEnv, &first).with_name("first"),
                    Hook::new(HookEvent::ShellEnv, &second).with_name("second"),
                    Hook::new(HookEvent::ShellEnv, &failing).with_name("failing"),
                ],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let context = HookContext::new().with_tool_name("exec_shell");
        let merged = executor.collect_shell_env(&context);

        assert_eq!(merged.get("SHARED"), Some(&"second".to_string()));
        assert_eq!(merged.get("ONLY_FIRST"), Some(&"1".to_string()));
        assert_eq!(merged.get("QUOTED"), Some(&"has spaces".to_string()));
        assert!(
            !merged.contains_key("NEVER"),
            "a failing shell_env hook must contribute nothing"
        );
    }

    #[cfg(unix)]
    #[test]
    fn shell_env_ignores_the_background_flag_and_still_collects_stdout() {
        // `background` is not honored here: the stdout IS the contract, so the
        // hook runs in the foreground regardless of how it is configured.
        let dir = tempfile::tempdir().expect("tempdir");
        let script = write_hook_script(&dir, "env_bg.sh", "#!/bin/sh\necho FROM_BG=yes\n");
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![
                    Hook::new(HookEvent::ShellEnv, &script)
                        .with_name("bg-shell-env")
                        .background(),
                ],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let merged = executor.collect_shell_env(&HookContext::new().with_tool_name("exec_shell"));
        assert_eq!(merged.get("FROM_BG"), Some(&"yes".to_string()));
    }

    #[cfg(unix)]
    #[test]
    fn shell_env_hook_receives_only_the_narrow_documented_context() {
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("shell-env-context.txt");
        let script = write_hook_script(
            &dir,
            "env_context.sh",
            &format!(
                "#!/bin/sh\nprintf 'name=%s args=%s session=%s mode=%s\\n' \
                 \"$DEEPSEEK_TOOL_NAME\" \"$DEEPSEEK_TOOL_ARGS\" \"$DEEPSEEK_SESSION_ID\" \
                 \"$DEEPSEEK_MODE\" > {}\n",
                out.display()
            ),
        );
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::ShellEnv, &script)],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let context = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_args(&serde_json::json!({ "command": "ls" }));
        let _ = executor.collect_shell_env(&context);

        let captured = std::fs::read_to_string(&out).expect("shell_env hook wrote nothing");
        assert!(captured.contains("name=exec_shell"), "{captured}");
        assert!(captured.contains(r#""command":"ls""#), "{captured}");
        // No session id or mode is supplied for this event, which is why a
        // `mode` condition on `shell_env` is rejected at load.
        assert!(captured.contains("session= "), "{captured}");
        assert!(captured.trim_end().ends_with("mode="), "{captured}");
    }

    /// Strictness has to travel on the result, because only the results tell
    /// you which hooks actually *matched* this call.
    #[cfg(unix)]
    #[test]
    fn results_carry_the_strictness_of_the_hook_that_produced_them() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut strict = Hook::new(HookEvent::ToolCallBefore, "true")
            .with_name("strict")
            .with_condition(HookCondition::ToolName {
                name: "write_file".to_string(),
            });
        strict.continue_on_error = false;
        let lenient = Hook::new(HookEvent::ToolCallBefore, "true")
            .with_name("lenient")
            .with_condition(HookCondition::ToolName {
                name: "exec_shell".to_string(),
            });

        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![strict, lenient],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        // Only the lenient hook matches an `exec_shell` call, so nothing about
        // this call is strict — even though a strict hook exists in config.
        let shell = executor.execute(
            HookEvent::ToolCallBefore,
            &HookContext::new().with_tool_name("exec_shell"),
        );
        assert_eq!(shell.len(), 1);
        assert_eq!(shell[0].name.as_deref(), Some("lenient"));
        assert!(!shell[0].strict);

        // The `write_file` call is the one the strict gate guards.
        let write = executor.execute(
            HookEvent::ToolCallBefore,
            &HookContext::new().with_tool_name("write_file"),
        );
        assert_eq!(write.len(), 1);
        assert_eq!(write[0].name.as_deref(), Some("strict"));
        assert!(write[0].strict);
    }

    #[cfg(unix)]
    #[test]
    fn background_results_are_never_strict() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
            .with_name("bg-strict")
            .background();
        hook.continue_on_error = false;
        let executor = HookExecutor::new(HooksConfig::default(), dir.path().to_path_buf());

        let result = executor.execute_background(&hook, &HashMap::new());
        assert!(result.background);
        assert!(
            !result.strict,
            "nothing is awaited, so there is no answer to withhold"
        );
    }

    /// A background hook that never reads stdin used to hang the supervising
    /// thread forever: the payload was written synchronously *before*
    /// `wait_timeout`, so a payload larger than the pipe buffer blocked, and
    /// the timeout / kill / reap below it were never reached.
    #[cfg(unix)]
    #[test]
    fn oversized_background_stdin_still_times_out_and_kills_the_tree() {
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("survived.txt");
        // Never reads stdin, and spawns a grandchild so this also covers the
        // process-group kill that the blocked write used to prevent.
        let command = write_hook_script(
            &dir,
            "ignores_stdin.sh",
            &format!(
                "#!/bin/sh\nsh -c 'sleep 6; echo survived > {}' &\nsleep 6\n",
                marker.display()
            ),
        );
        let hook = Hook::new(HookEvent::TurnEnd, &command)
            .with_name("deaf")
            .background()
            .with_timeout(1);
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![hook.clone()],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        // Far beyond any pipe buffer (64 KiB on Linux, 8–64 KiB on macOS).
        let payload = json!({ "event": "turn_end", "blob": "x".repeat(4 * 1024 * 1024) });

        let submitted = Instant::now();
        let result = executor.execute_background_with_stdin(&hook, &HashMap::new(), &payload);
        assert!(
            submitted.elapsed() < Duration::from_secs(2),
            "submission blocked on the stdin write: {:?}",
            submitted.elapsed()
        );
        assert!(result.background);
        assert!(result.success, "submission failed: {result:?}");

        // Past the hook's 1s budget and past the 6s the command wanted.
        std::thread::sleep(Duration::from_secs(8));
        assert!(
            !marker.exists(),
            "background hook with an unread oversized stdin outlived its timeout"
        );
    }

    #[test]
    fn spawn_failure_messages_carry_no_command_or_path() {
        let error = std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "'C:\\Users\\dev\\secret hooks\\gate.cmd' is not recognized",
        );
        let message = super::spawn_failure_message(&error);
        assert!(message.contains("NotFound"), "{message}");
        assert!(!message.contains("gate.cmd"), "{message}");
        assert!(!message.contains("C:\\"), "{message}");
        assert!(!message.contains("secret"), "{message}");
    }

    #[test]
    fn parse_env_lines_drops_nul_bearing_entries() {
        // `Command::env` panics on a NUL in a key or value, so a hook that
        // prints binary garbage must contribute nothing rather than take the
        // tool call down with it.
        let parsed = super::parse_env_lines("GOOD=fine\nBAD=tok\0en\nBA\0D2=x\nALSO_GOOD=2\n");
        assert_eq!(parsed.get("GOOD"), Some(&"fine".to_string()));
        assert_eq!(parsed.get("ALSO_GOOD"), Some(&"2".to_string()));
        assert!(!parsed.contains_key("BAD"), "{parsed:?}");
        assert_eq!(parsed.len(), 2, "{parsed:?}");
        for (key, value) in &parsed {
            assert!(!key.contains('\0'));
            assert!(!value.contains('\0'));
            // The invariants `Command::env` asserts on.
            assert!(!key.is_empty() && !key.contains('='));
        }
    }

    #[test]
    fn parse_env_lines_bounds_values_and_the_aggregate() {
        let huge = "x".repeat(super::SHELL_ENV_VALUE_MAX_BYTES + 1);
        let parsed = super::parse_env_lines(&format!("OK=1\nHUGE={huge}\n"));
        assert_eq!(parsed.get("OK"), Some(&"1".to_string()));
        assert!(!parsed.contains_key("HUGE"), "over-long value was kept");

        // Many individually-legal values still cannot add up to an unbounded
        // environment.
        let chunk = "y".repeat(16 * 1024);
        let mut stdout = String::new();
        for i in 0..64 {
            stdout.push_str(&format!("K{i}={chunk}\n"));
        }
        let bulk = super::parse_env_lines(&stdout);
        let total: usize = bulk.iter().map(|(k, v)| k.len() + v.len()).sum();
        assert!(total <= super::SHELL_ENV_TOTAL_MAX_BYTES, "{total} bytes");
        assert!(!bulk.is_empty(), "the bound must not drop everything");
    }

    #[cfg(unix)]
    #[test]
    fn shell_env_hook_printing_nul_contributes_nothing_and_does_not_panic() {
        let dir = tempfile::tempdir().expect("tempdir");
        let script = write_hook_script(
            &dir,
            "env_nul.sh",
            "#!/bin/sh\nprintf 'TOKEN=abc\\000def\\n'\nprintf 'SAFE=ok\\n'\n",
        );
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::ShellEnv, &script).with_name("nul")],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );

        let merged = executor.collect_shell_env(&HookContext::new().with_tool_name("exec_shell"));
        assert!(!merged.contains_key("TOKEN"), "{merged:?}");
        assert_eq!(merged.get("SAFE"), Some(&"ok".to_string()));
        // What `Command::env` would be handed must be panic-free.
        for (key, value) in &merged {
            assert!(!key.is_empty());
            assert!(!key.contains('=') && !key.contains('\0'));
            assert!(!value.contains('\0'));
        }
    }

    #[test]
    fn tool_call_before_text_fields_are_sanitized_and_bounded() {
        let long = "z".repeat(super::HOOK_TEXT_FIELD_MAX_CHARS * 3);
        let stdout = serde_json::json!({
            "decision": "deny",
            "reason": format!("blocked\u{1b}[31m {long}"),
            "additionalContext": format!("ctx\u{0}\r\nline {long}"),
        })
        .to_string();

        let parsed = super::parse_tool_call_before_stdout(&stdout);

        let reason = parsed.reason.expect("reason kept");
        assert!(reason.chars().count() <= super::HOOK_TEXT_FIELD_MAX_CHARS + 16);
        assert!(reason.ends_with("…[truncated]"), "{reason}");
        assert!(!reason.contains('\u{1b}'), "escape sequence survived");

        let context = parsed.additional_context.expect("context kept");
        assert!(context.chars().count() <= super::HOOK_TEXT_FIELD_MAX_CHARS + 16);
        assert!(!context.contains('\u{0}'));
        assert!(!context.contains('\r'));
        // Legitimate multi-line context still survives.
        assert!(
            context.contains('\n'),
            "{}",
            &context[..40.min(context.len())]
        );
    }

    #[test]
    fn hook_context_bounds_tool_args_environment_value() {
        let env = HookContext::new()
            .with_tool_args(&serde_json::json!({
                "command": "x".repeat(super::HOOK_TOOL_ARGS_ENV_MAX_BYTES * 3)
            }))
            .to_env_vars();
        let args = env.get("DEEPSEEK_TOOL_ARGS").expect("tool args env");
        assert!(
            args.len() <= super::HOOK_TOOL_ARGS_ENV_MAX_BYTES + "...[truncated]".len(),
            "{} bytes",
            args.len()
        );
        assert!(args.ends_with("...[truncated]"));
    }

    #[test]
    fn steering_objects_and_replacement_messages_have_independent_caps() {
        let oversized_input = serde_json::json!({
            "updatedInput": { "command": "x".repeat(super::HOOK_UPDATED_INPUT_MAX_BYTES * 2) }
        })
        .to_string();
        assert!(
            parse_tool_call_before_stdout(&oversized_input)
                .updated_input
                .is_none()
        );

        let oversized_message = serde_json::json!({
            "text": "x".repeat(super::HOOK_MESSAGE_REPLACEMENT_MAX_CHARS + 1)
        })
        .to_string();
        assert!(matches!(
            super::parse_message_submit_stdout(&oversized_message),
            super::MessageSubmitStdout::Invalid(reason)
                if reason.contains("exceeds")
        ));
    }

    #[test]
    fn turn_end_error_is_sanitized_and_bounded() {
        let context = HookContext::new();
        let usage = crate::models::Usage::default();
        let error = format!(
            "boom\u{1b}[2J{}",
            "x".repeat(super::HOOK_TURN_ERROR_MAX_CHARS * 2)
        );
        let payload = super::turn_end_payload(TurnEndPayloadInput {
            context: &context,
            created_at: chrono::Utc::now(),
            model_backed: true,
            provider: Some("test"),
            billing_surface: None,
            model: Some("test-model"),
            turn_id: "turn_test",
            status: "failed",
            error: Some(&error),
            duration: Duration::from_millis(1),
            usage: &usage,
            totals: TurnEndTotals {
                session_tokens: 0,
                conversation_tokens: 0,
                input_tokens: 0,
                output_tokens: 0,
            },
            tool_count: 0,
            queued_message_count: 0,
        });
        let rendered = payload["error"].as_str().expect("bounded error");
        assert!(!rendered.contains('\u{1b}'));
        assert!(rendered.ends_with("…[truncated]"));
        assert!(
            rendered.chars().count() <= super::HOOK_TURN_ERROR_MAX_CHARS + 16,
            "{} chars",
            rendered.chars().count()
        );
    }

    #[test]
    fn denial_reason_redacts_paths_arguments_and_secret_assignments() {
        let rendered = super::sanitize_hook_denial_reason(
            "denied /Users/alice/private --command token=SUPERSECRET safe",
        );
        assert_eq!(rendered, "denied [path] [argument] [secret] safe");
        assert!(!rendered.contains("alice"));
        assert!(!rendered.contains("SUPERSECRET"));
        assert!(!rendered.contains("--command"));

        let command = super::sanitize_hook_denial_reason("blocked command rm bearer abc123");
        assert_eq!(command, "blocked [command] [command] [secret] [secret]");
        assert!(!command.contains("rm"));
        assert!(!command.contains("abc123"));
    }

    #[test]
    fn denial_reason_redacts_adversarial_header_path_and_command_forms() {
        for reason in [
            r#"Denied Authorization: Bearer TOPSECRET path="/Users/alice/private key" command='rm -rf /tmp/private' safe"#,
            r#"Denied authorization:"Bearer TOPSECRET" path=../private command="curl --header secret" safe"#,
            r#"Denied (Authorization: Bearer TOPSECRET), path = C:\private command = "powershell -enc SECRET" safe"#,
        ] {
            let rendered = super::sanitize_hook_denial_reason(reason);
            for secret in [
                "TOPSECRET",
                "alice",
                "private key",
                "../private",
                "C:\\private",
                "curl",
                "powershell",
                "SECRET",
            ] {
                assert!(!rendered.contains(secret), "leaked {secret}: {rendered}");
            }
            assert!(rendered.contains("[secret]"), "{rendered}");
            assert!(rendered.contains("[path]"), "{rendered}");
            assert!(rendered.contains("[command]"), "{rendered}");
        }
    }

    #[test]
    fn denial_reason_redacts_auth_schemes_normalized_secrets_and_relative_paths() {
        for reason in [
            "Denied Authorization: Basic dXNlcjpwYXNz src/private/config.toml",
            "Denied Authorization=Digest deadbeef service.API-KEY=topsecret",
            "Denied authorization Negotiate kerberos AWS_SESSION_TOKEN=abc123",
            "Denied authorization NTLM credential internal_secret=hunter2",
            "Denied authorization Proprietary-Scheme opaque-credential src/private/key.txt",
        ] {
            let rendered = super::sanitize_hook_denial_reason(reason);
            for sensitive in [
                "dXNlcjpwYXNz",
                "deadbeef",
                "kerberos",
                "credential",
                "topsecret",
                "abc123",
                "hunter2",
                "src/private/config.toml",
                "opaque-credential",
                "src/private/key.txt",
            ] {
                assert!(
                    !rendered.contains(sensitive),
                    "leaked {sensitive}: {rendered}"
                );
            }
            assert!(rendered.contains("[secret]"), "{rendered}");
        }
    }

    #[test]
    fn observer_dispatch_failures_are_event_specific_and_fixed() {
        let config = HooksConfig {
            enabled: true,
            hooks: vec![Hook::new(HookEvent::TurnEnd, "true")],
            ..HooksConfig::default()
        };
        let mut full = HookExecutor::new(config.clone(), PathBuf::from("."));
        full.inject_observer_dispatch_full_for_test();
        let error = full
            .submit_observer(HookEvent::TurnEnd, HookContext::new())
            .expect_err("full queue must be visible");
        assert_eq!(
            error,
            "turn_end observer hook queue is full; event was not submitted"
        );

        let mut disconnected = HookExecutor::new(config, PathBuf::from("."));
        disconnected.inject_observer_dispatch_disconnect_for_test();
        let error = disconnected
            .submit_observer(HookEvent::TurnEnd, HookContext::new())
            .expect_err("disconnected dispatcher must be visible");
        assert_eq!(
            error,
            "turn_end observer hook dispatcher is unavailable; event was not submitted"
        );
    }

    #[test]
    fn observer_context_is_bounded_before_enqueue() {
        let huge = "用户".repeat(20_000);
        let bounded = HookContext {
            tool_args: Some(huge.clone()),
            tool_result: Some(huge.clone()),
            error_message: Some(huge.clone()),
            message: Some(huge.clone()),
            model: Some(huge),
            ..HookContext::new()
        }
        .bounded_for_observer();

        assert!(bounded.tool_args.expect("args").len() <= super::HOOK_TOOL_ARGS_ENV_MAX_BYTES + 16);
        assert!(
            bounded.tool_result.expect("result").len()
                <= super::HOOK_TOOL_RESULT_CONTEXT_MAX_BYTES + 16
        );
        assert!(
            bounded.error_message.expect("error").len() <= super::HOOK_ERROR_CONTEXT_MAX_BYTES + 16
        );
        assert!(
            bounded.message.expect("message").len() <= super::HOOK_MESSAGE_CONTEXT_MAX_BYTES + 16
        );
        assert!(
            bounded.model.expect("model").len() <= super::HOOK_OBSERVER_METADATA_MAX_BYTES + 16
        );
    }

    #[test]
    fn background_supervisor_saturation_is_a_failed_submission() {
        let hook = Hook::new(HookEvent::TurnEnd, "true").background();
        let mut executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![hook],
                ..HooksConfig::default()
            },
            PathBuf::from("."),
        );
        executor.inject_background_supervisor_full_for_test();

        let results = executor.execute(HookEvent::TurnEnd, &HookContext::new());
        assert_eq!(results.len(), 1);
        assert!(results[0].background);
        assert!(!results[0].success);
        assert_eq!(
            results[0].error.as_deref(),
            Some("background hook supervisor queue is full")
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn bounded_observer_dispatcher_executes_a_submitted_event() {
        let dir = tempfile::tempdir().expect("tempdir");
        let receipt = dir.path().join("observer-receipt.json");
        let command = write_hook_script(
            &dir,
            "persistent_observer.sh",
            &format!("#!/bin/sh\ncat > '{}'\n", receipt.display()),
        );
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::TurnEnd, &command)],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );
        executor
            .submit_json_observer(
                HookEvent::TurnEnd,
                HookContext::new(),
                serde_json::json!({"event": "turn_end", "turn_id": "turn_test"}),
            )
            .expect("bounded submission");

        let deadline = Instant::now() + Duration::from_secs(2);
        let payload = loop {
            if let Ok(raw) = std::fs::read_to_string(&receipt)
                && let Ok(payload) = serde_json::from_str::<serde_json::Value>(&raw)
            {
                break payload;
            }
            assert!(
                Instant::now() < deadline,
                "persistent worker did not finish a valid receipt"
            );
            std::thread::sleep(Duration::from_millis(10));
        };
        assert_eq!(payload["turn_id"], "turn_test");
    }

    #[cfg(unix)]
    #[test]
    fn explicit_message_denial_never_copies_raw_process_diagnostics() {
        let dir = tempfile::tempdir().expect("tempdir");
        let command = r#"printf '%s\n' '{"reason":"blocked /Users/alice/private --run token=SUPERSECRET"}'; printf '%s\n' 'stderr-secret /tmp/private' >&2; exit 2"#;
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![Hook::new(HookEvent::MessageSubmit, command)],
                ..HooksConfig::default()
            },
            dir.path().to_path_buf(),
        );
        let outcome = executor.execute_message_submit_transform(&HookContext::new(), "hello");
        let MessageSubmitOutcome::Blocked { reason } = outcome else {
            panic!("expected explicit block");
        };
        assert_eq!(reason, "blocked [path] [argument] [secret]");
        for secret in ["alice", "SUPERSECRET", "stderr-secret", "/tmp/private"] {
            assert!(!reason.contains(secret), "leaked {secret}: {reason}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn foreground_pipe_capture_is_bounded_while_verbose_child_is_drained() {
        let hook = Hook::new(
            HookEvent::SessionStart,
            "head -c 200000 /dev/zero | tr '\\0' o; head -c 200000 /dev/zero | tr '\\0' e >&2",
        )
        .with_timeout(5);
        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let result = executor.execute_sync(&hook, &HashMap::new());
        assert!(result.success, "{:?}", result.error);
        for output in [&result.stdout, &result.stderr] {
            assert!(output.ends_with("…[truncated]"));
            assert!(
                output.len() <= super::HOOK_PIPE_CAPTURE_MAX_BYTES + "…[truncated]".len(),
                "{} bytes",
                output.len()
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn helper_wait_and_uncontained_reap_paths_are_bounded() {
        let mut helper = Command::new("sh")
            .args(["-c", "sleep 30"])
            .spawn()
            .expect("spawn helper");
        let started = Instant::now();
        let error = super::wait_for_helper_status(&mut helper, Duration::from_millis(20))
            .expect_err("slow helper must time out");
        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        assert!(started.elapsed() < super::HOOK_REAP_TIMEOUT + Duration::from_secs(1));
        assert!(matches!(helper.try_wait(), Ok(Some(_))));

        let mut uncontained = Command::new("sh")
            .args(["-c", "sleep 30"])
            .spawn()
            .expect("spawn uncontained child");
        assert!(super::kill_and_reap_immediate_child(
            &mut uncontained,
            Duration::from_secs(1)
        ));
        assert!(matches!(uncontained.try_wait(), Ok(Some(_))));
    }

    #[test]
    fn sanitize_hook_text_keeps_short_text_verbatim() {
        assert_eq!(
            super::sanitize_hook_text("plain reason", 100),
            "plain reason"
        );
        assert_eq!(super::sanitize_hook_text("a\tb\nc", 100), "a\tb\nc");
        assert_eq!(super::sanitize_hook_text("", 100), "");
    }

    #[test]
    fn sanitize_hook_line_flattens_structure_characters() {
        assert_eq!(super::sanitize_hook_line("a\tb\nc", 100), "a b c");
        assert_eq!(super::sanitize_hook_line("a\u{1b}[2Jb\r", 100), "a [2Jb");
    }

    #[test]
    fn sanitize_hook_label_bounds_and_defangs_operator_names() {
        let noisy = format!("\u{1b}[2Jgate\twith\nnoise{}", "x".repeat(1_000));
        let label = super::sanitize_hook_label(Some(&noisy));
        assert!(!label.contains('\u{1b}'), "{label}");
        assert!(!label.contains('\n') && !label.contains('\t'), "{label}");
        assert!(label.contains("gate"), "{label}");
        assert!(
            label.chars().count() <= super::HOOK_LABEL_MAX_CHARS + 16,
            "{} chars",
            label.chars().count()
        );

        assert_eq!(super::sanitize_hook_label(None), "(unnamed)");
        assert_eq!(super::sanitize_hook_label(Some("")), "(unnamed)");
        assert_eq!(super::sanitize_hook_label(Some(" \t ")), "(unnamed)");
        assert_eq!(super::sanitize_hook_label(Some(" gate ")), "gate");
    }

    /// The point of the boundary: recognized failures are re-rendered from
    /// parts, and anything else — including a string a future producer forgot
    /// to genericize — collapses instead of passing through.
    #[test]
    fn generic_unavailable_detail_is_an_allowlist_not_a_passthrough() {
        use super::generic_unavailable_detail as detail;

        assert_eq!(
            detail(Some("Hook timed out after 30s")),
            "hook timed out after 30s"
        );
        assert_eq!(
            detail(Some("hook process could not be started (NotFound)")),
            "hook process could not be started (NotFound)"
        );
        assert_eq!(
            detail(Some("Failed to wait for hook: os error 10")),
            "hook did not complete cleanly"
        );
        assert_eq!(
            detail(Some("hook could not be reaped after its timeout")),
            "hook did not complete cleanly"
        );
        assert_eq!(
            detail(Some("Failed to submit background hook: os error 11")),
            "hook could not be submitted"
        );
        assert_eq!(
            detail(Some("hook executor did not run")),
            "hook executor did not run"
        );
        assert_eq!(detail(None), "hook returned no verdict");

        // A hypothetical future producer that leaks.
        let leaky = "spawn failed: /Users/someone/.aws/credentials --token=SECRET";
        let rendered = detail(Some(leaky));
        assert_eq!(rendered, "hook returned no verdict");
        assert!(!rendered.contains("SECRET"));
        assert!(!rendered.contains('/'));

        // And a recognized prefix cannot be used to smuggle a tail along.
        let smuggled = detail(Some(
            "Hook timed out after 30s while running /usr/bin/leak --token=SECRET",
        ));
        assert_eq!(smuggled, "hook timed out after 30s");
        let smuggled = detail(Some(
            "hook process could not be started (NotFound) /usr/bin/leak",
        ));
        assert_eq!(smuggled, "hook process could not be started (NotFound)");
    }

    /// The gate set the caller has to fail closed on if the executor is lost.
    #[cfg(unix)]
    #[test]
    fn matched_strict_gate_labels_names_only_gates_that_would_run() {
        use crate::hooks::{Hook, HookCondition, HookEvent, HooksConfig};

        let strict_shell = {
            let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
                .with_name("shell-gate")
                .with_condition(HookCondition::ToolName {
                    name: "exec_shell".into(),
                });
            hook.continue_on_error = false;
            hook
        };
        let strict_write = {
            let mut hook = Hook::new(HookEvent::ToolCallBefore, "true")
                .with_name("write-gate")
                .with_condition(HookCondition::ToolName {
                    name: "write_file".into(),
                });
            hook.continue_on_error = false;
            hook
        };
        let lenient_shell = Hook::new(HookEvent::ToolCallBefore, "true").with_name("lenient");
        let background_strict = {
            let mut hook = Hook::new(HookEvent::ToolCallBefore, "true").with_name("bg-gate");
            hook.continue_on_error = false;
            hook.background = true;
            hook
        };
        let other_event = {
            let mut hook = Hook::new(HookEvent::ToolCallAfter, "true").with_name("after-gate");
            hook.continue_on_error = false;
            hook
        };

        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![
                    strict_shell,
                    strict_write,
                    lenient_shell,
                    background_strict,
                    other_event,
                ],
                ..HooksConfig::default()
            },
            std::env::temp_dir(),
        );

        let labels = executor.matched_strict_gate_labels(
            HookEvent::ToolCallBefore,
            &HookContext::new().with_tool_name("exec_shell"),
        );
        assert_eq!(labels, vec!["shell-gate".to_string()], "{labels:?}");

        // Globally disabled hooks are not gates either.
        let disabled = HookExecutor::disabled();
        assert!(
            disabled
                .matched_strict_gate_labels(
                    HookEvent::ToolCallBefore,
                    &HookContext::new().with_tool_name("exec_shell"),
                )
                .is_empty()
        );
    }

    /// The reap after a kill is bounded. This asserts the ordinary case is
    /// still confirmed dead and, more importantly, that the call returns —
    /// the regression it guards is a hang, not a wrong value.
    #[cfg(unix)]
    #[test]
    fn timed_out_hook_is_killed_and_reaped_within_the_bound() {
        use crate::hooks::{Hook, HookEvent, HooksConfig};

        let hook = Hook::new(HookEvent::SessionStart, "sleep 30")
            .with_name("slow")
            .with_timeout(1);
        let executor = HookExecutor::new(
            HooksConfig {
                enabled: true,
                hooks: vec![hook],
                ..HooksConfig::default()
            },
            std::env::temp_dir(),
        );

        let started = Instant::now();
        let results = executor.execute(HookEvent::SessionStart, &HookContext::new());
        let elapsed = started.elapsed();

        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].error.as_deref(),
            Some("Hook timed out after 1s"),
            "the child was reaped, so the stronger claim is the honest one"
        );
        assert!(
            elapsed < Duration::from_secs(1) + super::HOOK_REAP_TIMEOUT + Duration::from_secs(5),
            "timeout path took {elapsed:?}"
        );
    }

    #[test]
    fn tool_exit_code_env_var_survives_a_windows_crash_code() {
        // 0xC0000005 (access violation) does not fit in an `i32`. It used to
        // be dropped on the floor before the hook ever saw it.
        let env = HookContext::new()
            .with_tool_result("crashed", false, Some(3_221_225_477))
            .to_env_vars();
        assert_eq!(
            env.get("DEEPSEEK_TOOL_EXIT_CODE"),
            Some(&"3221225477".to_string())
        );

        let executor = HookExecutor::new(HooksConfig::default(), PathBuf::from("."));
        let hook =
            Hook::new(HookEvent::ToolCallAfter, "true").with_condition(HookCondition::ExitCode {
                code: 3_221_225_477,
            });
        let context = HookContext::new()
            .with_tool_name("exec_shell")
            .with_tool_result("crashed", false, Some(3_221_225_477));
        assert!(executor.matches_condition(&hook, &context));
    }

    /// 2026-08-04: the category map knew only retired tool names, so every
    /// live call fell through to `other` and a `tool_category` deny hook —
    /// the security control `docs/HOOKS.md` documents — silently never fired.
    #[test]
    fn tool_category_classifies_the_names_the_registry_actually_registers() {
        use super::tool_category_for;

        // Anchor to the real catalog. Everything below this pins hardcoded
        // names, which would stay green through a tool rename while the gate
        // quietly reclassified the renamed tool. `DEFAULT_ACTIVE_NATIVE_TOOLS`
        // is the list the engine actually puts on the wire, so if a name here
        // stops being a name the product ships, this fails first.
        //
        // Note the fallback is "other", not "safe" — asserting against "safe"
        // here would never fire. This table is checked in both directions, so
        // a rename fails on the missing entry and a classifier change fails on
        // the mismatched category.
        const EXPECTED: &[(&str, &str)] = &[
            ("read", "safe"),
            ("write", "file_write"),
            ("edit", "file_write"),
            ("bash", "shell"),
            // The router itself touches nothing a hook needs to gate.
            ("agent", "other"),
            ("todo_write", "safe"),
        ];
        for name in crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS {
            let expected = EXPECTED.iter().find(|(n, _)| n == name).map(|(_, c)| *c);
            assert_eq!(
                Some(tool_category_for(name, None)),
                expected,
                "default-active tool {name:?} is not covered by this test's \
                 table. It was renamed or added without updating the hook \
                 gate's classifier, so the gate now sees a shipped tool it \
                 does not recognise."
            );
        }
        for (name, _) in EXPECTED {
            assert!(
                crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS.contains(name),
                "{name:?} is pinned here but is no longer default-active; drop \
                 it so this table keeps describing what actually ships."
            );
        }

        // The shell surface.
        assert_eq!(tool_category_for("Bash", None), "shell");
        // Retained: shell.rs stamps this for the shell_env event.
        assert_eq!(tool_category_for("exec_shell", None), "shell");
        // Run executes commands, so it gates with shell rather than safe.
        assert_eq!(tool_category_for("Run", None), "shell");

        // File is multi-action: the action decides.
        let read = r#"{"action":"read","path":"a.rs"}"#;
        let write = r#"{"action":"write","path":"a.rs","content":"x"}"#;
        assert_eq!(tool_category_for("File", Some(read)), "safe");
        assert_eq!(tool_category_for("File", Some(write)), "file_write");
        assert_eq!(
            tool_category_for("File", Some(r#"{"action":"edit"}"#)),
            "file_write"
        );
        assert_eq!(
            tool_category_for("File", Some(r#"{"action":"search_content"}"#)),
            "safe"
        );

        // A gate that cannot see the action must assume the dangerous one.
        assert_eq!(tool_category_for("File", None), "file_write");
        assert_eq!(tool_category_for("File", Some("not json")), "file_write");

        assert_eq!(tool_category_for("apply_patch", None), "file_write");
        assert_eq!(
            tool_category_for("Git", Some(r#"{"action":"log"}"#)),
            "safe"
        );
        assert_eq!(tool_category_for("web.run", None), "other");
    }
}