openlatch-client 0.5.2

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
//! Cline path resolution, and the test seam that keeps the suite off the
//! developer's real store.
//!
//! Verified against Cline tag v4.1.17. The sibling of
//! [`crate::hooks::claude_code`] and [`crate::hooks::codex_cli`] in shape, and
//! deliberately narrower in scope: this module owns **where Cline's three roots
//! are** and nothing else. There is no `AgentBinding` impl here, no `detect`,
//! and no arm in [`crate::hooks::binding::detect_all`] — detection arrives in a
//! later unit, on purpose. Arming it before these seams exist would point every
//! existing fixture at the developer's real `~/.cline`, which holds
//! `data/secrets.json` in plaintext at mode 0600.
//!
//! Nothing in `src/` consumes these resolvers yet. That is why they are `pub`
//! rather than private: CI runs `cargo clippy --all-targets --all-features --
//! -D warnings`, and a private module with no in-crate caller is `dead_code`.

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

use crate::core::path_compat::dedup_key;

/// Relocates Cline's **store** root — `rules/ workflows/ plugins/ skills/
/// agents/`.
///
/// Note the omission: Cline keeps a `hooks/` directory under this root *and* a
/// `Hooks/` directory under the user-asset root ([`asset_root`]), and they are
/// different directories. The VS Code lane — the only one in scope — discovers
/// hooks under the asset root, so that is where the later units key. Listing
/// `hooks/` here as well is how three units come to disagree about where the
/// hook surface lives, and a probe looking in the wrong place reports a
/// confident `absent`.
pub const STORE_DIR_ENV: &str = "CLINE_DIR";

/// Relocates Cline's **data** root — settings, secrets, the database, sessions.
///
/// Independent of [`STORE_DIR_ENV`] at a different level of the tree, not a
/// fallback for it: see [`data_root`] for the trap that distinction names.
pub const DATA_DIR_ENV: &str = "CLINE_DATA_DIR";

/// Relocates Cline's **user-asset** root — `~/Documents/Cline`, which holds
/// `Hooks/`.
///
/// Ours, not Cline's: upstream has no equivalent variable, so there is nothing
/// an operator could already have set to a value we would be reinterpreting.
/// It exists so a test — and `olbox` — can redirect a root that otherwise
/// resolves through `dirs::document_dir()`, which on Windows consults the shell
/// and ignores a redirected `HOME` entirely.
pub const ASSETS_DIR_ENV: &str = "OPENLATCH_CLINE_ASSETS_DIR";

/// The three seams, pointed under `root` at paths that are NEVER created, so a
/// stat-based detector answers `None` and a fixture stays a two-agent test
/// until detection is armed deliberately.
///
/// **One definition, because two out of three is a leak.** A fixture that names
/// the store and the data root but not the asset root writes the developer's
/// real `~/Documents/Cline`; one that names the store alone leaves
/// `~/.cline/data/secrets.json` — provider API keys, plaintext, mode 0600 —
/// exactly where an `install_hooks` walk can reach it. The asset root is the
/// seam no `$HOME` override can stand in for: it resolves through
/// `dirs::document_dir()`, which reads the known-folder API on Windows and
/// `home_dir()/Documents` on macOS.
///
/// **Absent, not merely relocated — these paths are NEVER created, and this
/// helper never creates them.** That is the whole point: a detector that stats
/// the directory answers `None`, so a fixture's agent count does not change the
/// day a `ClineBinding` lands. It also makes this the WRONG helper for a test
/// that needs a *present* Cline root — once a stat-based detector exists, an
/// existing directory is what reads as "Cline is installed here", which is the
/// opposite of what every caller below wants. A suite that needs a present root
/// adds its own helper beside this one; it must not create directories under
/// the paths this returns, or it silently arms Cline detection in all of them.
///
/// **It acquires no lock.** Mutual exclusion over these three process-wide
/// variables comes from [`SEAM_ENV_LOCK`], which the CALLER holds — the same
/// contract [`EnvOverride`] states. `SEAM_ENV_LOCK` is a non-reentrant
/// `std::sync::Mutex`, so a helper that took it on the caller's behalf would
/// hang every site that already holds it rather than failing.
///
/// **Set before detection is armed, deliberately.** A gate that only tightens
/// once the danger arrives is a gate nobody has exercised — and the spec
/// requires these seams be asserted by a fixture that fails loudly rather than
/// by convention. The hand-written triple this replaced, repeated across a
/// dozen files in four different directory spellings, was exactly that
/// convention.
///
/// Plain `pub` for the reason the rest of this module is: an integration target
/// under `tests/` links this crate as an ordinary dependency and cannot see a
/// `#[cfg(test)]` item. It costs the hot path nothing — `pub mod hooks` is
/// behind `full-cli`, which `openlatch-hook` does not enable.
pub fn absent_seams(root: &Path) -> [(&'static str, PathBuf); 3] {
    let store = root.join("absent-cline");
    [
        (STORE_DIR_ENV, store.clone()),
        (DATA_DIR_ENV, store.join("data")),
        (ASSETS_DIR_ENV, root.join("absent-cline-assets")),
    ]
}

/// The store root's name under the home directory, when no seam relocates it.
const DEFAULT_STORE_DIR_NAME: &str = ".cline";

/// The data root's name under the store root, when no seam relocates it.
pub(crate) const DEFAULT_DATA_DIR_NAME: &str = "data";

/// The user-asset root's name under the documents directory.
const ASSET_DIR_NAME: &str = "Cline";

/// The documents directory's name under the home directory, used only when
/// `dirs::document_dir()` answers `None`.
const DEFAULT_DOCUMENTS_DIR_NAME: &str = "Documents";

/// How a root was reached.
///
/// A bare `PathBuf` cannot carry this, and the answer is reported rather than
/// merely used: an operator who relocated a root needs to see that the client
/// followed them there, and an operator who did not needs to see that the
/// default is what was inspected. "Absent" means something different under each.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LocatedBy {
    /// No seam was set; the root was derived from the home directory.
    Default,
    /// A seam named the root explicitly.
    OperatorSupplied,
}

/// `$name` when it is set, non-empty **and absolute**.
///
/// Two filters, for two different reasons.
///
/// *Non-empty* is the conventional reading of an exported-but-blank variable
/// and the one both precedents take (`claude_code::relocated_dir`,
/// `codex_cli::relocated_dir`); Cline agrees, trimming before it tests.
///
/// *Absolute* is a **deliberate departure** from Cline, which returns a
/// relative value verbatim and resolves it against the process cwd at the
/// moment of the filesystem call. A daemon and an agent do not share a cwd, so
/// honouring a relative seam would have the two of them reading different
/// directories from the same configuration — and a `rules/` write landing
/// wherever the shell happened to be. Refusing falls back to the default root,
/// which is at least a place both processes agree on.
fn operator_supplied(name: &str) -> Option<PathBuf> {
    std::env::var_os(name)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}

/// Where Cline's store root *would* be, whether or not it exists:
/// `$CLINE_DIR` when set to an absolute, non-empty path, else `~/.cline`.
///
/// `None` only when there is no home directory to fall back to.
pub fn store_root() -> Option<(PathBuf, LocatedBy)> {
    match operator_supplied(STORE_DIR_ENV) {
        Some(path) => Some((path, LocatedBy::OperatorSupplied)),
        None => Some((
            dirs::home_dir()?.join(DEFAULT_STORE_DIR_NAME),
            LocatedBy::Default,
        )),
    }
}

/// Where Cline's data root *would* be: `$CLINE_DATA_DIR` when set to an
/// absolute, non-empty path, else `data/` under [`store_root`].
///
/// **The trap this shape names.** The default derives from `store_root`, so
/// setting `CLINE_DIR` alone moves `data/` along with it — but setting
/// `CLINE_DATA_DIR` alone leaves `rules/ workflows/ plugins/` on the real home.
/// They are two independent resolvers at two levels of one tree, not a fallback
/// chain, and a fixture that redirects one of them is still writing the
/// developer's files through the other. [`cline_isolated`] therefore requires
/// both.
pub fn data_root() -> Option<(PathBuf, LocatedBy)> {
    match operator_supplied(DATA_DIR_ENV) {
        Some(path) => Some((path, LocatedBy::OperatorSupplied)),
        None => Some((
            store_root()?.0.join(DEFAULT_DATA_DIR_NAME),
            LocatedBy::Default,
        )),
    }
}

/// Where our enforcement plugin *would* live — `<store root>/plugins/openlatch`
/// — whether or not it is there.
///
/// Resolution belongs here (D-01) and the directory *name* belongs to
/// [`crate::hooks::cline_plugin`], which owns the artefact; this composes the
/// two and is the only place that does. `None` only when there is no home
/// directory to fall back to, which is the same condition that makes
/// [`store_root`] answer `None`.
pub fn plugin_dir() -> Option<PathBuf> {
    Some(crate::hooks::cline_plugin::plugin_dir(
        &store_root()?.0.join(STORE_PLUGINS_DIR_NAME),
    ))
}

/// `disabledPlugins` from `global-settings.json`, read live.
///
/// The **asserted** half of DD-12's pair, for a caller outside the probe: the
/// binding needs it to answer `liveness()` and holds no attestation. Same file,
/// same projection and same three-valued read the probe uses — `None` is *we
/// could not tell*, which [`crate::hooks::cline_plugin::is_disabled`] is
/// careful not to render as the developer having switched us off.
///
/// **Read-only, in both senses.** C-6 names this file watchable, and nothing on
/// any path in this crate writes it: taking our plugin off that list is the
/// developer's decision, never ours.
pub fn asserted_disabled_plugins() -> Option<Vec<String>> {
    let settings = data_root()?.0.join(DATA_SETTINGS_DIR_NAME);
    read_projection::<GlobalSettingsProjection>(&settings.join(GLOBAL_SETTINGS_FILE_NAME))
        .value()?
        .disabled_plugins
}

/// This host's Cline enforcement surface, resolved and read live.
///
/// The composition — resolve, read the switch, then ask the **one** detector in
/// [`crate::hooks::cline_plugin::enforcement_surface`]. Two file touches, so a
/// caller asked repeatedly resolves it once and keeps the answer; see
/// [`crate::hooks::bindings::cline::ClineBinding`], which does exactly that in
/// `detect()`.
pub fn enforcement_surface() -> crate::hooks::cline_plugin::EnforcementSurface {
    let Some(dir) = plugin_dir() else {
        return crate::hooks::cline_plugin::EnforcementSurface::None;
    };
    crate::hooks::cline_plugin::enforcement_surface(&dir, asserted_disabled_plugins().as_deref())
}

/// Whether the resolved store is the machine's own `~/.cline`.
///
/// Mirrors `claude_code::config_is_machine_global` and
/// `codex_cli::config_is_machine_global` exactly, including their conservative
/// `true` on a resolution failure: if we cannot tell, we must assume the store
/// is shared, because the caller uses this to decide whether it may WRITE.
///
/// **Why this exists rather than a hardcoded `false` on the binding.** An
/// adversarial review (2026-09-14) established that `false` is not merely
/// imprecise but wrong: `~/.cline` is machine-global in exactly the sense the
/// trait means — every Cline session on the host shares it. The error is
/// dormant only while [`ClineBinding::model_relay_wiring`] returns `None`,
/// because every wiring loop skips such a binding before consulting ownership.
/// **I-2 lands that wiring**, at which point an isolated daemon on a
/// non-default port with `own_agent_wiring = true` would read `false` as
/// "relocated, safe to own" and write the developer's real store. Answering it
/// correctly now costs one delegation; answering it later costs a live write.
///
/// **Both data lanes count.** Cline's provider settings live under `data/`, and
/// the two bundles resolve it differently: legacy from `$CLINE_DIR/data`, next
/// from `$CLINE_DATA_DIR`. A sandbox that relocates the store but leaves
/// `CLINE_DATA_DIR` on the real `~/.cline/data` would otherwise read as isolated
/// while its next-bundle lane is the developer's own state file.
pub fn config_is_machine_global() -> bool {
    let Some((store, _)) = store_root() else {
        return true;
    };
    let Some((data, _)) = data_root() else {
        return true;
    };
    let Some(default_store) = dirs::home_dir().map(|home| home.join(DEFAULT_STORE_DIR_NAME)) else {
        return true;
    };
    let default_data = default_store.join(DEFAULT_DATA_DIR_NAME);
    let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    canonical(&store) == canonical(&default_store) || canonical(&data) == canonical(&default_data)
}

/// Where Cline's user-asset root *would* be — the `Cline` directory under the
/// user's documents directory, which is where the VS Code lane discovers
/// `Hooks/`.
///
/// `dirs::document_dir()` answers `None` on Linux whenever `xdg-user-dirs` is
/// unconfigured — which is most CI runners and any freshly redirected `HOME` —
/// so the home-relative form is a fallback, not an `expect()`. A panic here
/// would fire in exactly the environment the seam exists to make safe.
///
/// **A facade over [`asset_roots`] since the probe landed**, and still a bare
/// `Option<PathBuf>` because its one caller —
/// `crate::hooks::bindings::cline::ClineBinding::hook_config_path` — wants one
/// directory rather than a lane report. Delegating is not tidiness: Cline
/// resolves this root two ways (DD-03), and a binding that answered one lane
/// while the attestation reported the other would put two different `Hooks/`
/// directories in one `doctor` run. The answer is unchanged wherever the two
/// lanes agree, which is every macOS host, every Linux host with
/// `xdg-user-dirs` unconfigured, and every seam-redirected fixture.
///
/// Unlike its two siblings this returns no [`LocatedBy`] — [`asset_roots`]
/// carries the provenance, and duplicating it here would be a second thing that
/// can drift.
pub fn asset_root() -> Option<PathBuf> {
    asset_roots().resolved
}

/// Serializes every test that mutates one of the three Cline seams.
///
/// Environment variables are process-wide and `cargo test` runs a target's
/// tests as threads in one process, so without this two tests redirect the same
/// root at once and each reads the other's temp directory.
///
/// **Lock order**, so two tests cannot deadlock by taking these in opposite
/// orders: `config::OPENLATCH_DIR_ENV_LOCK` →
/// `claude_code::CONFIG_DIR_ENV_LOCK` → `staging::HOOK_BIN_ENV_LOCK` →
/// `codex_cli::CONFIG_DIR_ENV_LOCK` → this one. A config-directory lock is
/// always last, and this is the newest of them.
///
/// **Not `#[cfg(test)]`, unlike both precedents.** Theirs are gated because an
/// ungated `pub(crate)` static read only from tests is dead code and CI runs
/// clippy with `-D warnings`. That reason does not transfer: [`cline_isolated`]
/// is plain `pub` and reads this static from a non-`cfg(test)` item, so it is
/// not dead code — and a `#[cfg(test)]` static would fail to compile the moment
/// the `pub` guard referenced it.
pub(crate) static SEAM_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Proof that the three Cline seams point away from the developer's machine,
/// held for as long as the test that took it.
///
/// Holding it holds [`SEAM_ENV_LOCK`], so two tests cannot redirect the same
/// root at once.
///
/// **Field order is drop order.** The redirection goes back before the lock is
/// released, so a test blocked on the lock never observes this one's seams.
pub struct ClineSeam {
    _env: EnvOverride,
    _lock: std::sync::MutexGuard<'static, ()>,
}

/// Redirect the environment by `overrides` UNDER the seam lock, assert that
/// every Cline seam then points at an absolute path away from the machine's
/// own store, and hold both until the returned guard drops.
///
/// **The redirection is applied here, not by the caller.** This guard used to
/// be taken after the caller had already set the seams, so the write happened
/// outside the lock it was meant to hold: a sibling holding the lock with
/// `CLINE_DIR` unset saw a value appear mid-test, and its restore then erased
/// the caller's value before the caller got the lock. Two tests failed that
/// way in one full run (`a_same_format_provider_switch_rewires_and_restores`
/// and `an_isolated_instance_does_not_own_the_machines_own_store`). Taking the
/// overrides makes an unlocked write impossible to express.
///
/// **Panics** — loudly, by design — when a seam is unset, empty, relative, or
/// (for `CLINE_DIR`) equal to the default `~/.cline`. A test that reaches the
/// real store reads `data/secrets.json`: plaintext API keys, mode 0600. There
/// is nothing to degrade gracefully to.
///
/// **Plain `pub`, not `#[cfg(test)]`.** An integration target links this crate
/// as an ordinary dependency and cannot see `#[cfg(test)]` items, so a gated
/// guard would leave every fixture under `tests/` setting its seams *by
/// convention* — which is precisely what a fixture that "fails loudly rather
/// than by convention" exists to replace. A `test-support` cargo feature was
/// rejected for the same reason in reverse: every acceptance command would then
/// need `--features test-support`, or silently compile the guard out.
///
/// **It costs the hot path nothing.** `pub mod hooks` is behind `full-cli` and
/// `openlatch-hook` does not enable it, so this never links into the lean
/// binary. `cargo test --lib --no-default-features` is what proves that.
#[must_use = "the seam guard must be held for the test's lifetime; dropping it \
              immediately releases the lock and proves nothing"]
