symforge 11.18.3

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! Hook binary logic — reads the OS-tagged `.symforge/sidecar.<os>.port`, calls the
//! sidecar over sync HTTP, and outputs a single JSON line to stdout.
//!
//! Design constraints (HOOK-10):
//! - The ONLY thing written to stdout is the final JSON line.
//! - No tokio runtime. No tracing to stdout. No eprintln except for genuine errors.
//! - Sync I/O throughout — hooks must complete in well under 100 ms.
//! - Fail-open: if the sidecar is unreachable for any reason, output empty additionalContext
//!   JSON so Claude Code continues normally.

use std::io::{BufRead, Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::cli::HookSubcommand;
use crate::domain::ControlStateDir;

// hook-adoption.log is written AND read only inside this hook binary (single OS per
// process), so it stays un-tagged. The sidecar port/session files are cross-process
// (written by the sidecar/proxy, read here) and MUST be OS-tagged in lockstep with the
// writer — both sides derive the tag from `crate::paths::os_tagged_runtime_file_name`,
// so a given OS's hook and sidecar always agree. See `sidecar_port_file_rel` below.
const ADOPTION_LOG_FILE: &str = "hook-adoption.log";

fn process_control_state_dir() -> Option<ControlStateDir> {
    crate::paths::process_control_state_placement()
        .directory()
        .cloned()
}

fn sidecar_descriptor_path(control_state_dir: &ControlStateDir) -> PathBuf {
    crate::paths::control_state_path(control_state_dir, "sidecar/sessions")
}
/// Hard HTTP timeout — leaves margin within HOOK-03's 100 ms total budget.
const HTTP_TIMEOUT: Duration = Duration::from_millis(50);

/// Total deadline for the entire daemon fallback sequence
/// (port-file read + two HTTP round-trips + JSON parsing).
///
/// **Degraded-mode policy**: this intentionally exceeds HOOK-03's 100 ms
/// normal-path latency target.  The daemon fallback activates only when
/// the sidecar is unreachable and requires two sequential HTTP round-trips
/// that cannot reliably fit in 100 ms.  Accepting up to 500 ms of added
/// latency in this rare degraded scenario is preferable to returning
/// empty context when the daemon holds useful data.
///
/// Individual requests get whatever time remains within this budget.
const DAEMON_FALLBACK_DEADLINE: Duration = Duration::from_millis(500);

// ---------------------------------------------------------------------------
// Stdin JSON parsing structs
// ---------------------------------------------------------------------------

/// Deserialized representation of a Claude Code PostToolUse stdin payload.
///
/// The type is `pub` so integration tests can construct an empty payload via
/// `HookInput::default()` for [`run_hook_with_input`]; the fields stay
/// crate-private.
#[derive(serde::Deserialize, Default)]
pub struct HookInput {
    pub(crate) tool_name: Option<String>,
    pub(crate) tool_input: Option<HookToolInput>,
    pub(crate) cwd: Option<String>,
    pub(crate) prompt: Option<String>,
}

/// The `tool_input` field from the Claude Code hook event payload.
#[derive(serde::Deserialize, Default)]
pub(crate) struct HookToolInput {
    /// Absolute path to the file being read/edited/written.
    pub(crate) file_path: Option<String>,
    /// Search pattern for Grep events.
    pub(crate) pattern: Option<String>,
    /// Directory path for Grep events (alternative field name).
    pub(crate) path: Option<String>,
}

/// Workflow buckets used to reason about what SymForge should eventually own
/// at hook-decision time.
///
/// PR 1 only introduces the vocabulary and non-behavioral scaffolding so later
/// routing work can target stable concepts instead of raw client tool names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HookWorkflow {
    /// Repo-local source inspection such as reading a code file for orientation.
    SourceRead,
    /// Repo-local source search such as Grep over code intent.
    SourceSearch,
    /// First-contact project orientation at session start.
    RepoStart,
    /// Prompt-time narrowing when a user mentions files, symbols, or paths.
    PromptContext,
    /// Post-edit/write impact analysis on a touched file.
    PostEditImpact,
    /// Direct source-code mutation intent.
    CodeEdit,
    /// Everything intentionally left to fail-open or shell-native handling.
    PassThrough,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HookOutcome {
    Routed,
    NoSidecar,
    SidecarError,
    DaemonFallback,
}

impl HookOutcome {
    pub(crate) fn label(self) -> &'static str {
        match self {
            HookOutcome::Routed => "routed",
            HookOutcome::NoSidecar => "no-sidecar",
            HookOutcome::SidecarError => "sidecar-error",
            HookOutcome::DaemonFallback => "daemon-fallback",
        }
    }

    fn parse(raw: &str) -> Option<Self> {
        match raw {
            "routed" => Some(HookOutcome::Routed),
            "no-sidecar" => Some(HookOutcome::NoSidecar),
            "sidecar-error" => Some(HookOutcome::SidecarError),
            "daemon-fallback" => Some(HookOutcome::DaemonFallback),
            _ => None,
        }
    }
}

#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub(crate) struct WorkflowAdoptionCounts {
    pub routed: usize,
    pub no_sidecar: usize,
    pub sidecar_error: usize,
    pub daemon_fallback: usize,
}

impl WorkflowAdoptionCounts {
    fn record(&mut self, outcome: HookOutcome) {
        match outcome {
            HookOutcome::Routed => self.routed += 1,
            HookOutcome::NoSidecar => self.no_sidecar += 1,
            HookOutcome::SidecarError => self.sidecar_error += 1,
            HookOutcome::DaemonFallback => self.daemon_fallback += 1,
        }
    }

    pub(crate) fn total(&self) -> usize {
        self.routed + self.no_sidecar + self.sidecar_error + self.daemon_fallback
    }

    pub(crate) fn fail_open(&self) -> usize {
        self.no_sidecar + self.sidecar_error
    }
}

#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub(crate) struct HookAdoptionSnapshot {
    pub source_read: WorkflowAdoptionCounts,
    pub source_search: WorkflowAdoptionCounts,
    pub repo_start: WorkflowAdoptionCounts,
    pub prompt_context: WorkflowAdoptionCounts,
    pub post_edit_impact: WorkflowAdoptionCounts,
    pub first_repo_start: Option<HookOutcome>,
    /// Fail-open rows per recorded `reason=`; rows without one count as
    /// `unrecorded`.
    pub fail_open_reasons: std::collections::BTreeMap<String, usize>,
    /// The loader could not resolve which sidecar lifetime is current, so it
    /// counted nothing.
    pub session_unknown: bool,
    /// The session and lifetime the rows were filtered on, when resolved.
    pub scope: Option<String>,
    /// Rows anywhere in the log (both generations, every session and project
    /// sharing the control dir) recorded with no provable sidecar lifetime.
    /// Never attributed to the scoped lifetime; reported with that scope.
    pub unscoped_rows: usize,
}

impl HookAdoptionSnapshot {
    fn counts_mut(&mut self, workflow: HookWorkflow) -> Option<&mut WorkflowAdoptionCounts> {
        match workflow {
            HookWorkflow::SourceRead => Some(&mut self.source_read),
            HookWorkflow::SourceSearch => Some(&mut self.source_search),
            HookWorkflow::RepoStart => Some(&mut self.repo_start),
            HookWorkflow::PromptContext => Some(&mut self.prompt_context),
            HookWorkflow::PostEditImpact => Some(&mut self.post_edit_impact),
            HookWorkflow::CodeEdit | HookWorkflow::PassThrough => None,
        }
    }

    pub(crate) fn total_attempts(&self) -> usize {
        self.source_read.total()
            + self.source_search.total()
            + self.repo_start.total()
            + self.prompt_context.total()
            + self.post_edit_impact.total()
    }

    pub(crate) fn total_routed(&self) -> usize {
        self.source_read.routed
            + self.source_read.daemon_fallback
            + self.source_search.routed
            + self.source_search.daemon_fallback
            + self.repo_start.routed
            + self.repo_start.daemon_fallback
            + self.prompt_context.routed
            + self.prompt_context.daemon_fallback
            + self.post_edit_impact.routed
            + self.post_edit_impact.daemon_fallback
    }

    pub(crate) fn total_fail_open(&self) -> usize {
        self.source_read.fail_open()
            + self.source_search.fail_open()
            + self.repo_start.fail_open()
            + self.prompt_context.fail_open()
            + self.post_edit_impact.fail_open()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.total_attempts() == 0
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Entry point called by main.rs for `symforge hook [subcommand]`.
///
/// When `subcommand` is `None`, reads stdin JSON to determine the tool_name and
/// routes to the correct sidecar endpoint (Phase 6 stdin-routing mode).
///
/// When `subcommand` is `Some`, uses the subcommand directly (backward-compat
/// for manual testing: `symforge hook read`, `symforge hook edit`, etc.).
///
/// Never returns an error — failures produce the fail-open empty JSON.
pub fn run_hook(subcommand: Option<&HookSubcommand>) -> anyhow::Result<()> {
    // Always read stdin so we have context for path/query extraction.
    // For explicit subcommands the payload may be empty or absent — that's fine.
    run_hook_with_input(parse_stdin_input(), subcommand)
}

/// `run_hook` with the stdin payload supplied by the caller instead of read
/// from the process's stdin.
///
pub fn run_hook_with_input(
    input: HookInput,
    subcommand: Option<&HookSubcommand>,
) -> anyhow::Result<()> {
    run_hook_with_input_at(input, subcommand, process_control_state_dir())
}

/// Run a hook against an explicitly resolved control-state owner.
///
/// This is the seam in-process callers and integration harnesses use when
/// reading the real stdin would block or process-global placement would make
/// isolated state ownership impossible.
#[doc(hidden)]
pub fn run_hook_with_input_at(
    input: HookInput,
    subcommand: Option<&HookSubcommand>,
    control_state_dir: Option<ControlStateDir>,
) -> anyhow::Result<()> {
    let verbose = is_hook_verbose();
    let repo_root = std::env::current_dir().unwrap_or_default();

    // PreTool is a special case: no sidecar call needed, just output a
    // tool-preference suggestion based on the tool_name from stdin.
    //
    // Suppress hints when the SymForge sidecar is already running — this means
    // the agent is actively using SymForge tools and any Read/Grep/Edit calls
    // are intentional fallbacks (e.g., reading external crate source, editing
    // files where raw content is needed in context). Only show the hint when
    // there is no active sidecar, meaning the agent may not realize SymForge
    // is available.
    if matches!(subcommand, Some(HookSubcommand::PreTool)) {
        let sidecar_active = control_state_dir
            .as_ref()
            .is_some_and(|state_dir| read_sidecar_endpoint(state_dir, &repo_root).is_ok());
        if !sidecar_active {
            let suggestion = pre_tool_suggestion(&input);
            if !suggestion.is_empty() {
                println!("{}", success_json("PreToolUse", &json_escape(&suggestion)));
            }
        }
        return Ok(());
    }

    // Resolve the effective subcommand: explicit takes priority; otherwise
    // derive from the stdin tool_name.
    let resolved = if let Some(sub) = subcommand {
        Some(sub.clone())
    } else {
        resolve_subcommand_from_input(&input)
    };

    let event_name = resolved
        .as_ref()
        .map(event_name_for)
        .unwrap_or("PostToolUse");
    let workflow = workflow_for_subcommand(resolved.as_ref(), &input);

    // Conservatively fail open for workflows we do not want to semanticize.
    // This keeps docs/config/non-source reads and unknown tool events from
    // producing unrelated sidecar output.
    if workflow == HookWorkflow::PassThrough {
        if verbose {
            eprintln!("[symforge-hook] workflow=PassThrough — emitting fail-open");
        }
        println!("{}", fail_open_json(event_name));
        return Ok(());
    }

    // SF-TE-09: nothing worth asking (e.g. a regex Grep) — fail open with no
    // HTTP request and no adoption row; nothing was routed. Decided BEFORE
    // descriptor selection, whose daemon epoch probe is itself an HTTP GET.
    let Some((path, query)) = endpoint_for(resolved.as_ref(), &input) else {
        if verbose {
            eprintln!("[symforge-hook] no enrichment endpoint for this input — skipping");
        }
        println!("{}", fail_open_json(event_name));
        return Ok(());
    };

    let sidecar_endpoint = control_state_dir
        .as_ref()
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "process control state unavailable",
            )
        })
        .and_then(|state_dir| read_sidecar_endpoint(state_dir, &repo_root))
        .map(|identity| {
            let lifetime = adoption_lifetime_label(&identity);
            (
                identity.port,
                normalize_session_id(identity.session_id),
                lifetime,
            )
        });
    let session_id = sidecar_endpoint
        .as_ref()
        .ok()
        .and_then(|(_, session_id, _)| session_id.clone());
    // SF-ADOPT-03: a row carries the descriptor's lifetime only when it was
    // recorded against the descriptor's own session; a daemon-fallback
    // session is a different lifetime the descriptor proves nothing about.
    let descriptor_lifetime = sidecar_endpoint
        .as_ref()
        .ok()
        .and_then(|(_, _, lifetime)| lifetime.clone());
    let row_lifetime = |row_session: Option<&str>| {
        (row_session == session_id.as_deref())
            .then_some(descriptor_lifetime.as_deref())
            .flatten()
    };

    // Step 1 — read port file; if missing, try daemon fallback before fail-open.
    let (port, effective_session_id, used_daemon_fallback) = match sidecar_endpoint {
        Ok((p, descriptor_session_id, _)) => {
            if verbose {
                eprintln!("[symforge-hook] read port file: port={p}");
            }
            (p, descriptor_session_id, false)
        }
        Err(e) => {
            let port_file_path = control_state_dir
                .as_ref()
                .map(sidecar_descriptor_path)
                .unwrap_or_default();
            if verbose {
                eprintln!(
                    "[symforge-hook] port file not readable: {e} (searched {})",
                    port_file_path.display()
                );
            }

            // --- Gap 2: Daemon fallback ---
            // Before failing open, check if the SymForge daemon is running and
            // has an active session for this repository.
            if verbose {
                eprintln!("[symforge-hook] attempting daemon fallback...");
            }
            match try_daemon_fallback(&repo_root, None) {
                Some(fallback) => {
                    if verbose {
                        eprintln!(
                            "[symforge-hook] daemon fallback succeeded: port={}, session={}",
                            fallback.daemon_port, fallback.session_id
                        );
                    }
                    // Daemon has an active session — use its port and session id.
                    (fallback.daemon_port, Some(fallback.session_id), true)
                }
                None => {
                    if verbose {
                        eprintln!("[symforge-hook] daemon fallback failed — no active session");
                    }
                    // --- Gap 1: Enhanced diagnostics ---
                    emit_no_sidecar_diagnostic(&repo_root, &port_file_path);
                    maybe_emit_sidecar_hint(control_state_dir.as_ref());
                    if verbose {
                        eprintln!("[symforge-hook] outcome=NoSidecar reason=sidecar_port_missing");
                    }
                    record_hook_outcome_with_detail(
                        workflow,
                        HookOutcome::NoSidecar,
                        session_id.as_deref(),
                        row_lifetime(session_id.as_deref()),
                        Some(HookOutcomeDetail {
                            reason: "sidecar_port_missing",
                            searched_path: Some(&port_file_path.to_string_lossy()),
                            suggestion: Some("start_mcp_session"),
                            project_root: &repo_root.to_string_lossy(),
                        }),
                    );
                    println!("{}", fail_open_json(event_name));
                    return Ok(());
                }
            }
        }
    };
    // A descriptor carrying a session id already targets the daemon proxy.
    // Keep this separate from `used_daemon_fallback`: descriptor routing is a
    // normal route (and records `Routed`), but it must not rediscover and call
    // the same daemon a second time after a 503. Session ids are normalized at
    // descriptor read so this predicate is identical to `proxy_path` routing.
    let initial_endpoint_is_daemon = effective_session_id.is_some();

    // Step 2 — endpoint + query string were resolved above.
    let request_path = proxy_path(path, effective_session_id.as_deref());

    if verbose {
        eprintln!("[symforge-hook] HTTP GET 127.0.0.1:{port}{request_path}?{query}");
    }

    // Dogfood #6 / spec 012 FR-006b (hook half): pin the sidecar request to
    // the caller's repo root. A sidecar whose shared session was retargeted by
    // another agent's `index_folder` answers 409, and the daemon fallback
    // below re-resolves the caller's project BY ROOT. Keep the daemon request
    // pinned too: a session can remain open while its active project changes.
    let Some(query) = append_caller_root(query) else {
        if verbose {
            eprintln!(
                "[symforge-hook] project root is not valid UTF-8 — refusing enrichment authority and failing open"
            );
        }
        record_hook_outcome_with_detail(
            workflow,
            HookOutcome::NoSidecar,
            effective_session_id.as_deref(),
            row_lifetime(effective_session_id.as_deref()),
            Some(HookOutcomeDetail {
                reason: "project_root_not_utf8",
                searched_path: None,
                suggestion: None,
                project_root: &repo_root.to_string_lossy(),
            }),
        );
        println!("{}", fail_open_json(event_name));
        return Ok(());
    };
    // Keep a copy so the stale-sidecar daemon fallback can re-issue the same
    // root-pinned enrichment request — the first HTTP call consumes `query`.
    let fallback_query = query.clone();

    // Step 3/4 — make sync HTTP GET with 50 ms timeout.
    let (body, outcome, outcome_session_id) = match sync_enrichment_http_get(
        port,
        &request_path,
        query,
    ) {
        EnrichmentHttpResult::Success(b) => {
            let initial_outcome = if used_daemon_fallback {
                HookOutcome::DaemonFallback
            } else {
                HookOutcome::Routed
            };
            (b, initial_outcome, effective_session_id.clone())
        }
        initial_failure @ (EnrichmentHttpResult::IndexNotReady
        | EnrichmentHttpResult::RootConflict
        | EnrichmentHttpResult::HttpFailure(_)
        | EnrichmentHttpResult::Unavailable) => {
            let initial_index_not_ready =
                matches!(initial_failure, EnrichmentHttpResult::IndexNotReady);
            let initial_root_conflict =
                matches!(initial_failure, EnrichmentHttpResult::RootConflict);
            let initial_http_failure =
                matches!(initial_failure, EnrichmentHttpResult::HttpFailure(_));

            // Before failing open, try routing the SAME enrichment request
            // through the daemon. A local sidecar may still be loading while a
            // separate root-matched daemon session is already queryable.
            //
            // A 503 from a daemon-backed endpoint is authoritative for that
            // root-matched project and must not be retried through the same
            // daemon. A closed session (404/unavailable) or a root conflict can
            // still recover through a different active session, so rediscover
            // while excluding the session that just failed.
            let port_file_path = control_state_dir
                .as_ref()
                .map(sidecar_descriptor_path)
                .unwrap_or_default();

            if verbose {
                if initial_index_not_ready {
                    if initial_endpoint_is_daemon {
                        eprintln!("[symforge-hook] daemon index not ready — failing open");
                    } else {
                        eprintln!(
                            "[symforge-hook] index not ready — attempting daemon fallback before fail-open"
                        );
                    }
                } else if initial_root_conflict {
                    if initial_endpoint_is_daemon {
                        eprintln!(
                            "[symforge-hook] daemon root conflict — attempting alternate daemon session"
                        );
                    } else {
                        eprintln!(
                            "[symforge-hook] sidecar root conflict — attempting daemon fallback before fail-open"
                        );
                    }
                } else if initial_http_failure {
                    eprintln!(
                        "[symforge-hook] sidecar returned a live HTTP failure — attempting daemon fallback before fail-open"
                    );
                } else {
                    // Probe only transport failures. A 503 already proves the
                    // sidecar is live and must never produce a restart hint.
                    let liveness = control_state_dir
                        .as_ref()
                        .map(|state_dir| {
                            crate::sidecar::port_file::read_sidecar_status(
                                state_dir,
                                "127.0.0.1",
                                Some(&repo_root),
                            )
                            .liveness
                            .as_str()
                        })
                        .unwrap_or("unavailable");
                    if initial_endpoint_is_daemon {
                        eprintln!(
                            "[symforge-hook] daemon HTTP request failed — liveness={liveness}, attempting alternate daemon session"
                        );
                    } else {
                        eprintln!(
                            "[symforge-hook] HTTP request failed — sidecar liveness={liveness}, \
                             attempting daemon fallback before fail-open"
                        );
                    }
                }
            }

            let daemon_enriched = if initial_endpoint_is_daemon && initial_index_not_ready {
                None
            } else {
                let excluded_session_id = initial_endpoint_is_daemon
                    .then_some(effective_session_id.as_deref())
                    .flatten();
                match try_daemon_fallback(&repo_root, excluded_session_id) {
                    Some(fallback) => {
                        let fallback_session_id = fallback.session_id.clone();
                        let daemon_request_path = proxy_path(path, Some(&fallback.session_id));
                        if verbose {
                            eprintln!(
                                "[symforge-hook] daemon fallback (stale sidecar): \
                                 port={}, session={}",
                                fallback.daemon_port, fallback.session_id
                            );
                        }
                        Some((
                            sync_enrichment_http_get_with_timeout(
                                fallback.daemon_port,
                                &daemon_request_path,
                                fallback_query,
                                DAEMON_FALLBACK_DEADLINE,
                            ),
                            fallback_session_id,
                        ))
                    }
                    None => None,
                }
            };

            match daemon_enriched {
                Some((EnrichmentHttpResult::Success(b), daemon_session_id)) => {
                    if verbose {
                        eprintln!(
                            "[symforge-hook] daemon fallback succeeded — \
                             sidecar dead/degraded, served enriched result via daemon"
                        );
                    }
                    (b, HookOutcome::DaemonFallback, Some(daemon_session_id))
                }
                Some((EnrichmentHttpResult::IndexNotReady, daemon_session_id)) => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        Some(&daemon_session_id),
                        row_lifetime(Some(&daemon_session_id)),
                        "index_not_ready",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::RootConflict, daemon_session_id)) => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        Some(&daemon_session_id),
                        row_lifetime(Some(&daemon_session_id)),
                        "root_conflict",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::HttpFailure(_), daemon_session_id)) => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        Some(&daemon_session_id),
                        row_lifetime(Some(&daemon_session_id)),
                        "http_failure",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::Unavailable, _)) | None if initial_index_not_ready => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        effective_session_id.as_deref(),
                        row_lifetime(effective_session_id.as_deref()),
                        "index_not_ready",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::Unavailable, _)) | None if initial_root_conflict => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        effective_session_id.as_deref(),
                        row_lifetime(effective_session_id.as_deref()),
                        "root_conflict",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::Unavailable, _)) | None if initial_http_failure => {
                    emit_live_refusal_fail_open(
                        workflow,
                        event_name,
                        effective_session_id.as_deref(),
                        row_lifetime(effective_session_id.as_deref()),
                        "http_failure",
                        verbose,
                        &repo_root,
                    );
                    return Ok(());
                }
                Some((EnrichmentHttpResult::Unavailable, _)) | None => {
                    // Both sidecar and daemon are unreachable: degrade to a
                    // pass-through, never hang, never error the editor.
                    if verbose {
                        eprintln!(
                            "[symforge-hook] daemon fallback unavailable — \
                             outcome=NoSidecar reason=sidecar_port_stale"
                        );
                    }
                    maybe_emit_sidecar_hint(control_state_dir.as_ref());
                    record_hook_outcome_with_detail(
                        workflow,
                        HookOutcome::NoSidecar,
                        effective_session_id.as_deref(),
                        row_lifetime(effective_session_id.as_deref()),
                        Some(HookOutcomeDetail {
                            reason: "sidecar_port_stale",
                            searched_path: Some(&port_file_path.to_string_lossy()),
                            suggestion: Some("restart_sidecar"),
                            project_root: &repo_root.to_string_lossy(),
                        }),
                    );
                    println!("{}", fail_open_json(event_name));
                    return Ok(());
                }
            }
        }
    };

    if verbose {
        eprintln!("[symforge-hook] outcome={}", outcome.label());
    }

    // Step 5/6 — output result JSON.
    record_hook_outcome(
        workflow,
        outcome,
        outcome_session_id.as_deref(),
        row_lifetime(outcome_session_id.as_deref()),
    );
    println!("{}", success_json(event_name, &body));
    Ok(())
}

fn emit_live_refusal_fail_open(
    workflow: HookWorkflow,
    event_name: &str,
    session_id: Option<&str>,
    lifetime: Option<&str>,
    reason: &str,
    verbose: bool,
    repo_root: &std::path::Path,
) {
    if verbose {
        eprintln!("[symforge-hook] outcome=SidecarError reason={reason}");
    }
    // SF-ADOPT-02: persist the refusal reason, not just the outcome lane.
    record_hook_outcome_with_detail(
        workflow,
        HookOutcome::SidecarError,
        session_id,
        lifetime,
        Some(HookOutcomeDetail {
            reason,
            searched_path: None,
            suggestion: None,
            project_root: &repo_root.to_string_lossy(),
        }),
    );
    // A session that starts while the index is still loading is told so in
    // one line instead of silently getting no context. Only on an observed
    // index-not-ready answer: nothing else here proves indexing is under way.
    if event_name == "SessionStart" && reason == "index_not_ready" {
        let project = repo_root
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_else(|| repo_root.display().to_string());
        let notice = format!(
            "symforge: {project}: {}.",
            crate::protocol::format::INDEXING_IN_PROGRESS
        );
        println!("{}", success_json(event_name, &notice));
        return;
    }
    println!("{}", fail_open_json(event_name));
}

// ---------------------------------------------------------------------------
// Helpers (pub for unit-testing, not part of the public module API)
// ---------------------------------------------------------------------------

/// Reads all available stdin lines and deserializes them as a Claude Code
/// PostToolUse JSON payload.
///
/// Returns `HookInput::default()` on any parse failure (fail-open).
/// Upper bound on waiting for the hook payload on stdin.
///
/// Claude Code writes the payload and closes the pipe at spawn, so the read
/// normally completes in well under a millisecond. The bound only matters when
/// stdin is held open with no writer (e.g. the hook is invoked interactively,
/// or from an environment that never closes the inherited pipe) — without it
/// the read blocks forever and the hook hangs the session instead of failing
/// open.
const STDIN_READ_TIMEOUT_MS: u64 = 250;

pub(crate) fn parse_stdin_input() -> HookInput {
    // The blocking read happens on a helper thread so the hook can enforce a
    // deadline. On timeout the thread is leaked — it stays parked on the stdin
    // read — which is acceptable because the hook is a one-shot process and
    // exits immediately after responding. In-process callers (tests) must use
    // `run_hook_with_input` and never reach this function.
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let stdin = std::io::stdin();
        let mut stdin_json = String::new();
        for line in stdin.lock().lines() {
            match line {
                Ok(l) => {
                    stdin_json.push_str(&l);
                    stdin_json.push('\n');
                }
                Err(_) => break,
            }
        }
        let _ = tx.send(stdin_json);
    });
    match rx.recv_timeout(Duration::from_millis(STDIN_READ_TIMEOUT_MS)) {
        Ok(stdin_json) => serde_json::from_str(&stdin_json).unwrap_or_default(),
        // Timeout or disconnected sender: fail open with an empty payload.
        Err(_) => HookInput::default(),
    }
}

/// Converts an absolute path to a relative path by stripping the `cwd` prefix.
///
/// Uses `std::path::Path::strip_prefix` for correct platform-aware stripping,
/// then normalises backslashes to forward slashes for the sidecar query.
/// Returns `absolute` unchanged if it does not start with `cwd`.
pub(crate) fn relative_path(absolute: &str, cwd: &str) -> String {
    let abs = std::path::Path::new(absolute);
    let base = std::path::Path::new(cwd);
    match abs.strip_prefix(base) {
        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
        Err(_) => absolute.to_string(),
    }
}

/// Maps a `tool_name` string from the stdin JSON to a `HookSubcommand`.
fn resolve_subcommand_from_input(input: &HookInput) -> Option<HookSubcommand> {
    if input.prompt.as_deref().is_some() {
        return Some(HookSubcommand::PromptSubmit);
    }

    match input.tool_name.as_deref() {
        Some("Read") => Some(HookSubcommand::Read),
        Some("Edit") => Some(HookSubcommand::Edit),
        Some("Write") => Some(HookSubcommand::Write),
        Some("Grep") => Some(HookSubcommand::Grep),
        _ => None,
    }
}

/// Returns the `hookEventName` string for a given subcommand.
pub fn event_name_for(subcommand: &HookSubcommand) -> &'static str {
    match subcommand {
        HookSubcommand::SessionStart => "SessionStart",
        HookSubcommand::PromptSubmit => "UserPromptSubmit",
        HookSubcommand::PreTool => "PreToolUse",
        _ => "PostToolUse",
    }
}