pub fn cline_isolated<I>(overrides: I) -> ClineSeam
where
    I: IntoIterator<Item = (&'static str, Option<std::ffi::OsString>)>,
{
    // Poison is ignored: a panicking test has already failed, and this lock
    // only orders access.
    let lock = SEAM_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    // Restored on unwind as well: a refused seam below panics with this held.
    let env = EnvOverride::apply(overrides);

    let store = require_seam(STORE_DIR_ENV, std::env::var_os(STORE_DIR_ENV));
    require_seam(DATA_DIR_ENV, std::env::var_os(DATA_DIR_ENV));
    require_seam(ASSETS_DIR_ENV, std::env::var_os(ASSETS_DIR_ENV));
    reject_default_store(&store, dirs::home_dir().as_deref());

    ClineSeam {
        _env: env,
        _lock: lock,
    }
}

/// Panics unless `value` is a non-empty, absolute path.
///
/// Takes the value rather than reading it so the guard's own tests can call the
/// panicking check **directly**, with no environment mutation and no lock. That
/// is the whole reason it is a separate function: without it, one engineer adds
/// a `with_override()` escape hatch to the constructor and another exempts the
/// resolver tests from the guard entirely.
fn require_seam(name: &str, value: Option<std::ffi::OsString>) -> PathBuf {
    let value = value.filter(|value| !value.is_empty()).unwrap_or_else(|| {
        panic!(
            "CLINE seam {name} unset: this test would read the developer's real store, \
             which holds plaintext API keys"
        )
    });
    let path = PathBuf::from(value);
    assert!(
        path.is_absolute(),
        "CLINE seam {name} is relative ({}): a relative seam resolves against whatever \
         cwd the process happens to have, which is not isolation",
        path.display()
    );
    path
}

/// Panics when `store` is the machine's own `~/.cline`.
///
/// Set-but-equal counts as unset: `CLINE_DIR="$HOME/.cline"` is a no-op that
/// reads like isolation, and it is exactly what a half-finished copy-paste
/// produces.
///
/// **Checked on `CLINE_DIR` alone, deliberately.** `CLINE_DATA_DIR`'s default
/// derives from an already-redirected [`store_root`], so "equal to the default"
/// is ambiguous there between `~/.cline/data` (the real home) and
/// `$CLINE_DIR/data` (a perfectly isolated value a correct fixture would use).
/// A guard that rejects the second is worse than no guard.
///
/// `home` is a parameter for the same reason `value` is one above: the test
/// calls this directly, against a temp directory, rather than through the
/// developer's real home.
fn reject_default_store(store: &Path, home: Option<&Path>) {
    let Some(home) = home else {
        return;
    };
    let default = home.join(DEFAULT_STORE_DIR_NAME);
    assert_ne!(
        dedup_key(store),
        dedup_key(&default),
        "CLINE seam {STORE_DIR_ENV} points at the machine's own store ({}): set-but-equal \
         counts as unset",
        store.display()
    );
}

/// Applies a set of environment overrides, restoring what was there on drop —
/// on unwind as well as on success. `None` removes the variable.
///
/// Save/restore only: the mutual exclusion comes from the locks the caller
/// holds, which is why every use is declared *after* the guard that holds them
/// and therefore dropped *before* it.
///
/// Plain `pub`, and out of `#[cfg(test)]`, for the reason [`absent_seams`] is:
/// three fixtures elsewhere in this crate hand-rolled this same save/set/restore
/// loop, and a copy that restores on `return` but not on unwind leaks a
/// redirected seam into the next test in the binary.
pub struct EnvOverride(Vec<(&'static str, Option<OsString>)>);

impl EnvOverride {
    /// Takes any iterable of pairs, not a fixed-size array: a caller that
    /// composes [`absent_seams`] with overrides of its own has a `Vec`, and one
    /// that writes its pairs out by hand has an array.
    pub fn apply<I>(pairs: I) -> Self
    where
        I: IntoIterator<Item = (&'static str, Option<OsString>)>,
    {
        let mut saved = Vec::new();
        for (key, value) in pairs {
            saved.push((key, std::env::var_os(key)));
            match value {
                Some(value) => std::env::set_var(key, value),
                None => std::env::remove_var(key),
            }
        }
        Self(saved)
    }

    /// Points the three Cline seams at [`absent_seams`] paths under `root` for
    /// the returned guard's lifetime.
    ///
    /// Hold it for the whole test: dropping it immediately restores the seams
    /// and leaves the fixture reading the developer's real store.
    #[must_use = "the seams are restored the moment this guard drops"]
    pub fn absent_cline_seams(root: &Path) -> Self {
        Self::apply(absent_seams(root).map(|(key, value)| (key, Some(value.into_os_string()))))
    }
}

impl Drop for EnvOverride {
    fn drop(&mut self) {
        for (key, value) in self.0.drain(..) {
            match value {
                Some(value) => std::env::set_var(key, value),
                None => std::env::remove_var(key),
            }
        }
    }
}

// ---------------------------------------------------------------------------
// The user-asset root's two lanes (DD-03)
// ---------------------------------------------------------------------------

/// Which of Cline's two user-asset lanes produced a path.
///
/// Cline resolves this root **twice, and the two answers disagree on Windows** —
/// verified at tag `v4.1.17`. The VS Code lane (`documents-path.ts:6-40`) shells
/// out to `powershell … GetFolderPath(SpecialFolder.MyDocuments)`, which follows
/// a OneDrive Known-Folder Move; the SDK/CLI lane (`paths.ts:162-163`) is a
/// plain `join(HOME, "Documents", "Cline")`, which does not.
///
/// **And the in-scope lane is not deterministic.** It falls back to
/// `os.homedir()/Documents` when the PowerShell call throws, and again when
/// `mkdir` fails (`disk.ts:88-96`). Cline itself may therefore have written to
/// either directory on any given machine, so a resolver that picks one is wrong
/// exactly whenever the other happened — which is why the probe checks both and
/// records which one it found.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssetLane {
    /// The VS Code extension lane — the only lane in scope, and the KFM-aware
    /// one.
    ///
    /// Resolved through `dirs::document_dir()` rather than by spawning
    /// PowerShell. On Windows that is `SHGetKnownFolderPath(FOLDERID_Documents)`,
    /// which reads the same known folder `GetFolderPath(MyDocuments)` does, and
    /// it costs no process: `doctor` runs on hosts where spawning a shell is
    /// slow, audited, or blocked outright, and a diagnostic that hangs on a
    /// PowerShell invocation is not a diagnostic.
    KnownFolder,
    /// The SDK/CLI lane — `join(HOME, "Documents")` — which is also what the
    /// VS Code lane degrades to on **both** of its failure paths.
    HomeRelative,
}

impl AssetLane {
    /// The wire spelling. Hyphenated like every other enumerated value in the
    /// attestation (`operator-supplied`, `mcp_settings` is a field name, not a
    /// value).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::KnownFolder => "known-folder",
            Self::HomeRelative => "home-relative",
        }
    }
}

/// One lane's candidate root, and whether it is on disk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetLaneRoot {
    /// Which lane derived [`Self::path`].
    pub lane: AssetLane,
    /// Where that lane says Cline's user assets are.
    pub path: PathBuf,
    /// Whether that directory is actually there. The whole point of reporting
    /// two lanes is that this can differ between them.
    pub exists: bool,
}

/// Which lane produced the root the rest of the client uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssetLaneHit {
    /// [`ASSETS_DIR_ENV`] named the root, so neither lane was consulted. An
    /// operator who relocated it is told we followed them there.
    OperatorSupplied,
    /// Exactly one lane is on disk, and this is it.
    Lane(AssetLane),
    /// Both are. On macOS that is the ordinary case rather than an anomaly —
    /// `document_dir()` is `home_dir()/Documents` there, so the two lanes name
    /// one directory. [`AssetRoots::lanes_agree`] is what separates "one
    /// directory found twice" from "two directories, both real".
    Both,
    /// Neither is. The reported root is where the in-scope lane says to look,
    /// which is the honest answer to "where would it be".
    Neither,
}

impl AssetLaneHit {
    /// The wire spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::OperatorSupplied => "operator-supplied",
            Self::Lane(lane) => lane.as_str(),
            Self::Both => "both",
            Self::Neither => "neither",
        }
    }
}

/// Both lanes, which of them is on disk, and the one root everything else uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetRoots {
    /// Whether a seam named this root or the host derived it. The same
    /// asserted-versus-observed distinction [`store_root`] reports (DD-12).
    pub located_by: LocatedBy,
    /// Every lane that resolved, in declaration order — in scope first. Empty
    /// when a seam superseded both: there is then nothing to compare, and an
    /// empty list says so more clearly than two entries nobody consulted.
    pub lanes: Vec<AssetLaneRoot>,
    /// Which lane the assets were found under.
    pub hit: AssetLaneHit,
    /// Whether the two lanes name the same directory. `true` with a seam set,
    /// and `true` on macOS and on any Linux box with `xdg-user-dirs`
    /// unconfigured — where a reader would otherwise read `both` as evidence of
    /// two installs.
    pub lanes_agree: bool,
    /// The root the binding and the probe both use. `None` only when there is
    /// no home directory and no seam.
    pub resolved: Option<PathBuf>,
}

/// Resolve both user-asset lanes and say which one is on disk (DD-03).
///
/// The seam wins outright when it is set — it is the operator telling us where
/// to look, and a fork that keeps its assets somewhere neither lane would guess
/// is found no other way.
pub fn asset_roots() -> AssetRoots {
    asset_roots_from(
        operator_supplied(ASSETS_DIR_ENV),
        dirs::document_dir(),
        dirs::home_dir(),
    )
}

/// The body of [`asset_roots`] with its three inputs passed in.
///
/// Separate for the reason [`require_seam`] and [`reject_default_store`] are:
/// `dirs::document_dir()` cannot be steered on macOS — it is
/// `home_dir()/Documents` unconditionally — so a test that drives the real
/// resolver can never make the two lanes *differ*, which is the only
/// interesting case. Passing the two candidate documents directories in is what
/// makes DD-03 testable on the machine this is written on.
fn asset_roots_from(
    seam: Option<PathBuf>,
    known_folder: Option<PathBuf>,
    home: Option<PathBuf>,
) -> AssetRoots {
    if let Some(path) = seam {
        return AssetRoots {
            located_by: LocatedBy::OperatorSupplied,
            lanes: Vec::new(),
            hit: AssetLaneHit::OperatorSupplied,
            lanes_agree: true,
            resolved: Some(path),
        };
    }

    let home_relative = home.map(|home| home.join(DEFAULT_DOCUMENTS_DIR_NAME));
    // `document_dir()` answers `None` on Linux whenever `xdg-user-dirs` is
    // unconfigured — most CI runners, and any freshly redirected `HOME`. The
    // in-scope lane's own fallback is the home-relative path, so mirroring that
    // here keeps the two lanes reporting what Cline would have done rather than
    // dropping the lane entirely.
    let known_folder = known_folder.or_else(|| home_relative.clone());

    let mut lanes = Vec::new();
    for (lane, documents) in [
        (AssetLane::KnownFolder, known_folder.clone()),
        (AssetLane::HomeRelative, home_relative.clone()),
    ] {
        if let Some(documents) = documents {
            let path = documents.join(ASSET_DIR_NAME);
            let exists = path.is_dir();
            lanes.push(AssetLaneRoot { lane, path, exists });
        }
    }

    let lane_path = |wanted: AssetLane| {
        lanes
            .iter()
            .find(|candidate| candidate.lane == wanted)
            .map(|candidate| candidate.path.clone())
    };
    let lanes_agree = match (
        lane_path(AssetLane::KnownFolder),
        lane_path(AssetLane::HomeRelative),
    ) {
        (Some(a), Some(b)) => dedup_key(&a) == dedup_key(&b),
        // One lane or none: there is no disagreement to report.
        _ => true,
    };

    let present: Vec<AssetLane> = lanes
        .iter()
        .filter(|candidate| candidate.exists)
        .map(|candidate| candidate.lane)
        .collect();
    let hit = match present.as_slice() {
        [] => AssetLaneHit::Neither,
        [only] => AssetLaneHit::Lane(*only),
        _ => AssetLaneHit::Both,
    };

    // The in-scope lane wins a tie and is the answer when nothing is on disk;
    // a lane that is genuinely there beats one that is not. That ordering is
    // what keeps `hook_config_path()` and the attestation naming ONE `Hooks/`
    // directory — three units disagreeing about where the hook surface lives is
    // the trap `STORE_DIR_ENV`'s documentation names.
    let resolved = match hit {
        AssetLaneHit::Lane(lane) => lane_path(lane),
        _ => lane_path(AssetLane::KnownFolder).or_else(|| lane_path(AssetLane::HomeRelative)),
    };

    AssetRoots {
        located_by: LocatedBy::Default,
        lanes,
        hit,
        lanes_agree,
        resolved,
    }
}

// ---------------------------------------------------------------------------
// The surface probe and its attestation (PRD C-1)
// ---------------------------------------------------------------------------

/// The two codes this probe raises — **OL-1408** for a surface that is not
/// there, **OL-1409** for one we could not tell about.
///
/// Defined in `src/core/error.rs` with every other `OL-` code and pinned by
/// `test_error_code_constants_exist`, so a second allocation of either number
/// collides in a test rather than in a customer's log; re-exported here because
/// this module is where they are raised, and a reader of the probe should not
/// have to leave the file to learn what it emits.
pub use crate::error::{ERR_CLINE_SURFACE_ABSENT, ERR_CLINE_SURFACE_UNDETERMINED};

/// The largest any single Cline config file is read for.
///
/// A bound rather than a slurp: the reader is a `Take` over a `BufReader`, so a
/// pathological or adversarial file costs one megabyte and a parse error —
/// which surfaces as `undetermined`, not as a confident absence.
const MAX_CONFIG_READ_BYTES: u64 = 1 << 20;

/// The hook directory's name under the user-asset root.
///
/// Capitalised — Cline's spelling, not ours. The store root holds a lowercase
/// `hooks/` which is a **different directory**; [`STORE_DIR_ENV`] documents the
/// trap and [`STORE_HOOKS_DIR_NAME`] is that other one.
///
/// **The one spelling in the tree.** `bindings::cline` used to keep a second
/// copy and a test to hold the two together; it now reads this, so there is
/// nothing left to hold together.
pub const ASSET_HOOKS_DIR_NAME: &str = "Hooks";

/// The hook directory's name under the **store** root — lowercase, and a
/// different directory from [`ASSET_HOOKS_DIR_NAME`].
///
/// **C-6's listing-only surface.** It sits inside the store, which also holds
/// `data/secrets.json`: this build lists its filenames to answer whether it is
/// there, and **never opens a file under it**.
/// `the_store_hooks_dir_is_listed_never_read` is the guard.
const STORE_HOOKS_DIR_NAME: &str = "hooks";

/// The two workspace-relative hook roots, each holding a `hooks/` child.
///
/// A *workspace* is the cwd of the invoking process and nothing else — nothing
/// in `src/` has any other notion of one. See [`probe_in`] for what happens
/// when there is no usable cwd.
const WORKSPACE_RULES_DIR_NAME: &str = ".clinerules";
const WORKSPACE_LOCAL_DIR_NAME: &str = ".cline";

/// The `hooks/` child both workspace lanes look under.
///
/// Its own constant rather than a second use of [`STORE_HOOKS_DIR_NAME`]: the
/// two agree today and are not the same fact. Joined one segment at a time,
/// which `ci/check-portability.py` requires of every path in this crate.
const WORKSPACE_HOOKS_DIR_NAME: &str = "hooks";

/// What each of [`ClineAttestation::hook_dirs`]' four rows is, in Cline's own
/// precedence order.
///
/// Positional, because the rows are: a reader — and an acceptance step indexing
/// `hook_dirs[0]` — has to know which lane a row belongs to without
/// re-deriving it from a path that may be `null`. A label per row rather than a
/// sixth [`Surface`] variant, which would be a schema change the platform sees.
const HOOK_DIR_LABELS: [&str; 4] = [
    "install, asset root",
    "store",
    "workspace .clinerules",
    "workspace .cline",
];

/// The plugin directory's name under the store root.
///
/// `pub(crate)` so the binding's `plugin_surface()` builds the installer's
/// target from the same constant the probe classifies — one spelling of the
/// directory, or an installer and a probe that disagree about which one Cline
/// reads.
pub(crate) const STORE_PLUGINS_DIR_NAME: &str = "plugins";

/// The settings directory under the data root.
const DATA_SETTINGS_DIR_NAME: &str = "settings";

/// Cline's MCP registry.
const MCP_SETTINGS_FILE_NAME: &str = "cline_mcp_settings.json";

/// The credential-bearing provider file. Read for **ids and `baseUrl` presence
/// only** — C-6's one narrowed exception.
const PROVIDERS_FILE_NAME: &str = "providers.json";

/// The settings file C-6 names as watchable, and the only place this probe
/// learns what Cline *asserts* about its own plugins.
const GLOBAL_SETTINGS_FILE_NAME: &str = "global-settings.json";

/// The key inside a provider entry's `settings` container that carries its
/// endpoint.
///
/// The attestation reports its **presence** and never its value (C-6); the
/// request plane reads and writes the value, which is a different, narrower
/// purpose that never reaches a report. One constant, so the probe and the
/// writer cannot come to disagree about which key that is.
pub const BASE_URL_KEY: &str = "baseUrl";

/// Store-root children this build can name. Anything else is residual (DD-13).
const STORE_KNOWN_CHILDREN: &[&str] = &[
    "rules",
    "workflows",
    "plugins",
    "hooks",
    "skills",
    "agents",
    "data",
];

/// User-asset-root children this build can name.
const ASSET_KNOWN_CHILDREN: &[&str] = &["hooks", "workflows", "rules", "plugins"];

/// The editor roots searched for a Cline-lineage extension, before the
/// `-server` variants are derived from them.
///
/// Six families, and the list is deliberately a constant rather than a scan:
/// walking a developer's home directory looking for candidate editors is
/// expensive, ambiguous and a privacy problem (PRD D-16). A fork whose editor
/// root is not here reports `absent` and the store is still detected — which is
/// the AC-5 case, and the reason detection is store-keyed and never
/// extension-keyed.
const EXTENSION_ROOT_BASES: &[&str] = &[
    ".vscode",
    ".vscode-insiders",
    ".vscode-oss",
    ".cursor",
    ".windsurf",
    ".antigravity",
];