/// Returns a tool-preference suggestion for the given tool, or empty string if
/// no suggestion applies (e.g. non-source files, unknown tools).
///
/// This is the core of the PreToolUse interception: it tells the model which
/// SymForge tool to use instead of the built-in tool it's about to call.
fn pre_tool_suggestion(input: &HookInput) -> String {
    let tool = input.tool_name.as_deref().unwrap_or("");
    let cwd = input.cwd.as_deref().unwrap_or("");

    // Suppress hints for targets outside the workspace root: SymForge cannot
    // serve paths outside the indexed repo (e.g. %TEMP% task outputs, other
    // repos), so the hint would be pure noise. Fail-open silent.
    let target = input
        .tool_input
        .as_ref()
        .and_then(|ti| ti.file_path.as_deref().or(ti.path.as_deref()))
        .unwrap_or("");
    if is_outside_workspace(target, cwd) {
        return String::new();
    }

    let file = extract_file_path(input, cwd);
    let pattern = input
        .tool_input
        .as_ref()
        .and_then(|ti| ti.pattern.as_deref().or(ti.path.as_deref()))
        .unwrap_or("");

    match pre_tool_workflow(input) {
        HookWorkflow::SourceSearch if !pattern.is_empty() => format!(
            "SymForge can answer this more directly. Start with search_text(query=\"{pattern}\") for symbol-aware source matches, or search_symbols(query=\"{pattern}\") if this is likely a symbol name."
        ),
        HookWorkflow::SourceSearch => "SymForge can answer this more directly. Prefer search_text for source-code search with enclosing symbol context, or search_symbols when you are searching by name/kind.".to_string(),
        HookWorkflow::SourceRead if !file.is_empty() => format!(
            "SymForge can answer this more efficiently. Start with get_file_context(path=\"{file}\") for structure and key references, or get_symbol/get_symbol_context if you only need a specific symbol."
        ),
        HookWorkflow::SourceRead => "SymForge can answer this more efficiently. Prefer get_file_context for source-file structure and get_symbol/get_symbol_context for targeted symbol reads.".to_string(),
        HookWorkflow::CodeEdit => "SymForge MCP is connected. Prefer replace_symbol_body, edit_within_symbol, or batch_edit over Edit for source code modifications — they resolve by symbol name, auto-indent, and re-index atomically.".to_string(),
        HookWorkflow::PassThrough if tool == "Glob" && !pattern.is_empty() => format!(
            "SymForge can narrow this faster. Prefer search_files(query=\"{pattern}\") for ranked path discovery, or get_repo_map if you need a project overview first."
        ),
        HookWorkflow::PassThrough if tool == "Glob" => "SymForge can narrow this faster. Prefer search_files for ranked path discovery, or get_repo_map for repository overview.".to_string(),
        _ => String::new(),
    }
}

/// Classifies the workflow intent behind a pre-tool event.
///
/// This helper intentionally preserves current PR 1 behavior:
/// - source `Read` gets a SymForge suggestion
/// - docs/config/non-source `Read` remains pass-through
/// - `Grep` is treated as source search
/// - `Edit` is treated as code-edit intent
/// - everything else remains pass-through for now
fn pre_tool_workflow(input: &HookInput) -> HookWorkflow {
    let tool = input.tool_name.as_deref().unwrap_or("");
    let file_path = input
        .tool_input
        .as_ref()
        .and_then(|ti| ti.file_path.as_deref())
        .unwrap_or("");

    match tool {
        "Read" if !should_fail_open_read(file_path) => HookWorkflow::SourceRead,
        "Grep" => HookWorkflow::SourceSearch,
        "Edit" => HookWorkflow::CodeEdit,
        _ => HookWorkflow::PassThrough,
    }
}

/// Classifies the workflow intent behind a resolved hook subcommand.
///
/// PR 1 does not change endpoint routing with this helper yet; it exists so
/// later routing work can move from raw tool-name branching to workflow-aware
/// decisions without redefining the vocabulary.
fn workflow_for_subcommand(subcommand: Option<&HookSubcommand>, input: &HookInput) -> HookWorkflow {
    match subcommand {
        Some(HookSubcommand::Read) if !should_fail_open_read(&extract_file_path(input, "")) => {
            HookWorkflow::SourceRead
        }
        Some(HookSubcommand::Read) => HookWorkflow::PassThrough,
        Some(HookSubcommand::Grep) => HookWorkflow::SourceSearch,
        Some(HookSubcommand::SessionStart) => HookWorkflow::RepoStart,
        Some(HookSubcommand::PromptSubmit) => HookWorkflow::PromptContext,
        Some(HookSubcommand::Edit | HookSubcommand::Write) => HookWorkflow::PostEditImpact,
        Some(HookSubcommand::PreTool) => pre_tool_workflow(input),
        None => HookWorkflow::PassThrough,
    }
}

/// True when `target` is an absolute path that does not live under the
/// workspace root (`root`, falling back to the hook's current directory).
///
/// SymForge tools resolve paths relative to the indexed project root, so an
/// absolute path outside it (temp dirs, other repos) can never be served and
/// must not produce an efficiency hint. Relative and empty targets are always
/// treated as in-workspace. Cheap by design: string prefix check after
/// normalization, no filesystem access beyond an optional `current_dir`.
fn is_outside_workspace(target: &str, root: &str) -> bool {
    if target.is_empty() || !std::path::Path::new(target).is_absolute() {
        return false;
    }
    let root_norm = if root.is_empty() {
        match std::env::current_dir() {
            Ok(d) => normalize_path_for_match(&d),
            // Fail-open: cannot determine the root, keep existing behavior.
            Err(_) => return false,
        }
    } else {
        normalize_path_for_match(std::path::Path::new(root))
    };
    if root_norm.is_empty() {
        return false;
    }
    let target_norm = normalize_path_for_match(std::path::Path::new(target));
    target_norm != root_norm && !target_norm.starts_with(&format!("{root_norm}/"))
}

/// Returns true when a read should stay conservative and fail open instead of
/// being steered into semantic code-inspection flows.
///
/// This is intentionally broader than `is_non_source_path`: SymForge may index
/// many config files, but exact raw reads of docs/configs are still often the
/// correct user intent.
fn should_fail_open_read(path: &str) -> bool {
    if is_non_source_path(path) {
        return true;
    }

    let p = path.replace('\\', "/").to_lowercase();
    let literal_read_exts = [
        ".md", ".mdx", ".txt", ".json", ".toml", ".yaml", ".yml", ".env",
    ];
    literal_read_exts.iter().any(|ext| p.ends_with(ext))
}

/// Returns true for paths that are clearly outside source-code inspection
/// flows, such as docs directories, binary-ish assets, and other non-code
/// artifacts.
///
/// This helper is intentionally coarser than `should_fail_open_read`: config
/// and doc-like extensions can still stay out of semantic hook routing even if
/// we do not classify them as broad non-source paths here.
fn is_non_source_path(path: &str) -> bool {
    let p = path.replace('\\', "/").to_lowercase();

    // Broadly non-source file extensions. Literal docs/config reads are handled
    // separately by `should_fail_open_read`.
    let non_source_exts = [
        ".txt",
        ".xml",
        ".csv",
        ".lock",
        ".gitignore",
        ".dockerignore",
        ".editorconfig",
        ".prettierrc",
        ".eslintrc",
        ".ini",
        ".cfg",
        ".conf",
        // `.html` / `.css` are indexed languages (SF-DOG-05); never list an
        // extension `LanguageId` parses — the unit test below pins that.
        ".svg",
        ".png",
        ".jpg",
        ".jpeg",
        ".gif",
        ".ico",
    ];
    if non_source_exts.iter().any(|ext| p.ends_with(ext)) {
        return true;
    }

    // Non-source directories
    let non_source_dirs = [
        "/docs/",
        "/doc/",
        "/.github/",
        "/.planning/",
        "/.claude/",
        "/.gemini/",
        "/.codex/",
        "/node_modules/",
        "/.git/",
    ];
    if non_source_dirs.iter().any(|dir| p.contains(dir)) {
        return true;
    }

    false
}

/// True when a Grep pattern is a bare code identifier worth a symbol lookup.
/// Regexes, globs, and multi-token phrases can never match a symbol name, so
/// forwarding them only produces zero-hit noise in prompt context (dogfood #8).
fn is_plausible_symbol_name(pattern: &str) -> bool {
    let mut chars = pattern.chars();
    chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
/// Maps a resolved subcommand + stdin input to `(path, query_string)`.
///
/// The `input` carries the file path and search pattern extracted from the
/// Claude Code PostToolUse payload. `None` means there is nothing worth
/// asking the sidecar: the caller must fail open without an HTTP request and
/// without recording an adoption row (SF-TE-09 — the old `/health` stand-in
/// injected index-health JSON into context and counted it as routed).
pub(crate) fn endpoint_for(
    subcommand: Option<&HookSubcommand>,
    input: &HookInput,
) -> Option<(&'static str, String)> {
    let cwd = input.cwd.as_deref().unwrap_or("");

    match subcommand {
        Some(HookSubcommand::Read) => {
            let file = extract_file_path(input, cwd);
            let query = if file.is_empty() {
                String::new()
            } else {
                format!("path={}", url_encode(&file))
            };
            Some(("/outline", query))
        }
        Some(HookSubcommand::Edit) => {
            let file = extract_file_path(input, cwd);
            let query = if file.is_empty() {
                String::new()
            } else {
                format!("path={}", url_encode(&file))
            };
            Some(("/impact", query))
        }
        Some(HookSubcommand::Write) => {
            let file = extract_file_path(input, cwd);
            let query = if file.is_empty() {
                "new_file=true".to_string()
            } else {
                format!("path={}&new_file=true", url_encode(&file))
            };
            Some(("/impact", query))
        }
        Some(HookSubcommand::Grep) => {
            // Use `pattern` field first, then fall back to `path` (directory) field.
            let q = input
                .tool_input
                .as_ref()
                .and_then(|ti| ti.pattern.as_deref().or(ti.path.as_deref()))
                .unwrap_or("");
            // Dogfood #8 (2026-07-06): grep patterns are often regexes or
            // multi-token phrases (`Tip:`, `compact|SYMFORGE_SURFACE`) — not
            // symbol names. Forwarding them buys a guaranteed zero-hit report
            // in prompt context. Only a bare identifier is worth the lookup.
            if q.is_empty() || !is_plausible_symbol_name(q) {
                return None;
            }
            Some(("/symbol-context", format!("name={}", url_encode(q))))
        }
        Some(HookSubcommand::SessionStart) => Some(("/repo-map", String::new())),
        Some(HookSubcommand::PromptSubmit) => {
            let prompt = input.prompt.as_deref().unwrap_or("");
            let query = if prompt.is_empty() {
                String::new()
            } else {
                format!("text={}", url_encode(prompt))
            };
            Some(("/prompt-context", query))
        }
        // PreTool is handled before endpoint_for is called; unknown tool
        // names resolve to PassThrough. Neither has anything to ask.
        Some(HookSubcommand::PreTool) | None => None,
    }
}

/// Append the hook's repo root (its cwd, canonicalized) as `caller_root` so
/// the sidecar's root guard can 409 a wrong-project answer (dogfood #6 /
/// spec 012 FR-006b).
fn append_caller_root(query: String) -> Option<String> {
    let cwd = std::env::current_dir().unwrap_or_default();
    let root = std::fs::canonicalize(&cwd).unwrap_or(cwd);
    append_caller_root_for_path(query, &root)
}

fn append_caller_root_for_path(query: String, root: &Path) -> Option<String> {
    let encoded = url_encode(root.to_str()?);
    Some(if query.is_empty() {
        format!("caller_root={encoded}")
    } else {
        format!("{query}&caller_root={encoded}")
    })
}

/// Returns the fail-open JSON: empty `additionalContext`.
pub fn fail_open_json(event_name: &str) -> String {
    format!(r#"{{"hookSpecificOutput":{{"hookEventName":"{event_name}","additionalContext":""}}}}"#)
}

/// Returns the success JSON with `context` as the `additionalContext` value.
///
/// The `context` string is JSON-escaped (backslash + quote safe) so it can be
/// embedded as a JSON string value.
pub fn success_json(event_name: &str, context: &str) -> String {
    let escaped = json_escape(context);
    format!(
        r#"{{"hookSpecificOutput":{{"hookEventName":"{event_name}","additionalContext":"{escaped}"}}}}"#
    )
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Extract and relativize the file path from stdin input.
fn extract_file_path(input: &HookInput, cwd: &str) -> String {
    let abs = input
        .tool_input
        .as_ref()
        .and_then(|ti| ti.file_path.as_deref())
        .unwrap_or("");
    if abs.is_empty() || cwd.is_empty() {
        abs.to_string()
    } else {
        relative_path(abs, cwd)
    }
}

fn read_sidecar_endpoint(
    control_state_dir: &ControlStateDir,
    project_root: &Path,
) -> std::io::Result<crate::sidecar::port_file::SidecarEndpointIdentity> {
    crate::sidecar::port_file::read_sidecar_endpoint_identity(
        control_state_dir,
        "127.0.0.1",
        Some(project_root),
    )
}

/// The sidecar lifetime an adoption row belongs to (SF-ADOPT-03): the daemon
/// boot epoch for daemon-backed descriptors (a restarted daemon re-mints
/// `session-1`, so the session id alone aliases lifetimes), else the
/// descriptor pid. `None` when the descriptor proves neither.
fn adoption_lifetime_label(
    identity: &crate::sidecar::port_file::SidecarEndpointIdentity,
) -> Option<String> {
    match (identity.daemon_started_at, identity.pid) {
        (Some(epoch), _) => Some(format!("daemon:{epoch}")),
        (None, Some(pid)) => Some(format!("pid:{pid}")),
        (None, None) => None,
    }
}

fn normalize_session_id(session_id: Option<String>) -> Option<String> {
    session_id
        .map(|session_id| session_id.trim().to_string())
        .filter(|session_id| !session_id.is_empty())
}

fn proxy_path(base_path: &str, session_id: Option<&str>) -> String {
    match session_id {
        Some(session_id) if !session_id.trim().is_empty() => {
            format!("/v1/sessions/{}/sidecar{}", session_id.trim(), base_path)
        }
        _ => base_path.to_string(),
    }
}

fn tracked_workflow_name(workflow: HookWorkflow) -> Option<&'static str> {
    match workflow {
        HookWorkflow::SourceRead => Some("source-read"),
        HookWorkflow::SourceSearch => Some("source-search"),
        HookWorkflow::RepoStart => Some("repo-start"),
        HookWorkflow::PromptContext => Some("prompt-context"),
        HookWorkflow::PostEditImpact => Some("post-edit-impact"),
        HookWorkflow::CodeEdit | HookWorkflow::PassThrough => None,
    }
}

fn parse_tracked_workflow(raw: &str) -> Option<HookWorkflow> {
    match raw {
        "source-read" => Some(HookWorkflow::SourceRead),
        "source-search" => Some(HookWorkflow::SourceSearch),
        "repo-start" => Some(HookWorkflow::RepoStart),
        "prompt-context" => Some(HookWorkflow::PromptContext),
        "post-edit-impact" => Some(HookWorkflow::PostEditImpact),
        _ => None,
    }
}

fn record_hook_outcome(
    workflow: HookWorkflow,
    outcome: HookOutcome,
    session_id: Option<&str>,
    lifetime: Option<&str>,
) {
    record_hook_outcome_with_detail(workflow, outcome, session_id, lifetime, None);
}

fn record_hook_outcome_at(
    control_state_dir: &ControlStateDir,
    workflow: HookWorkflow,
    outcome: HookOutcome,
    session_id: Option<&str>,
    lifetime: Option<&str>,
    detail: Option<&HookOutcomeDetail<'_>>,
) {
    let Some(workflow_name) = tracked_workflow_name(workflow) else {
        return;
    };
    let row = adoption_row(session_id, lifetime, workflow_name, outcome.label(), detail);
    let _ = append_adoption_row(&adoption_log_path(control_state_dir), &row);
}

// ---------------------------------------------------------------------------
// Daemon fallback (Gap 2)
// ---------------------------------------------------------------------------

/// Result of a successful daemon fallback lookup.
struct DaemonFallbackResult {
    daemon_port: u16,
    session_id: String,
}

/// Try to find an active daemon session for the given repo root.
///
/// Returns `Some(DaemonFallbackResult)` if the daemon is running and has a
/// session whose canonical_root matches `repo_root`. Returns `None` if the
/// daemon is unreachable, has no matching project, or any step times out.
///
/// Total budget: DAEMON_FALLBACK_DEADLINE (500ms shared across all steps).
fn try_daemon_fallback(
    repo_root: &Path,
    excluded_session_id: Option<&str>,
) -> Option<DaemonFallbackResult> {
    let deadline = std::time::Instant::now() + DAEMON_FALLBACK_DEADLINE;

    // Step 1: Read the daemon port file (~/.symforge/daemon.port).
    let daemon_port = crate::daemon::read_daemon_port_file().ok()?;

    // Step 2: Query GET /v1/projects for the list of active projects.
    let remaining = deadline.checked_duration_since(std::time::Instant::now())?;
    let projects_json =
        sync_http_get_with_timeout(daemon_port, "/v1/projects", String::new(), remaining).ok()?;

    // Step 3: Parse the projects list and find one matching this repo root.
    let canon_root = std::fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf());
    // Minimal serde structs for daemon JSON responses.
    // The daemon returns a JSON array of objects with `canonical_root`,
    // `project_id`, and `session_count` fields.
    let projects: Vec<DaemonProjectEntry> = serde_json::from_str(&projects_json).ok()?;

    let matching = projects
        .iter()
        .find(|project| daemon_project_matches_native_root(project, &canon_root))?;

    if matching.session_count == 0 {
        return None;
    }

    // Step 4: Query GET /v1/projects/{project_id}/sessions to get a session id.
    let remaining = deadline.checked_duration_since(std::time::Instant::now())?;
    let sessions_path = format!("/v1/projects/{}/sessions", url_encode(&matching.project_id));
    let sessions_json =
        sync_http_get_with_timeout(daemon_port, &sessions_path, String::new(), remaining).ok()?;

    let sessions: Vec<DaemonSessionEntry> = serde_json::from_str(&sessions_json).ok()?;

    // A session listed under this project may since have activated another
    // project. Only route through a session whose current active project still
    // matches the root-resolved project, then prefer the most recently seen.
    let session = sessions
        .iter()
        .filter(|session| {
            session.project_id == matching.project_id
                && !session.session_id.trim().is_empty()
                && excluded_session_id.is_none_or(|excluded| session.session_id.trim() != excluded)
        })
        .max_by_key(|session| session.last_seen_at_unix_secs)?;

    Some(DaemonFallbackResult {
        daemon_port,
        session_id: session.session_id.trim().to_string(),
    })
}

/// Minimal deserialization struct for daemon project list entries.
#[derive(serde::Deserialize)]
struct DaemonProjectEntry {
    project_id: String,
    canonical_root: String,
    session_count: usize,
}

fn daemon_project_matches_native_root(project: &DaemonProjectEntry, root: &Path) -> bool {
    let expected_project_id = crate::daemon::project_key(root);
    project.project_id == expected_project_id
        && crate::daemon::project_key(Path::new(&project.canonical_root)) == project.project_id
}

/// Minimal deserialization struct for daemon session list entries.
#[derive(serde::Deserialize)]
struct DaemonSessionEntry {
    session_id: String,
    project_id: String,
    last_seen_at_unix_secs: u64,
}

#[derive(Debug, PartialEq, Eq)]
struct HttpResponse {
    status_code: u16,
    body: String,
}

#[derive(Debug, PartialEq, Eq)]
enum EnrichmentHttpResult {
    Success(String),
    IndexNotReady,
    RootConflict,
    HttpFailure(u16),
    Unavailable,
}

fn normalize_path_text_for_match(path_text: &str, windows: bool) -> String {
    let normalized = crate::daemon::normalized_path_text(path_text, windows);
    let trimmed = normalized.trim_end_matches('/');
    if windows {
        trimmed.to_ascii_lowercase()
    } else {
        trimmed.to_string()
    }
}

/// Normalize a native path for cross-platform comparison: Windows accepts
/// either slash spelling and compares case-insensitively; Unix preserves a
/// literal backslash because it is a valid filename byte.
fn normalize_path_for_match(path: &Path) -> String {
    normalize_path_text_for_match(&path.to_string_lossy(), cfg!(windows))
}

fn sync_http_response_with_timeout(
    port: u16,
    path: &str,
    query: String,
    timeout: Duration,
) -> anyhow::Result<HttpResponse> {
    const MAX_HTTP_HEADER_BYTES: usize = 32 * 1024;
    const MAX_HTTP_BODY_BYTES: usize = 8 * 1024 * 1024;
    const MAX_HTTP_WIRE_BODY_BYTES: usize = 16 * 1024 * 1024;

    let addr = format!("127.0.0.1:{port}");
    let sock_addr: std::net::SocketAddr = addr.parse()?;
    let deadline = std::time::Instant::now() + timeout;

    let mut stream = TcpStream::connect_timeout(&sock_addr, timeout)?;

    let request_path = if query.is_empty() {
        path.to_string()
    } else {
        format!("{path}?{query}")
    };

    // Resolve the daemon auth token the same way the MCP proxy does — env pin
    // first, then the daemon's persisted token file — so the hook authenticates
    // against the now fail-closed daemon even when it has no env pin of its own.
    let auth_header = crate::daemon::resolve_daemon_auth_token()
        .map(|token| format!("Authorization: Bearer {token}\r\n"))
        .unwrap_or_default();
    let request = format!(
        "GET {request_path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{auth_header}Connection: close\r\n\r\n"
    );

    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
    anyhow::ensure!(!remaining.is_zero(), "HTTP request timed out");
    stream.set_write_timeout(Some(remaining))?;
    stream.write_all(request.as_bytes())?;

    let mut response = Vec::new();
    let mut chunk = [0_u8; 8192];
    loop {
        let remaining = deadline.saturating_duration_since(std::time::Instant::now());
        anyhow::ensure!(!remaining.is_zero(), "HTTP response timed out");
        stream.set_read_timeout(Some(remaining))?;
        let count = match stream.read(&mut chunk) {
            Ok(count) => count,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(error.into()),
        };
        if count > 0 {
            response.extend_from_slice(&chunk[..count]);
            anyhow::ensure!(
                response.len() <= MAX_HTTP_HEADER_BYTES + MAX_HTTP_WIRE_BODY_BYTES,
                "HTTP response exceeds size limit"
            );
        }

        let Some(header_end) = response.windows(4).position(|bytes| bytes == b"\r\n\r\n") else {
            anyhow::ensure!(
                response.len() <= MAX_HTTP_HEADER_BYTES,
                "HTTP headers exceed size limit"
            );
            anyhow::ensure!(count != 0, "malformed HTTP response: incomplete headers");
            continue;
        };
        anyhow::ensure!(
            header_end + 4 <= MAX_HTTP_HEADER_BYTES,
            "HTTP headers exceed size limit"
        );
        let headers = std::str::from_utf8(&response[..header_end])?;
        let status_line = headers
            .lines()
            .next()
            .ok_or_else(|| anyhow::anyhow!("malformed HTTP response: empty headers"))?;
        let status_code: u16 = status_line
            .split_whitespace()
            .nth(1)
            .ok_or_else(|| anyhow::anyhow!("malformed HTTP status line"))?
            .parse()
            .map_err(|_| anyhow::anyhow!("non-numeric HTTP status code"))?;

        let mut content_length = None;
        let mut transfer_encoding = None;
        for line in headers.lines().skip(1) {
            let (name, value) = line
                .split_once(':')
                .ok_or_else(|| anyhow::anyhow!("malformed HTTP header"))?;
            let value = value.trim();
            if name.eq_ignore_ascii_case("content-length") {
                let length: usize = value.parse()?;
                anyhow::ensure!(
                    content_length.is_none_or(|previous| previous == length),
                    "conflicting HTTP content lengths"
                );
                content_length = Some(length);
            } else if name.eq_ignore_ascii_case("transfer-encoding") {
                anyhow::ensure!(
                    transfer_encoding.is_none(),
                    "duplicate HTTP transfer encoding"
                );
                transfer_encoding = Some(value);
            }
        }
        anyhow::ensure!(
            content_length.is_none() || transfer_encoding.is_none(),
            "ambiguous HTTP body framing"
        );
        let body_start = header_end + 4;
        let wire_body = &response[body_start..];
        let body = if let Some(encoding) = transfer_encoding {
            anyhow::ensure!(
                encoding.eq_ignore_ascii_case("chunked"),
                "unsupported HTTP transfer encoding"
            );
            decode_chunked_body(wire_body, MAX_HTTP_BODY_BYTES)?
        } else if let Some(length) = content_length {
            anyhow::ensure!(
                length <= MAX_HTTP_BODY_BYTES,
                "HTTP body exceeds size limit"
            );
            (wire_body.len() >= length).then(|| wire_body[..length].to_vec())
        } else if count == 0 {
            anyhow::ensure!(
                wire_body.len() <= MAX_HTTP_BODY_BYTES,
                "HTTP body exceeds size limit"
            );
            Some(wire_body.to_vec())
        } else {
            anyhow::ensure!(
                wire_body.len() <= MAX_HTTP_BODY_BYTES,
                "HTTP body exceeds size limit"
            );
            None
        };
        if let Some(body) = body {
            let body = String::from_utf8(body)?;
            anyhow::ensure!(
                std::time::Instant::now() <= deadline,
                "HTTP response timed out"
            );
            return Ok(HttpResponse { status_code, body });
        }
        anyhow::ensure!(count != 0, "malformed HTTP response: incomplete body");
    }
}

/// Like `sync_http_get` but with a configurable timeout.
fn sync_http_get_with_timeout(
    port: u16,
    path: &str,
    query: String,
    timeout: Duration,
) -> anyhow::Result<String> {
    let response = sync_http_response_with_timeout(port, path, query, timeout)?;
    if !(200..=299).contains(&response.status_code) {
        anyhow::bail!("HTTP {} from {path}", response.status_code);
    }
    Ok(response.body)
}

fn classify_enrichment_response(response: HttpResponse) -> EnrichmentHttpResult {
    match response.status_code {
        200..=299 => EnrichmentHttpResult::Success(response.body),
        409 => EnrichmentHttpResult::RootConflict,
        503 => EnrichmentHttpResult::IndexNotReady,
        status_code => EnrichmentHttpResult::HttpFailure(status_code),
    }
}

fn sync_enrichment_http_get_with_timeout(
    port: u16,
    path: &str,
    query: String,
    timeout: Duration,
) -> EnrichmentHttpResult {
    match sync_http_response_with_timeout(port, path, query, timeout) {
        Ok(response) => classify_enrichment_response(response),
        Err(_) => EnrichmentHttpResult::Unavailable,
    }
}

/// Decode a complete chunked body, including its terminating chunk and trailers.
/// An incomplete frame needs more bytes; a malformed frame fails the request.
fn decode_chunked_body(raw: &[u8], max_body_bytes: usize) -> anyhow::Result<Option<Vec<u8>>> {
    let mut body = Vec::new();
    let mut position = 0;
    loop {
        let Some(line_end) = raw[position..]
            .windows(2)
            .position(|bytes| bytes == b"\r\n")
        else {
            return Ok(None);
        };
        let size_line = &raw[position..position + line_end];
        let size_text = std::str::from_utf8(size_line.split(|byte| *byte == b';').next().unwrap())?;
        let size = usize::from_str_radix(size_text.trim(), 16)?;
        position += line_end + 2;
        if size == 0 {
            // An empty trailer is CRLF; named trailers end with an empty line.
            let trailer = &raw[position..];
            if trailer.starts_with(b"\r\n") || trailer.windows(4).any(|bytes| bytes == b"\r\n\r\n")
            {
                return Ok(Some(body));
            }
            return Ok(None);
        }
        anyhow::ensure!(
            size <= max_body_bytes - body.len(),
            "HTTP body exceeds size limit"
        );
        let Some(data_end) = position.checked_add(size) else {
            anyhow::bail!("HTTP chunk size overflow");
        };
        let Some(frame_end) = data_end.checked_add(2) else {
            anyhow::bail!("HTTP chunk size overflow");
        };
        if raw.len() < frame_end {
            return Ok(None);
        }
        anyhow::ensure!(&raw[data_end..frame_end] == b"\r\n", "malformed HTTP chunk");
        body.extend_from_slice(&raw[position..data_end]);
        position = frame_end;
    }
}

// ---------------------------------------------------------------------------
// Enhanced diagnostics (Gap 1)
// ---------------------------------------------------------------------------

/// Structured detail for a fail-open adoption row: why the hook did not route
/// (SF-ADOPT-02), so `health` can break fail-open down by cause.
struct HookOutcomeDetail<'a> {
    reason: &'a str,
    searched_path: Option<&'a str>,
    suggestion: Option<&'a str>,
    project_root: &'a str,
}

/// Check whether verbose hook diagnostics are enabled.
///
/// Set `SYMFORGE_HOOK_VERBOSE=1` to enable detailed stderr output from the hook.
fn is_hook_verbose() -> bool {
    std::env::var("SYMFORGE_HOOK_VERBOSE").is_ok_and(|v| v == "1")
}

/// Marker file path for the one-time sidecar hint (HOOK-03).
const HOOK_HINT_MARKER: &str = "hook-hint-shown";

/// Freshness window for the sidecar hint marker file (30 minutes).
const HOOK_HINT_FRESHNESS: Duration = Duration::from_secs(30 * 60);

/// CLI invocation advertised by the sidecar hint to set up MCP integration.
///
/// Must remain a valid `symforge` subcommand (asserted in tests). The earlier
/// `symforge --stdio` form was never a valid flag — clap rejected it with
/// exit 2 — so first-run users following the hint hit an immediate error.
const SIDECAR_HINT_COMMAND: &str = "symforge init";

/// Emit a one-time hint to stderr when the sidecar is not running (HOOK-03).
///
/// Uses a marker file (`.symforge/hook-hint-shown`) to avoid repeating the hint
/// within a 30-minute window. The hint is written to stderr regardless of
/// `SYMFORGE_HOOK_VERBOSE` — it is specifically a user-facing one-time hint.
///
/// All I/O failures are silently ignored to preserve fail-open behavior.
fn maybe_emit_sidecar_hint(control_state_dir: Option<&ControlStateDir>) {
    let Some(control_state_dir) = control_state_dir else {
        return;
    };
    let marker_path = crate::paths::control_state_path(control_state_dir, HOOK_HINT_MARKER);

    // Check if the marker file is fresh (modified within the last 30 minutes).
    if let Ok(metadata) = std::fs::metadata(&marker_path)
        && let Ok(modified) = metadata.modified()
        && let Ok(elapsed) = modified.elapsed()
        && elapsed < HOOK_HINT_FRESHNESS
    {
        // Hint was shown recently — skip.
        return;
    }

    // Write the hint to stderr.
    eprintln!("[symforge-hook] SymForge sidecar is not running. To enable rich context:");
    eprintln!(
        "[symforge-hook]   \u{2022} Configure SymForge as an MCP server in your editor settings"
    );
    eprintln!("[symforge-hook]   \u{2022} Or run: {SIDECAR_HINT_COMMAND}");
    eprintln!("[symforge-hook] (This hint appears once per session)");

    // Touch / create the marker file so we don't repeat within 30 minutes.
    if let Some(parent) = marker_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(&marker_path, "");
}