/// The directory an editor root keeps its extensions in.
const EXTENSION_DIR_NAME: &str = "extensions";

/// Substrings that mark an extension directory as Cline-lineage.
///
/// **A weak heuristic, and it decides nothing** (DD-10). Detection is
/// store-keyed — [`crate::hooks::bindings::cline::ClineBinding::detect`] stats
/// the store root and never looks at an extension — so a rebranded fork with no
/// marketplace publisher id and no signature is detected and attested exactly
/// as Cline is, with its `extension` surface reported `absent`. This list only
/// answers *which editor root held it* when the answer is cheap, and its
/// failure is visible rather than silent.
const EXTENSION_LINEAGE_MARKERS: &[&str] = &["cline", "claude-dev"];

/// One of C-1's five enumerated surfaces.
///
/// Closed by construction, which is exactly the osquery trap DD-13 names — and
/// why [`ClineAttestation::unclassified`] exists beside it. Adding a sixth
/// surface here is a schema change the platform sees; putting a finding in the
/// residual is not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
    /// The store root — `~/.cline`, or wherever [`STORE_DIR_ENV`] points.
    Store,
    /// `Hooks/` under the user-asset root.
    HookDir,
    /// `plugins/` under the store root.
    PluginDir,
    /// The MCP registry under the data root.
    McpSettings,
    /// A Cline-lineage extension in any enumerated editor root.
    Extension,
}

impl Surface {
    /// Every surface, in reporting order.
    pub const ALL: [Surface; 5] = [
        Surface::Store,
        Surface::HookDir,
        Surface::PluginDir,
        Surface::McpSettings,
        Surface::Extension,
    ];

    /// The wire spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Store => "store",
            Self::HookDir => "hook_dir",
            Self::PluginDir => "plugin_dir",
            Self::McpSettings => "mcp_settings",
            Self::Extension => "extension",
        }
    }
}

/// Three states, never two (DD-11).
///
/// A probe that can only say *present* or *absent* turns every lookup bug into
/// a confident false negative — the `@supports` failure mode, where a malformed
/// query *"silently reports unsupported rather than erroring"*. Absence is what
/// we ask a customer to act on, so "we could not tell" must be expressible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SurfaceState {
    /// We looked and it is there.
    Present,
    /// We looked and it is not there.
    Absent,
    /// We could not tell — the root did not resolve, or the filesystem refused
    /// to answer with anything but "not found".
    Undetermined,
}

impl SurfaceState {
    /// The wire spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Present => "present",
            Self::Absent => "absent",
            Self::Undetermined => "undetermined",
        }
    }
}

/// One surface's finding: `{surface, state, code, remedy}`, per C-1.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SurfaceFinding {
    /// Which surface.
    pub surface: Surface,
    /// What we found — three-valued.
    pub state: SurfaceState,
    /// `None` only when [`Self::state`] is [`SurfaceState::Present`]. Anything
    /// a reader is asked to act on carries a code.
    pub code: Option<&'static str>,
    /// `None` only when [`Self::state`] is [`SurfaceState::Present`], and never
    /// a restatement of the finding: a remedy names what to do.
    pub remedy: Option<&'static str>,
}

impl SurfaceFinding {
    /// The finding for `surface` in `state`, with the code and remedy that pair
    /// with it.
    ///
    /// Built in one place so the "every non-present finding carries a code
    /// **and** a remedy" rule is a property of the constructor rather than of
    /// six call sites remembering it.
    fn new(surface: Surface, state: SurfaceState) -> Self {
        let code = match state {
            SurfaceState::Present => None,
            SurfaceState::Absent => Some(ERR_CLINE_SURFACE_ABSENT),
            SurfaceState::Undetermined => Some(ERR_CLINE_SURFACE_UNDETERMINED),
        };
        Self {
            surface,
            state,
            code,
            remedy: remedy_for(surface, state),
        }
    }

    /// The JSON object C-1 specifies — exactly four keys.
    fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "surface": self.surface.as_str(),
            "state": self.state.as_str(),
            "code": self.code,
            "remedy": self.remedy,
        })
    }
}

/// What to do about a surface that is absent or undetermined.
///
/// `None` for a present surface, and never a paraphrase of the state: a reader
/// who has the state and the code still needs to be told what to do next, which
/// is the whole of `Check::validate`'s requirement.
fn remedy_for(surface: Surface, state: SurfaceState) -> Option<&'static str> {
    match (surface, state) {
        (_, SurfaceState::Present) => None,
        (_, SurfaceState::Undetermined) => Some(
            "openlatch could not read this path. Check its permissions, or set CLINE_DIR, \
             CLINE_DATA_DIR and OPENLATCH_CLINE_ASSETS_DIR to roots this user can stat.",
        ),
        (Surface::Store, SurfaceState::Absent) => Some(
            "Install Cline, or set CLINE_DIR to the store your build uses — a rebranded fork \
             is found because an operator names it, never by scanning the machine.",
        ),
        (Surface::HookDir, SurfaceState::Absent) => Some(
            "No Hooks directory under Cline's user-asset root. Run Cline once so it creates \
             one, or set OPENLATCH_CLINE_ASSETS_DIR if this build keeps user assets elsewhere.",
        ),
        (Surface::PluginDir, SurfaceState::Absent) => Some(
            "No plugins directory under Cline's store root. Install a Cline plugin, or set \
             CLINE_DIR if this build keeps its store elsewhere.",
        ),
        (Surface::McpSettings, SurfaceState::Absent) => Some(
            "No MCP registry under Cline's data root. Register an MCP server in Cline, or set \
             CLINE_DATA_DIR if this build keeps its data elsewhere.",
        ),
        (Surface::Extension, SurfaceState::Absent) => Some(
            "Cline's store is on this host but no Cline-lineage extension was found in any \
             known editor root. If this host runs a rebranded build, report its editor root \
             so the install guide can name it.",
        ),
    }
}

/// A root that resolved, how it was reached, and whether it is there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootReport {
    /// Where we looked. `None` when no home directory resolved and no seam was
    /// set — the only way a root has no path at all.
    pub path: Option<PathBuf>,
    /// Told, or discovered (PRD D-16).
    pub located_by: LocatedBy,
    /// What was there.
    pub state: SurfaceState,
}

/// A path the probe inspected, and what it found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathReport {
    /// Where we looked.
    pub path: Option<PathBuf>,
    /// What was there.
    pub state: SurfaceState,
}

/// One provider's id and whether it declares a `baseUrl`.
///
/// **There is no field for the value, and that is the enforcement.** C-6 permits
/// reading `providers.json` for provider ids and `baseUrl` *presence* only; a
/// struct that cannot hold the value cannot leak it into a log, a support bundle
/// or the attestation, which is DD-15's *"machine-readable sensitivity plus
/// opt-in retrieval"* read into a document that has no `SELECT`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderReport {
    /// The provider id, verbatim — never normalised. Cline's encoding is the
    /// vendor's (DD-12).
    pub id: String,
    /// Whether the entry carries a `baseUrl` key at all.
    pub base_url_present: bool,
}

/// An editor root, and whether it held a Cline-lineage extension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtensionRootReport {
    /// The editor root — `~/.vscode`, `~/.cursor`, and so on.
    pub path: PathBuf,
    /// Whether the root itself is on disk.
    pub exists: bool,
    /// Whether a Cline-lineage extension was found under it. Three-valued for
    /// the same reason every other surface is: an `extensions/` directory we
    /// were refused is not an absence.
    pub lineage: SurfaceState,
    /// The extension directory names that matched, verbatim. Only matches are
    /// named — enumerating every extension a developer has installed is a
    /// privacy cost the attestation has no use for.
    pub matched: Vec<String>,
    /// How many entries were looked at, so `absent` can be told apart from
    /// `there was nothing to look at`.
    pub entries_scanned: usize,
}

/// Which client Cline was driven from, where that is distinguishable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostShellReport {
    /// `vscode`, `cli` or `jetbrains`.
    pub shell: &'static str,
    /// [`SurfaceState::Present`] when there is evidence of use;
    /// [`SurfaceState::Undetermined`] when this build cannot tell. Never
    /// `absent` — `~/.cline` is shared by all three, so "no evidence" is not
    /// evidence of no.
    pub state: SurfaceState,
    /// What was looked at to reach that answer. Without it a reader cannot tell
    /// an honest `undetermined` from an unimplemented one.
    pub basis: &'static str,
}

/// Something under a resolved root that this build could not classify.
///
/// **The field that makes this a fork probe rather than a checklist** (DD-13).
/// osquery's `chrome_extensions` enumerates 18 fixed browsers, so an installed
/// fork outside that enum *"yields no rows at all, with no residual evidence
/// that something unrecognised was present"* — silence indistinguishable from a
/// clean host. A Cosmos build that exposes something we never thought of lands
/// here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnclassifiedEntry {
    /// `store` or `asset` — which resolved root it was found directly under.
    pub root: &'static str,
    /// The entry's name, verbatim.
    pub name: String,
    /// `dir`, `file`, or `other` for anything else (a symlink whose target we
    /// did not follow, a device node).
    pub kind: &'static str,
}

/// What a Cline-lineage agent exposes on this host, as of a moment.
///
/// The probe's whole output, and PRD **C-1**'s shape. It **writes nothing**: every
/// field below is a stat, a directory listing, one of three narrowly projected
/// reads of Cline's own files, or a read of our own plugin's marker line. It is
/// produced by running the probe and is never
/// inherited from upstream Cline — a fork that removed a surface produces an
/// attestation saying so.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClineAttestation {
    /// RFC 3339, UTC, **required**. Without it this is not a dated claim
    /// (PRD D-9), and a reader cannot tell a live finding from one cached
    /// through a reinstall.
    pub as_of: String,
    /// The store root, and whether an operator named it.
    pub store_root: RootReport,
    /// Both user-asset lanes and which one hit (DD-03).
    pub asset_root: AssetRoots,
    /// Which client the store shows evidence of. May be several; may be
    /// indeterminate.
    pub host_shells: Vec<HostShellReport>,
    /// **All four** directories Cline discovers hook files in, in its own
    /// precedence order — [`HOOK_DIR_LABELS`] names them:
    ///
    /// ```text
    /// 0. <asset_root>/Hooks            the one we install into
    /// 1. <CLINE_DIR>/hooks             C-6: filenames listed, never read
    /// 2. <workspace>/.clinerules/hooks
    /// 3. <workspace>/.cline/hooks
    /// ```
    ///
    /// **Always four entries**, whatever this host resolved. A row we could not
    /// look at carries `path: None` and [`SurfaceState::Undetermined`] — *we
    /// could not tell*, never `Absent`, which would claim we looked. A consumer
    /// may therefore index a row positionally; a length check alone passes on
    /// four rows that are all wrong.
    pub hook_dirs: Vec<PathReport>,
    /// Filenames present in `hook_dirs[0]` — the directory this build installs
    /// into. `None` when it could not be listed at all; `[]` means empty, which
    /// is a different fact.
    ///
    /// **This is what is installed, not what is honoured.** Establishing which
    /// events a fork actually fires would mean analysing a bundled extension and
    /// is out of scope. Do not rename this to `hook_events`: a filename is not
    /// an event, and the honest limit is the point of the field.
    pub hook_dir_entries: Option<Vec<String>>,
    /// The plugin directory under the store root.
    pub plugin_dir: PathReport,
    /// Plugin directory entries — what is **observed**.
    pub plugin_dir_entries: Option<Vec<String>>,
    /// `disabledPlugins` from `global-settings.json` — what Cline **asserts**
    /// (DD-12). `None` when the file or the key is absent, which is not the
    /// same as an empty list.
    pub plugins_asserted_disabled: Option<Vec<String>>,
    /// Which lane can refuse a tool call on this host: `plugin`, `disabled` or
    /// `none`.
    ///
    /// **Not an `Option`, and that is the point.** Every other field here can
    /// say *we could not look*; this one always answers, because "we found
    /// nothing of ours" is itself one of the three. An assertion on
    /// `.agents.cline.enforcement_surface` therefore cannot pass by the key
    /// being absent — which is how an enforcement claim would go missing
    /// unnoticed.
    ///
    /// It is the structured *why* beside [`crate::error::ERR_CLINE_NOT_ENFORCING`],
    /// never a second verdict: both come off the same detector
    /// ([`crate::hooks::cline_plugin::enforcement_surface`]), so a document
    /// reporting `plugin` beside a `Monitored — enforcing nothing` row is not a
    /// state this build can produce.
    pub enforcement_surface: crate::hooks::cline_plugin::EnforcementSurface,
    /// The MCP registry file.
    pub mcp_settings: PathReport,
    /// Configured MCP server ids, sorted. **Ids only** — an `env` block
    /// routinely carries API keys and is never deserialized into anything that
    /// could hold it. `None` when the file could not be parsed.
    pub mcp_servers: Option<Vec<String>>,
    /// Configured providers: ids, and `baseUrl` presence. Never a value.
    pub providers: Option<Vec<ProviderReport>>,
    /// Editor roots searched, and which held a Cline-lineage extension.
    pub extension_roots: Vec<ExtensionRootReport>,
    /// The five enumerated surfaces, each with its own state, code and remedy.
    /// Per surface, never aggregated (DD-14).
    pub surfaces: Vec<SurfaceFinding>,
    /// The residual: what was found under the resolved roots and could not be
    /// classified (DD-13).
    pub unclassified: Vec<UnclassifiedEntry>,
}

/// Interrogate this host and produce a dated attestation.
///
/// **Reads only.** Nothing here creates a directory, opens a file outside the
/// three narrowly projected reads below, or writes a byte — `doctor` runs on a
/// developer's machine and this is the command that is supposed to be safe.
///
/// The C-6 exclusion list is honoured structurally rather than by convention:
/// `data/secrets.json`, `data/db/`, `data/sessions/`, `data/tasks/`, `data/cron/`
/// and `data/logs/` are never opened and the data root is **never enumerated** —
/// its contents *are* the exclusion list, so a listing is one refactor away from
/// a leak. The three files of Cline's that are opened are
/// `cline_mcp_settings.json` (ids only), `global-settings.json` (C-6 names it
/// watchable), and `providers.json` (ids and `baseUrl` presence only, C-6's one
/// narrowed exception).
///
/// A fourth file is opened and it is **ours**: `plugins/openlatch/index.js`,
/// read for its ownership marker so `enforcement_surface` can say whether this
/// host enforces. C-6 governs Cline's data and has nothing to say about an
/// artefact this build wrote.
///
/// The workspace comes from `std::env::current_dir()`, which is the right
/// answer for `doctor` — a foreground command the developer runs from their
/// project — and the wrong one anywhere else. A caller whose cwd means nothing,
/// the daemon above all, calls [`probe_in`] with `None`.
pub fn probe() -> ClineAttestation {
    probe_in(std::env::current_dir().ok().as_deref())
}