/// Emit a diagnostic message to stderr explaining why the hook is failing open.
///
/// This helps users who run hooks manually understand what's missing and how
/// to fix it. The message is written to stderr so it doesn't interfere with
/// the JSON output on stdout.
///
/// Gated behind `SYMFORGE_HOOK_VERBOSE=1` (HOOK-02).
fn emit_no_sidecar_diagnostic(repo_root: &Path, port_file_path: &Path) {
    if !is_hook_verbose() {
        return;
    }

    let daemon_status = if crate::daemon::read_daemon_port_file().is_ok() {
        "SymForge daemon is running but has no active session for this project."
    } else {
        "SymForge daemon is not running."
    };

    eprintln!(
        "[symforge-hook] sidecar not running. No matching control-state descriptor for {}.",
        repo_root.display()
    );
    eprintln!("[symforge-hook]   Searched: {}", port_file_path.display());
    eprintln!("[symforge-hook]   {daemon_status}");
    eprintln!(
        "[symforge-hook]   To start: run 'symforge' as an MCP server, or start a Claude/Codex session with SymForge configured."
    );
    eprintln!("[symforge-hook]   Hook falling back to pass-through mode.");
}

/// Record a hook outcome with optional structured detail for the adoption log.
fn record_hook_outcome_with_detail(
    workflow: HookWorkflow,
    outcome: HookOutcome,
    session_id: Option<&str>,
    lifetime: Option<&str>,
    detail: Option<HookOutcomeDetail<'_>>,
) {
    let Some(control_state_dir) = process_control_state_dir() else {
        return;
    };
    record_hook_outcome_at(
        &control_state_dir,
        workflow,
        outcome,
        session_id,
        lifetime,
        detail.as_ref(),
    );
}

/// Rotate the adoption log at this size so `health` never re-reads an
/// unbounded file. ponytail: one `.1` generation; rows older than that drop.
const ADOPTION_LOG_MAX_BYTES: u64 = 4 * 1024 * 1024;

/// Build one adoption row, newline included.
///
/// Format (tab-separated; columns after the third are `key=value`, so the
/// loader reads them in any order and ignores unknown keys):
///   session \t workflow \t outcome \t lifetime=X [\t reason=X [\t searched_path=X]
///   [\t suggestion=X] \t project_root=X]
fn adoption_row(
    session_id: Option<&str>,
    lifetime: Option<&str>,
    workflow_name: &str,
    outcome_label: &str,
    detail: Option<&HookOutcomeDetail<'_>>,
) -> String {
    let session = session_id
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .unwrap_or("-");
    let lifetime = lifetime.unwrap_or("-");
    let mut row = format!("{session}\t{workflow_name}\t{outcome_label}\tlifetime={lifetime}");
    if let Some(d) = detail {
        row.push_str(&format!("\treason={}", d.reason));
        if let Some(path) = d.searched_path {
            row.push_str(&format!("\tsearched_path={path}"));
        }
        if let Some(suggestion) = d.suggestion {
            row.push_str(&format!("\tsuggestion={suggestion}"));
        }
        row.push_str(&format!("\tproject_root={}", d.project_root));
    }
    row.push('\n');
    row
}

/// Append one whole row with a single `write_all` on an append-mode handle,
/// so concurrent hook processes cannot interleave partial rows.
fn append_adoption_row(log_path: &Path, row: &str) -> std::io::Result<()> {
    if let Some(parent) = log_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    rotate_adoption_log_if_full(log_path);
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_path)?;
    file.write_all(row.as_bytes())
}

/// A rotation lock older than this is left by a crashed rotator and broken.
const ADOPTION_LOG_ROTATE_LOCK_STALE: Duration = Duration::from_secs(30);

/// Rotate the log to `.1` once it reaches the cap, with a single winner: the
/// rotator holds an exclusive `create_new` lock file, re-checks the size under
/// it (a rotation that already won leaves a small live file, so a second
/// rename that would replace the fresh `.1` never happens), and losers just
/// append. ponytail: two processes breaking the same stale lock at the same
/// instant can still both rotate; that needs a crash plus exact contention.
fn rotate_adoption_log_if_full(log_path: &Path) {
    let is_full = |path: &Path| {
        std::fs::metadata(path).is_ok_and(|meta| meta.len() >= ADOPTION_LOG_MAX_BYTES)
    };
    if !is_full(log_path) {
        return;
    }
    let lock_path = log_path.with_extension("log.rotate-lock");
    let acquire = || {
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&lock_path)
    };
    let lock = match acquire() {
        Ok(lock) => lock,
        Err(_) => {
            let stale = std::fs::metadata(&lock_path)
                .and_then(|meta| meta.modified())
                .ok()
                .and_then(|modified| modified.elapsed().ok())
                .is_some_and(|age| age >= ADOPTION_LOG_ROTATE_LOCK_STALE);
            if !stale {
                return;
            }
            let _ = std::fs::remove_file(&lock_path);
            match acquire() {
                Ok(lock) => lock,
                Err(_) => return,
            }
        }
    };
    if is_full(log_path) {
        let _ = std::fs::rename(log_path, rotated_adoption_log_path(log_path));
    }
    drop(lock);
    let _ = std::fs::remove_file(&lock_path);
}

/// The single rotated generation of the adoption log (`hook-adoption.log.1`).
fn rotated_adoption_log_path(log_path: &Path) -> PathBuf {
    log_path.with_extension("log.1")
}

#[cfg(test)]
fn append_hook_adoption_event_with_detail(
    log_path: &Path,
    session_id: Option<&str>,
    workflow_name: &str,
    outcome_label: &str,
    detail: Option<HookOutcomeDetail<'_>>,
) -> std::io::Result<()> {
    let row = adoption_row(
        session_id,
        None,
        workflow_name,
        outcome_label,
        detail.as_ref(),
    );
    append_adoption_row(log_path, &row)
}

#[cfg(test)]
fn append_hook_adoption_event(
    log_path: &Path,
    session_id: Option<&str>,
    workflow_name: &str,
    outcome_label: &str,
) -> std::io::Result<()> {
    append_adoption_row(
        log_path,
        &adoption_row(session_id, None, workflow_name, outcome_label, None),
    )
}

fn adoption_log_path(control_state_dir: &ControlStateDir) -> PathBuf {
    crate::paths::control_state_path(control_state_dir, ADOPTION_LOG_FILE)
}

/// Tally adoption rows. `session_filter` and `lifetime_filter` each, when
/// set, keep only rows whose session column / `lifetime=` column equals it;
/// rows written before the lifetime column existed never match a lifetime.
fn load_hook_adoption_snapshot_from_path(
    log_path: &Path,
    session_filter: Option<&str>,
    lifetime_filter: Option<&str>,
) -> std::io::Result<HookAdoptionSnapshot> {
    // Read the rotated generation first (older rows) so a lifetime that
    // straddles the rotation keeps its whole tally and its first repo start.
    let rotated = std::fs::read_to_string(rotated_adoption_log_path(log_path)).unwrap_or_default();
    let live = std::fs::read_to_string(log_path).unwrap_or_default();
    let contents = rotated + &live;

    let mut snapshot = HookAdoptionSnapshot::default();
    for line in contents.lines() {
        let mut parts = line.split('\t');
        let Some(session_id) = parts.next() else {
            continue;
        };
        let Some(workflow_raw) = parts.next() else {
            continue;
        };
        let Some(outcome_raw) = parts.next() else {
            continue;
        };
        let mut lifetime = None;
        let mut reason = None;
        for column in parts {
            if let Some(value) = column.strip_prefix("lifetime=") {
                lifetime = Some(value);
            } else if let Some(value) = column.strip_prefix("reason=") {
                reason = Some(value);
            }
        }

        // Rows explicitly written without a provable lifetime (a daemon
        // fallback through another session, or no descriptor) cannot be
        // attributed to the scoped lifetime. They are counted across the
        // whole log, before any session filter, and reported as such.
        if lifetime_filter.is_some() && lifetime == Some("-") {
            snapshot.unscoped_rows += 1;
            continue;
        }
        if let Some(filter) = session_filter
            && session_id != filter
        {
            continue;
        }
        if let Some(filter) = lifetime_filter
            && lifetime != Some(filter)
        {
            continue;
        }

        let Some(workflow) = parse_tracked_workflow(workflow_raw) else {
            continue;
        };
        let Some(outcome) = HookOutcome::parse(outcome_raw) else {
            continue;
        };

        if workflow == HookWorkflow::RepoStart && snapshot.first_repo_start.is_none() {
            snapshot.first_repo_start = Some(outcome);
        }
        if let Some(counts) = snapshot.counts_mut(workflow) {
            counts.record(outcome);
            if matches!(outcome, HookOutcome::NoSidecar | HookOutcome::SidecarError) {
                let reason = reason.unwrap_or("unrecorded").to_string();
                *snapshot.fail_open_reasons.entry(reason).or_default() += 1;
            }
        }
    }

    Ok(snapshot)
}

pub(crate) fn load_hook_adoption_snapshot(repo_root: Option<&Path>) -> HookAdoptionSnapshot {
    let Some(control_state_dir) = process_control_state_dir() else {
        return HookAdoptionSnapshot::default();
    };
    load_hook_adoption_snapshot_at(&control_state_dir, repo_root)
}

fn load_hook_adoption_snapshot_at(
    control_state_dir: &ControlStateDir,
    repo_root: Option<&Path>,
) -> HookAdoptionSnapshot {
    // SF-ADOPT-03: count only the resolved sidecar lifetime. Without a
    // descriptor that proves one, report the session as unknown instead of
    // tallying every row in the log.
    let identity = crate::sidecar::port_file::read_sidecar_endpoint_identity(
        control_state_dir,
        "127.0.0.1",
        repo_root,
    )
    .ok();
    let Some((session, lifetime)) = identity.and_then(|identity| {
        let lifetime = adoption_lifetime_label(&identity)?;
        let session = normalize_session_id(identity.session_id).unwrap_or_else(|| "-".to_string());
        Some((session, lifetime))
    }) else {
        return HookAdoptionSnapshot {
            session_unknown: true,
            ..HookAdoptionSnapshot::default()
        };
    };
    let mut snapshot = load_hook_adoption_snapshot_from_path(
        &adoption_log_path(control_state_dir),
        Some(&session),
        Some(&lifetime),
    )
    .unwrap_or_default();
    snapshot.scope = Some(format!("session {session}, {lifetime}"));
    snapshot
}

/// Make a synchronous enrichment GET to `127.0.0.1:{port}{path}?{query}`.
///
/// Uses a raw `TcpStream` (no HTTP client crate) so there is no async runtime
/// and the startup cost is near zero. A 503 is kept distinct from transport
/// failure so an index-loading refusal is not reported as a dead sidecar.
fn sync_enrichment_http_get(port: u16, path: &str, query: String) -> EnrichmentHttpResult {
    sync_enrichment_http_get_with_timeout(port, path, query, HTTP_TIMEOUT)
}

/// Minimal percent-encoding for query parameter values.
///
/// Only encodes characters that are unsafe in a query string: space, `&`, `=`, `+`,
/// `%`, and non-ASCII bytes.  This is sufficient for file paths and symbol names.
fn url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' | b':' => {
                out.push(b as char)
            }
            b => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// Minimal JSON string escape — handles backslash, double-quote, and common
/// control characters.  Sufficient for embedding sidecar response bodies.
fn json_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use once_cell::sync::Lazy;
    use serde_json::Value;
    use std::sync::Mutex;
    use tempfile::TempDir;

    static HOOK_VERBOSE_ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    #[test]
    fn daemon_fallback_path_identity_treats_backslash_as_a_separator_only_on_windows() {
        let literal = r"/work/a\b";
        let nested = "/work/a/b";
        assert_ne!(
            normalize_path_text_for_match(literal, false),
            normalize_path_text_for_match(nested, false)
        );
        assert_eq!(
            normalize_path_text_for_match(literal, true),
            normalize_path_text_for_match(nested, true)
        );
    }

    #[cfg(unix)]
    #[test]
    fn daemon_fallback_path_matching_preserves_literal_backslash_components_on_unix() {
        let root = TempDir::new().expect("create hook path identity fixture");
        let literal = root.path().join(r"a\b");
        let nested = root.path().join("a").join("b");
        std::fs::create_dir_all(&literal).expect("create literal-backslash root");
        std::fs::create_dir_all(&nested).expect("create nested root");

        assert_ne!(
            normalize_path_for_match(&literal),
            normalize_path_for_match(&nested),
            "daemon fallback must not route a nested Unix root to a literal-backslash project"
        );
    }

    #[cfg(unix)]
    #[test]
    fn hook_authority_refuses_non_utf8_lossy_root_collisions() {
        use std::os::unix::ffi::OsStringExt;

        let native = PathBuf::from(std::ffi::OsString::from_vec(vec![b'a', 0xff, b'b']));
        let lossy = PathBuf::from("a\u{fffd}b");
        assert_eq!(native.to_string_lossy(), lossy.to_string_lossy());

        let foreign = DaemonProjectEntry {
            project_id: crate::daemon::project_key(&lossy),
            canonical_root: lossy.to_str().expect("UTF-8 root").to_string(),
            session_count: 1,
        };
        assert!(!daemon_project_matches_native_root(&foreign, &native));
        assert!(append_caller_root_for_path(String::new(), &native).is_none());
    }

    // --- fail_open_json ---

    #[test]
    fn test_fail_open_json_is_valid() {
        let json = fail_open_json("PostToolUse");
        let v: Value = serde_json::from_str(&json).expect("fail_open_json must produce valid JSON");

        let output = &v["hookSpecificOutput"];
        assert_eq!(output["hookEventName"], "PostToolUse");
        assert_eq!(output["additionalContext"], "");
    }

    #[test]
    fn test_fail_open_json_session_start_event_name() {
        let json = fail_open_json("SessionStart");
        let v: Value = serde_json::from_str(&json).expect("must be valid JSON");
        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "SessionStart");
    }

    // --- success_json ---

    #[test]
    fn test_success_json_is_valid() {
        let json = success_json("PostToolUse", "hello world");
        let v: Value = serde_json::from_str(&json).expect("success_json must produce valid JSON");

        let output = &v["hookSpecificOutput"];
        assert_eq!(output["hookEventName"], "PostToolUse");
        assert_eq!(output["additionalContext"], "hello world");
    }

    #[test]
    fn test_success_json_escapes_special_chars() {
        let context = r#"{"key":"value"}"#;
        let json = success_json("PostToolUse", context);
        // The outer JSON must parse correctly.
        let v: Value = serde_json::from_str(&json)
            .expect("success_json with embedded quotes must be valid JSON");
        // The additionalContext value is the escaped string, not a nested object.
        let ctx = v["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .expect("additionalContext must be a string");
        assert_eq!(ctx, context);
    }

    #[test]
    fn enrichment_response_keeps_live_refusals_distinct_from_transport_failure() {
        assert_eq!(
            classify_enrichment_response(HttpResponse {
                status_code: 503,
                body: "partial index data must not be injected".to_string(),
            }),
            EnrichmentHttpResult::IndexNotReady
        );
        assert_eq!(
            classify_enrichment_response(HttpResponse {
                status_code: 409,
                body: String::new(),
            }),
            EnrichmentHttpResult::RootConflict
        );
        assert_eq!(
            classify_enrichment_response(HttpResponse {
                status_code: 500,
                body: String::new(),
            }),
            EnrichmentHttpResult::HttpFailure(500)
        );
        assert_eq!(
            classify_enrichment_response(HttpResponse {
                status_code: 404,
                body: String::new(),
            }),
            EnrichmentHttpResult::HttpFailure(404)
        );
        assert_eq!(
            classify_enrichment_response(HttpResponse {
                status_code: 200,
                body: "trusted context".to_string(),
            }),
            EnrichmentHttpResult::Success("trusted context".to_string())
        );
    }

    fn fixture_http_response(response: Vec<u8>, hold_open: bool) -> anyhow::Result<HttpResponse> {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind fixture");
        let port = listener.local_addr().expect("fixture address").port();
        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("accept hook request");
            stream
                .set_read_timeout(Some(Duration::from_millis(200)))
                .expect("fixture request timeout");
            let mut request = Vec::new();
            let mut chunk = [0_u8; 1024];
            while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") {
                let count = stream.read(&mut chunk).expect("read hook request");
                assert!(count > 0, "complete hook request");
                request.extend_from_slice(&chunk[..count]);
            }
            stream.write_all(&response).expect("write fixture response");
            stream.flush().expect("flush complete response");
            if hold_open {
                std::thread::sleep(Duration::from_millis(200));
            } else {
                stream
                    .shutdown(std::net::Shutdown::Write)
                    .expect("finish fixture response");
                // Keep the read half alive until the hook consumes the FIN.
                let _ = stream.read(&mut chunk);
            }
        });
        let result = sync_http_response_with_timeout(
            port,
            "/v1/context",
            String::new(),
            Duration::from_millis(50),
        );
        server.join().expect("fixture server");
        result
    }

    #[test]
    fn framed_http_response_completes_before_connection_close() {
        let response = b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n";
        let result = fixture_http_response(response.to_vec(), true).expect("complete 503 frame");
        assert_eq!(
            classify_enrichment_response(result),
            EnrichmentHttpResult::IndexNotReady
        );
    }

    #[test]
    fn framed_http_body_preserves_crlf_blank_lines_and_utf8() {
        let body = "first\r\n\r\nživa\nlast";
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n{body}",
            body.len()
        );
        let result = fixture_http_response(response.into_bytes(), true).expect("complete body");
        assert_eq!(result.body, body);
    }

    #[test]
    fn framed_chunked_http_response_completes_before_connection_close() {
        let response =
            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: keep-alive\r\n\r\n5\r\nhello\r\n0\r\n\r\n";
        let result = fixture_http_response(response.to_vec(), true).expect("complete chunks");
        assert_eq!(result.body, "hello");
    }

    #[test]
    fn incomplete_framed_http_response_is_rejected() {
        let response = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhi";
        assert!(fixture_http_response(response.to_vec(), false).is_err());
        let response = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhi";
        assert!(fixture_http_response(response.to_vec(), false).is_err());
    }

    #[test]
    fn eof_delimited_http_response_preserves_body() {
        let response = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nhello\r\nworld";
        let result = fixture_http_response(response.to_vec(), false).expect("EOF body");
        assert_eq!(result.body, "hello\r\nworld");
    }

    #[test]
    fn unframed_open_http_response_respects_deadline() {
        let response = b"HTTP/1.1 200 OK\r\nConnection: keep-alive\r\n\r\npartial";
        assert!(fixture_http_response(response.to_vec(), true).is_err());
    }

    // --- parse_stdin_input ---

    #[test]
    fn test_parse_stdin_returns_default_on_empty() {
        // We cannot pipe into stdin in a unit test, but we can verify that
        // parsing an empty string returns Default (no panics).
        let result: HookInput = serde_json::from_str("").unwrap_or_default();
        assert!(result.tool_name.is_none());
        assert!(result.tool_input.is_none());
        assert!(result.cwd.is_none());
    }

    #[test]
    fn test_parse_stdin_deserializes_read_payload() {
        let json =
            r#"{"tool_name":"Read","tool_input":{"file_path":"/abs/src/foo.rs"},"cwd":"/abs"}"#;
        let result: HookInput = serde_json::from_str(json).unwrap_or_default();
        assert_eq!(result.tool_name.as_deref(), Some("Read"));
        assert_eq!(
            result
                .tool_input
                .as_ref()
                .and_then(|ti| ti.file_path.as_deref()),
            Some("/abs/src/foo.rs")
        );
        assert_eq!(result.cwd.as_deref(), Some("/abs"));
    }

    #[test]
    fn test_parse_stdin_deserializes_grep_payload() {
        let json = r#"{"tool_name":"Grep","tool_input":{"pattern":"TODO","path":"/abs/src"},"cwd":"/abs"}"#;
        let result: HookInput = serde_json::from_str(json).unwrap_or_default();
        assert_eq!(result.tool_name.as_deref(), Some("Grep"));
        let ti = result.tool_input.as_ref().unwrap();
        assert_eq!(ti.pattern.as_deref(), Some("TODO"));
        assert_eq!(ti.path.as_deref(), Some("/abs/src"));
    }

    #[test]
    fn test_parse_stdin_returns_default_on_invalid_json() {
        let result: HookInput = serde_json::from_str("not valid json").unwrap_or_default();
        assert!(result.tool_name.is_none());
    }

    // --- relative_path ---

    #[test]
    fn test_relative_path_strips_unix_cwd_prefix() {
        let rel = relative_path("/home/user/project/src/foo.rs", "/home/user/project");
        assert_eq!(rel, "src/foo.rs");
    }

    #[test]
    fn test_relative_path_strips_windows_cwd_prefix() {
        // Test that strip_prefix works for Windows-style paths.
        // Path::strip_prefix is platform-aware, but we test the string normalization.
        // On Windows the actual separator is backslash; strip_prefix handles it.
        // We simulate by using a path that has a clear prefix relationship.
        let rel = relative_path("C:/Users/dev/project/src/foo.rs", "C:/Users/dev/project");
        // After strip_prefix the result should use forward slashes.
        assert!(
            rel.contains("src/foo.rs") || rel == "C:/Users/dev/project/src/foo.rs",
            "got: {rel}"
        );
    }

    #[test]
    fn test_relative_path_unchanged_when_no_prefix_match() {
        let rel = relative_path("/unrelated/path.rs", "/home/user/project");
        assert_eq!(rel, "/unrelated/path.rs");
    }

    #[test]
    #[cfg(windows)]
    fn test_relative_path_normalizes_backslashes() {
        // Simulate a Windows-style result from strip_prefix.
        // Since we're on MSYS/Windows the path may use backslashes.
        let rel = relative_path(
            "C:\\Users\\dev\\project\\src\\foo.rs",
            "C:\\Users\\dev\\project",
        );
        // Must not contain backslashes in result.
        assert!(
            !rel.contains('\\'),
            "backslashes must be normalized to forward slashes; got: {rel}"
        );
    }

    // --- endpoint_for (stdin-routing) ---

    #[test]
    fn test_endpoint_for_read_stdin_routes_to_outline() {
        let input = make_input("Read", Some("/abs/src/foo.rs"), None, "/abs");
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::Read), &input).expect("routed endpoint");
        assert_eq!(path, "/outline");
        assert!(
            query.contains("src/foo.rs"),
            "query must include relative path; got: {query}"
        );
    }

    #[test]
    fn test_endpoint_for_edit_stdin_routes_to_impact() {
        let input = make_input("Edit", Some("/abs/src/bar.rs"), None, "/abs");
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::Edit), &input).expect("routed endpoint");
        assert_eq!(path, "/impact");
        assert!(
            query.contains("src/bar.rs"),
            "query must include relative path; got: {query}"
        );
    }

    #[test]
    fn test_endpoint_for_write_routes_to_impact_with_new_file() {
        let input = make_input("Write", Some("/abs/src/new.rs"), None, "/abs");
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::Write), &input).expect("routed endpoint");
        assert_eq!(path, "/impact");
        assert!(
            query.contains("new_file=true"),
            "Write must set new_file=true; got: {query}"
        );
        assert!(
            query.contains("src/new.rs"),
            "Write must include file path; got: {query}"
        );
    }

    #[test]
    fn test_endpoint_for_grep_stdin_routes_to_symbol_context() {
        let json = r#"{"tool_name":"Grep","tool_input":{"pattern":"TODO","path":"/abs/src"},"cwd":"/abs"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap_or_default();
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::Grep), &input).expect("routed endpoint");
        assert_eq!(path, "/symbol-context");
        assert!(
            query.contains("TODO"),
            "Grep query must include pattern; got: {query}"
        );
    }

    #[test]
    fn test_endpoint_for_grep_regex_pattern_fails_open() {
        // Dogfood #8: regex / multi-token grep patterns are not symbol names —
        // forwarding them guarantees a zero-hit report in prompt context.
        for pattern in [
            "compact|SYMFORGE_SURFACE",
            "Tip:",
            "fn .*_handler",
            "two words",
            "foo.bar",
            "^anchor",
        ] {
            let json = format!(
                r#"{{"tool_name":"Grep","tool_input":{{"pattern":"{pattern}"}},"cwd":"/abs"}}"#
            );
            let input: HookInput = serde_json::from_str(&json).unwrap_or_default();
            assert_eq!(
                endpoint_for(Some(&HookSubcommand::Grep), &input),
                None,
                "pattern {pattern:?} must skip enrichment, not route to /health"
            );
        }
        // Bare identifiers still get the lookup.
        for pattern in ["classify_admission", "TODO", "_private", "Vec2d"] {
            let json = format!(
                r#"{{"tool_name":"Grep","tool_input":{{"pattern":"{pattern}"}},"cwd":"/abs"}}"#
            );
            let input: HookInput = serde_json::from_str(&json).unwrap_or_default();
            let (path, _) =
                endpoint_for(Some(&HookSubcommand::Grep), &input).expect("routed endpoint");
            assert_eq!(
                path, "/symbol-context",
                "pattern {pattern:?} is a plausible symbol"
            );
        }
    }

    #[test]
    fn test_endpoint_for_session_start_routes_to_repo_map() {
        let input = HookInput::default();
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::SessionStart), &input).expect("routed endpoint");
        assert_eq!(path, "/repo-map");
        assert!(query.is_empty(), "repo-map has no query params");
    }

    #[test]
    fn test_endpoint_for_prompt_submit_routes_to_prompt_context() {
        let input = HookInput {
            prompt: Some("please inspect src/foo.rs".to_string()),
            ..HookInput::default()
        };
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::PromptSubmit), &input).expect("routed endpoint");
        assert_eq!(path, "/prompt-context");
        assert!(
            query.contains("please%20inspect%20src/foo.rs"),
            "prompt query must be URL-encoded; got: {query}"
        );
    }

    #[test]
    fn test_proxy_path_uses_daemon_session_namespace_when_present() {
        let path = proxy_path("/repo-map", Some("session-42"));
        assert_eq!(path, "/v1/sessions/session-42/sidecar/repo-map");
    }

    #[test]
    fn test_proxy_path_returns_base_path_without_session() {
        let path = proxy_path("/repo-map", None);
        assert_eq!(path, "/repo-map");
    }

    #[test]
    fn test_endpoint_for_unknown_tool_returns_fail_open() {
        // None subcommand with unknown/missing tool_name → fail-open /health endpoint
        let input = HookInput {
            tool_name: Some("UnknownTool".to_string()),
            ..Default::default()
        };
        // Unknown tool → explicit skip; no /health request is made.
        assert_eq!(endpoint_for(None, &input), None);
    }

    // --- event_name_for ---

    #[test]
    fn test_event_name_for_session_start() {
        assert_eq!(
            event_name_for(&HookSubcommand::SessionStart),
            "SessionStart"
        );
    }

    #[test]
    fn test_event_name_for_prompt_submit() {
        assert_eq!(
            event_name_for(&HookSubcommand::PromptSubmit),
            "UserPromptSubmit"
        );
    }

    #[test]
    fn test_event_name_for_post_tool_use_variants() {
        for sub in [
            HookSubcommand::Read,
            HookSubcommand::Edit,
            HookSubcommand::Write,
            HookSubcommand::Grep,
        ] {
            assert_eq!(
                event_name_for(&sub),
                "PostToolUse",
                "Read/Edit/Write/Grep must produce PostToolUse event name"
            );
        }
    }

    // --- explicit subcommand routing remains available ---

    #[test]
    fn test_hook_subcommand_to_endpoint_read_backward_compat() {
        let input = HookInput::default();
        let (path, _query) =
            endpoint_for(Some(&HookSubcommand::Read), &input).expect("routed endpoint");
        assert_eq!(path, "/outline");
    }

    #[test]
    fn test_hook_subcommand_to_endpoint_edit_backward_compat() {
        let input = HookInput::default();
        let (path, _query) =
            endpoint_for(Some(&HookSubcommand::Edit), &input).expect("routed endpoint");
        assert_eq!(path, "/impact");
    }

    #[test]
    fn test_hook_subcommand_to_endpoint_grep_backward_compat() {
        // Empty pattern skips enrichment (dogfood #8, SF-TE-09): with nothing
        // to look up, /symbol-context could only produce a zero-hit report.
        let input = HookInput::default();
        assert_eq!(endpoint_for(Some(&HookSubcommand::Grep), &input), None);
    }

    #[test]
    fn test_hook_subcommand_to_endpoint_session_start_backward_compat() {
        let input = HookInput::default();
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::SessionStart), &input).expect("routed endpoint");
        assert_eq!(path, "/repo-map");
        assert!(query.is_empty(), "repo-map has no query params");
    }

    #[test]
    fn test_hook_subcommand_to_endpoint_prompt_submit_backward_compat() {
        let input = HookInput {
            prompt: Some("review MinioService".to_string()),
            ..HookInput::default()
        };
        let (path, query) =
            endpoint_for(Some(&HookSubcommand::PromptSubmit), &input).expect("routed endpoint");
        assert_eq!(path, "/prompt-context");
        assert!(query.contains("review%20MinioService"));
    }

    // --- resolve_subcommand_from_input ---

    #[test]
    fn test_resolve_subcommand_read() {
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            ..Default::default()
        };
        assert!(matches!(
            resolve_subcommand_from_input(&input),
            Some(HookSubcommand::Read)
        ));
    }

    #[test]
    fn test_resolve_subcommand_write() {
        let input = HookInput {
            tool_name: Some("Write".to_string()),
            ..Default::default()
        };
        assert!(matches!(
            resolve_subcommand_from_input(&input),
            Some(HookSubcommand::Write)
        ));
    }

    #[test]
    fn test_resolve_subcommand_unknown_returns_none() {
        let input = HookInput {
            tool_name: Some("Bash".to_string()),
            ..Default::default()
        };
        assert!(resolve_subcommand_from_input(&input).is_none());
    }

    // --- helpers ---

    // --- pre_tool_suggestion ---

    #[test]
    fn test_pre_tool_suggestion_grep_suggests_search_text() {
        let input = HookInput {
            tool_name: Some("Grep".to_string()),
            tool_input: Some(HookToolInput {
                pattern: Some("helper".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(s.contains("search_text"), "should suggest search_text: {s}");
        assert!(
            s.contains("helper"),
            "should include the query in the hint: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_read_source_suggests_get_file_context() {
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            tool_input: Some(HookToolInput {
                file_path: Some("/repo/src/main.rs".to_string()),
                ..Default::default()
            }),
            cwd: Some("/repo".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.contains("get_file_context"),
            "should suggest get_file_context for source: {s}"
        );
        assert!(
            s.contains("src/main.rs"),
            "should include the path hint: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_read_markdown_is_empty() {
        // PR 2 keeps docs/config conservative at hook time.
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            tool_input: Some(HookToolInput {
                file_path: Some("docs/README.md".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.is_empty(),
            "should stay pass-through for markdown reads: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_read_csv_is_empty() {
        // CSV is still non-source — should not suggest
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            tool_input: Some(HookToolInput {
                file_path: Some("data/export.csv".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(s.is_empty(), "should not suggest for .csv files: {s}");
    }

    #[test]
    fn test_pre_tool_suggestion_glob_suggests_search_files() {
        let input = HookInput {
            tool_name: Some("Glob".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.contains("search_files"),
            "should suggest search_files: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_edit_suggests_replace_symbol_body() {
        let input = HookInput {
            tool_name: Some("Edit".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.contains("replace_symbol_body"),
            "should suggest replace_symbol_body: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_read_outside_workspace_is_empty() {
        // B5: Read of a %TEMP%-style path outside the repo root must not hint —
        // get_file_context cannot serve paths outside every indexed root.
        let temp_target = std::env::temp_dir()
            .join("claude")
            .join("tasks")
            .join("1.output");
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            tool_input: Some(HookToolInput {
                file_path: Some(temp_target.to_string_lossy().into_owned()),
                ..Default::default()
            }),
            cwd: Some("/repo".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(s.is_empty(), "should not hint outside the workspace: {s}");
    }

    #[test]
    fn test_pre_tool_suggestion_read_in_repo_absolute_still_hints() {
        // In-repo absolute path under cwd keeps the hint. Use a real absolute
        // path so the check is exercised on every platform.
        let cwd = std::env::current_dir().unwrap();
        let target = cwd.join("src").join("main.rs");
        let input = HookInput {
            tool_name: Some("Read".to_string()),
            tool_input: Some(HookToolInput {
                file_path: Some(target.to_string_lossy().into_owned()),
                ..Default::default()
            }),
            cwd: Some(cwd.to_string_lossy().into_owned()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.contains("get_file_context"),
            "in-repo absolute read should still hint: {s}"
        );
    }

    #[test]
    fn test_pre_tool_suggestion_grep_outside_workspace_is_empty() {
        // B5: Grep scoped to a directory outside the repo root must not hint.
        let temp_dir = std::env::temp_dir().join("scratch");
        let input = HookInput {
            tool_name: Some("Grep".to_string()),
            tool_input: Some(HookToolInput {
                pattern: Some("helper".to_string()),
                path: Some(temp_dir.to_string_lossy().into_owned()),
                ..Default::default()
            }),
            cwd: Some("/repo".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(
            s.is_empty(),
            "should not hint for grep outside the workspace: {s}"
        );
    }

    #[test]
    fn test_pre_tool_workflow_classifies_source_read() {
        let input = make_input("Read", Some("/repo/src/lib.rs"), None, "/repo");
        assert_eq!(pre_tool_workflow(&input), HookWorkflow::SourceRead);
    }

    #[test]
    fn test_pre_tool_workflow_leaves_non_source_read_as_passthrough() {
        let input = make_input("Read", Some("/repo/docs/guide.md"), None, "/repo");
        assert_eq!(pre_tool_workflow(&input), HookWorkflow::PassThrough);
    }

    #[test]
    fn test_workflow_for_subcommand_leaves_non_source_read_as_passthrough() {
        let input = make_input("Read", Some("/repo/docs/guide.md"), None, "/repo");
        assert_eq!(
            workflow_for_subcommand(Some(&HookSubcommand::Read), &input),
            HookWorkflow::PassThrough
        );
    }

    #[test]
    fn test_workflow_for_subcommand_leaves_config_read_as_passthrough() {
        let input = make_input("Read", Some("/repo/Cargo.toml"), None, "/repo");
        assert_eq!(
            workflow_for_subcommand(Some(&HookSubcommand::Read), &input),
            HookWorkflow::PassThrough
        );
    }

    #[test]
    fn test_workflow_for_subcommand_classifies_repo_start() {
        let input = HookInput::default();
        assert_eq!(
            workflow_for_subcommand(Some(&HookSubcommand::SessionStart), &input),
            HookWorkflow::RepoStart
        );
    }

    #[test]
    fn test_workflow_for_subcommand_classifies_prompt_context() {
        let input = HookInput {
            prompt: Some("read src/lib.rs".to_string()),
            ..HookInput::default()
        };
        assert_eq!(
            workflow_for_subcommand(Some(&HookSubcommand::PromptSubmit), &input),
            HookWorkflow::PromptContext
        );
    }

    #[test]
    fn test_pre_tool_suggestion_unknown_tool_is_empty() {
        let input = HookInput {
            tool_name: Some("Bash".to_string()),
            ..Default::default()
        };
        let s = pre_tool_suggestion(&input);
        assert!(s.is_empty(), "should not suggest for unknown tools: {s}");
    }

    #[test]
    fn test_is_non_source_path_allows_config_files() {
        // These are not treated as broad non-source paths; literal-read routing
        // is decided separately by `should_fail_open_read`.
        assert!(!is_non_source_path("package.json"));
        assert!(!is_non_source_path("Cargo.toml"));
        assert!(!is_non_source_path("README.md"));
        assert!(!is_non_source_path(".env"));
        assert!(!is_non_source_path("config.yaml"));
        assert!(!is_non_source_path("docker-compose.yml"));
    }

    #[test]
    fn test_is_non_source_path_still_skips_non_config() {
        assert!(is_non_source_path("data.csv"));
        assert!(is_non_source_path("notes.txt"));
        assert!(is_non_source_path("icon.png"));
        assert!(is_non_source_path("Cargo.lock"));
    }

    #[test]
    fn test_is_non_source_path_allows_source_files() {
        assert!(!is_non_source_path("src/main.rs"));
        assert!(!is_non_source_path("tests/test_foo.py"));
        assert!(!is_non_source_path("lib/parser.js"));
    }

    #[test]
    fn test_is_non_source_path_never_skips_an_indexed_language() {
        // SF-DOG-05: an extension the index parses must reach the hook. `Text` is
        // the plaintext knowledge catch-all (`.txt`, `.ini`, `.xml`, ...), whose
        // reads are literal by design, so it is the one family excluded here.
        for language in crate::domain::LanguageId::ALL {
            if language == crate::domain::LanguageId::Text {
                continue;
            }
            for ext in language.extensions() {
                let path = format!("src/file.{ext}");
                assert!(
                    !is_non_source_path(&path),
                    "{language:?} extension .{ext} is indexed but classified non-source"
                );
            }
        }
    }

    #[test]
    fn test_load_hook_adoption_snapshot_filters_to_current_session() {
        let tmp = TempDir::new().unwrap();
        let control_state = ControlStateDir::new(tmp.path().join(".symforge"));
        let log_path = adoption_log_path(&control_state);

        crate::sidecar::port_file::write_session_descriptor(
            &control_state,
            41_321,
            Some("session-a"),
            Some(tmp.path()),
            None,
        )
        .unwrap();
        let lifetime = format!("pid:{}", std::process::id());
        let row = |session, workflow, outcome| {
            append_adoption_row(
                &log_path,
                &adoption_row(Some(session), Some(&lifetime), workflow, outcome, None),
            )
            .unwrap()
        };
        row("session-a", "source-read", "routed");
        row("session-a", "repo-start", "no-sidecar");
        row("session-b", "source-search", "routed");

        let snapshot = load_hook_adoption_snapshot_at(&control_state, Some(tmp.path()));
        assert_eq!(snapshot.source_read.routed, 1);
        assert_eq!(snapshot.source_search.routed, 0);
        assert_eq!(snapshot.repo_start.no_sidecar, 1);
        assert_eq!(snapshot.first_repo_start, Some(HookOutcome::NoSidecar));
    }

    #[test]
    fn test_load_hook_adoption_snapshot_tracks_sidecar_errors_and_totals() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");

        append_hook_adoption_event(
            &log_path,
            Some("session-z"),
            "prompt-context",
            "sidecar-error",
        )
        .unwrap();
        append_hook_adoption_event(&log_path, Some("session-z"), "post-edit-impact", "routed")
            .unwrap();
        append_hook_adoption_event(&log_path, Some("session-z"), "source-read", "no-sidecar")
            .unwrap();

        let snapshot =
            load_hook_adoption_snapshot_from_path(&log_path, Some("session-z"), None).unwrap();
        assert_eq!(snapshot.prompt_context.sidecar_error, 1);
        assert_eq!(snapshot.post_edit_impact.routed, 1);
        assert_eq!(snapshot.source_read.no_sidecar, 1);
        assert_eq!(snapshot.total_routed(), 1);
        assert_eq!(snapshot.total_fail_open(), 2);
        assert_eq!(snapshot.total_attempts(), 3);
    }

    #[test]
    fn test_adoption_loader_parses_extra_columns_and_tallies_reasons() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        std::fs::write(
            &log_path,
            "s\tsource-read\tsidecar-error\tlifetime=pid:7\tfuture=1\treason=index_not_ready\tproject_root=/r\n\
             s\tsource-read\tno-sidecar\n\
             s\tsource-read\trouted\tlifetime=pid:7\tunknown_key=x\n",
        )
        .unwrap();
        let snapshot = load_hook_adoption_snapshot_from_path(&log_path, Some("s"), None).unwrap();
        assert_eq!(snapshot.source_read.total(), 3);
        assert_eq!(snapshot.fail_open_reasons.get("index_not_ready"), Some(&1));
        assert_eq!(snapshot.fail_open_reasons.get("unrecorded"), Some(&1));
        // A lifetime filter excludes rows that predate the lifetime column.
        let scoped =
            load_hook_adoption_snapshot_from_path(&log_path, Some("s"), Some("pid:7")).unwrap();
        assert_eq!(scoped.source_read.total(), 2);
    }

    #[test]
    fn test_adoption_two_daemon_lifetimes_with_same_session_do_not_share_a_tally() {
        let tmp = TempDir::new().unwrap();
        let control_state = ControlStateDir::new(tmp.path().join(".symforge"));
        let log_path = adoption_log_path(&control_state);
        for (lifetime, outcome) in [
            ("daemon:100", "no-sidecar"),
            ("daemon:100", "no-sidecar"),
            ("daemon:200", "routed"),
        ] {
            let row = adoption_row(
                Some("session-1"),
                Some(lifetime),
                "source-read",
                outcome,
                None,
            );
            append_adoption_row(&log_path, &row).unwrap();
        }
        crate::sidecar::port_file::write_session_descriptor(
            &control_state,
            41_322,
            Some("session-1"),
            Some(tmp.path()),
            Some(200),
        )
        .unwrap();
        let snapshot = load_hook_adoption_snapshot_at(&control_state, Some(tmp.path()));
        assert!(!snapshot.session_unknown);
        assert_eq!(snapshot.source_read.routed, 1);
        assert_eq!(
            snapshot.source_read.no_sidecar, 0,
            "the earlier lifetime leaked in"
        );
        assert_eq!(
            snapshot.scope.as_deref(),
            Some("session session-1, daemon:200")
        );
    }

    #[test]
    fn test_adoption_loader_reads_rotated_generation_and_reports_unscoped_rows() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let row = |session, lifetime, outcome| {
            adoption_row(Some(session), lifetime, "source-read", outcome, None)
        };
        std::fs::write(
            rotated_adoption_log_path(&log_path),
            row("s", Some("pid:7"), "routed"),
        )
        .unwrap();
        append_adoption_row(&log_path, &row("s", Some("pid:7"), "no-sidecar")).unwrap();
        append_adoption_row(&log_path, &row("other", None, "daemon-fallback")).unwrap();
        let snapshot =
            load_hook_adoption_snapshot_from_path(&log_path, Some("s"), Some("pid:7")).unwrap();
        assert_eq!(snapshot.source_read.routed, 1, "rotated rows were dropped");
        assert_eq!(snapshot.source_read.no_sidecar, 1);
        assert_eq!(snapshot.unscoped_rows, 1);
        let rendered = crate::protocol::format::format_hook_adoption(&snapshot);
        assert!(
            rendered.contains("Rows with no recorded lifetime in the whole log: 1"),
            "unscoped rows must be reported: {rendered}"
        );
    }

    #[test]
    fn test_adoption_rotation_moves_log_to_dot_one_at_cap() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let filler = "x".repeat(ADOPTION_LOG_MAX_BYTES as usize);
        std::fs::write(&log_path, &filler).unwrap();
        append_adoption_row(&log_path, "s\tsource-read\trouted\tlifetime=pid:7\n").unwrap();
        assert_eq!(
            std::fs::read_to_string(rotated_adoption_log_path(&log_path)).unwrap(),
            filler
        );
        assert_eq!(
            std::fs::read_to_string(&log_path).unwrap(),
            "s\tsource-read\trouted\tlifetime=pid:7\n"
        );
    }

    #[test]
    fn test_adoption_concurrent_writers_crossing_the_cap_lose_no_rows() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        // One filler line leaves the log just under the cap, so the first
        // rows push it over while every writer is racing to rotate.
        let filler = format!("{}\n", "x".repeat(ADOPTION_LOG_MAX_BYTES as usize - 64));
        std::fs::write(&log_path, &filler).unwrap();
        const WRITERS: usize = 8;
        const ROWS: usize = 50;
        std::thread::scope(|scope| {
            for writer in 0..WRITERS {
                let log_path = &log_path;
                scope.spawn(move || {
                    for row in 0..ROWS {
                        let session = format!("w{writer}-{row}");
                        let line = adoption_row(
                            Some(&session),
                            Some("pid:1"),
                            "source-read",
                            "routed",
                            None,
                        );
                        append_adoption_row(log_path, &line).unwrap();
                    }
                });
            }
        });
        let rotated = std::fs::read_to_string(rotated_adoption_log_path(&log_path)).unwrap();
        let live = std::fs::read_to_string(&log_path).unwrap();
        assert!(
            rotated.starts_with(&filler),
            "the filled generation must be the rotated one"
        );
        let mut sessions: Vec<&str> = rotated
            .lines()
            .chain(live.lines())
            .filter(|line| line.contains('\t'))
            .map(|line| line.split('\t').next().unwrap())
            .collect();
        sessions.sort_unstable();
        sessions.dedup();
        assert_eq!(
            sessions.len(),
            WRITERS * ROWS,
            "rows were lost across live + .1"
        );
        assert!(!log_path.with_extension("log.rotate-lock").exists());
    }

    #[test]
    fn test_adoption_rotation_breaks_a_stale_lock_but_respects_a_fresh_one() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let lock_path = log_path.with_extension("log.rotate-lock");
        let filler = "x".repeat(ADOPTION_LOG_MAX_BYTES as usize);

        // A fresh lock means another rotator is at work: skip, just append.
        std::fs::write(&log_path, &filler).unwrap();
        std::fs::write(&lock_path, "").unwrap();
        append_adoption_row(&log_path, "a\tsource-read\trouted\n").unwrap();
        assert!(!rotated_adoption_log_path(&log_path).exists());

        // A lock left by a crashed rotator must not block rotation forever.
        let old = std::time::SystemTime::now() - ADOPTION_LOG_ROTATE_LOCK_STALE * 2;
        std::fs::File::options()
            .write(true)
            .open(&lock_path)
            .unwrap()
            .set_modified(old)
            .unwrap();
        append_adoption_row(&log_path, "b\tsource-read\trouted\n").unwrap();
        assert!(rotated_adoption_log_path(&log_path).exists());
        assert_eq!(
            std::fs::read_to_string(&log_path).unwrap(),
            "b\tsource-read\trouted\n"
        );
        assert!(!lock_path.exists());
    }

    #[test]
    fn test_adoption_unresolvable_session_yields_empty_unknown_tally() {
        let tmp = TempDir::new().unwrap();
        let control_state = ControlStateDir::new(tmp.path().join(".symforge"));
        let log_path = adoption_log_path(&control_state);
        append_hook_adoption_event(&log_path, Some("session-a"), "source-read", "routed").unwrap();
        append_hook_adoption_event(&log_path, None, "source-read", "no-sidecar").unwrap();
        let snapshot = load_hook_adoption_snapshot_at(&control_state, Some(tmp.path()));
        assert!(snapshot.session_unknown);
        assert_eq!(snapshot.total_attempts(), 0);
    }

    #[test]
    fn test_adoption_concurrent_writers_produce_no_torn_rows() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let long_root = "r".repeat(2_000);
        std::thread::scope(|scope| {
            for writer in 0..8 {
                let log_path = &log_path;
                let long_root = &long_root;
                scope.spawn(move || {
                    for _ in 0..50 {
                        let session = format!("w{writer}");
                        let detail = HookOutcomeDetail {
                            reason: "http_failure",
                            searched_path: None,
                            suggestion: None,
                            project_root: long_root,
                        };
                        let row = adoption_row(
                            Some(&session),
                            Some("pid:1"),
                            "source-read",
                            "sidecar-error",
                            Some(&detail),
                        );
                        append_adoption_row(log_path, &row).unwrap();
                    }
                });
            }
        });
        let contents = std::fs::read_to_string(&log_path).unwrap();
        let lines: Vec<&str> = contents.lines().collect();
        assert_eq!(lines.len(), 400);
        for line in lines {
            let columns: Vec<&str> = line.split('\t').collect();
            assert_eq!(columns.len(), 6, "torn row: {line:.80}");
            assert!(columns[0].starts_with('w'), "torn row: {line:.80}");
            assert_eq!(columns[5].len(), "project_root=".len() + 2_000);
        }
    }

    // ---- Hook-adoption metric regression tests ----
    //
    // These pin the user-visible contract documented in CONTEXT.md:
    // `health` output must render `Owned workflows routed: N/M (P%)` after
    // hooks fire, and must visibly degrade (or disappear) when they don't.
    //
    // Chain under test: record_hook_outcome → ADOPTION_LOG_FILE on disk →
    // load_hook_adoption_snapshot → format_hook_adoption. A regression at
    // any link drops the "2/2 (100%)" contract, and these tests fail loudly.
    //
    // Not covered here: whether `run_hook` still calls record_hook_outcome
    // at its dispatch sites. That wire-up is guarded by code review — see
    // src/cli/hook.rs::run_hook lines 307/350/378.

    #[test]
    fn test_health_hook_adoption_metric_pins_published_contract() {
        let tmp = TempDir::new().unwrap();
        let control = ControlStateDir::new(tmp.path().join("control"));
        let log_path = adoption_log_path(&control);

        // Two tracked workflows, both routed — mirrors the "2/2 (100%)"
        // contract shown in CONTEXT.md §Project rules.
        append_hook_adoption_event(&log_path, Some("sess-live"), "repo-start", "routed").unwrap();
        append_hook_adoption_event(&log_path, Some("sess-live"), "prompt-context", "routed")
            .unwrap();
        // adoption_log_path and load_hook_adoption_snapshot must agree on
        // where the log lives — pin that too.
        assert_eq!(adoption_log_path(&control), log_path);

        let snapshot = load_hook_adoption_snapshot_from_path(&log_path, Some("sess-live"), None)
            .expect("load adoption snapshot");
        assert_eq!(snapshot.total_routed(), 2);
        assert_eq!(snapshot.total_attempts(), 2);
        assert_eq!(snapshot.total_fail_open(), 0);

        let rendered = crate::protocol::format::format_hook_adoption(&snapshot);
        assert!(
            rendered.contains("── Hook Adoption ──"),
            "missing section header: {rendered}"
        );
        assert!(
            rendered.contains("Owned workflows routed: 2/2 (100%)"),
            "published contract string missing: {rendered}"
        );
        assert!(
            rendered.contains("Fail-open outcomes: 0"),
            "should show zero fail-open when all routed: {rendered}"
        );
        assert!(
            rendered.contains("Repo start: routed 1"),
            "missing per-workflow line for repo-start: {rendered}"
        );
        assert!(
            rendered.contains("Prompt context: routed 1"),
            "missing per-workflow line for prompt-context: {rendered}"
        );
        assert!(
            rendered.contains("First repo start: routed"),
            "first-repo-start outcome must render: {rendered}"
        );
    }

    #[test]
    fn test_health_hook_adoption_metric_flags_silent_failure_when_all_fail_open() {
        // Regression guard for the scenario CONTEXT.md warns about:
        // "a regression where hooks silently stop firing would drop this to
        // 0/2 or 1/2 and nothing automated would notice".
        let tmp = TempDir::new().unwrap();
        let control = ControlStateDir::new(tmp.path().join("control"));
        let log_path = adoption_log_path(&control);

        append_hook_adoption_event(&log_path, Some("sess-down"), "source-read", "no-sidecar")
            .unwrap();
        append_hook_adoption_event(&log_path, Some("sess-down"), "prompt-context", "no-sidecar")
            .unwrap();
        let snapshot = load_hook_adoption_snapshot_from_path(&log_path, Some("sess-down"), None)
            .expect("load adoption snapshot");
        let rendered = crate::protocol::format::format_hook_adoption(&snapshot);

        assert!(
            rendered.contains("Owned workflows routed: 0/2 (0%)"),
            "degraded metric must visibly read 0/2, not be absent: {rendered}"
        );
        assert!(
            rendered.contains("Fail-open outcomes: 2 (no sidecar 2"),
            "fail-open breakdown must surface the real cause: {rendered}"
        );
        assert!(
            rendered.contains("⚠ All hook attempts failed open"),
            "user-facing warning must render when no workflow routed: {rendered}"
        );
    }

    #[test]
    fn test_record_hook_outcome_writes_to_adoption_log_file_constant() {
        // Pins the wire-up between record_hook_outcome and the
        // ADOPTION_LOG_FILE path constant. A rename of either — or a
        // rewrite of record_hook_outcome that stops calling
        // append_hook_adoption_event — trips this test.
        let tmp = TempDir::new().unwrap();
        let control = ControlStateDir::new(tmp.path().join("control"));
        record_hook_outcome_at(
            &control,
            HookWorkflow::SourceRead,
            HookOutcome::Routed,
            Some("sess-wireup"),
            None,
            None,
        );

        let log_path = adoption_log_path(&control);
        assert!(
            log_path.exists(),
            "record_hook_outcome must create {ADOPTION_LOG_FILE} in control state; missing at {}",
            log_path.display()
        );
        let contents = std::fs::read_to_string(&log_path).expect("log readable");
        assert!(
            contents.contains("sess-wireup\tsource-read\trouted"),
            "log must contain the tab-separated routed event; got: {contents:?}"
        );
    }

    // ---- HOOK-02: is_hook_verbose ----

    #[allow(unsafe_code)] // test-only env mutation is serialized by HOOK_VERBOSE_ENV_LOCK.
    #[test]
    fn hook_verbose_returns_false_when_unset() {
        let _guard = HOOK_VERBOSE_ENV_LOCK.lock().unwrap();
        // SAFETY: test-only env manipulation; tests run with --test-threads=1.
        unsafe { std::env::remove_var("SYMFORGE_HOOK_VERBOSE") };
        assert!(!is_hook_verbose());
    }

    #[allow(unsafe_code)] // test-only env mutation is serialized by HOOK_VERBOSE_ENV_LOCK.
    #[test]
    fn hook_verbose_returns_true_when_set_to_1() {
        let _guard = HOOK_VERBOSE_ENV_LOCK.lock().unwrap();
        // SAFETY: test-only env manipulation; tests run with --test-threads=1.
        unsafe { std::env::set_var("SYMFORGE_HOOK_VERBOSE", "1") };
        let result = is_hook_verbose();
        unsafe { std::env::remove_var("SYMFORGE_HOOK_VERBOSE") };
        assert!(result);
    }

    #[allow(unsafe_code)] // test-only env mutation is serialized by HOOK_VERBOSE_ENV_LOCK.
    #[test]
    fn hook_verbose_returns_false_for_other_values() {
        let _guard = HOOK_VERBOSE_ENV_LOCK.lock().unwrap();
        for val in &["0", "true", "yes", "2", ""] {
            // SAFETY: test-only env manipulation; tests run with --test-threads=1.
            unsafe { std::env::set_var("SYMFORGE_HOOK_VERBOSE", val) };
            assert!(
                !is_hook_verbose(),
                "should be false for SYMFORGE_HOOK_VERBOSE={val}"
            );
        }
        unsafe { std::env::remove_var("SYMFORGE_HOOK_VERBOSE") };
    }

    // ---- HOOK-01: adoption log detail fields ----

    #[test]
    fn adoption_log_missing_port_includes_reason_and_project_root() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let detail = HookOutcomeDetail {
            reason: "sidecar_port_missing",
            searched_path: Some("/repo/.symforge/sidecar.port"),
            suggestion: Some("start_mcp_session"),
            project_root: "/repo",
        };
        append_hook_adoption_event_with_detail(
            &log_path,
            Some("sess-1"),
            "source-read",
            "no-sidecar",
            Some(detail),
        )
        .unwrap();
        let content = std::fs::read_to_string(&log_path).unwrap();
        assert!(
            content.contains("reason=sidecar_port_missing"),
            "missing reason field"
        );
        assert!(
            content.contains("project_root=/repo"),
            "missing project_root field"
        );
        assert!(content.contains("searched_path=/repo/.symforge/sidecar.port"));
        assert!(content.contains("suggestion=start_mcp_session"));
    }

    #[test]
    fn adoption_log_stale_port_has_distinct_reason() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        let detail = HookOutcomeDetail {
            reason: "sidecar_port_stale",
            searched_path: Some("/repo/.symforge/sidecar.port"),
            suggestion: Some("restart_sidecar"),
            project_root: "/repo",
        };
        append_hook_adoption_event_with_detail(
            &log_path,
            Some("sess-2"),
            "source-read",
            "no-sidecar",
            Some(detail),
        )
        .unwrap();
        let content = std::fs::read_to_string(&log_path).unwrap();
        assert!(
            content.contains("reason=sidecar_port_stale"),
            "should have stale reason"
        );
        assert!(content.contains("project_root=/repo"));
    }

    #[test]
    fn adoption_log_without_detail_has_no_reason_or_project_root() {
        let tmp = TempDir::new().unwrap();
        let log_path = tmp.path().join("hook-adoption.log");
        append_hook_adoption_event_with_detail(
            &log_path,
            Some("sess-3"),
            "source-read",
            "routed",
            None,
        )
        .unwrap();
        let content = std::fs::read_to_string(&log_path).unwrap();
        assert!(
            !content.contains("reason="),
            "should have no reason without detail"
        );
        assert!(
            !content.contains("project_root="),
            "should have no project_root without detail"
        );
    }

    // ---- HOOK-03: one-time sidecar hint ----

    #[test]
    fn sidecar_hint_creates_marker_file() {
        let tmp = TempDir::new().unwrap();
        let control = ControlStateDir::new(tmp.path().join("control"));
        let marker = crate::paths::control_state_path(&control, HOOK_HINT_MARKER);
        assert!(!marker.exists());
        maybe_emit_sidecar_hint(Some(&control));
        assert!(marker.exists(), "marker file should be created");
    }

    #[test]
    fn sidecar_hint_skips_when_marker_fresh() {
        let tmp = TempDir::new().unwrap();
        let control = ControlStateDir::new(tmp.path().join("control"));
        let marker = crate::paths::control_state_path(&control, HOOK_HINT_MARKER);
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "").unwrap();
        // Marker was just created — should be fresh.
        // We can't easily capture stderr in a unit test, but we can verify
        // the marker file's mtime is NOT updated (proving the function returned early).
        let mtime_before = std::fs::metadata(&marker).unwrap().modified().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        maybe_emit_sidecar_hint(Some(&control));
        let mtime_after = std::fs::metadata(&marker).unwrap().modified().unwrap();
        assert_eq!(
            mtime_before, mtime_after,
            "marker mtime should not change when fresh"
        );
    }

    /// SF-STRESS-020: the sidecar hint must advertise a command the binary
    /// actually accepts. The previous `symforge --stdio` form was rejected by
    /// clap with exit 2, so first-run users following the hint hit an error.
    #[test]
    fn sidecar_hint_command_parses_as_valid_cli_invocation() {
        use clap::Parser;
        let args: Vec<&str> = SIDECAR_HINT_COMMAND.split_whitespace().collect();
        assert_eq!(
            args.first().copied(),
            Some("symforge"),
            "hint command must invoke the symforge binary"
        );
        crate::cli::Cli::try_parse_from(args).unwrap_or_else(|e| {
            panic!("sidecar hint command `{SIDECAR_HINT_COMMAND}` must parse as a valid CLI invocation, got: {e}")
        });
    }

    // --- helpers ---

    fn make_input(
        tool_name: &str,
        file_path: Option<&str>,
        pattern: Option<&str>,
        cwd: &str,
    ) -> HookInput {
        HookInput {
            tool_name: Some(tool_name.to_string()),
            tool_input: Some(HookToolInput {
                file_path: file_path.map(|s| s.to_string()),
                pattern: pattern.map(|s| s.to_string()),
                path: None,
            }),
            cwd: Some(cwd.to_string()),
            prompt: None,
        }
    }
}