/// [`probe`] with the workspace passed in — `None` for *we could not look*.
///
/// **`<workspace>` is the cwd of the invoking process, and nothing else.**
/// Nothing in `src/` has any other notion of a Cline workspace, and a
/// supervised daemon's cwd is an artefact of how it was started rather than a
/// project the developer is in. Passing it in is the same device
/// [`asset_roots_from`] and [`classify_metadata`] use: it is what makes the
/// no-workspace case testable, and it is what keeps a daemon-side caller from
/// having to remember not to trust its own cwd — it has no cwd to pass.
///
/// With `None`, `hook_dirs[2]` and `hook_dirs[3]` report
/// [`SurfaceState::Undetermined`] with no path. Never `Absent`: we did not look
/// and fail to find, we could not look, and that distinction is the whole
/// reason the state is three-valued (DD-11).
pub fn probe_in(workspace: Option<&Path>) -> ClineAttestation {
    let as_of = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);

    let store = store_root();
    let store_path = store.as_ref().map(|(path, _)| path.clone());
    let store_report = RootReport {
        path: store_path.clone(),
        located_by: store
            .as_ref()
            .map_or(LocatedBy::Default, |(_, located)| *located),
        state: state_of(store_path.as_deref()),
    };

    let data_path = data_root().map(|(path, _)| path);
    let settings_dir = data_path.map(|data| data.join(DATA_SETTINGS_DIR_NAME));

    // Each surface below is classified from its stat **and** from the follow-up
    // lookup its own fields depend on: a stat that succeeds and a read that then
    // fails leaves a surface we cannot describe, and `present` is not one of the
    // honest answers for it (see [`path_report`]). The follow-ups therefore run
    // here, before `surfaces` is built, rather than inside the struct literal
    // below.
    let asset_root = asset_roots();

    // The four, in Cline's precedence order, and all four are reported whatever
    // resolved — see `ClineAttestation::hook_dirs`. Only the first is listed for
    // its FILENAMES; the other three are listed to classify the directory and
    // the names are dropped, which for the store lane is C-6's rule rather than
    // an economy.
    let install_dir = asset_root
        .resolved
        .as_ref()
        .map(|root| root.join(ASSET_HOOKS_DIR_NAME));
    let hook_dir_entries = entry_names(install_dir.as_deref());

    let store_hooks_dir = store_path
        .as_ref()
        .map(|store| store.join(STORE_HOOKS_DIR_NAME));
    let workspace_rules_dir = workspace.map(|workspace| {
        workspace
            .join(WORKSPACE_RULES_DIR_NAME)
            .join(WORKSPACE_HOOKS_DIR_NAME)
    });
    let workspace_local_dir = workspace.map(|workspace| {
        workspace
            .join(WORKSPACE_LOCAL_DIR_NAME)
            .join(WORKSPACE_HOOKS_DIR_NAME)
    });

    let hook_dirs = vec![
        path_report(install_dir.as_deref(), &hook_dir_entries),
        path_report(
            store_hooks_dir.as_deref(),
            &entry_names(store_hooks_dir.as_deref()),
        ),
        path_report(
            workspace_rules_dir.as_deref(),
            &entry_names(workspace_rules_dir.as_deref()),
        ),
        path_report(
            workspace_local_dir.as_deref(),
            &entry_names(workspace_local_dir.as_deref()),
        ),
    ];

    let plugin_dir_path = store_path
        .as_ref()
        .map(|store| store.join(STORE_PLUGINS_DIR_NAME));
    let plugin_dir_entries = entry_names(plugin_dir_path.as_deref());
    let plugin_dir = path_report(plugin_dir_path.as_deref(), &plugin_dir_entries);

    // Hoisted out of the struct literal below because the enforcement surface
    // is a function of it: the switch is read once and both fields are
    // rendered from that one read, rather than the document carrying a list
    // read at one instant and a verdict read at another.
    let plugins_asserted_disabled = settings_dir
        .as_ref()
        .and_then(|settings| {
            read_projection::<GlobalSettingsProjection>(&settings.join(GLOBAL_SETTINGS_FILE_NAME))
                .value()
        })
        .and_then(|projection| projection.disabled_plugins);

    // THE detector, the same one the binding's `liveness()` and
    // `capabilities()` go through — reached here with the two facts already in
    // hand rather than through the live resolver, so this stays a probe of the
    // roots it resolved at the top and not a second, later resolution.
    //
    // The fourth file this probe opens, and the only one that is **ours**: our
    // own plugin, read to check its ownership marker. C-6's exclusion list is
    // about Cline's data and is untouched by it.
    let enforcement_surface = plugin_dir_path.as_deref().map_or(
        crate::hooks::cline_plugin::EnforcementSurface::None,
        |plugins| {
            crate::hooks::cline_plugin::enforcement_surface(
                &crate::hooks::cline_plugin::plugin_dir(plugins),
                plugins_asserted_disabled.as_deref(),
            )
        },
    );

    let mcp_path = settings_dir
        .as_ref()
        .map(|settings| settings.join(MCP_SETTINGS_FILE_NAME));
    let mcp_registry = mcp_path
        .as_deref()
        .map_or(FollowUp::Missing, read_projection::<McpSettingsProjection>);
    let mcp_settings = path_report(mcp_path.as_deref(), &mcp_registry);

    let home = dirs::home_dir();
    let editor_roots = extension_roots(home.as_deref());
    let extension_state = extension_state(home.is_some(), &editor_roots);

    let surfaces = vec![
        SurfaceFinding::new(Surface::Store, store_report.state),
        SurfaceFinding::new(Surface::HookDir, hook_dir_state(&hook_dirs)),
        SurfaceFinding::new(Surface::PluginDir, plugin_dir.state),
        SurfaceFinding::new(Surface::McpSettings, mcp_settings.state),
        SurfaceFinding::new(Surface::Extension, extension_state),
    ];

    let mut unclassified = unclassified_under("store", store_path.as_deref(), STORE_KNOWN_CHILDREN);
    unclassified.extend(unclassified_under(
        "asset",
        asset_root.resolved.as_deref(),
        ASSET_KNOWN_CHILDREN,
    ));

    ClineAttestation {
        as_of,
        host_shells: host_shells(&editor_roots),
        hook_dir_entries: hook_dir_entries.value(),
        plugin_dir_entries: plugin_dir_entries.value(),
        plugins_asserted_disabled,
        enforcement_surface,
        mcp_servers: mcp_registry
            .value()
            .map(|projection| projection.mcp_servers.into_keys().collect()),
        providers: settings_dir
            .as_ref()
            .and_then(|settings| {
                read_projection::<ProvidersProjection>(&settings.join(PROVIDERS_FILE_NAME)).value()
            })
            .map(|projection| {
                projection
                    .providers
                    .into_iter()
                    .map(|(id, presence)| ProviderReport {
                        id,
                        base_url_present: presence.0,
                    })
                    .collect()
            }),
        store_root: store_report,
        asset_root,
        hook_dirs,
        plugin_dir,
        mcp_settings,
        extension_roots: editor_roots,
        surfaces,
        unclassified,
    }
}

impl ClineAttestation {
    /// The machine rendering — the object `doctor --json` merges in under
    /// `agents.cline`.
    ///
    /// Hand-written rather than derived, per DD-06: `src/cli/report.rs` carries
    /// zero `Serialize` derives across its seven types, so the derive route
    /// means annotating a module rather than a struct. Hand-writing also keeps
    /// every emitted key visible in one place — which is what makes "the value
    /// of a `baseUrl` is not in here" reviewable.
    ///
    /// **No per-field versioning** (DD-16). LSP tags each feature `@since` and
    /// ships a `metaModel.json` so an independently released consumer can
    /// compute which fields a producer may emit; hand-extending a JSON document
    /// gives none of that. Accepted cost, recorded rather than silent.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "as_of": self.as_of,
            "store_root": {
                "path": path_json(self.store_root.path.as_deref()),
                "located_by": self.store_root.located_by.as_str(),
                "state": self.store_root.state.as_str(),
            },
            "asset_root": {
                "path": path_json(self.asset_root.resolved.as_deref()),
                "located_by": self.asset_root.located_by.as_str(),
                "hit": self.asset_root.hit.as_str(),
                "lanes_agree": self.asset_root.lanes_agree,
                "lanes": self.asset_root.lanes.iter().map(|lane| serde_json::json!({
                    "lane": lane.lane.as_str(),
                    "path": crate::core::path_compat::display_path(&lane.path),
                    "exists": lane.exists,
                })).collect::<Vec<_>>(),
            },
            "host_shells": self.host_shells.iter().map(|shell| serde_json::json!({
                "shell": shell.shell,
                "state": shell.state.as_str(),
                "basis": shell.basis,
            })).collect::<Vec<_>>(),
            // All four, positionally, in Cline's own precedence order — a
            // consumer indexes `hook_dirs[0]` for the one we install into.
            "hook_dirs": self.hook_dirs.iter().map(|dir| serde_json::json!({
                "path": path_json(dir.path.as_deref()),
                "state": dir.state.as_str(),
            })).collect::<Vec<_>>(),
            // What is INSTALLED, not what is HONOURED. Never `hook_events`.
            "hook_dir_entries": self.hook_dir_entries,
            "plugin_dir": {
                "path": path_json(self.plugin_dir.path.as_deref()),
                "state": self.plugin_dir.state.as_str(),
                "entries": self.plugin_dir_entries,
                "asserted_disabled": self.plugins_asserted_disabled,
            },
            // Top-level, not nested under `plugin_dir`: the enforcement surface
            // is a fact about the HOST, and it is the one field in this
            // document a consumer asserts on to decide whether this machine
            // enforces. `plugin_dir` is what was observed under a root.
            //
            // Always a string, never `null` — see the field's own note.
            "enforcement_surface": self.enforcement_surface.as_str(),
            "mcp_settings": {
                "path": path_json(self.mcp_settings.path.as_deref()),
                "state": self.mcp_settings.state.as_str(),
            },
            "mcp_servers": self.mcp_servers,
            "providers": self.providers.as_ref().map(|providers| {
                providers.iter().map(|provider| serde_json::json!({
                    "id": provider.id,
                    "base_url_present": provider.base_url_present,
                })).collect::<Vec<_>>()
            }),
            "extension_roots": self.extension_roots.iter().map(|root| serde_json::json!({
                "path": crate::core::path_compat::display_path(&root.path),
                "exists": root.exists,
                "lineage": root.lineage.as_str(),
                "matched": root.matched,
                "entries_scanned": root.entries_scanned,
            })).collect::<Vec<_>>(),
            "surfaces_absent": self.surfaces.iter().map(SurfaceFinding::to_json).collect::<Vec<_>>(),
            "surfaces_unclassified": self.unclassified.iter().map(|entry| serde_json::json!({
                "root": entry.root,
                "name": entry.name,
                "kind": entry.kind,
            })).collect::<Vec<_>>(),
        })
    }

    /// One line naming the store root and what was found under it.
    ///
    /// Carries the resolved store path deliberately: it is the one string in
    /// `doctor`'s output that belongs to this attestation and to nothing else,
    /// so an acceptance step can prove the attestation was rendered rather than
    /// matching the word "Cline" from an unrelated remedy.
    pub fn summary(&self) -> String {
        format!(
            "Cline store {} ({}, {}) — {} of {} surfaces present, as of {}",
            self.store_root
                .path
                .as_deref()
                .map_or_else(|| "<unresolved>".to_string(), display_root),
            self.store_root.located_by.as_str(),
            self.store_root.state.as_str(),
            self.surfaces
                .iter()
                .filter(|finding| finding.state == SurfaceState::Present)
                .count(),
            self.surfaces.len(),
            self.as_of,
        )
    }

    /// The human rendering, one line per fact, isomorphic to [`Self::to_json`]
    /// (P7 — DD-07).
    ///
    /// `to_json` is documented as *"the machine rendering, isomorphic to the
    /// human one"*, so an attestation that reached `--json` alone would break a
    /// stated invariant of a file this unit does not even touch.
    pub fn human_lines(&self) -> Vec<String> {
        let mut lines = vec![self.summary()];

        lines.push(format!(
            "Cline user assets {} ({}, lane: {}, lanes {})",
            self.asset_root
                .resolved
                .as_deref()
                .map_or_else(|| "<unresolved>".to_string(), display_root),
            self.asset_root.located_by.as_str(),
            self.asset_root.hit.as_str(),
            if self.asset_root.lanes_agree {
                "agree"
            } else {
                "disagree"
            },
        ));
        for lane in &self.asset_root.lanes {
            lines.push(format!(
                "Cline asset lane {} {} ({})",
                lane.lane.as_str(),
                display_root(&lane.path),
                if lane.exists { "present" } else { "absent" },
            ));
        }

        // One line per search directory, numbered from 1 so the number in the
        // text is the lane and the label says which. The first line carries the
        // installed-entry list as well: it is the only one of the four this
        // build writes into, and the only one whose filenames are reported.
        for (index, dir) in self.hook_dirs.iter().enumerate() {
            let label = HOOK_DIR_LABELS.get(index).copied().unwrap_or("unnamed");
            let path = dir
                .path
                .as_deref()
                .map_or_else(|| "<unresolved>".to_string(), display_root);
            let state = dir.state.as_str();
            lines.push(if index == 0 {
                format!(
                    "Cline hook dir {} ({label}) {path} ({state}); \
                     installed entries (not events): {}",
                    index + 1,
                    render_list(self.hook_dir_entries.as_deref()),
                )
            } else {
                format!("Cline hook dir {} ({label}) {path} ({state})", index + 1)
            });
        }
        lines.push(format!(
            "Cline plugin dir {} ({}); observed {}; asserted disabled {}",
            self.plugin_dir
                .path
                .as_deref()
                .map_or_else(|| "<unresolved>".to_string(), display_root),
            self.plugin_dir.state.as_str(),
            render_list(self.plugin_dir_entries.as_deref()),
            render_list(self.plugins_asserted_disabled.as_deref()),
        ));
        // Its own line rather than a clause on the one above, because it is the
        // line a developer reading `doctor --verbose` is looking for: not what
        // is in the directory, but whether this host can refuse anything.
        lines.push(format!(
            "Cline enforcement surface: {}",
            self.enforcement_surface.as_str(),
        ));
        lines.push(format!(
            "Cline MCP registry {} ({}); servers: {}",
            self.mcp_settings
                .path
                .as_deref()
                .map_or_else(|| "<unresolved>".to_string(), display_root),
            self.mcp_settings.state.as_str(),
            render_list(self.mcp_servers.as_deref()),
        ));
        lines.push(format!(
            "Cline providers: {}",
            match &self.providers {
                None => "undetermined".to_string(),
                Some(providers) if providers.is_empty() => "none".to_string(),
                Some(providers) => providers
                    .iter()
                    .map(|provider| format!(
                        "{} (baseUrl {})",
                        provider.id,
                        if provider.base_url_present {
                            "declared"
                        } else {
                            "absent"
                        }
                    ))
                    .collect::<Vec<_>>()
                    .join(", "),
            }
        ));
        for shell in &self.host_shells {
            lines.push(format!(
                "Cline host shell {}: {} ({})",
                shell.shell,
                shell.state.as_str(),
                shell.basis
            ));
        }
        for root in &self.extension_roots {
            lines.push(format!(
                "Cline editor root {} (root {}, lineage {}, {} entries scanned){}",
                display_root(&root.path),
                if root.exists { "present" } else { "absent" },
                root.lineage.as_str(),
                root.entries_scanned,
                if root.matched.is_empty() {
                    String::new()
                } else {
                    format!(": {}", root.matched.join(", "))
                }
            ));
        }
        for entry in &self.unclassified {
            lines.push(format!(
                "Cline unclassified under {} root: {} ({})",
                entry.root, entry.name, entry.kind
            ));
        }
        for finding in &self.surfaces {
            lines.push(format!(
                "Cline surface {}: {}{}",
                finding.surface.as_str(),
                finding.state.as_str(),
                match (finding.code, finding.remedy) {
                    (Some(code), Some(remedy)) => format!(" ({code}) — {remedy}"),
                    _ => String::new(),
                }
            ));
        }
        lines
    }

    /// Spec **AC-4**: the store is on this host and no editor root held a
    /// Cline-lineage extension.
    ///
    /// A state `doctor` warns about by name and never renders green — it is the
    /// shape a rebranded fork takes, and the install guide is blocked on knowing
    /// which one it is. Deliberately **not** true when the store is absent (this
    /// host simply has no Cline) or when either answer is undetermined (a
    /// warning we cannot substantiate is noise).
    pub fn store_without_extension(&self) -> bool {
        self.state_of_surface(Surface::Store) == Some(SurfaceState::Present)
            && self.state_of_surface(Surface::Extension) == Some(SurfaceState::Absent)
    }

    /// One surface's state, for a caller that wants a single row (DD-14).
    pub fn state_of_surface(&self, surface: Surface) -> Option<SurfaceState> {
        self.surfaces
            .iter()
            .find(|finding| finding.surface == surface)
            .map(|finding| finding.state)
    }
}

impl LocatedBy {
    /// The wire spelling — `default` or `operator-supplied` (PRD D-16).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::OperatorSupplied => "operator-supplied",
        }
    }
}

/// A path as it should appear to a human or on the wire.
fn display_root(path: &Path) -> String {
    crate::core::path_compat::display_path(path)
}

/// `null` when a root did not resolve at all, which is a different fact from an
/// empty string.
fn path_json(path: Option<&Path>) -> serde_json::Value {
    match path {
        Some(path) => serde_json::Value::String(display_root(path)),
        None => serde_json::Value::Null,
    }
}

/// `undetermined` / `none` / the list — the human form of an `Option<Vec<_>>`,
/// where `None` and `[]` are different findings.
fn render_list(items: Option<&[String]>) -> String {
    match items {
        None => "undetermined".to_string(),
        Some([]) => "none".to_string(),
        Some(items) => items.join(", "),
    }
}

/// [`Surface::HookDir`]'s one state, rolled up from the four rows.
///
/// `Surface::ALL` is closed at five and a sixth variant is a schema change the
/// platform sees, so the enumerated surface stays one finding and
/// [`ClineAttestation::hook_dirs`] carries the per-directory detail beside it
/// (DD-14 is satisfied by the rows, not by splitting the surface).
///
/// The ordering is [`extension_state`]'s, for the same reason: a directory that
/// is genuinely there beats one that is not, and *we could not tell* beats a
/// confident `absent` (DD-11). So one present row makes the surface present,
/// and absent is only reached when every row was looked at and none was there.
fn hook_dir_state(dirs: &[PathReport]) -> SurfaceState {
    if dirs.iter().any(|dir| dir.state == SurfaceState::Present) {
        return SurfaceState::Present;
    }
    if dirs
        .iter()
        .any(|dir| dir.state == SurfaceState::Undetermined)
    {
        return SurfaceState::Undetermined;
    }
    SurfaceState::Absent
}

/// What a path's existence says, three-valued.
fn state_of(path: Option<&Path>) -> SurfaceState {
    match path {
        // No home directory and no seam: we never looked anywhere. That is not
        // an absence.
        None => SurfaceState::Undetermined,
        Some(path) => classify_metadata(std::fs::metadata(path)),
    }
}

/// The body of [`state_of`] with the filesystem's answer passed in.
///
/// A separate function because the interesting cases cannot be produced
/// portably from a temp directory: `PermissionDenied` on a path we can name
/// requires either root or a platform-specific chmod dance, and DD-11 is
/// precisely the rule that a refused lookup must not read as a confident
/// absence. Passing the `io::Result` in is the same device [`require_seam`]
/// uses.
fn classify_metadata(metadata: std::io::Result<std::fs::Metadata>) -> SurfaceState {
    match metadata {
        Ok(_) => SurfaceState::Present,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => SurfaceState::Absent,
        // Permission denied, a name too long, a broken mount: we looked and the
        // filesystem refused to answer. Reporting `absent` here is the
        // `@supports` failure mode DD-11 names.
        Err(_) => SurfaceState::Undetermined,
    }
}

/// What a surface's required follow-up lookup did.
///
/// **The type that keeps DD-11 from being restated at four call sites.** A
/// surface is classified by stat-ing its path, but every surface that has a
/// follow-up — list this directory, parse this registry — can have the stat
/// succeed and the follow-up fail. Reporting `present` there puts the two
/// renderings in disagreement inside one run: `surfaces_absent` says `present`
/// and `doctor` renders green, while the detail line beside it says
/// `undetermined`. Reporting `absent` is worse still, and is the confident
/// absence DD-11 forbids outright.
enum FollowUp<T> {
    /// It answered.
    Read(T),
    /// There was nothing to read, which is what the stat already said.
    Missing,
    /// It is there and this build could not read it. `absent` is not one of the
    /// answers available from here.
    Refused,
}

impl<T> FollowUp<T> {
    /// What this outcome does to the state the stat produced.
    ///
    /// One direction only: a refused follow-up takes any state to
    /// `undetermined`. A follow-up never manufactures `present` or `absent` —
    /// [`state_of`] owns those.
    fn refine(&self, state: SurfaceState) -> SurfaceState {
        match self {
            Self::Refused => SurfaceState::Undetermined,
            Self::Read(_) | Self::Missing => state,
        }
    }

    /// The payload, where `None` means *we do not have it* — the shape C-1's
    /// optional fields keep, in which `None` and `[]` are different findings.
    fn value(self) -> Option<T> {
        match self {
            Self::Read(value) => Some(value),
            Self::Missing | Self::Refused => None,
        }
    }
}

/// A path's report: where we looked, and what the stat **and** the follow-up
/// together say was there.
///
/// **The single place a surface with a follow-up is classified.** Scattering
/// the rule across the three call sites is how the two renderings come to
/// disagree; keeping it here is what makes "a present surface we could not read
/// is `undetermined`" a property of the constructor rather than of three
/// callers remembering it.
fn path_report<T>(path: Option<&Path>, follow_up: &FollowUp<T>) -> PathReport {
    PathReport {
        path: path.map(Path::to_path_buf),
        state: follow_up.refine(state_of(path)),
    }
}

/// Directory entry names, sorted.
///
/// [`FollowUp::Missing`] is *there is no such directory* — the fact the stat
/// already reports — and [`FollowUp::Refused`] is *it is there and we could not
/// list it*, which covers both a refused `read_dir` and a `read_dir` that opened
/// and then failed part-way through.
fn entry_names(dir: Option<&Path>) -> FollowUp<Vec<String>> {
    let Some(dir) = dir else {
        // No path resolved at all: `state_of` already reads this `undetermined`
        // and there is nothing here to read.
        return FollowUp::Missing;
    };
    match std::fs::read_dir(dir) {
        Ok(entries) => classify_entries(entries.map(|entry| entry.map(|entry| entry.file_name()))),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => FollowUp::Missing,
        Err(_) => FollowUp::Refused,
    }
}

/// The body of [`entry_names`] with the directory's answers passed in.
///
/// A separate function for the reason [`classify_metadata`] is one: the
/// interesting case cannot be produced from a temp directory. A directory whose
/// *open* is refused is one `chmod` away, but one that opens and then fails
/// **mid-iteration** — a mount that went away, a `getdents` that returned EIO —
/// is not reproducible on demand, and it is exactly the case where discarding
/// the per-entry error turns a partial listing into a confident empty one.
fn classify_entries(
    entries: impl IntoIterator<Item = std::io::Result<OsString>>,
) -> FollowUp<Vec<String>> {
    let mut names = Vec::new();
    for entry in entries {
        let Ok(name) = entry else {
            // One refused entry and this is not a listing. What was read is
            // dropped rather than returned short: a partial list read as a
            // complete one is the confident absence DD-11 forbids.
            return FollowUp::Refused;
        };
        names.push(name.to_string_lossy().into_owned());
    }
    names.sort();
    FollowUp::Read(names)
}

/// Everything directly under `root` that `known` does not name (DD-13).
///
/// Depth one, deliberately: the residual answers *"what is here that we do not
/// recognise"*, and walking a developer's store recursively would both cost
/// real time on every `doctor` run and reach into trees C-6 excludes.
fn unclassified_under(
    label: &'static str,
    root: Option<&Path>,
    known: &[&str],
) -> Vec<UnclassifiedEntry> {
    let Some(root) = root else {
        return Vec::new();
    };
    let Ok(entries) = std::fs::read_dir(root) else {
        return Vec::new();
    };

    let mut residual: Vec<UnclassifiedEntry> = entries
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            // Case-insensitive, because a fork may capitalise differently and a
            // `Rules/` we failed to classify would be residual noise rather
            // than a finding. The observed name is kept verbatim either way —
            // never destroy the vendor encoding while normalising (DD-12).
            if known
                .iter()
                .any(|candidate| candidate.eq_ignore_ascii_case(&name))
            {
                return None;
            }
            let kind = match entry.file_type() {
                Ok(kind) if kind.is_dir() => "dir",
                Ok(kind) if kind.is_file() => "file",
                _ => "other",
            };
            Some(UnclassifiedEntry {
                root: label,
                name,
                kind,
            })
        })
        .collect();
    residual.sort_by(|a, b| a.name.cmp(&b.name));
    residual
}

/// Every editor root this build knows, and what each held.
fn extension_roots(home: Option<&Path>) -> Vec<ExtensionRootReport> {
    let Some(home) = home else {
        return Vec::new();
    };
    EXTENSION_ROOT_BASES
        .iter()
        .flat_map(|base| [(*base).to_string(), format!("{base}-server")])
        .map(|name| extension_root_report(home.join(name)))
        .collect()
}

/// One editor root's report.
fn extension_root_report(root: PathBuf) -> ExtensionRootReport {
    let exists = root.is_dir();
    let extensions = root.join(EXTENSION_DIR_NAME);
    // The reader the hook and plugin directories use, for the reason they use
    // it: a listing that could not be *completed* must not come back as an
    // empty one. An `extensions/` we were refused part-way through would
    // otherwise leave `matched` empty, and an empty `matched` is what fires
    // spec AC-4's "no Cline-lineage extension was found" against a host nobody
    // managed to look at.
    let (lineage, matched, entries_scanned) = match entry_names(Some(&extensions)) {
        // Already sorted by the reader, so the filter's output is too.
        FollowUp::Read(names) => {
            let matched: Vec<String> = names
                .iter()
                .filter(|name| is_cline_lineage(name))
                .cloned()
                .collect();
            let lineage = if matched.is_empty() {
                SurfaceState::Absent
            } else {
                SurfaceState::Present
            };
            (lineage, matched, names.len())
        }
        // Not there at all: we enumerated the search space and it was empty.
        FollowUp::Missing => (SurfaceState::Absent, Vec::new(), 0),
        // Refused, at the open or mid-listing. Reporting `absent` would
        // manufacture the finding DD-11 forbids.
        FollowUp::Refused => (SurfaceState::Undetermined, Vec::new(), 0),
    };
    ExtensionRootReport {
        path: root,
        exists,
        lineage,
        matched,
        entries_scanned,
    }
}

/// Whether an extension directory name reads as Cline-lineage.
///
/// **Decides nothing** (DD-10). Detection is store-keyed; this only answers
/// *which editor root held it*, and a fork that matches nothing here is still
/// detected, still attested, and reports its `extension` surface `absent` —
/// which is spec AC-5.
fn is_cline_lineage(name: &str) -> bool {
    let name = name.to_ascii_lowercase();
    EXTENSION_LINEAGE_MARKERS
        .iter()
        .any(|marker| name.contains(marker))
}

/// The `extension` surface's state, aggregated over every editor root.
fn extension_state(home_resolved: bool, roots: &[ExtensionRootReport]) -> SurfaceState {
    if !home_resolved {
        // Nowhere to look. Not an absence.
        return SurfaceState::Undetermined;
    }
    if roots
        .iter()
        .any(|root| root.lineage == SurfaceState::Present)
    {
        return SurfaceState::Present;
    }
    if roots
        .iter()
        .any(|root| root.lineage == SurfaceState::Undetermined)
    {
        return SurfaceState::Undetermined;
    }
    // Every root in the search space was enumerated and none held one. AC-5's
    // case: a store with no extension metadata at all is attested, with this
    // reading `absent`.
    SurfaceState::Absent
}

/// Which client shows evidence of use.
///
/// `~/.cline/` is shared by the extension, the CLI and JetBrains — C-1 says so —
/// so this reports what it can distinguish and says when it cannot. The one
/// signal this build has is an extension in an editor root; inventing a CLI or
/// JetBrains detector from an unverified artifact would be worse than
/// `undetermined`, because a reader cannot tell a wrong answer from a careful
/// one.
fn host_shells(roots: &[ExtensionRootReport]) -> Vec<HostShellReport> {
    let vscode = if roots
        .iter()
        .any(|root| root.lineage == SurfaceState::Present)
    {
        SurfaceState::Present
    } else {
        SurfaceState::Undetermined
    };
    vec![
        HostShellReport {
            shell: "vscode",
            state: vscode,
            basis: "a Cline-lineage extension in an enumerated editor root",
        },
        HostShellReport {
            shell: "cli",
            state: SurfaceState::Undetermined,
            basis: "the store root is shared by the extension, the CLI and JetBrains; this \
                    build distinguishes no CLI-only artifact",
        },
        HostShellReport {
            shell: "jetbrains",
            state: SurfaceState::Undetermined,
            basis: "the store root is shared by the extension, the CLI and JetBrains; this \
                    build distinguishes no JetBrains-only artifact",
        },
    ]
}

/// Cline's MCP registry, projected to server ids.
///
/// `IgnoredAny` is the enforcement: an `env` block — which routinely carries API
/// keys — is skipped by the deserializer rather than read into a value we then
/// choose not to print. `BTreeMap` sorts the ids, so two runs of the probe
/// produce comparable output.
#[derive(serde::Deserialize)]
struct McpSettingsProjection {
    #[serde(default, rename = "mcpServers")]
    mcp_servers: std::collections::BTreeMap<String, serde::de::IgnoredAny>,
}

/// `global-settings.json`, projected to the one key this probe reads.
///
/// The **asserted** half of DD-12's pair: Cline's own claim about which plugins
/// are switched off, kept beside the plugin directory entries we observed.
/// C-6 names this file watchable, so reading it is in contract.
#[derive(serde::Deserialize)]
struct GlobalSettingsProjection {
    #[serde(default, rename = "disabledPlugins")]
    disabled_plugins: Option<Vec<String>>,
}

/// `providers.json`, projected to ids and `baseUrl` presence — C-6's one
/// narrowed exception, and nothing more.
#[derive(serde::Deserialize)]
struct ProvidersProjection {
    #[serde(default)]
    providers: std::collections::BTreeMap<String, BaseUrlPresence>,
}

/// Whether a provider entry declares a `baseUrl`, deserialized without ever
/// materialising the value.
///
/// Every value in the entry — the `baseUrl`, an `apiKey`, anything a fork added
/// — is consumed as [`serde::de::IgnoredAny`], which skips it in the parser
/// rather than allocating it. C-6 says a reader that *"slurps the whole file to
/// find one field violates this contract even if it discards the rest"*; this
/// is what not slurping looks like in a typed parser.
struct BaseUrlPresence(bool);

impl<'de> serde::Deserialize<'de> for BaseUrlPresence {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = BaseUrlPresence;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a provider entry")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                let mut present = false;
                while let Some(key) = map.next_key::<String>()? {
                    if key == PROVIDER_SETTINGS_KEY {
                        // Descend exactly one level, through THIS SAME visitor —
                        // so the nested object is also read key-only, with every
                        // value consumed as `IgnoredAny`. C-6 holds at the leaf:
                        // there is still no branch on which a `baseUrl` VALUE is
                        // read, and no field that could hold one.
                        let nested: BaseUrlPresence = map.next_value()?;
                        present |= nested.0;
                    } else {
                        // Unconditional, and before the comparison: there is no
                        // branch on which a value is read.
                        map.next_value::<serde::de::IgnoredAny>()?;
                    }
                    // The flat shape is still accepted. A fork that keeps
                    // `baseUrl` at the entry's top level is exactly the case
                    // DD-10 means by attesting to capability rather than
                    // identity — degrade honestly, do not assume our layout.
                    present |= key == BASE_URL_KEY;
                }
                Ok(BaseUrlPresence(present))
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
                Ok(BaseUrlPresence(false))
            }

            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                deserializer.deserialize_any(Visitor)
            }

            fn visit_none<E>(self) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_bool<E>(self, _value: bool) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_i64<E>(self, _value: i64) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_u64<E>(self, _value: u64) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_f64<E>(self, _value: f64) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }

            fn visit_str<E>(self, _value: &str) -> Result<Self::Value, E> {
                Ok(BaseUrlPresence(false))
            }
        }

        // `deserialize_any`, not `deserialize_map`: a fork whose provider entry
        // is a string or a null must not take the whole provider list to
        // `undetermined` with it. Every non-map arm answers "declares no
        // baseUrl", which is true of all of them.
        deserializer.deserialize_any(Visitor)
    }
}

/// Read one config file into a projection.
///
/// Three-valued rather than an `Option`, because the surface above it is: a file
/// that is **not there** is an absence the stat already reports, and a file that
/// is there and did not parse — malformed, refused mid-read, or truncated at
/// [`MAX_CONFIG_READ_BYTES`] — is a surface whose contents we do not know. The
/// second of those must not reach the reader as `present` with an empty list
/// beside it. The reader is a bounded `Take` over a `BufReader`, so the file is
/// streamed into the projection rather than read into memory and then discarded.
fn read_projection<T: serde::de::DeserializeOwned>(path: &Path) -> FollowUp<T> {
    use std::io::Read;

    let file = match std::fs::File::open(path) {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return FollowUp::Missing,
        Err(_) => return FollowUp::Refused,
    };
    let reader = std::io::BufReader::new(file.take(MAX_CONFIG_READ_BYTES));
    match serde_json::from_reader(reader) {
        Ok(projection) => FollowUp::Read(projection),
        Err(_) => FollowUp::Refused,
    }
}

// ---------------------------------------------------------------------------
// The request plane — where Cline's provider settings live
// ---------------------------------------------------------------------------

/// The root object holding one entry per configured provider.
pub(crate) const PROVIDERS_ROOT_KEY: &str = "providers";

/// The container inside a provider entry that carries its connection settings.
///
/// **Cline nests one level deeper than the base-URL key** — the path is
/// `providers.<id>.settings.baseUrl`. Verified against a real `v4.1.17` store
/// carrying four providers; an entry's own keys are only `settings` /
/// `tokenSource` / `updatedAt`.
///
/// PRD C-2 and both units' plans specified the two-level
/// `providers.<id>.baseUrl`. That error had already shipped once: I-1's probe
/// scanned an entry's own keys and so answered `base_url_present: false` for
/// **every provider on every real store** — a confidently wrong fact in the one
/// document a customer is asked to act on. The writer would have made the
/// mirror-image mistake, putting a key Cline never reads. One constant now, so
/// the reader, the writer and the probe cannot drift apart on it again.
pub(crate) const PROVIDER_SETTINGS_KEY: &str = "settings";

/// Cline's `providers.json`, under the **data** root.
///
/// **Not `store_root()`/`config_dir()`.** [`DATA_DIR_ENV`] is an independent
/// resolver at a different level of the tree (see [`data_root`]), so a customer
/// who sets it has `data/` somewhere else entirely and `config_dir().join("data")`
/// writes to a directory Cline never reads — a wiring that passes every test
/// and captures nothing.
///
/// A bare `data_root()` call rather than `cline::data_root()`: this is inside
/// the module, which is not a path root of itself.
pub fn providers_json_path() -> Option<PathBuf> {
    Some(
        data_root()?
            .0
            .join(DATA_SETTINGS_DIR_NAME)
            .join(PROVIDERS_FILE_NAME),
    )
}

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

    /// Everything a Cline resolver test runs under: a redirected `HOME`, all
    /// three seams pointed at temp directories, and the seam guard held.
    ///
    /// **Field order is drop order.** The overrides go back before either lock
    /// is released, so a test blocked on the seam lock never observes another
    /// test's redirection.
    struct Isolated {
        _seam: ClineSeam,
        _home_lock: std::sync::MutexGuard<'static, ()>,
        /// Held only by [`isolated_with_state`]. `OPENLATCH_DIR` is
        /// process-wide and has its OWN lock, which comes FIRST in the crate's
        /// total order — a fixture that redirected it while holding only the
        /// others would let a sibling's `OPENLATCH_DIR` land under this test's
        /// endpoint-record write, and both would read the other's file.
        _state_lock: Option<std::sync::MutexGuard<'static, ()>>,
        root: TempDir,
    }

    impl Isolated {
        /// Unix-only, because every caller is. The assertions that use it
        /// expect a `$HOME`-relative store (`~/.cline`), which is not where
        /// Cline lives on Windows; they are already `#[cfg(unix)]`. Without the
        /// same gate here the method is dead code on Windows and `-D warnings`
        /// fails `windows-cross` on it.
        #[cfg(unix)]
        fn home(&self) -> PathBuf {
            self.root.path().join("home")
        }
        fn store(&self) -> PathBuf {
            self.root.path().join("store")
        }
        fn data(&self) -> PathBuf {
            self.root.path().join("data")
        }
    }

    /// Take the locks first, then the guard, which redirects under the seam
    /// lock.
    ///
    /// `HOME` belongs to `claude_code::CONFIG_DIR_ENV_LOCK` by that lock's own
    /// documentation, and it comes before [`SEAM_ENV_LOCK`] in the crate's
    /// total order.
    fn isolated() -> Isolated {
        isolated_inner(false)
    }

    fn isolated_inner(redirect_state: bool) -> Isolated {
        // FIRST in the crate's documented lock order, before the home lock.
        let state_lock = redirect_state.then(|| {
            crate::config::OPENLATCH_DIR_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner())
        });
        let home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        // Never created, like every other seam this crate points a fixture at:
        // the resolvers below are pure string work and stat nothing, so a
        // directory that exists buys the test nothing and would arm a
        // stat-based detector the day one lands.
        let root = tempfile::tempdir().expect("tempdir");

        let state_dir = root.path().join("openlatch");
        if redirect_state {
            std::fs::create_dir_all(&state_dir).expect("create the isolated OPENLATCH_DIR");
        }
        let seam = cline_isolated([
            ("HOME", Some(root.path().join("home").into_os_string())),
            (
                "OPENLATCH_DIR",
                redirect_state.then(|| state_dir.into_os_string()),
            ),
            (
                STORE_DIR_ENV,
                Some(root.path().join("store").into_os_string()),
            ),
            (
                DATA_DIR_ENV,
                Some(root.path().join("data").into_os_string()),
            ),
            (
                ASSETS_DIR_ENV,
                Some(root.path().join("assets").into_os_string()),
            ),
        ]);

        Isolated {
            _seam: seam,
            _home_lock: home_lock,
            _state_lock: state_lock,
            root,
        }
    }

    // -----------------------------------------------------------------------
    // The request plane (I-2)
    // -----------------------------------------------------------------------

    /// **M3.** The path follows the DATA root, which is an independent resolver.
    ///
    /// `config_dir().join("data")` passes a naive test — the two agree whenever
    /// only `CLINE_DIR` is set — and writes where Cline never reads for every
    /// customer who has set `CLINE_DATA_DIR`. The fixture points the two
    /// somewhere genuinely different, which is the only shape that can tell
    /// them apart.
    #[test]
    fn providers_path_follows_data_root_not_store_root() {
        let iso = isolated();

        let path = providers_json_path().expect("a data root resolves");

        assert_eq!(path, iso.data().join("settings").join("providers.json"));
        assert!(
            !path.starts_with(iso.store()),
            "the store root is a different tree: {}",
            path.display()
        );
        assert_ne!(
            path,
            iso.store()
                .join("data")
                .join("settings")
                .join("providers.json"),
            "deriving the path from config_dir() would write here, which Cline never reads"
        );
    }

    /// **A customer's own loopback endpoint is not ours.**
    ///
    /// `remover_returns_early_when_entry_is_not_ours` above proves this for a
    /// REMOTE foreign endpoint (`https://qwen.internal.bea`), which is the half
    /// the predicate gets right. Ownership is
    /// [`crate::hooks::is_openlatch_loopback_base_url`], which tests the HOST
    /// alone — so a customer running Ollama, LM Studio or llama.cpp on
    /// `127.0.0.1` has their own entry collected as one we wrote, and every
    /// caller guarded by it then acts on a claim that was never true.
    /// A relocated store with the next bundle's data lane still on the real
    /// `~/.cline/data` is not isolated: that lane is the developer's own
    /// `globalState.json` and `providers.json`.
    #[test]
    fn config_is_machine_global_checks_the_data_lanes() {
        let _home_lock = crate::hooks::claude_code::CONFIG_DIR_ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _seam_lock = SEAM_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let root = tempfile::tempdir().expect("tempdir");
        let home = root.path().join("home");
        let sandbox = root.path().join("sandbox");
        let with = |data: PathBuf| {
            EnvOverride::apply([
                ("HOME", Some(home.clone().into_os_string())),
                (STORE_DIR_ENV, Some(sandbox.join("cline").into_os_string())),
                (DATA_DIR_ENV, Some(data.into_os_string())),
            ])
        };

        let isolated = with(sandbox.join("cline-data"));
        assert!(!config_is_machine_global(), "both lanes relocated");
        // The machine-global lane is whatever `dirs::home_dir()` answers under
        // this override — asked here, while it is applied, rather than built
        // from the redirected `HOME`. On Windows `dirs::home_dir()` resolves
        // `FOLDERID_Profile` through `SHGetKnownFolderPath` and reads no
        // environment variable at all, so a `HOME`-derived path is not the
        // machine's own directory there and the case under test never arose.
        // Nothing is created: the predicate only canonicalizes and compares.
        let machine_data = dirs::home_dir()
            .expect("a home directory")
            .join(DEFAULT_STORE_DIR_NAME)
            .join(DEFAULT_DATA_DIR_NAME);
        drop(isolated);

        let _half = with(machine_data);
        assert!(
            config_is_machine_global(),
            "the next bundle's lane is the machine's own data directory"
        );
    }

    /// The message a panicking check produced.
    ///
    /// The hook is silenced for the duration so a deliberate panic does not
    /// print a backtrace that reads like a failure, and restored immediately.
    fn panic_message(f: impl FnOnce()) -> String {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
        std::panic::set_hook(previous);

        let payload = caught.expect_err("the checked call must panic");
        payload
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
            .expect("a panic payload carrying a message")
    }

    /// An exported-but-blank seam reads as unset — the conventional reading,
    /// what Cline itself does (it trims before it tests), and what both
    /// precedents in this module's siblings do.
    #[test]
    fn empty_env_reads_as_unset() {
        let iso = isolated();
        let _empty = EnvOverride::apply([(STORE_DIR_ENV, Some(OsString::new()))]);

        let (root, located) = store_root().expect("a home directory resolves");

        assert_eq!(
            located,
            LocatedBy::Default,
            "an empty CLINE_DIR must fall through to the default, not resolve to \"\""
        );
        assert_ne!(
            root,
            iso.store(),
            "and certainly not to the value it was overriding"
        );
        // `dirs::home_dir()` reads `$HOME` on unix and `FOLDERID_Profile` on
        // Windows, where a redirected `HOME` cannot reach it.
        #[cfg(unix)]
        assert_eq!(root, iso.home().join(".cline"));
    }

    /// DD-02: a relative seam is refused, not resolved against the process cwd.
    ///
    /// The deliberate departure from Cline, which returns the value verbatim
    /// and lets the filesystem call resolve it — so a daemon and an agent with
    /// different cwds read different directories from one configuration.
    #[test]
    fn relative_path_refused() {
        let iso = isolated();
        let _relative = EnvOverride::apply([(STORE_DIR_ENV, Some(OsString::from("./x")))]);

        let (root, located) = store_root().expect("a home directory resolves");

        assert_eq!(
            located,
            LocatedBy::Default,
            "a relative CLINE_DIR must be refused, leaving the default in place"
        );
        assert!(
            root.is_absolute(),
            "and the answer is absolute either way: {}",
            root.display()
        );
        assert_ne!(root, PathBuf::from("./x"));
        assert_ne!(
            root,
            iso.store(),
            "and not the absolute value the relative one replaced"
        );
        #[cfg(unix)]
        assert_eq!(root, iso.home().join(".cline"));
    }

    /// The provenance a later unit reports: `OperatorSupplied` when a seam
    /// named the root, `Default` when the home directory derived it.
    #[test]
    fn store_root_reports_located_by() {
        let iso = isolated();

        let (root, located) = store_root().expect("a home directory resolves");
        assert_eq!(located, LocatedBy::OperatorSupplied);
        assert_eq!(root, iso.store(), "and it is the operator's own path");

        // Unset inside the guard's lifetime, against the redirected HOME — the
        // fallback would otherwise name the developer's real `~/.cline`.
        let _unset = EnvOverride::apply([(STORE_DIR_ENV, None)]);
        let (root, located) = store_root().expect("a home directory resolves");
        assert_eq!(located, LocatedBy::Default);
        #[cfg(unix)]
        assert_eq!(root, iso.home().join(".cline"));
        assert!(root.ends_with(".cline"));
    }

    /// Two seams at two levels of one tree, not a fallback chain.
    ///
    /// The criterion that catches the "fallback chain" error: with
    /// `CLINE_DATA_DIR` set and `CLINE_DIR` unset, `rules/` stays on the
    /// default root while `data/` follows the seam. The reverse also holds —
    /// `CLINE_DIR` alone moves `data/` too, because the default derives.
    #[test]
    fn data_dir_independent_of_store_dir() {
        let iso = isolated();

        // Both set, at two different temp directories: guard-legal, and the
        // premise of the rest of the test.
        assert_eq!(store_root().expect("store").0, iso.store());
        assert_eq!(data_root().expect("data").0, iso.data());
        assert_ne!(
            iso.data(),
            iso.store().join("data"),
            "the premise: the data seam is not under the store seam"
        );

        // CLINE_DATA_DIR alone: `rules/` is left on the default root.
        let store_unset = EnvOverride::apply([(STORE_DIR_ENV, None)]);
        let (store, located) = store_root().expect("store");
        assert_eq!(
            located,
            LocatedBy::Default,
            "CLINE_DATA_DIR does not move the store root — the trap DD-01 names"
        );
        #[cfg(unix)]
        assert_eq!(store, iso.home().join(".cline"));
        assert!(store.ends_with(".cline"));
        assert_eq!(
            data_root().expect("data").0,
            iso.data(),
            "while data/ stays where CLINE_DATA_DIR put it"
        );
        drop(store_unset);

        // CLINE_DIR alone: `data/` follows it, because the default derives.
        let _data_unset = EnvOverride::apply([(DATA_DIR_ENV, None)]);
        assert_eq!(
            data_root().expect("data"),
            (iso.store().join("data"), LocatedBy::Default),
            "CLINE_DIR alone still moves data/"
        );
    }

    /// `dirs::document_dir()` answering `None` yields the home-relative answer
    /// rather than a panic.
    ///
    /// **Gated to Linux because it is VACUOUS anywhere else.** `dirs 6.0.0`
    /// resolves `document_dir()` through `known_folder_documents()` on Windows
    /// and `home_dir()/Documents` on macOS, so the `None` branch is unreachable
    /// on both and this test would be green while proving nothing on the
    /// developer's machine. On Linux it reads
    /// `$XDG_CONFIG_HOME`-or-`$HOME/.config/user-dirs.dirs`, which a freshly
    /// redirected `HOME` does not have — the unconfigured case exactly.
    #[cfg(target_os = "linux")]
    #[test]
    fn asset_root_survives_missing_xdg() {
        let iso = isolated();
        let _unset = EnvOverride::apply([(ASSETS_DIR_ENV, None), ("XDG_CONFIG_HOME", None)]);

        assert!(
            dirs::document_dir().is_none(),
            "the premise: an unconfigured xdg-user-dirs answers None"
        );
        let root = asset_root().expect("the home-relative fallback, not a panic");
        assert_eq!(root, iso.home().join("Documents").join("Cline"));
    }

    /// Each of the three seams, individually, refused when unset — and the
    /// panic names the variable, because "a seam is unset" is not something an
    /// engineer can act on.
    ///
    /// Calls the check **directly** rather than through [`cline_isolated`]:
    /// the constructor panics before it can return a guard, so there is no
    /// lifetime inside which one variable could be unset.
    #[test]
    fn guard_panics_when_any_seam_unset() {
        for name in [STORE_DIR_ENV, DATA_DIR_ENV, ASSETS_DIR_ENV] {
            for value in [None, Some(OsString::new())] {
                let message = panic_message(|| {
                    require_seam(name, value.clone());
                });
                assert!(
                    message.contains(name),
                    "the panic must name the seam it is missing: {message}"
                );
                assert!(
                    message.contains("unset"),
                    "and say what is wrong with it: {message}"
                );
            }
        }

        let relative = panic_message(|| {
            require_seam(STORE_DIR_ENV, Some(OsString::from("relative/store")));
        });
        assert!(
            relative.contains(STORE_DIR_ENV) && relative.contains("relative"),
            "a relative seam is refused too, and named: {relative}"
        );
    }

    /// `CLINE_DIR` set to the machine's own `~/.cline` counts as unset.
    ///
    /// Only `CLINE_DIR` — see [`reject_default_store`] for why the data seam
    /// has no equivalent check.
    #[test]
    fn guard_panics_on_set_but_equal_store_dir() {
        let home = tempfile::tempdir().expect("tempdir");
        let machines_own = home.path().join(DEFAULT_STORE_DIR_NAME);

        let message = panic_message(|| reject_default_store(&machines_own, Some(home.path())));
        assert!(
            message.contains(STORE_DIR_ENV),
            "the panic must name the seam: {message}"
        );

        // A genuinely redirected store passes, and so does a home that does not
        // resolve at all — there is no default to be equal to.
        reject_default_store(&home.path().join("isolated-store"), Some(home.path()));
        reject_default_store(&machines_own, None);
    }

    // -----------------------------------------------------------------------
    // The probe (PRD C-1)
    // -----------------------------------------------------------------------

    /// `mkdir -p`, for a test that needs a root to be PRESENT.
    ///
    /// Every path handed to this is under [`Isolated`]'s temp directory and
    /// behind the seam guard, which is the whole reason a Cline test may create
    /// a directory at all: [`absent_seams`] exists so a fixture's roots are
    /// never there, and creating one under it would arm detection everywhere.
    fn seed_dir(path: &Path) {
        std::fs::create_dir_all(path).expect("create a seeded directory");
    }

    /// Write a file, creating its parent.
    fn seed_file(path: &Path, contents: &str) {
        seed_dir(path.parent().expect("a parent directory"));
        std::fs::write(path, contents).expect("write a seeded file");
    }

    /// Restores a directory's mode when it goes out of scope.
    ///
    /// Not tidiness: `TempDir`'s own cleanup has to list the tree it removes,
    /// so a directory left at mode `0o000` is one the temp root can never be
    /// removed through.
    #[cfg(unix)]
    struct ModeGuard {
        dir: PathBuf,
        original: std::fs::Permissions,
    }

    #[cfg(unix)]
    impl Drop for ModeGuard {
        fn drop(&mut self) {
            let _ = std::fs::set_permissions(&self.dir, self.original.clone());
        }
    }

    /// Make `dir` unlistable for the guard's lifetime, or say loudly why this
    /// host cannot and hand back `None`.
    ///
    /// `chmod 0o000` is the one way to provoke a non-`NotFound` refusal without
    /// root — and **root walks straight through it**, as does a filesystem that
    /// ignores mode bits. So the refusal is verified rather than assumed: a
    /// caller that gets `None` has been told, in the test output, that it is
    /// skipping and why.
    #[cfg(unix)]
    #[must_use]
    fn refuse_reads(dir: &Path) -> Option<ModeGuard> {
        use std::os::unix::fs::PermissionsExt;

        let original = std::fs::metadata(dir)
            .expect("the directory to lock down must exist")
            .permissions();
        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).expect("chmod 0o000");
        let guard = ModeGuard {
            dir: dir.to_path_buf(),
            original,
        };

        if std::fs::read_dir(dir).is_ok() {
            // Dropping `guard` here puts the mode back before we leave.
            eprintln!(
                "SKIPPED: {} is still listable at mode 0o000, so this case cannot produce \
                 the refusal it is about. Run this suite as an unprivileged user — root \
                 bypasses the permission check, and so do some container filesystems.",
                dir.display()
            );
            return None;
        }
        Some(guard)
    }

    impl Isolated {
        /// The settings directory under the redirected data root.
        fn settings(&self) -> PathBuf {
            self.data().join("settings")
        }

        /// The `Hooks/` directory under the redirected asset root.
        fn hooks(&self) -> PathBuf {
            self.root.path().join("assets").join("Hooks")
        }
    }

    /// DD-03: both lanes are resolved, and the attestation says which one hit.
    ///
    /// Driven through [`asset_roots_from`] rather than the environment because
    /// `dirs::document_dir()` is `home_dir()/Documents` unconditionally on
    /// macOS — the two lanes cannot be made to *differ* there, and a test that
    /// cannot make them differ proves nothing about a decision whose entire
    /// subject is their disagreement.
    #[test]
    fn asset_root_reports_which_lane_hit() {
        let root = tempfile::tempdir().expect("tempdir");
        let known_folder = root.path().join("OneDrive").join("Documents");
        let home_relative_home = root.path().join("home");
        let home_relative = home_relative_home.join(DEFAULT_DOCUMENTS_DIR_NAME);

        let lanes = |roots: &AssetRoots| -> Vec<(AssetLane, bool)> {
            roots
                .lanes
                .iter()
                .map(|lane| (lane.lane, lane.exists))
                .collect()
        };

        // Neither on disk: the in-scope lane is still where we say to look.
        let roots = asset_roots_from(
            None,
            Some(known_folder.clone()),
            Some(home_relative_home.clone()),
        );
        assert_eq!(roots.hit, AssetLaneHit::Neither);
        assert!(!roots.lanes_agree, "the premise: the two lanes differ here");
        assert_eq!(roots.located_by, LocatedBy::Default);
        assert_eq!(
            lanes(&roots),
            vec![
                (AssetLane::KnownFolder, false),
                (AssetLane::HomeRelative, false)
            ],
            "both lanes are reported even when neither is on disk"
        );
        assert_eq!(roots.resolved, Some(known_folder.join(ASSET_DIR_NAME)));

        // Only the SDK/CLI lane is on disk — the case that happens whenever
        // Cline's PowerShell call threw. The probe must follow the directory
        // that is actually there.
        seed_dir(&home_relative.join(ASSET_DIR_NAME));
        let roots = asset_roots_from(
            None,
            Some(known_folder.clone()),
            Some(home_relative_home.clone()),
        );
        assert_eq!(roots.hit, AssetLaneHit::Lane(AssetLane::HomeRelative));
        assert_eq!(roots.hit.as_str(), "home-relative");
        assert_eq!(roots.resolved, Some(home_relative.join(ASSET_DIR_NAME)));

        // Both on disk: the in-scope lane wins, and `lanes_agree` says these are
        // two directories rather than one found twice.
        seed_dir(&known_folder.join(ASSET_DIR_NAME));
        let roots = asset_roots_from(
            None,
            Some(known_folder.clone()),
            Some(home_relative_home.clone()),
        );
        assert_eq!(roots.hit, AssetLaneHit::Both);
        assert!(!roots.lanes_agree);
        assert_eq!(roots.resolved, Some(known_folder.join(ASSET_DIR_NAME)));
        assert_eq!(
            lanes(&roots),
            vec![
                (AssetLane::KnownFolder, true),
                (AssetLane::HomeRelative, true)
            ]
        );

        // A seam supersedes both, and says so rather than reporting a lane.
        let seam = root.path().join("relocated");
        let roots = asset_roots_from(
            Some(seam.clone()),
            Some(known_folder.clone()),
            Some(home_relative_home.clone()),
        );
        assert_eq!(roots.hit, AssetLaneHit::OperatorSupplied);
        assert_eq!(roots.located_by, LocatedBy::OperatorSupplied);
        assert_eq!(roots.resolved, Some(seam));
        assert!(
            roots.lanes.is_empty(),
            "no lane was consulted, so none is reported"
        );

        // And with no home at all there is nothing to report — not an empty
        // path, and not a panic.
        let roots = asset_roots_from(None, None, None);
        assert_eq!(roots.resolved, None);
        assert_eq!(roots.hit, AssetLaneHit::Neither);
        assert!(roots.lanes.is_empty());
    }

    /// A Linux box with `xdg-user-dirs` unconfigured has one directory, found
    /// twice — and must not read as two installs.
    #[test]
    fn lanes_agree_when_the_known_folder_is_unavailable() {
        let root = tempfile::tempdir().expect("tempdir");
        let roots = asset_roots_from(None, None, Some(root.path().to_path_buf()));

        assert!(roots.lanes_agree);
        assert_eq!(roots.lanes.len(), 2, "both lanes still reported");
        assert_eq!(
            roots.lanes[0].path, roots.lanes[1].path,
            "and they name the same directory"
        );
    }

    /// PRD **D-9**: an attestation without `as_of` is not a dated claim.
    #[test]
    fn attestation_has_as_of() {
        let _iso = isolated();
        let attestation = probe();

        chrono::DateTime::parse_from_rfc3339(&attestation.as_of)
            .expect("as_of must be RFC 3339 — a reader cannot date the claim otherwise");
        assert_eq!(
            attestation.to_json()["as_of"],
            serde_json::Value::String(attestation.as_of.clone()),
            "and the machine rendering carries it too"
        );
    }

    /// PRD **D-16**: a reader must be able to tell being *told* where to look
    /// from having *discovered* it. A rebranded fork is only ever found because
    /// an operator pointed `CLINE_DIR` at it.
    #[test]
    fn attestation_records_located_by() {
        let iso = isolated();

        let attestation = probe();
        assert_eq!(
            attestation.store_root.located_by,
            LocatedBy::OperatorSupplied
        );
        assert_eq!(attestation.store_root.path, Some(iso.store()));
        assert_eq!(
            attestation.to_json()["store_root"]["located_by"],
            serde_json::Value::String("operator-supplied".to_string())
        );

        // The default half reads the home directory, and only a redirected
        // `HOME` keeps that off the developer's real `~/.cline` — which `dirs`
        // honours on unix and ignores on Windows.
        #[cfg(unix)]
        {
            let _unset = EnvOverride::apply([(STORE_DIR_ENV, None)]);
            let attestation = probe();
            assert_eq!(attestation.store_root.located_by, LocatedBy::Default);
            assert_eq!(
                attestation.to_json()["store_root"]["located_by"],
                serde_json::Value::String("default".to_string())
            );
            assert_eq!(
                attestation.store_root.path,
                Some(iso.home().join(".cline")),
                "and it is the default root that was inspected"
            );
        }
    }

    /// **DD-11.** Two states is a bug: a probe looking in the wrong place would
    /// report `absent`, and absence is the finding we ask a customer to act on.
    ///
    /// The three classifications are asserted against the filesystem's own
    /// answer — [`classify_metadata`] takes the `io::Result` for the reason
    /// [`require_seam`] takes its value, because a `PermissionDenied` cannot be
    /// produced portably from a temp directory.
    #[test]
    fn surfaces_absent_has_three_states() {
        use std::io::{Error, ErrorKind};

        let root = tempfile::tempdir().expect("tempdir");
        assert_eq!(
            classify_metadata(std::fs::metadata(root.path())),
            SurfaceState::Present
        );
        assert_eq!(
            classify_metadata(Err(Error::from(ErrorKind::NotFound))),
            SurfaceState::Absent
        );
        assert_eq!(
            classify_metadata(Err(Error::from(ErrorKind::PermissionDenied))),
            SurfaceState::Undetermined,
            "a refused lookup is not an absence"
        );

        // All three are expressible in a finding, and only a present one may
        // omit the code and the remedy.
        for state in [
            SurfaceState::Present,
            SurfaceState::Absent,
            SurfaceState::Undetermined,
        ] {
            let finding = SurfaceFinding::new(Surface::HookDir, state);
            assert_eq!(finding.state, state);
            if state == SurfaceState::Present {
                assert_eq!(finding.code, None);
                assert_eq!(finding.remedy, None);
            } else {
                assert!(
                    finding.code.is_some() && finding.remedy.is_some(),
                    "{state:?} is something we ask a reader to act on, so it carries both"
                );
            }
        }
        assert_ne!(
            SurfaceFinding::new(Surface::HookDir, SurfaceState::Absent).code,
            SurfaceFinding::new(Surface::HookDir, SurfaceState::Undetermined).code,
            "and the two are distinguishable by code, not only by prose"
        );
    }

    /// **DD-13**, the field that makes this a fork probe rather than a
    /// checklist: something we could not classify under a resolved root appears
    /// rather than producing silence indistinguishable from a clean host.
    #[test]
    fn surfaces_unclassified_reports_residual() {
        let iso = isolated();
        seed_dir(&iso.store().join("rules"));
        seed_dir(&iso.store().join("cosmos-connectors"));
        seed_file(&iso.store().join("cosmos.manifest"), "{}");
        seed_dir(&iso.hooks());
        seed_dir(&iso.root.path().join("assets").join("Telemetry"));

        let attestation = probe();
        let residual: Vec<(&str, &str, &str)> = attestation
            .unclassified
            .iter()
            .map(|entry| (entry.root, entry.name.as_str(), entry.kind))
            .collect();

        assert!(
            residual.contains(&("store", "cosmos-connectors", "dir")),
            "an unrecognised directory under the store must surface: {residual:?}"
        );
        assert!(
            residual.contains(&("store", "cosmos.manifest", "file")),
            "and an unrecognised file, with its kind: {residual:?}"
        );
        assert!(
            residual.contains(&("asset", "Telemetry", "dir")),
            "the user-asset root is a resolved root too: {residual:?}"
        );
        assert!(
            !residual.iter().any(|(_, name, _)| *name == "rules"),
            "while what we can name is not residual: {residual:?}"
        );
        assert!(
            !residual.iter().any(|(_, name, _)| *name == "Hooks"),
            "case included — a fork's capitalisation is not a finding: {residual:?}"
        );
        assert_eq!(
            attestation.to_json()["surfaces_unclassified"]
                .as_array()
                .map(Vec::len),
            Some(attestation.unclassified.len()),
            "and the machine rendering carries every one of them"
        );
    }

    /// **C-6's narrowed exception**: `providers.json` is read for provider ids
    /// and `baseUrl` **presence** only, and no value from it can reach the
    /// attestation — there is no field that could hold one.
    #[test]
    fn base_url_presence_finds_the_real_nested_shape() {
        // REGRESSION, 2026-09-14. This scanned `providers.<id>`'s own keys for
        // `baseUrl` — but a real Cline 4.1.17 entry's keys are only
        // `settings` / `tokenSource` / `updatedAt`, so it answered FALSE for
        // every provider on every real store, including one plainly holding a
        // baseUrl. Verified against a live install carrying four providers.
        let real = serde_json::json!({
            "settings": { "provider": "ollama", "baseUrl": "http://127.0.0.1:11434" },
            "tokenSource": "none",
            "updatedAt": 1,
        });
        let nested: BaseUrlPresence = serde_json::from_value(real).expect("deserialize");
        assert!(
            nested.0,
            "a provider whose settings carry a baseUrl must report present"
        );

        // The flat shape a fork might use is still accepted (DD-10: attest by
        // capability, not by assuming our own layout).
        let flat = serde_json::json!({ "baseUrl": "http://127.0.0.1:11434" });
        let flat: BaseUrlPresence = serde_json::from_value(flat).expect("deserialize");
        assert!(flat.0, "the flat shape must still be recognised");

        // And a provider with NO baseUrl anywhere still reports absent — without
        // this the test would pass against an implementation that always says true.
        let none = serde_json::json!({
            "settings": { "provider": "gemini", "apiKey": "x", "model": "m" },
            "tokenSource": "none",
        });
        let none: BaseUrlPresence = serde_json::from_value(none).expect("deserialize");
        assert!(
            !none.0,
            "absence must still be reportable, or this proves nothing"
        );
    }

    #[test]
    fn providers_report_presence_never_value() {
        let iso = isolated();
        seed_file(
            &iso.settings().join("providers.json"),
            r#"{"providers":{
                 "bea-internal":{"baseUrl":"https://qwen.bea.example.internal/v1",
                                 "apiKey":"sk-DO-NOT-READ-THIS"},
                 "anthropic":{"model":"claude"},
                 "odd-fork-entry":"a string, not an object"
               }}"#,
        );

        let attestation = probe();
        let providers = attestation.providers.clone().expect("providers parse");
        assert_eq!(
            providers
                .iter()
                .map(|provider| (provider.id.as_str(), provider.base_url_present))
                .collect::<Vec<_>>(),
            vec![
                ("anthropic", false),
                ("bea-internal", true),
                ("odd-fork-entry", false)
            ],
            "ids and baseUrl PRESENCE — and a non-object entry does not take the \
             whole list to undetermined with it"
        );

        let rendered = format!(
            "{}\n{}",
            attestation.to_json(),
            attestation.human_lines().join("\n")
        );
        for secret in [
            "qwen.bea.example.internal",
            "sk-DO-NOT-READ-THIS",
            "https://",
        ] {
            assert!(
                !rendered.contains(secret),
                "a value from providers.json reached a rendering: {secret}"
            );
        }
    }

    /// C-1: MCP servers are **ids and count only, never an `env` block**, which
    /// routinely carries API keys.
    #[test]
    fn mcp_servers_are_ids_never_env() {
        let iso = isolated();
        seed_file(
            &iso.settings().join("cline_mcp_settings.json"),
            r#"{"mcpServers":{
                 "github":{"command":"npx","env":{"GITHUB_TOKEN":"ghp_DO_NOT_READ"}},
                 "filesystem":{"command":"node"}
               }}"#,
        );

        let attestation = probe();
        assert_eq!(
            attestation.mcp_servers.as_deref(),
            Some(["filesystem".to_string(), "github".to_string()].as_slice()),
            "ids, sorted, so two runs are comparable"
        );
        assert_eq!(
            attestation.state_of_surface(Surface::McpSettings),
            Some(SurfaceState::Present)
        );

        let rendered = format!(
            "{}\n{}",
            attestation.to_json(),
            attestation.human_lines().join("\n")
        );
        for secret in ["ghp_DO_NOT_READ", "GITHUB_TOKEN"] {
            assert!(
                !rendered.contains(secret),
                "an env block reached a rendering: {secret}"
            );
        }
    }

    /// **PRD D-9 / DD-14**: surfaces can appear after the probe runs, so the
    /// probe is re-runnable and its second answer reflects the change.
    #[test]
    fn probe_reruns_and_reflects_change() {
        let iso = isolated();
        seed_dir(&iso.settings());

        let before = probe();
        assert_eq!(
            before.mcp_servers, None,
            "no registry file at all is undetermined, not an empty list"
        );

        seed_file(
            &iso.settings().join("cline_mcp_settings.json"),
            r#"{"mcpServers":{"probe-canary":{"command":"true"}}}"#,
        );
        let after = probe();

        assert_eq!(
            after.mcp_servers.as_deref(),
            Some(["probe-canary".to_string()].as_slice())
        );
        assert_ne!(
            before.to_json()["mcp_servers"],
            after.to_json()["mcp_servers"],
            "a change between two runs must be visible in the rendering"
        );
    }

    /// Spec **AC-1**: every C-1 field is carried — including the three that no
    /// other row in the plan claimed.
    ///
    /// `hook_dir_entries` is what is **installed**, not what is **honoured**:
    /// C-1 says so explicitly, and a rename to `hook_events` must fail here.
    #[test]
    fn attestation_carries_every_c1_field() {
        let _iso = isolated();
        let json = probe().to_json();
        let object = json.as_object().expect("an object");

        for field in [
            "as_of",
            "store_root",
            "host_shells",
            // C-1 named ONE hook directory; the amended article names all four
            // Cline searches, so the field is plural and always four rows long.
            "hook_dirs",
            "hook_dir_entries",
            "mcp_servers",
            "plugin_dir",
            "providers",
            "extension_roots",
            "surfaces_absent",
            "surfaces_unclassified",
            // Not C-1's, and required all the same: DD-03's answer, and the
            // path whose state `mcp_servers == null` is ambiguous without.
            "asset_root",
            "mcp_settings",
        ] {
            assert!(object.contains_key(field), "C-1 field missing: {field}");
        }
        assert_eq!(
            json["hook_dirs"].as_array().map(Vec::len),
            Some(4),
            "four search directories, always — a consumer indexes them positionally"
        );
        assert!(
            object.contains_key("hook_dir_entries") && !object.contains_key("hook_events"),
            "C-1: this is what is INSTALLED, not what is HONOURED — do not name it hook_events"
        );
        assert!(
            !json.to_string().contains("hook_events"),
            "and the name must not appear anywhere in the document either"
        );
        assert!(
            json["store_root"].get("located_by").is_some(),
            "store_root carries how it was located (D-16), not just a path"
        );
        assert!(
            json["host_shells"].is_array() && !json["host_shells"].as_array().unwrap().is_empty(),
            "host_shells names what it can distinguish and what it cannot — never nothing"
        );
    }

    /// **DD-14**: surfaces appear individually, each with its own state, code
    /// and remedy. One aggregated verdict cannot say *which* surface is missing,
    /// and "which" is the whole content of the finding.
    #[test]
    fn attestation_reports_per_surface_not_aggregate() {
        let iso = isolated();
        seed_dir(&iso.store());
        seed_dir(&iso.hooks());

        let attestation = probe();
        let mut names: Vec<&str> = attestation
            .surfaces
            .iter()
            .map(|finding| finding.surface.as_str())
            .collect();
        names.sort_unstable();
        assert_eq!(
            names,
            vec![
                "extension",
                "hook_dir",
                "mcp_settings",
                "plugin_dir",
                "store"
            ],
            "C-1's enumerated set, one entry each"
        );

        assert_eq!(
            attestation.state_of_surface(Surface::Store),
            Some(SurfaceState::Present)
        );
        assert_eq!(
            attestation.state_of_surface(Surface::HookDir),
            Some(SurfaceState::Present)
        );
        assert_eq!(
            attestation.state_of_surface(Surface::PluginDir),
            Some(SurfaceState::Absent),
            "one attestation carries different states for different surfaces"
        );

        // And every non-present entry in the rendering carries both halves of
        // what a reader acts on.
        for entry in attestation.to_json()["surfaces_absent"]
            .as_array()
            .expect("an array")
        {
            if entry["state"] == serde_json::Value::String("present".to_string()) {
                continue;
            }
            assert!(
                !entry["code"].is_null() && !entry["remedy"].is_null(),
                "a finding without a code or a remedy cannot be acted on: {entry}"
            );
        }
    }

    /// **DD-12**: what Cline *asserts* is kept beside what we *observed*, and
    /// neither is resolved away into the other.
    #[test]
    fn plugin_dir_records_asserted_beside_observed() {
        let iso = isolated();
        seed_dir(&iso.store().join("plugins").join("cosmos-guardrails"));
        seed_file(
            &iso.settings().join("global-settings.json"),
            r#"{"disabledPlugins":["cosmos-guardrails"],"telemetryLevel":"off"}"#,
        );

        let attestation = probe();
        assert_eq!(
            attestation.plugin_dir_entries.as_deref(),
            Some(["cosmos-guardrails".to_string()].as_slice()),
            "observed: the plugin is on disk"
        );
        assert_eq!(
            attestation.plugins_asserted_disabled.as_deref(),
            Some(["cosmos-guardrails".to_string()].as_slice()),
            "asserted: and Cline's own settings say it is switched off"
        );
        let json = attestation.to_json();
        assert!(
            !json["plugin_dir"]["entries"].is_null()
                && !json["plugin_dir"]["asserted_disabled"].is_null(),
            "both halves survive into the rendering: {}",
            json["plugin_dir"]
        );
    }

    /// **`enforcement_surface` is one of exactly three, and it is never
    /// absent.**
    ///
    /// The absence half is the point. `"none"` is an *answer*, not a missing
    /// key — so `.agents.cline.enforcement_surface == "none"` is a positive
    /// assertion a consumer can make, where a field this build only emitted
    /// when it had something to say would let `!= "plugin"` pass on a document
    /// that never mentioned Cline at all.
    ///
    /// All four arrangements a host can be in are walked, and each is asserted
    /// in **both** renderings: the isomorphism gate in `tests/cline_probe.rs`
    /// proves a human line exists, this proves the two say the same thing.
    #[test]
    fn enforcement_surface_is_one_of_three() {
        let iso = isolated();
        seed_dir(&iso.store());
        let plugin_dir =
            crate::hooks::cline_plugin::plugin_dir(&iso.store().join(STORE_PLUGINS_DIR_NAME));

        // The closed vocabulary, asserted against the arrangement that produces
        // each spelling. `install` writes the body, so the marker under test is
        // the installer's own and not one this fixture invented.
        let arrangements: [(&str, &dyn Fn()); 4] = [
            ("none", &|| {}),
            ("plugin", &|| {
                crate::hooks::cline_plugin::install(&plugin_dir, Path::new("/tmp/openlatch"))
                    .expect("install the plugin");
            }),
            ("disabled", &|| {
                seed_file(
                    &iso.settings().join("global-settings.json"),
                    &format!(
                        r#"{{"disabledPlugins":["{}"]}}"#,
                        crate::hooks::cline_plugin::PLUGIN_ID
                    ),
                );
            }),
            ("none", &|| {
                std::fs::remove_file(crate::hooks::cline_plugin::entry_path(&plugin_dir))
                    .expect("remove the plugin");
            }),
        ];

        for (expected, arrange) in arrangements {
            arrange();

            let attestation = probe_in(None);
            assert_eq!(
                attestation.enforcement_surface.as_str(),
                expected,
                "the detector's answer for this arrangement"
            );

            let json = attestation.to_json();
            let rendered = json["enforcement_surface"].as_str().unwrap_or_else(|| {
                panic!(
                    "`enforcement_surface` must always be a string — a Cline host always has \
                     one of the three: {json}"
                )
            });
            assert_eq!(rendered, expected);
            assert!(
                ["plugin", "disabled", "none"].contains(&rendered),
                "`{rendered}` is outside the closed vocabulary a consumer matches on"
            );
            assert!(
                attestation
                    .human_lines()
                    .iter()
                    .any(|line| line == &format!("Cline enforcement surface: {expected}")),
                "the human rendering must carry the same answer: {:?}",
                attestation.human_lines()
            );
        }
    }

    /// C-1: `hook_dir_entries` is a listing of what is installed. `None` and
    /// `[]` are different findings, and the directory's own state is what
    /// separates them.
    #[test]
    fn hook_dir_entries_name_what_is_installed() {
        let iso = isolated();

        let attestation = probe();
        assert_eq!(
            attestation.state_of_surface(Surface::HookDir),
            Some(SurfaceState::Absent)
        );
        assert_eq!(
            attestation.hook_dir_entries, None,
            "a directory that is not there has no listing — not an empty one"
        );

        seed_dir(&iso.hooks());
        assert_eq!(
            probe().hook_dir_entries,
            Some(Vec::new()),
            "and an empty directory has an empty listing"
        );

        seed_file(&iso.hooks().join("pre-tool-use.ps1"), "# shim");
        let attestation = probe();
        assert_eq!(
            attestation.hook_dir_entries.as_deref(),
            Some(["pre-tool-use.ps1".to_string()].as_slice())
        );
        assert_eq!(
            attestation.hook_dirs[0].path,
            Some(iso.hooks()),
            "under the user-asset root, not the store's lowercase hooks/"
        );
    }

    /// Spec **AC-4**: the store is here and no editor root held a Cline-lineage
    /// extension. `doctor` warns naming that state and never renders green.
    ///
    /// Unix-gated because the six editor roots derive from `home_dir()`, which
    /// `dirs` reads from `$HOME` on unix and from `FOLDERID_Profile` on Windows
    /// — where a redirected `HOME` cannot reach it and this test would scan the
    /// developer's real machine and invert depending on whether they run Cursor.
    #[cfg(unix)]
    #[test]
    fn extension_roots_warn_when_store_without_extension() {
        let iso = isolated();
        seed_dir(&iso.store());
        seed_dir(&iso.home());

        let attestation = probe();
        assert!(
            attestation
                .extension_roots
                .iter()
                .any(|root| root.path == iso.home().join(".vscode")),
            "the six editor roots and their -server variants are enumerated"
        );
        assert!(
            attestation
                .extension_roots
                .iter()
                .any(|root| root.path == iso.home().join(".cursor-server")),
            "including the -server variants"
        );
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Absent)
        );
        assert!(
            attestation.store_without_extension(),
            "store present, extension absent — the state doctor must warn about"
        );

        // An extension in any one root closes it.
        seed_dir(
            &iso.home()
                .join(".cursor")
                .join("extensions")
                .join("saoudrizwan.claude-dev-4.1.17"),
        );
        let attestation = probe();
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Present)
        );
        assert!(!attestation.store_without_extension());
        assert!(
            attestation
                .host_shells
                .iter()
                .any(|shell| shell.shell == "vscode" && shell.state == SurfaceState::Present),
            "and that is the one host shell this build can evidence"
        );

        // No store at all is not this warning: that host simply has no Cline.
        std::fs::remove_dir_all(iso.store()).expect("remove the seeded store");
        assert!(!probe().store_without_extension());
    }

    /// Spec **AC-5** / PRD **D-12**: a fork with no marketplace publisher id and
    /// no signature — no extension metadata at all — is still detected and
    /// still attested.
    ///
    /// Detection is store-keyed by construction, which is what makes this cheap;
    /// *probably true* is not a criterion, so it is asserted.
    #[cfg(unix)]
    #[test]
    fn attestation_survives_unsigned_unpublished_fork() {
        let iso = isolated();
        seed_dir(&iso.store().join("rules"));
        seed_dir(&iso.home().join(".vscode").join("extensions"));

        let attestation = probe();
        assert_eq!(
            attestation.state_of_surface(Surface::Store),
            Some(SurfaceState::Present),
            "the store is what detection keys on, and no name decided it"
        );
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Absent),
            "with the extension surface reported absent rather than the whole \
             attestation failing"
        );
        assert!(
            !attestation.as_of.is_empty(),
            "and it is a dated claim like any other"
        );

        // A rebranded extension directory is not classified — and that failure
        // is reported rather than hidden, because the store still is.
        seed_dir(
            &iso.home()
                .join(".vscode")
                .join("extensions")
                .join("bea.cosmos-1.0.0"),
        );
        let attestation = probe();
        assert_eq!(
            attestation.state_of_surface(Surface::Extension),
            Some(SurfaceState::Absent),
            "a name we do not recognise decides nothing (DD-10)"
        );
        let vscode_root = attestation
            .extension_roots
            .iter()
            .find(|root| root.path == iso.home().join(".vscode"))
            .expect("the root we seeded");
        assert_eq!(
            vscode_root.entries_scanned, 1,
            "and the root says it looked at something, so 'absent' is not \
             'there was nothing to look at'"
        );
    }

    /// **D-05**: the attestation reports **all four** directories Cline
    /// discovers hooks in, positionally, with their own states.
    ///
    /// The paths **and** the states, not the length: four rows that are all
    /// wrong pass a length check, and the whole reason the field is plural is
    /// that a developer whose hooks live in `<workspace>/.cline/hooks` was
    /// previously told the surface was absent.
    #[test]
    fn the_probe_reports_four_directories() {
        let iso = isolated();
        seed_dir(&iso.hooks());

        // A workspace inside the fixture's own temp root. `probe_in` takes it,
        // so no test in this file depends on — or changes — the process cwd.
        let workspace = iso.root.path().join("workspace");
        seed_dir(
            &workspace
                .join(WORKSPACE_LOCAL_DIR_NAME)
                .join(WORKSPACE_HOOKS_DIR_NAME),
        );

        let attestation = probe_in(Some(&workspace));
        assert_eq!(attestation.hook_dirs.len(), 4, "always four");

        assert_eq!(
            attestation
                .hook_dirs
                .iter()
                .map(|dir| (dir.path.clone(), dir.state))
                .collect::<Vec<_>>(),
            vec![
                (Some(iso.hooks()), SurfaceState::Present),
                (
                    Some(iso.store().join(STORE_HOOKS_DIR_NAME)),
                    SurfaceState::Absent
                ),
                (
                    Some(
                        workspace
                            .join(WORKSPACE_RULES_DIR_NAME)
                            .join(WORKSPACE_HOOKS_DIR_NAME)
                    ),
                    SurfaceState::Absent
                ),
                (
                    Some(
                        workspace
                            .join(WORKSPACE_LOCAL_DIR_NAME)
                            .join(WORKSPACE_HOOKS_DIR_NAME)
                    ),
                    SurfaceState::Present
                ),
            ],
            "Cline's own precedence order, each row with the state of ITS path"
        );

        // With no usable cwd — the daemon's case — the two workspace rows say
        // "we could not look", never "we looked and it was not there".
        let blind = probe_in(None);
        assert_eq!(blind.hook_dirs.len(), 4);
        for index in [2, 3] {
            assert_eq!(blind.hook_dirs[index].path, None);
            assert_eq!(
                blind.hook_dirs[index].state,
                SurfaceState::Undetermined,
                "never Absent: we did not look and fail to find, we could not look"
            );
        }
        assert_eq!(
            blind.hook_dirs[0].state,
            SurfaceState::Present,
            "and the two rows that do not need a workspace are unaffected"
        );

        // The enumerated surface is the rollup over the four.
        assert_eq!(
            blind.state_of_surface(Surface::HookDir),
            Some(SurfaceState::Present)
        );
    }

    /// **C-6**: `<CLINE_DIR>/hooks` is listed for its filenames and never read.
    ///
    /// It is inside the store, whose `data/secrets.json` holds plaintext API
    /// keys at mode 0600. The rule is not "do not read secrets.json", it is
    /// "do not open a file under the store that C-6 did not name" — so the
    /// proof is that a file seeded there contributes its existence and not one
    /// byte of its body to either rendering.
    #[test]
    fn the_store_hooks_dir_is_listed_never_read() {
        let iso = isolated();
        let canary = "OPENLATCH-C6-CANARY-THIS-BODY-MUST-NEVER-BE-READ";
        seed_file(
            &iso.store().join(STORE_HOOKS_DIR_NAME).join("PreToolUse"),
            canary,
        );

        let attestation = probe();

        // Listed: `present` is only reachable through a `read_dir` that
        // succeeded — a refused listing refines the stat to `undetermined`.
        assert_eq!(
            attestation.hook_dirs[1].path,
            Some(iso.store().join(STORE_HOOKS_DIR_NAME))
        );
        assert_eq!(attestation.hook_dirs[1].state, SurfaceState::Present);

        // Never read.
        let rendered = format!(
            "{}\n{}",
            attestation.to_json(),
            attestation.human_lines().join("\n")
        );
        assert!(
            !rendered.contains(canary),
            "a file under the store's hooks/ was OPENED and its body reached a rendering \
             that leaves this machine:\n{rendered}"
        );
    }

    /// The binding **installs into** the directory the probe reports first.
    ///
    /// `bindings::cline` no longer keeps its own `"Hooks"` literal — it reads
    /// [`ASSET_HOOKS_DIR_NAME`], so the two spellings that used to need holding
    /// together are one. What still needs holding together is the *lane*: the
    /// probe now reports FOUR directories, three of which this build never
    /// writes to, and the install target is `hook_dirs[0]` by position. Reorder
    /// the four, or point the binding at a different one, and this fails.
    ///
    /// Three units disagreeing about where the hook surface lives is the trap
    /// [`STORE_DIR_ENV`] documents, and it ends with a probe reporting a
    /// confident `absent` against a directory that is right there.
    #[test]
    fn the_binding_and_the_probe_name_one_hook_directory() {
        use crate::hooks::binding::{AgentBinding, HookSurface};

        let iso = isolated();
        seed_dir(&iso.hooks());

        let attestation = probe();
        let binding = crate::hooks::bindings::cline::ClineBinding::detached();
        assert_eq!(
            attestation.hook_dirs[0].path,
            Some(binding.hook_config_path()),
            "the FIRST hook directory is the one the binding installs into"
        );
        assert_eq!(
            binding.hook_surface(),
            HookSurface::Directory(binding.hook_config_path()),
            "and the binding says it is a directory, so nothing JSON-shaped reaches it"
        );
        assert_eq!(
            attestation.hook_dirs[0].path,
            asset_root().map(|root| root.join(ASSET_HOOKS_DIR_NAME)),
            "and both are the resolved asset root joined with Cline's own spelling"
        );
        assert_ne!(
            attestation.hook_dirs[0].path, attestation.hook_dirs[1].path,
            "the store's lowercase hooks/ is a DIFFERENT directory, and we never install into it"
        );
    }

    /// **DD-07 / P7**: the human rendering is not optional, and it renders the
    /// same facts the machine one does.
    #[test]
    fn human_rendering_carries_the_same_facts() {
        let iso = isolated();
        seed_dir(&iso.store());
        seed_file(
            &iso.settings().join("cline_mcp_settings.json"),
            r#"{"mcpServers":{"probe-canary":{"command":"true"}}}"#,
        );

        let attestation = probe();
        let rendered = attestation.human_lines().join("\n");

        assert!(
            rendered.contains(&crate::core::path_compat::display_path(&iso.store())),
            "the store root is the one string that belongs to this attestation \
             and to nothing else in doctor's output: {rendered}"
        );
        assert!(rendered.contains("probe-canary"), "{rendered}");
        assert!(rendered.contains(&attestation.as_of), "{rendered}");
        for finding in &attestation.surfaces {
            assert!(
                rendered.contains(finding.surface.as_str()),
                "every surface appears in the human rendering too: {}",
                finding.surface.as_str()
            );
            if let Some(code) = finding.code {
                assert!(rendered.contains(code), "with its code: {code}");
            }
        }
        assert!(
            attestation
                .summary()
                .contains(&crate::core::path_compat::display_path(&iso.store())),
            "and the one-line summary names it as well"
        );
    }

    /// **DD-11**: a directory listing that failed *mid-iteration* is not an
    /// empty listing.
    ///
    /// The regression this pins: `read_dir` opening successfully while the
    /// iteration yields an error, the error being dropped on the floor, and the
    /// empty `Vec` that results reading as a confident `absent`. Under
    /// [`extension_root_report`] that is spec **AC-4**'s actionable *"no
    /// Cline-lineage extension was found in any known editor root"* fired
    /// against a host nobody managed to look at.
    ///
    /// Injected rather than provoked, for the reason [`classify_metadata`]'s
    /// own documentation gives: a directory that opens and then fails part-way
    /// through is not reproducible from a temp directory on demand, on any
    /// platform. [`crate::hooks::cline`]'s integration target covers the
    /// refused-*open* half against a real `chmod`.
    #[test]
    fn a_listing_refused_mid_iteration_is_never_an_empty_one() {
        let complete = classify_entries(vec![
            Ok(OsString::from("ms-python.python-2024.1")),
            Ok(OsString::from("saoudrizwan.claude-dev-3.0.0")),
        ]);
        assert_eq!(
            complete.refine(SurfaceState::Present),
            SurfaceState::Present,
            "a listing that completed leaves the state the stat produced alone"
        );
        assert_eq!(
            complete.value(),
            Some(vec![
                "ms-python.python-2024.1".to_string(),
                "saoudrizwan.claude-dev-3.0.0".to_string(),
            ]),
            "and it is read, sorted"
        );

        // The case the defect discarded: entries were being read, and then the
        // filesystem refused.
        let refused = classify_entries(vec![
            Ok(OsString::from("ms-python.python-2024.1")),
            Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
        ]);
        assert_eq!(
            refused.refine(SurfaceState::Present),
            SurfaceState::Undetermined,
            "a per-entry error must reach the caller — discarding it is what lets an \
             INCOMPLETE listing read as a complete one, and an empty complete listing is \
             the confident absence DD-11 forbids"
        );
        assert_eq!(
            refused.value(),
            None,
            "and what was read before the refusal is not handed back as the whole answer"
        );

        // Nothing read at all, refused immediately: the same answer, never
        // `absent`.
        assert_eq!(
            classify_entries(vec![Err(std::io::Error::from(
                std::io::ErrorKind::PermissionDenied
            ))])
            .refine(SurfaceState::Absent),
            SurfaceState::Undetermined
        );

        // And an empty directory really is empty — the fact `Refused` must stay
        // distinguishable from.
        assert_eq!(
            classify_entries(Vec::new()).value(),
            Some(Vec::new()),
            "`[]` is a finding: the directory is there and holds nothing"
        );
    }

    /// The same rule one layer up: an `extensions/` listing the filesystem
    /// refused makes that editor root [`SurfaceState::Undetermined`], never
    /// [`SurfaceState::Absent`].
    ///
    /// `#[cfg(unix)]` twice over: the editor roots derive from `home_dir()`,
    /// which a redirected `HOME` reaches on unix only, and the refusal is a
    /// `chmod`.
    #[cfg(unix)]
    #[test]
    fn a_refused_extensions_listing_is_never_an_editor_root_without_cline() {
        let iso = isolated();
        let extensions = iso.home().join(".cursor").join(EXTENSION_DIR_NAME);
        seed_dir(&extensions);

        // Absent is only ever the NOT-FOUND answer, so a root whose
        // `extensions/` is simply not there still reads absent.
        let untouched = extension_root_report(iso.home().join(".vscode"));
        assert_eq!(untouched.lineage, SurfaceState::Absent);
        assert_eq!(untouched.entries_scanned, 0);

        // A listing that IS there and holds nothing is absent too.
        let empty = extension_root_report(iso.home().join(".cursor"));
        assert_eq!(empty.lineage, SurfaceState::Absent);

        // And one the filesystem refuses is not.
        let Some(_guard) = refuse_reads(&extensions) else {
            return;
        };
        let refused = extension_root_report(iso.home().join(".cursor"));
        assert_eq!(
            refused.lineage,
            SurfaceState::Undetermined,
            "a root we were refused is not a root without Cline in it (DD-11)"
        );
        assert!(
            refused.matched.is_empty() && refused.entries_scanned == 0,
            "and it claims nothing about what was there"
        );
    }
}