malvin 0.2.5

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

Harbor Dockerfiles install dependencies at image build time into ``/app``. At
runtime the host workspace is mounted over ``/app``, which can desynchronize
editable installs and leave site-packages inconsistent with the checkout
(HISTORY: pydantic v1 vs v2 on FastAPI tasks).

Two-phase prep enforces a strict contract for Python tasks:

1. **Image build (network on):** reconcile declared dependencies from Dockerfile
   pins, ``pyproject.toml``, and ``uv.lock``, then run mandatory verification
   probes. Image build fails when probes fail after reconcile.
2. **Runtime prep (network off):** offline editable replay (``--no-deps
   --no-build-isolation``) plus verification probes. Fail fast with a clear error
   when sync or probes fail — do not run malvin in a known-bad environment.
"""

from __future__ import annotations

import base64
import os
import re
import shlex
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import click

try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib

from harbor_tests import (
    added_python_sources_from_patch,
    collect_only_pytest_command,
    distribution_name_for_import,
    harbor_imports_from_tests_dir,
    resolve_harbor_test_sh_body,
    test_sh_invokes_pytest,
)
from toolchain_repos import malvin_repo_root

_clone_cached_venv = None

TIMEOUT_EXIT_CODE = 124

def _remaining_sec(deadline: float) -> float:
    return max(0.0, deadline - time.monotonic())

def _normalize_run_command(command: str) -> str:
    """Collapse Dockerfile line continuations into a single shell line."""
    no_continuations = command.replace("\\", " ")
    return " ".join(no_continuations.split())

def _run_shell(
    command: str,
    workspace: Path,
    *,
    timeout_sec: float | None = None,
) -> tuple[int, str, bool]:
    if timeout_sec is not None and timeout_sec <= 0:
        return TIMEOUT_EXIT_CODE, "phase deadline exhausted before prep command", True
    run_kwargs: dict[str, Any] = {
        "args": ["bash", "-lc", command],
        "cwd": str(workspace),
        "text": True,
        "capture_output": True,
        "check": False,
    }
    if timeout_sec is not None:
        run_kwargs["timeout"] = timeout_sec
    try:
        proc = subprocess.run(**run_kwargs)
    except subprocess.TimeoutExpired as exc:
        detail_parts: list[str] = []
        if exc.stdout:
            detail_parts.append(exc.stdout)
        if exc.stderr:
            detail_parts.append(exc.stderr)
        detail = "".join(detail_parts).strip() or "prep command timed out"
        click.echo(detail, err=True)
        return TIMEOUT_EXIT_CODE, detail, True
    if proc.stdout:
        click.echo(proc.stdout, nl=False)
    if proc.stderr:
        click.echo(proc.stderr, nl=False, err=True)
    detail = (proc.stderr or proc.stdout or "").strip()
    return proc.returncode, detail, False

_SKIP_RUN_SUBSTRINGS = (
    "git clone",
    "git checkout",
    "git submodule",
    "curl ",
    "wget ",
    "apt-get",
    "apt install",
    "rustup",
    "cargo install --path",
    "cursor.com/install",
)

_SYNC_RUN_SUBSTRINGS = (
    "pip install",
    "pip3 install",
    "python -m pip",
    "python3 -m pip",
    "uv sync",
    "uv pip",
    "go mod",
    "cargo build",
    "cargo fetch",
    "npm ci",
    "npm install",
    "poetry install",
    "pdm install",
)

@dataclass(frozen=True)
class SandboxPrepResult:
    sync_commands: tuple[str, ...]
    sync_warnings: tuple[str, ...]
    probe_errors: tuple[str, ...]
    ok: bool
    timed_out: bool = False

    def as_dict(self) -> dict[str, Any]:
        return {
            "sync_commands": list(self.sync_commands),
            "sync_warnings": list(self.sync_warnings),
            "probe_errors": list(self.probe_errors),
            "ok": self.ok,
            "timed_out": self.timed_out,
        }

def _join_continued_run_lines(lines: list[str]) -> list[str]:
    """Merge Dockerfile RUN instructions continued with backslashes."""
    runs: list[str] = []
    current: str | None = None
    for raw in lines:
        stripped = raw.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if stripped.upper().startswith("RUN "):
            if current is not None:
                runs.append(current)
            current = stripped[4:].strip()
            if not stripped.endswith("\\"):
                runs.append(_normalize_run_command(current))
                current = None
            continue
        if current is None:
            continue
        if stripped.endswith("\\"):
            current += " " + stripped[:-1].strip()
        else:
            current += " " + stripped
            runs.append(_normalize_run_command(current))
            current = None
    if current is not None:
        runs.append(_normalize_run_command(current))
    return runs

def parse_dockerfile_run_commands(dockerfile_text: str) -> list[str]:
    """Return shell bodies of Dockerfile RUN instructions in file order."""
    return _join_continued_run_lines(dockerfile_text.splitlines())

def should_replay_run_command(command: str) -> bool:
    """True when a RUN line should be replayed after workspace mount."""
    lower = command.lower()
    if any(skip in lower for skip in _SKIP_RUN_SUBSTRINGS):
        return False
    return any(sync in lower for sync in _SYNC_RUN_SUBSTRINGS)

def _split_shell_segments(command: str) -> list[str]:
    return [segment.strip() for segment in re.split(r"\s*&&\s*", command) if segment.strip()]

_EDITABLE_PIP_FLAG = re.compile(r"(?:^|\s)(?:-e|--editable)\s")
_PIP_INSTALL_RE = re.compile(r"(?:^|\s)(?:pip3?|python3? -m pip)(?:\s|$)")

def _is_pip_install_segment(segment: str) -> bool:
    """True for ``pip`` / ``pip3`` / ``python -m pip`` install segments."""
    return bool(_PIP_INSTALL_RE.search(segment))

def _is_editable_pip_segment(segment: str) -> bool:
    """True when a shell segment is ``pip install -e`` (not ``dirty-equals``)."""
    return _is_pip_install_segment(segment) and bool(_EDITABLE_PIP_FLAG.search(segment))

def _is_bulk_pip_segment(segment: str) -> bool:
    """True for non-editable pip installs that require PyPI/registry network."""
    return _is_pip_install_segment(segment) and not _is_editable_pip_segment(segment)

def _offline_editable_command(command: str) -> str:
    """Replay editable installs without PyPI in offline agent sandboxes."""
    out = command.strip()
    if "--no-deps" not in out:
        out += " --no-deps"
    if "--no-build-isolation" not in out:
        out += " --no-build-isolation"
    return out

def _is_network_only_segment(segment: str) -> bool:
    """True for install segments that need registry/network (not offline replay)."""
    lower = segment.lower()
    return (
        _is_bulk_pip_segment(segment)
        or "poetry install" in lower
        or "pnpm install" in lower
        or "npm ci" in lower
        or "npm install" in lower
        or "cargo fetch" in lower
        or "cargo build" in lower
        or "go mod" in lower
    )

def _sync_commands_from_runs(runs: list[str], *, offline_editable: bool = True) -> list[str]:
    sync: list[str] = []
    for cmd in runs:
        if not should_replay_run_command(cmd):
            continue
        segments = _split_shell_segments(cmd)
        editable = [segment for segment in segments if _is_editable_pip_segment(segment)]
        network_only = [segment for segment in segments if _is_network_only_segment(segment)]
        non_pip = [
            segment
            for segment in segments
            if not _is_pip_install_segment(segment) and not _is_network_only_segment(segment)
        ]
        if offline_editable:
            for segment in editable:
                sync.append(_offline_editable_command(segment))
        if network_only or editable:
            continue
        if non_pip:
            sync.append(cmd)
    return sync

def workspace_sync_commands_from_dockerfile(
    dockerfile: Path,
    *,
    offline_editable: bool = True,
) -> list[str]:
    """Dependency-install RUN lines to replay offline against a mounted workspace.

    Bulk ``pip install`` segments are skipped (network). Editable ``pip install -e``
    segments are replayed with ``--no-deps --no-build-isolation``.
    """
    if not dockerfile.is_file():
        return []
    runs = parse_dockerfile_run_commands(dockerfile.read_text(encoding="utf-8"))
    return _sync_commands_from_runs(runs, offline_editable=offline_editable)

def dockerfile_image_build_commands(dockerfile: Path) -> list[str]:
    """Editable pip segments to re-run during Modal image build (network on).

    Modal may cache Dockerfile ``pip install -e`` layers incorrectly (e.g. mars-base
    pydantic v1 survives). Re-running editable segments after ``from_dockerfile``
    busts the cache without replaying bulk ``pip install`` waves that can upgrade
    transitive deps (starlette) and break Harbor verifiers (httpx2).
    """
    if not dockerfile.is_file():
        return []
    runs = parse_dockerfile_run_commands(dockerfile.read_text(encoding="utf-8"))
    commands: list[str] = []
    for cmd in runs:
        if not should_replay_run_command(cmd):
            continue
        segments = _split_shell_segments(cmd)
        editable = [segment for segment in segments if _is_editable_pip_segment(segment)]
        if editable:
            commands.extend(editable)
        else:
            commands.append(cmd)
    return commands

def dockerfile_bulk_pip_commands(dockerfile: Path) -> list[str]:
    """Non-editable ``pip install`` segments from Dockerfile RUN lines (build-time replay)."""
    if not dockerfile.is_file():
        return []
    runs = parse_dockerfile_run_commands(dockerfile.read_text(encoding="utf-8"))
    commands: list[str] = []
    for cmd in runs:
        if not should_replay_run_command(cmd):
            continue
        segments = _split_shell_segments(cmd)
        bulk = [segment for segment in segments if _is_bulk_pip_segment(segment)]
        commands.extend(bulk)
    return commands

_REQUIREMENTS_FILE_RE = re.compile(r"(?:^|\s)-r\s+(\S+)")
_PKG_PIN_RE = re.compile(
    r"(?<![\w.-])([a-zA-Z0-9][a-zA-Z0-9._-]*)==([\d][\w.]*(?:\+[\w.-]+)?)"
)
_BASH_LC_RE = re.compile(r"""bash\s+-lc\s+(["'])(.*)\1""", re.DOTALL)

_PIP_INSTALL_CMD_RE = re.compile(
    r"(?:(?:python3?|\$\{?PYTHON[^}\s]*\}?)\s+-m\s+)?pip3?\s+install\b[^;\n]*",
    re.IGNORECASE,
)
_PYDANTIC_PIN_RE = re.compile(r"^pydantic==([\d.]+)\s*(?:#.*)?$", re.MULTILINE)
_PYDANTIC_CORE_PIN_RE = re.compile(r"^pydantic-core==([\d.]+)\s*(?:#.*)?$", re.MULTILINE)
_SHELL_NOISE_NAMES = frozenset(
    {
        "fi",
        "if",
        "then",
        "else",
        "elif",
        "do",
        "done",
        "for",
        "while",
        "in",
        "pip",
        "pip3",
        "python",
        "python3",
        "install",
        "true",
        "false",
        "apt-get",
        "apt",
        "npm",
        "yarn",
        "poetry",
        "uv",
        "bash",
        "sh",
        "sudo",
        "command",
        "type",
        "which",
        
        "any",
        "author",
        "contact",
        "doc",
        "docs",
        "extras",
        "homepage",
        "license",
        "requirements",
        "utf-8",
        "version",
        "description",
        "keywords",
        "maintainer",
        "platforms",
        "url",
        "setup",
        "test",
        "tests",
        "testing",
        "r",
        "t",
    }
)

def _is_plausible_distribution_name(name: str) -> bool:
    """False for setup.py string noise and requirements filenames mistaken as packages."""
    if not name or len(name) < 2:
        return False
    if name in _SHELL_NOISE_NAMES:
        return False
    
    if "." in name or "/" in name:
        return False
    return True

def _extract_pip_install_commands(shell_text: str) -> list[str]:
    """Return normalized ``pip install …`` commands found in *shell_text*."""
    found: list[str] = []
    for match in _PIP_INSTALL_CMD_RE.finditer(shell_text):
        cmd = " ".join(match.group(0).split()).rstrip('"').rstrip("'")
        if cmd:
            found.append(cmd)
    return found

def collect_pip_install_intents(dockerfile_text: str) -> list[str]:
    """Return pip install shell segments from Dockerfile RUN lines (incl. ``bash -lc``)."""
    intents: list[str] = []
    seen: set[str] = set()

    def _add(command: str) -> None:
        normalized = " ".join(command.split())
        if not normalized or normalized in seen:
            return
        if not _is_pip_install_segment(normalized):
            return
        seen.add(normalized)
        intents.append(normalized)

    for run in parse_dockerfile_run_commands(dockerfile_text):
        for segment in _split_shell_segments(run):
            _add(segment)
            bash_match = _BASH_LC_RE.search(segment)
            if bash_match:
                for cmd in _extract_pip_install_commands(bash_match.group(2)):
                    _add(cmd)
            else:
                for cmd in _extract_pip_install_commands(segment):
                    _add(cmd)
    return intents

def _pins_from_requirements_file(requirements_path: Path) -> dict[str, str]:
    if not requirements_path.is_file():
        return {}
    pins: dict[str, str] = {}
    for raw in requirements_path.read_text(encoding="utf-8").splitlines():
        line = _strip_requirement_comment(raw.strip())
        if not line or line.startswith("#"):
            continue
        match = _PKG_PIN_RE.search(line)
        if match:
            pins[match.group(1).lower()] = match.group(2)
    return pins

def _requirement_line_package(line: str) -> tuple[str, str] | None:
    """Return ``(normalized_name, remainder_spec)`` for a requirements line, if any."""
    stripped = _strip_requirement_comment(line.strip())
    if not stripped or stripped.startswith("#"):
        return None
    if stripped.startswith(("-e", "--editable", "-r", "--requirement", "-c", "--constraint")):
        return None
    if stripped.startswith(("-", ".", "/", "~")):
        return None
    dep = stripped.split(";", 1)[0].strip()
    dep = dep.split("[", 1)[0].strip()
    if "@" in dep:
        return None
    match = re.match(r"^([A-Za-z0-9][\w.-]*)(.*)$", dep)
    if not match:
        return None
    name = _normalize_package_name(match.group(1))
    if name in _SHELL_NOISE_NAMES:
        return None
    return name, match.group(2).strip()

def _constraints_from_requirements_file(requirements_path: Path) -> dict[str, str]:
    """Collect non-``==`` version constraints (``>=``, ``~=``, …) from a requirements file."""
    if not requirements_path.is_file():
        return {}
    constraints: dict[str, str] = {}
    for raw in requirements_path.read_text(encoding="utf-8").splitlines():
        parsed = _requirement_line_package(raw)
        if not parsed:
            continue
        name, rest = parsed
        if not rest or rest.startswith("=="):
            continue
        if rest.startswith((">=", "<=", "!=", "~=", ">", "<")):
            constraints[name] = rest
    return constraints

def _unpinned_from_requirements_file(requirements_path: Path) -> frozenset[str]:
    """Bare package names (no version operator) from a requirements file."""
    if not requirements_path.is_file():
        return frozenset()
    names: set[str] = set()
    for raw in requirements_path.read_text(encoding="utf-8").splitlines():
        parsed = _requirement_line_package(raw)
        if not parsed:
            continue
        name, rest = parsed
        if not rest:
            names.add(name)
    return frozenset(names)

def _editable_lines_from_requirements_file(requirements_path: Path) -> list[str]:
    """Return synthetic ``pip install -e …`` intents for editable lines in *requirements_path*."""
    if not requirements_path.is_file():
        return []
    lines: list[str] = []
    for raw in requirements_path.read_text(encoding="utf-8").splitlines():
        stripped = raw.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if stripped.startswith("-e ") or stripped.startswith("--editable "):
            target = stripped.split(None, 1)[1].strip()
            lines.append(f"pip install -e {target}")
        elif stripped.startswith("-e=") or stripped.startswith("--editable="):
            target = stripped.split("=", 1)[1].strip()
            lines.append(f"pip install -e {target}")
    return lines

def collect_pinned_packages(workspace: Path, intents: list[str]) -> dict[str, str]:
    """Collect ``name==version`` pins from pip intents and referenced ``-r`` files."""
    pins: dict[str, str] = {}
    workspace = workspace.resolve()
    for intent in intents:
        for req_match in _REQUIREMENTS_FILE_RE.finditer(intent):
            pins.update(_pins_from_requirements_file(workspace / req_match.group(1)))
        for match in _PKG_PIN_RE.finditer(intent):
            pins[match.group(1).lower()] = match.group(2)
    return pins

def collect_requirement_constraints(workspace: Path, intents: list[str]) -> dict[str, str]:
    """Collect non-equality version constraints from referenced requirements files."""
    constraints: dict[str, str] = {}
    workspace = workspace.resolve()
    for intent in intents:
        for req_match in _REQUIREMENTS_FILE_RE.finditer(intent):
            constraints.update(
                _constraints_from_requirements_file(workspace / req_match.group(1))
            )
    return constraints

def collect_requirement_unpinned_names(workspace: Path, intents: list[str]) -> frozenset[str]:
    """Bare names from referenced requirements files (and nested ``-r`` editables handled elsewhere)."""
    names: set[str] = set()
    workspace = workspace.resolve()
    for intent in intents:
        for req_match in _REQUIREMENTS_FILE_RE.finditer(intent):
            names |= set(
                _unpinned_from_requirements_file(workspace / req_match.group(1))
            )
    return frozenset(names)

def collect_requirement_editable_intents(workspace: Path, intents: list[str]) -> list[str]:
    """Editable install intents declared inside ``-r`` requirements files."""
    found: list[str] = []
    seen: set[str] = set()
    workspace = workspace.resolve()
    for intent in intents:
        for req_match in _REQUIREMENTS_FILE_RE.finditer(intent):
            for editable in _editable_lines_from_requirements_file(
                workspace / req_match.group(1)
            ):
                if editable not in seen:
                    seen.add(editable)
                    found.append(editable)
    return found

_PIP_OPTION_WITH_VALUE = frozenset(
    {
        "-c",
        "--constraint",
        "-e",
        "--editable",
        "-f",
        "--find-links",
        "-i",
        "--index-url",
        "--extra-index-url",
        "--trusted-host",
        "-r",
        "--requirement",
        "-t",
        "--target",
        "--platform",
        "--python-version",
        "--implementation",
        "--abi",
        "--root",
        "--prefix",
        "--src",
        "--config-settings",
        "--global-option",
        "--no-binary",
        "--only-binary",
    }
)

def collect_unpinned_package_names(intents: list[str]) -> frozenset[str]:
    """Bare distribution names from ``pip install`` intents (bulk or alongside ``-e``)."""
    names: set[str] = set()
    for intent in intents:
        if not _is_pip_install_segment(intent):
            continue
        try:
            tokens = shlex.split(intent)
        except ValueError:
            
            try:
                tokens = shlex.split(intent.rstrip('"').rstrip("'"))
            except ValueError:
                continue
        install_at = None
        for idx, tok in enumerate(tokens):
            if tok == "install":
                install_at = idx
                break
        if install_at is None:
            continue
        i = install_at + 1
        while i < len(tokens):
            tok = tokens[i].rstrip('"').rstrip("'")
            if tok.startswith("-"):
                opt = tok.split("=", 1)[0]
                if opt in _PIP_OPTION_WITH_VALUE and "=" not in tok:
                    i += 2
                    continue
                i += 1
                continue
            if tok.startswith(("/", ".", "~")) or tok.endswith((".txt", ".in")):
                i += 1
                continue
            
            bare = tok.split(";", 1)[0].strip()
            bare = bare.split("[", 1)[0].strip()
            if "@" in bare:
                i += 1
                continue
            name_match = re.match(r"^([A-Za-z0-9][\w.-]*)", bare)
            if not name_match:
                i += 1
                continue
            name = _normalize_package_name(name_match.group(1))
            if name in _SHELL_NOISE_NAMES:
                i += 1
                continue
            rest = bare[len(name_match.group(1)) :].strip()
            
            if rest.startswith("=="):
                i += 1
                continue
            names.add(name)
            i += 1
    return frozenset(names)

_EDITABLE_TARGET_RE = re.compile(
    r"(?:^|\s)(?:-e|--editable)(?:\s*=\s*|\s+)(\S+)",
)

def _editable_target_paths(segment: str, workspace: Path) -> list[Path]:
    """Local paths targeted by ``pip install -e`` / ``--editable`` in *segment*."""
    paths: list[Path] = []
    for match in _EDITABLE_TARGET_RE.finditer(segment):
        raw = match.group(1).strip().strip("'\"")
        raw = raw.split("[", 1)[0].strip()
        if not raw or raw.startswith(("git+", "http://", "https://", "svn+", "hg+")):
            continue
        if raw.startswith("file:"):
            raw = raw[len("file:") :]
            if raw.startswith("//"):
                raw = raw[2:]
        candidate = Path(raw)
        if not candidate.is_absolute():
            candidate = (workspace / candidate).resolve()
        else:
            candidate = candidate.resolve()
        if candidate.is_file():
            candidate = candidate.parent
        if candidate.is_dir():
            paths.append(candidate)
    return paths

def _read_distribution_name(project_root: Path) -> str | None:
    """Return the packaging distribution name declared at *project_root*, if any."""
    pyproject = project_root / "pyproject.toml"
    if pyproject.is_file():
        try:
            raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
        except (OSError, tomllib.TOMLDecodeError, TypeError):
            raw = {}
        project = raw.get("project") if isinstance(raw, dict) else None
        if isinstance(project, dict):
            name = project.get("name")
            if isinstance(name, str) and name.strip():
                return _normalize_package_name(name)
        tool = raw.get("tool") if isinstance(raw, dict) else None
        if isinstance(tool, dict):
            poetry = tool.get("poetry")
            if isinstance(poetry, dict):
                name = poetry.get("name")
                if isinstance(name, str) and name.strip():
                    return _normalize_package_name(name)
    setup_cfg = project_root / "setup.cfg"
    if setup_cfg.is_file():
        try:
            text = setup_cfg.read_text(encoding="utf-8")
        except OSError:
            text = ""
        match = re.search(
            r"(?m)^\s*name\s*=\s*([A-Za-z0-9][\w.-]*)\s*$",
            text,
        )
        if match:
            return _normalize_package_name(match.group(1))
    for pattern in (
        r"""(?m)^\s*name\s*=\s*['"]([^'"]+)['"]""",
        r"""(?m)^\s*NAME\s*=\s*['"]([^'"]+)['"]""",
    ):
        setup_py = project_root / "setup.py"
        if not setup_py.is_file():
            break
        try:
            text = setup_py.read_text(encoding="utf-8")
        except OSError:
            break
        match = re.search(pattern, text)
        if match:
            return _normalize_package_name(match.group(1))
    return None

def _top_level_txt_roots(project_root: Path) -> set[str]:
    """Import roots listed in egg-info / dist-info ``top_level.txt`` files."""
    roots: set[str] = set()
    for path in project_root.glob("*.egg-info/top_level.txt"):
        try:
            text = path.read_text(encoding="utf-8")
        except OSError:
            continue
        for line in text.splitlines():
            name = line.strip()
            if name:
                roots.add(name.split(".", 1)[0])
    for path in project_root.glob("*.dist-info/top_level.txt"):
        try:
            text = path.read_text(encoding="utf-8")
        except OSError:
            continue
        for line in text.splitlines():
            name = line.strip()
            if name:
                roots.add(name.split(".", 1)[0])
    return roots

def _filesystem_package_roots(project_root: Path) -> set[str]:
    """Heuristic import roots from common src-/flat- layouts under *project_root*."""
    roots: set[str] = set()
    skip = {
        "tests",
        "test",
        "docs",
        "doc",
        "examples",
        "example",
        "scripts",
        "benchmarks",
        "benchmark",
        "build",
        "dist",
        "requirements",
        "venv",
        ".venv",
        "node_modules",
        "__pycache__",
    }
    src = project_root / "src"
    search_roots = [src] if src.is_dir() else [project_root]
    for base in search_roots:
        try:
            entries = list(base.iterdir())
        except OSError:
            continue
        for entry in entries:
            if not entry.is_dir() or entry.name.startswith(".") or entry.name in skip:
                continue
            if (entry / "__init__.py").is_file() or (entry / "__init__.pyi").is_file():
                roots.add(entry.name)
    return roots

def import_roots_provided_by_project(project_root: Path) -> set[str]:
    """Import roots satisfied by installing the project at *project_root* editable."""
    roots = set(_top_level_txt_roots(project_root))
    roots |= _filesystem_package_roots(project_root)
    dist_name = _read_distribution_name(project_root)
    if dist_name:
        roots.add(dist_name.replace("-", "_"))
        
        roots.add(dist_name)
    return {r for r in roots if r}

def dockerfile_uses_poetry_install(dockerfile_text: str) -> bool:
    """True when a Dockerfile RUN installs the project via Poetry."""
    return bool(re.search(r"\bpoetry\s+install\b", dockerfile_text, re.IGNORECASE))

def pythonpath_entries_from_dockerfile(
    dockerfile_text: str,
    workspace: Path,
) -> list[Path]:
    """Resolve ``ENV PYTHONPATH=…`` entries that fall under *workspace*."""
    workspace = workspace.resolve()
    paths: list[Path] = []
    for match in re.finditer(
        r"(?im)^\s*ENV\s+PYTHONPATH=(\S+)",
        dockerfile_text,
    ):
        raw = match.group(1).strip().strip("'\"")
        for part in raw.split(":"):
            part = part.strip()
            if not part:
                continue
            if part in ("/app", "."):
                paths.append(workspace)
                continue
            if part.startswith("/app/"):
                rel = part[len("/app/") :]
                candidate = (workspace / rel).resolve()
            else:
                candidate = Path(part)
                if not candidate.is_absolute():
                    candidate = (workspace / candidate).resolve()
            if candidate == workspace or workspace in candidate.parents or candidate.is_dir():
                paths.append(candidate)
    return paths

def workspace_mount_provided_import_roots(
    workspace: Path,
    dockerfile: Path | None = None,
) -> set[str]:
    """Import roots satisfied by the mounted workspace (editable, PYTHONPATH, or layout).

    Harbor grades run with ``cwd=/app``. Flat layouts are importable via ``sys.path``;
    ``ENV PYTHONPATH`` and Poetry installs also expose the project without a separate
    DeclaredDeps pin. Always include filesystem/distribution roots for the workspace
    itself so package-under-test imports are not marked unmapped.
    """
    workspace = workspace.resolve()
    provided = import_roots_provided_by_project(workspace)
    if dockerfile is None or not dockerfile.is_file():
        return provided
    text = dockerfile.read_text(encoding="utf-8")
    for path in pythonpath_entries_from_dockerfile(text, workspace):
        provided |= import_roots_provided_by_project(path)
        
        provided |= _filesystem_package_roots(
            path if path.name != "src" else path.parent
        )
        if path.name == "src" or (path / "src").is_dir():
            provided |= _filesystem_package_roots(
                path if path.name == "src" else path / "src"
            )
    return provided

def editable_provided_import_roots(
    workspace: Path,
    editable_segments: tuple[str, ...],
    dockerfile: Path | None = None,
) -> set[str]:
    """Union of import roots from editable installs plus the mounted workspace project."""
    provided: set[str] = set()
    workspace = workspace.resolve()
    for segment in editable_segments:
        for path in _editable_target_paths(segment, workspace):
            provided |= import_roots_provided_by_project(path)
    provided |= workspace_mount_provided_import_roots(workspace, dockerfile)
    return provided

def requirements_paths_from_dockerfile(dockerfile: Path) -> list[str]:
    """Return ``-r`` requirements paths referenced by Dockerfile bulk pip installs."""
    if not dockerfile.is_file():
        return []
    intents = collect_pip_install_intents(dockerfile.read_text(encoding="utf-8"))
    paths: list[str] = []
    for intent in intents:
        paths.extend(match.group(1) for match in _REQUIREMENTS_FILE_RE.finditer(intent))
    return paths

def read_pydantic_pins_from_requirements(requirements_path: Path) -> tuple[str | None, str | None]:
    """Return ``(pydantic, pydantic-core)`` pins from a requirements file, if present."""
    if not requirements_path.is_file():
        return None, None
    text = requirements_path.read_text(encoding="utf-8")
    pydantic_match = _PYDANTIC_PIN_RE.search(text)
    core_match = _PYDANTIC_CORE_PIN_RE.search(text)
    return (
        pydantic_match.group(1) if pydantic_match else None,
        core_match.group(1) if core_match else None,
    )

def _precommit_pin_from_workspace(workspace: Path) -> str | None:
    """Return a pinned ``pre-commit`` version declared by the workspace, if any."""
    workspace = workspace.resolve()
    candidates: list[Path] = []
    req_dir = workspace / "requirements"
    if req_dir.is_dir():
        candidates.extend(sorted(req_dir.rglob("*.txt")))
    for name in ("requirements.txt", "dev-requirements.txt", "lint-requirements.txt"):
        path = workspace / name
        if path.is_file():
            candidates.append(path)
    seen: set[Path] = set()
    for path in candidates:
        resolved = path.resolve()
        if resolved in seen:
            continue
        seen.add(resolved)
        pin = _pins_from_requirements_file(path).get("pre-commit")
        if pin:
            return pin
    pyproject = workspace / "pyproject.toml"
    if pyproject.is_file():
        raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
        dep_lists: list[list[str]] = []
        optional = raw.get("project", {}).get("optional-dependencies")
        if isinstance(optional, dict):
            dep_lists.extend(
                deps for deps in optional.values() if isinstance(deps, list)
            )
        groups = raw.get("dependency-groups")
        if isinstance(groups, dict):
            dep_lists.extend(deps for deps in groups.values() if isinstance(deps, list))
        for deps in dep_lists:
            for dep in deps:
                if not isinstance(dep, str):
                    continue
                parsed = _parse_dependency_spec(dep.split(";", 1)[0].strip())
                if parsed and parsed[0] == "pre-commit" and parsed[1].startswith("=="):
                    return parsed[1][2:]
    lockfile = workspace / "uv.lock"
    if lockfile.is_file():
        for match in _UV_LOCK_PACKAGE_RE.finditer(lockfile.read_text(encoding="utf-8")):
            if match.group(1).lower() == "pre-commit":
                return match.group(2)
    return None

def pins_for_task(
    dockerfile: Path | None,
    workspace: Path | None = None,
) -> dict[str, str]:
    """Pinned packages for a task workspace (Modal image build / cache bust)."""
    if dockerfile is None or not dockerfile.is_file() or workspace is None:
        return {}
    intents = collect_pip_install_intents(dockerfile.read_text(encoding="utf-8"))
    return collect_pinned_packages(workspace.resolve(), intents)

_DEP_SPEC_RE = re.compile(
    r"^([A-Za-z0-9][\w.-]*)(\[[^\]]+\])?\s*([^;]*?)(?:\s*;\s*.*)?$"
)
_UV_LOCK_PACKAGE_RE = re.compile(
    r'^\[\[package\]\]\s*\nname = "([^"]+)"\s*\nversion = "([^"]+)"',
    re.MULTILINE,
)

@dataclass(frozen=True)
class DeclaredDeps:
    """Canonical Python dependency declarations for one task workspace."""

    bulk_pins: dict[str, str]
    constraints: dict[str, str]
    editable_segments: tuple[str, ...]
    lockfile_pins: dict[str, str]
    unpinned_names: frozenset[str] = frozenset()

    def package_names(self) -> set[str]:
        keys = (
            set(self.bulk_pins)
            | set(self.constraints)
            | set(self.lockfile_pins)
            | set(self.unpinned_names)
        )
        return {name.lower() for name in keys}

    def effective_spec(self, name: str) -> str | None:
        key = name.lower()
        if key in self.bulk_pins:
            return f"=={self.bulk_pins[key]}"
        constraint = self.constraints.get(key)
        if constraint is not None:
            return constraint
        if key in self.lockfile_pins:
            return f"=={self.lockfile_pins[key]}"
        return None

    def pip_install_spec(self, name: str) -> str | None:
        """Return a pip package argument for *name*, or None when not declared."""
        key = name.lower()
        spec = self.effective_spec(key)
        if spec is None:
            if key in self.unpinned_names:
                return key
            return None
        if not spec:
            return key
        
        if spec.startswith("[") or spec.startswith(
            ("==", ">=", "<=", "!=", "~=", ">", "<")
        ):
            return f"{key}{spec}"
        return f"{key}=={spec}"

def _normalize_package_name(name: str) -> str:
    return name.lower().replace("_", "-")

def _strip_requirement_comment(line: str) -> str:
    """Strip unquoted ``# …`` tails from requirements lines (OpenStack-style license tags)."""
    in_quote: str | None = None
    for i, ch in enumerate(line):
        if in_quote is not None:
            if ch == in_quote:
                in_quote = None
            continue
        if ch in ("'", '"'):
            in_quote = ch
            continue
        if ch == "#":
            return line[:i].rstrip()
    return line.rstrip()

def _parse_dependency_spec(raw: str) -> tuple[str, str] | None:
    line = _strip_requirement_comment(raw.strip())
    if not line or line.startswith("#"):
        return None
    match = _DEP_SPEC_RE.match(line)
    if not match:
        return None
    name = _normalize_package_name(match.group(1))
    extras = match.group(2) or ""
    ver = (match.group(3) or "").strip()
    return name, f"{extras}{ver}"

def _split_pyproject_dependency(raw: str) -> tuple[str, str, str | None] | None:
    """Return ``(name, spec, marker)`` from one PEP 508 dependency string."""
    line = _strip_requirement_comment(raw.strip())
    if not line or line.startswith("#"):
        return None
    marker: str | None = None
    dep_part = line
    if ";" in line:
        dep_part, marker_text = line.split(";", 1)
        marker = marker_text.strip() or None
    parsed = _parse_dependency_spec(dep_part)
    if not parsed:
        return None
    return parsed[0], parsed[1], marker

def _version_tuple(version: str) -> tuple[int, ...]:
    parts: list[int] = []
    for piece in version.split("."):
        digits = re.match(r"(\d+)", piece)
        if not digits:
            break
        parts.append(int(digits.group(1)))
    return tuple(parts)

def _compare_version_tuple(left: tuple[int, ...], op: str, right: tuple[int, ...]) -> bool:
    width = max(len(left), len(right))
    left_padded = left + (0,) * (width - len(left))
    right_padded = right + (0,) * (width - len(right))
    if op == "<":
        return left_padded < right_padded
    if op == "<=":
        return left_padded <= right_padded
    if op == ">":
        return left_padded > right_padded
    if op == ">=":
        return left_padded >= right_padded
    if op == "==":
        return left_padded == right_padded
    if op == "!=":
        return left_padded != right_padded
    return True

def _environment_marker_applies(marker: str | None) -> bool:
    """True when a PEP 508 environment marker matches the current interpreter."""
    if not marker:
        return True
    try:
        from packaging.markers import Marker

        return Marker(marker).evaluate()
    except Exception:
        pass
    match = re.match(
        r"^python_version\s*(<|<=|>=|>|==|!=)\s*['\"]([\d.]+)['\"]\s*$",
        marker.strip(),
    )
    if match:
        op, bound = match.group(1), _version_tuple(match.group(2))
        current = sys.version_info[: max(len(bound), 2)]
        return _compare_version_tuple(current, op, bound)
    return False

def _read_pyproject_dependencies(
    pyproject: Path,
) -> tuple[dict[str, str], frozenset[str]]:
    """Return ``(versioned_constraints, bare_unpinned_names)`` from ``[project]`` deps."""
    if not pyproject.is_file():
        return {}, frozenset()
    raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    constraints: dict[str, str] = {}
    bare: set[str] = set()
    project = raw.get("project") or {}
    for dep in project.get("dependencies") or []:
        if not isinstance(dep, str):
            continue
        parsed = _split_pyproject_dependency(dep)
        if not parsed:
            continue
        name, spec, marker = parsed
        if not _environment_marker_applies(marker):
            continue
        if not spec:
            bare.add(name)
        else:
            constraints[name] = spec
    return constraints, frozenset(bare)

def _read_uv_lock_pins(lock_path: Path, names: set[str]) -> dict[str, str]:
    if not lock_path.is_file() or not names:
        return {}
    text = lock_path.read_text(encoding="utf-8")
    pins: dict[str, str] = {}
    for match in _UV_LOCK_PACKAGE_RE.finditer(text):
        pkg = _normalize_package_name(match.group(1))
        if pkg in names:
            pins[pkg] = match.group(2)
    return pins

def _editable_segments_from_dockerfile(dockerfile_text: str) -> tuple[str, ...]:
    segments: list[str] = []
    for run in parse_dockerfile_run_commands(dockerfile_text):
        if not should_replay_run_command(run):
            continue
        for segment in _split_shell_segments(run):
            if _is_editable_pip_segment(segment):
                segments.append(segment)
    return tuple(segments)

def _extras_names_from_editable_target(target: str) -> list[str]:
    """Return extras names from an editable target like ``.[test,dev]`` or ``pkg[extra]``."""
    match = re.search(r"\[([^\]]+)\]", target)
    if not match:
        return []
    return [part.strip() for part in match.group(1).split(",") if part.strip()]

def _optional_dependency_specs_from_pyproject(
    pyproject: Path,
    extras: list[str],
) -> tuple[dict[str, str], frozenset[str]]:
    """Return ``(constraints, bare_names)`` from ``[project.optional-dependencies]`` extras."""
    if not extras or not pyproject.is_file():
        return {}, frozenset()
    try:
        raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    except (OSError, tomllib.TOMLDecodeError, TypeError):
        return {}, frozenset()
    optional = (raw.get("project") or {}).get("optional-dependencies") or {}
    if not isinstance(optional, dict):
        return {}, frozenset()
    constraints: dict[str, str] = {}
    bare: set[str] = set()
    for extra in extras:
        deps = optional.get(extra) or optional.get(extra.replace("-", "_")) or []
        if not isinstance(deps, list):
            continue
        for dep in deps:
            if not isinstance(dep, str):
                continue
            parsed = _split_pyproject_dependency(dep)
            if not parsed:
                continue
            name, spec, marker = parsed
            if not _environment_marker_applies(marker):
                continue
            if not spec:
                bare.add(name)
            else:
                constraints[name] = spec
    return constraints, frozenset(bare)

def _poetry_dependency_names(
    pyproject: Path,
    *,
    include_groups: tuple[str, ...] = ("dev",),
    include_optional: bool = False,
) -> frozenset[str]:
    """Distribution names declared under Poetry dependencies / groups / extras tables."""
    if not pyproject.is_file():
        return frozenset()
    try:
        raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    except (OSError, tomllib.TOMLDecodeError, TypeError):
        return frozenset()
    tool = raw.get("tool") or {}
    poetry = tool.get("poetry") if isinstance(tool, dict) else None
    if not isinstance(poetry, dict):
        return frozenset()
    names: set[str] = set()

    def _absorb(section: object, *, optional_ok: bool) -> None:
        if not isinstance(section, dict):
            return
        for key, value in section.items():
            if not isinstance(key, str):
                continue
            if key.lower() == "python":
                continue
            if isinstance(value, dict) and value.get("optional") and not optional_ok:
                continue
            names.add(_normalize_package_name(key))

    _absorb(poetry.get("dependencies"), optional_ok=include_optional)
    group = poetry.get("group")
    if isinstance(group, dict):
        for group_name in include_groups:
            block = group.get(group_name)
            if isinstance(block, dict):
                _absorb(block.get("dependencies"), optional_ok=True)
    _absorb(poetry.get("dev-dependencies"), optional_ok=True)
    return frozenset(names)

def _poetry_extra_package_names(pyproject: Path, extras: list[str]) -> frozenset[str]:
    """Package names listed in Poetry ``extras.<name> = [...]`` for requested extras."""
    if not extras or not pyproject.is_file():
        return frozenset()
    try:
        raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    except (OSError, tomllib.TOMLDecodeError, TypeError):
        return frozenset()
    poetry = ((raw.get("tool") or {}).get("poetry") or {})
    if not isinstance(poetry, dict):
        return frozenset()
    extra_table = poetry.get("extras")
    if not isinstance(extra_table, dict):
        return frozenset()
    names: set[str] = set()
    for extra in extras:
        listed = extra_table.get(extra) or extra_table.get(extra.replace("_", "-"))
        if not isinstance(listed, list):
            continue
        for item in listed:
            if isinstance(item, str) and item.strip():
                names.add(_normalize_package_name(item.strip()))
    return frozenset(names)

_SETUP_REQ_STRING_RE = re.compile(
    r"""['"]([A-Za-z0-9][\w.-]*(?:\[[^\]]+\])?(?:\s*(?:==|>=|<=|!=|~=|<|>)[^'"]*)?)['"]"""
)
_SETUP_EXTRAS_REQUIRE_KEYS_RE = re.compile(
    r"""extras_require\s*=\s*\{(.*)\}\s*,""",
    re.DOTALL,
)
_SETUP_DICT_KEY_RE = re.compile(r"""['"]([A-Za-z0-9][\w.-]*)['"]\s*:""")

def _extras_require_keys_from_setup_py(setup_py: Path) -> frozenset[str]:
    """Return ``extras_require`` dict keys (setuptools extra names, not packages)."""
    if not setup_py.is_file():
        return frozenset()
    try:
        text = setup_py.read_text(encoding="utf-8")
    except OSError:
        return frozenset()
    match = _SETUP_EXTRAS_REQUIRE_KEYS_RE.search(text)
    if not match:
        return frozenset()
    return frozenset(
        _normalize_package_name(key)
        for key in _SETUP_DICT_KEY_RE.findall(match.group(1))
    )

def _requirement_files_for_setuptools_extra(workspace: Path, extra: str) -> list[Path]:
    """Conventional requirement-file locations for a setuptools extra name."""
    candidates = (
        workspace / "requirements" / "extras" / f"{extra}.txt",
        workspace / "requirements" / "extras" / extra,
        workspace / "requirements" / f"{extra}.txt",
        workspace / "requirements" / extra,
    )
    return [path for path in candidates if path.is_file()]

def _specs_from_setuptools_extra_files(
    workspace: Path,
    extras: list[str],
) -> tuple[dict[str, str], dict[str, str], frozenset[str]]:
    """Return ``(pins, constraints, bare_names)`` from requirements files for *extras*.

    Celery/Kombu-style projects map ``extras_require`` values to
    ``requirements/extras/<name>.txt`` instead of inline PEP 508 strings. Prefer
    those files over scraping setup.py string literals (which otherwise picks up
    the extra *keys* as fake PyPI names).
    """
    pins: dict[str, str] = {}
    constraints: dict[str, str] = {}
    bare: set[str] = set()
    for extra in extras:
        for req_path in _requirement_files_for_setuptools_extra(workspace, extra):
            pins.update(_pins_from_requirements_file(req_path))
            constraints.update(_constraints_from_requirements_file(req_path))
            bare |= set(_unpinned_from_requirements_file(req_path))
    return pins, constraints, frozenset(bare)

def _requirement_names_from_setup_py(setup_py: Path) -> frozenset[str]:
    """Best-effort package names from quoted requirement strings in ``setup.py``.

    Accepts versioned PEP 508 strings anywhere, and bare names only when the whole
    line is a list item (``\"aiofiles\",``). That drops ``name='pkg'``, ``hasattr``
    string args, and other metadata noise while keeping inline extras bodies (gql).
    """
    if not setup_py.is_file():
        return frozenset()
    try:
        text = setup_py.read_text(encoding="utf-8")
    except OSError:
        return frozenset()
    extra_keys = _extras_require_keys_from_setup_py(setup_py)
    names: set[str] = set()
    for match in _SETUP_REQ_STRING_RE.finditer(text):
        raw = match.group(1).split(";", 1)[0].strip()
        bare = raw.split("[", 1)[0].strip()
        name_match = re.match(r"^([A-Za-z0-9][\w.-]*)", bare)
        if not name_match:
            continue
        name = _normalize_package_name(name_match.group(1))
        if not _is_plausible_distribution_name(name) or name in {"gql", "returns"}:
            continue
        
        if name in extra_keys:
            continue
        has_version = any(
            op in raw for op in ("==", ">=", "<=", "!=", "~=", ">", "<")
        )
        if not has_version:
            line_start = text.rfind("\n", 0, match.start()) + 1
            line_end = text.find("\n", match.end())
            line = text[line_start : line_end if line_end != -1 else None].strip()
            
            if not re.fullmatch(r"""['"][^'"]+['"]\s*,?""", line):
                continue
        
        if name_match.group(1)[0].isupper() and not has_version:
            continue
        names.add(name)
    return frozenset(names)

def declared_python_dependencies(
    workspace: Path,
    dockerfile: Path | None = None,
) -> DeclaredDeps:
    """Collect declared Python deps from Dockerfile pins, pyproject, and uv.lock."""
    workspace = workspace.resolve()
    dockerfile_text = dockerfile.read_text(encoding="utf-8") if dockerfile and dockerfile.is_file() else ""
    intents = collect_pip_install_intents(dockerfile_text) if dockerfile_text else []
    req_editables = collect_requirement_editable_intents(workspace, intents) if intents else []
    bulk_pins = collect_pinned_packages(workspace, intents) if intents else {}
    constraints, pyproject_bare = _read_pyproject_dependencies(workspace / "pyproject.toml")
    req_constraints = collect_requirement_constraints(workspace, intents) if intents else {}
    for name, spec in req_constraints.items():
        constraints.setdefault(name, spec)
    for key in bulk_pins:
        constraints.pop(key, None)
    unpinned = collect_unpinned_package_names(intents) if intents else frozenset()
    unpinned |= collect_requirement_unpinned_names(workspace, intents) if intents else frozenset()
    unpinned |= pyproject_bare
    
    editable_seed = list(_editable_segments_from_dockerfile(dockerfile_text)) if dockerfile_text else []
    editable_seed.extend(req_editables)
    extras_requested: list[str] = []
    for segment in editable_seed:
        for match in _EDITABLE_TARGET_RE.finditer(segment):
            extras = _extras_names_from_editable_target(match.group(1))
            extras_requested.extend(extras)
            extra_constraints, extra_bare = _optional_dependency_specs_from_pyproject(
                workspace / "pyproject.toml",
                extras,
            )
            for name, spec in extra_constraints.items():
                constraints.setdefault(name, spec)
            unpinned |= extra_bare
            unpinned |= _poetry_extra_package_names(workspace / "pyproject.toml", extras)
    if extras_requested:
        
        
        
        extra_pins, extra_constraints, extra_bare = _specs_from_setuptools_extra_files(
            workspace,
            extras_requested,
        )
        for name, ver in extra_pins.items():
            bulk_pins.setdefault(name, ver)
            constraints.pop(name, None)
        for name, spec in extra_constraints.items():
            if name not in bulk_pins:
                constraints.setdefault(name, spec)
        unpinned |= extra_bare
        unpinned |= _requirement_names_from_setup_py(workspace / "setup.py")
    
    
    
    
    if editable_seed:
        default_req = workspace / "requirements" / "default.txt"
        if default_req.is_file():
            for name, ver in _pins_from_requirements_file(default_req).items():
                bulk_pins.setdefault(name, ver)
                constraints.pop(name, None)
            for name, spec in _constraints_from_requirements_file(default_req).items():
                if name not in bulk_pins:
                    constraints.setdefault(name, spec)
            unpinned |= _unpinned_from_requirements_file(default_req)
        
        
        for segment in editable_seed:
            for target in _editable_target_paths(segment, workspace):
                pkg_constraints, pkg_bare = _read_pyproject_dependencies(
                    target / "pyproject.toml"
                )
                for name, spec in pkg_constraints.items():
                    if name not in bulk_pins:
                        constraints.setdefault(name, spec)
                unpinned |= pkg_bare
    
    unpinned |= _poetry_dependency_names(
        workspace / "pyproject.toml",
        include_groups=("dev",) if (
            dockerfile_text and dockerfile_uses_poetry_install(dockerfile_text)
        ) else (),
        include_optional=bool(extras_requested),
    )
    if dockerfile_text and dockerfile_uses_poetry_install(dockerfile_text):
        
        if "pip install -e ." not in editable_seed:
            editable_seed.append("pip install -e .")
    unpinned = frozenset(
        name
        for name in unpinned
        if name not in bulk_pins
        and name not in constraints
        and _is_plausible_distribution_name(name)
    )
    lockfile_pins = _read_uv_lock_pins(
        workspace / "uv.lock",
        {name.lower() for name in constraints} | set(bulk_pins) | set(unpinned),
    )
    
    seen_edit: set[str] = set()
    editable_segments: list[str] = []
    for segment in editable_seed:
        if segment not in seen_edit:
            seen_edit.add(segment)
            editable_segments.append(segment)
    
    
    
    
    return DeclaredDeps(
        bulk_pins=bulk_pins,
        constraints=constraints,
        editable_segments=tuple(editable_segments),
        lockfile_pins=lockfile_pins,
        unpinned_names=unpinned,
    )

def format_prep_error(
    task_id: str,
    *,
    phase: str,
    package: str | None = None,
    observed: str | None = None,
    expected: str | None = None,
    detail: str | None = None,
    hint: str | None = None,
) -> str:
    """Human-readable short-abort message for dependency prep failures."""
    parts = [f"sandbox {phase} failed ({task_id})"]
    if package:
        parts.append(f": {package}")
    if observed is not None and expected is not None:
        parts.append(f" — observed {observed}, expected {expected}")
    elif detail:
        parts.append(f" — {detail}")
    if hint:
        parts.append(f"; hint: {hint}")
    return "".join(parts)

VERIFIER_VENV_PATH = "/opt/malvin-verifier"
VERIFIER_PYTHON = f"{VERIFIER_VENV_PATH}/bin/python"
VERIFIER_PIP = f"{VERIFIER_VENV_PATH}/bin/pip"

def _verifier_pip(spec: VerifierSpec | None = None, *, venv_path: str | None = None) -> str:
    """Pip binary inside the verifier venv (honors ``spec.venv_path`` overrides)."""
    root = venv_path
    if root is None and spec is not None:
        root = spec.venv_path
    if root is None:
        root = VERIFIER_VENV_PATH
    return f"{root}/bin/pip"

@dataclass(frozen=True)
class PluginPolicy:
    """Grade-subprocess-only pytest plugin policy (never bake into agent image env).

    ``as_env`` sets ``PYTEST_DISABLE_PLUGIN_AUTOLOAD`` and optional ``-p`` allowlist
    tokens. Callers that merge into an existing env must append allowlist tokens to
    any pre-existing ``PYTEST_ADDOPTS`` (see ``verifier_grade_subprocess_env``).
    ``MALVIN_VERIFIER_PLUGIN_ALLOWLIST`` is debug metadata only; pytest does not read it.
    """

    disable_autoload: bool = False
    allowlist: tuple[str, ...] = ()

    def as_env(self) -> dict[str, str]:
        if not self.disable_autoload:
            return {}
        env = {"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}
        if self.allowlist:
            
            env["PYTEST_ADDOPTS"] = " ".join(f"-p {name}" for name in self.allowlist)
            env["MALVIN_VERIFIER_PLUGIN_ALLOWLIST"] = ",".join(self.allowlist)
        return env

def _merge_pytest_addopts(existing: str | None, addition: str | None) -> str:
    """Append *addition* tokens to *existing* ``PYTEST_ADDOPTS`` without dropping either."""
    parts = [p for p in ((existing or "").strip(), (addition or "").strip()) if p]
    return " ".join(parts)

@dataclass(frozen=True)
class VerifierSpec:
    """Public + grade-only Harbor verifier dependency discovery result.

    Public fields may appear on the agent image. Grade-only fields (``harbor_imports``,
    closure install specs, plugin policy, unmapped imports) are verifier secrets —
    persist them only in grade-phase / host metadata, never in agent-readable
    ``sandbox_prep`` payloads.
    """

    declared: DeclaredDeps
    public_install_specs: tuple[str, ...]
    editable_segments: tuple[str, ...]
    harbor_imports: tuple[str, ...] = ()
    grade_closure_install_specs: tuple[str, ...] = ()
    unmapped_imports: tuple[str, ...] = ()
    test_sh_body: str | None = None
    plugin_policy: PluginPolicy | None = None
    venv_path: str = VERIFIER_VENV_PATH
    
    grade_pythonpath: tuple[str, ...] = ()

    def public_view(self) -> dict[str, Any]:
        """Agent-safe summary: no ``test.patch``-derived import or closure fields."""
        return {
            "venv_path": self.venv_path,
            "public_install_specs": list(self.public_install_specs),
            "editable_segments": list(self.editable_segments),
            "declared_packages": sorted(self.declared.package_names()),
        }

    def grade_view(self) -> dict[str, Any]:
        """Host/grade-only view including secret discovery fields."""
        payload = self.public_view()
        payload.update(
            {
                "harbor_imports": list(self.harbor_imports),
                "grade_closure_install_specs": list(self.grade_closure_install_specs),
                "unmapped_imports": list(self.unmapped_imports),
                "grade_pythonpath": list(self.grade_pythonpath),
                "plugin_policy": (
                    {
                        "disable_autoload": self.plugin_policy.disable_autoload,
                        "allowlist": list(self.plugin_policy.allowlist),
                    }
                    if self.plugin_policy
                    else None
                ),
            }
        )
        return payload

def _public_install_specs(declared: DeclaredDeps) -> tuple[str, ...]:
    specs: list[str] = []
    for name in sorted(declared.package_names()):
        spec = declared.pip_install_spec(name)
        if spec:
            specs.append(spec)
    return tuple(specs)

def discover_verifier_spec(
    workspace: Path,
    tests_dir: Path | None = None,
    dockerfile: Path | None = None,
) -> VerifierSpec:
    """Discover public DeclaredDeps and optional grade-only Harbor import closure.

    When ``tests_dir`` is None (agent image path), grade-only fields stay empty so
    ``test.patch`` secrets are never ingested.

    ``grade_closure_install_specs`` lists declared pin specs required by Harbor
    imports (even when those pins are already in ``public_install_specs``). Grade
    prep may reinstall them into ``/opt/malvin-verifier``; agent-image materialize
    never runs those grade-only commands. Unmapped third-party imports are recorded
    for probe handling and are never invented as unpinned PyPI installs. Imports
    satisfied by Dockerfile editable installs or the mounted workspace project are
    not unmapped (editable replay / workspace layout provides them).
    """
    workspace = workspace.resolve()
    declared = declared_python_dependencies(workspace, dockerfile)
    editable_segments = list(declared.editable_segments)
    dockerfile_text = (
        dockerfile.read_text(encoding="utf-8")
        if dockerfile is not None and dockerfile.is_file()
        else ""
    )
    pythonpath_entries = (
        pythonpath_entries_from_dockerfile(dockerfile_text, workspace)
        if dockerfile_text
        else []
    )
    grade_pythonpath = tuple(str(p) for p in pythonpath_entries)
    
    
    
    
    if import_roots_provided_by_project(workspace) and not pythonpath_entries:
        covers_workspace = False
        for segment in editable_segments:
            for path in _editable_target_paths(segment, workspace):
                if path.resolve() == workspace:
                    covers_workspace = True
                    break
            if covers_workspace:
                break
        if not covers_workspace:
            editable_segments.append("pip install --no-deps -e .")
            declared = DeclaredDeps(
                bulk_pins=declared.bulk_pins,
                constraints=declared.constraints,
                editable_segments=tuple(editable_segments),
                lockfile_pins=declared.lockfile_pins,
                unpinned_names=declared.unpinned_names,
            )
    public_specs = _public_install_specs(declared)
    harbor_imports = harbor_imports_from_tests_dir(tests_dir)
    editable_imports = editable_provided_import_roots(
        workspace,
        declared.editable_segments,
        dockerfile=dockerfile,
    )
    editable_imports_normalized = {
        name.replace("-", "_").lower() for name in editable_imports
    } | {name.lower() for name in editable_imports}
    closure: list[str] = []
    unmapped: list[str] = []
    for import_name in harbor_imports:
        import_key = import_name.replace("-", "_").lower()
        if (
            import_name in editable_imports
            or import_key in editable_imports_normalized
            or import_name.lower() in editable_imports_normalized
        ):
            
            continue
        dist = distribution_name_for_import(import_name)
        spec = declared.pip_install_spec(dist)
        if spec is None:
            
            spec = declared.pip_install_spec(import_name)
        if spec is None:
            unmapped.append(import_name)
            continue
        
        if spec not in closure:
            closure.append(spec)
    test_sh = resolve_harbor_test_sh_body(tests_dir)
    return VerifierSpec(
        declared=declared,
        public_install_specs=public_specs,
        editable_segments=declared.editable_segments,
        harbor_imports=harbor_imports,
        grade_closure_install_specs=tuple(closure),
        unmapped_imports=tuple(unmapped),
        test_sh_body=test_sh,
        grade_pythonpath=grade_pythonpath,
    )

def verifier_venv_materialize_public_commands(
    spec: VerifierSpec,
    *,
    workspace: Path | None = None,
) -> list[str]:
    """Create ``/opt/malvin-verifier`` and install **public** DeclaredDeps only."""
    pip_bin = _verifier_pip(spec)
    commands = [
        f"python3 -m venv {shlex.quote(spec.venv_path)}",
        f"{shlex.quote(pip_bin)} install --upgrade pip setuptools wheel",
    ]
    if spec.public_install_specs:
        pkgs = " ".join(shlex.quote(s) for s in spec.public_install_specs)
        commands.append(
            f"{shlex.quote(pip_bin)} install --no-cache-dir {pkgs}"
        )
    if workspace is not None and spec.editable_segments:
        commands.extend(
            verifier_venv_build_system_commands(workspace, spec=spec)
        )
    for segment in spec.editable_segments:
        
        rewritten = _rewrite_pip_segment_python(segment, pip_bin)
        if "--no-deps" not in rewritten:
            rewritten += " --no-deps"
        commands.append(rewritten)
    return commands

def _rewrite_pip_segment_python(segment: str, pip_bin: str) -> str:
    """Point a Dockerfile pip segment at *pip_bin*."""
    out = segment.strip()
    replacements = (
        ("python3 -m pip", pip_bin),
        ("python -m pip", pip_bin),
        ("pip3 ", f"{pip_bin} "),
        ("pip ", f"{pip_bin} "),
    )
    for old, new in replacements:
        if old in out:
            return out.replace(old, new, 1)
    if out.startswith(pip_bin):
        return out
    return f"{pip_bin} {out}" if not out.startswith("pip") else out.replace("pip", pip_bin, 1)

def verifier_venv_apply_grade_closure_commands(spec: VerifierSpec) -> list[str]:
    """Install grade-only closure specs into the verifier venv (requires ``/tests``)."""
    if not spec.grade_closure_install_specs:
        return []
    pkgs = " ".join(shlex.quote(s) for s in spec.grade_closure_install_specs)
    pip_bin = _verifier_pip(spec)
    return [f"{shlex.quote(pip_bin)} install --no-cache-dir {pkgs}"]

def verifier_venv_replay_editable_commands(spec: VerifierSpec) -> list[str]:
    """Replay Dockerfile editables into the verifier venv against the live workspace.

    Image-build materialize may have installed editables against a copied ``/app``.
    Runtime remounts replace ``/app``, so grade prep must re-link editables offline.
    """
    pip_bin = _verifier_pip(spec)
    commands: list[str] = []
    for segment in spec.editable_segments:
        rewritten = _rewrite_pip_segment_python(segment, pip_bin)
        if "--no-deps" not in rewritten:
            rewritten += " --no-deps"
        if "--no-build-isolation" not in rewritten:
            rewritten += " --no-build-isolation"
        commands.append(rewritten)
    return commands

def _distribution_name_from_requirement(req: str) -> str:
    """Best-effort PEP 508 name token for dedupe (ignores extras/markers/versions)."""
    token = req.split(";", 1)[0].strip()
    token = token.split("[", 1)[0].strip()
    for sep in ("===", "==", ">=", "<=", "!=", "~=", ">", "<"):
        if sep in token:
            token = token.split(sep, 1)[0].strip()
            break
    return _normalize_package_name(token)

def _editable_offline_seed_specs(
    workspace: Path,
    *,
    dockerfile: Path | None = None,
    editable_segments: tuple[str, ...] | None = None,
) -> list[str]:
    """Packages required in the target env before offline ``--no-build-isolation`` editables.

    Hatchling imports ``editables`` at editable-build time even when it is absent
    from ``[build-system].requires`` (python-statemachine: requires = [\"hatchling\"] only).

    Build backends are collected from the workspace root pyproject and from every local
    path targeted by Dockerfile / verifier ``pip install -e`` segments (langchain-style
    monorepos keep hatchling under ``libs/*/pyproject.toml``, not the repo root).
    """
    pyprojects: list[Path] = [workspace / "pyproject.toml"]
    segments: list[str] = []
    if editable_segments:
        segments.extend(editable_segments)
    elif dockerfile is not None and dockerfile.is_file():
        segments.extend(
            _editable_segments_from_dockerfile(dockerfile.read_text(encoding="utf-8"))
        )
    for segment in segments:
        for target in _editable_target_paths(segment, workspace):
            pyprojects.append(target / "pyproject.toml")
    requires: list[str] = []
    seen_names: set[str] = set()
    for pyproject in pyprojects:
        for req in _read_pyproject_build_system_requires(pyproject):
            name = _distribution_name_from_requirement(req)
            if name in seen_names:
                continue
            seen_names.add(name)
            requires.append(req)
    if "editables" not in seen_names:
        requires.append("editables")
    return requires

def default_pip_editable_seed_command(
    workspace: Path,
    dockerfile: Path | None,
) -> str | None:
    """Seed default ``pip`` with build backends before offline Dockerfile editable replay.

    Image warm installs Hatchling/editables into ``.venv`` via uv, but agent Prep sync
    replays Dockerfile ``pip install -e`` against system/default pip. Without this seed,
    ``--no-build-isolation`` fails with ``ModuleNotFoundError: editables``.
    """
    if dockerfile is None or not dockerfile.is_file():
        return None
    if not workspace_sync_commands_from_dockerfile(dockerfile, offline_editable=True):
        return None
    specs = _editable_offline_seed_specs(workspace, dockerfile=dockerfile)
    if not specs:
        return None
    pkgs = " ".join(shlex.quote(s) for s in specs)
    return f"pip install --no-cache-dir {pkgs}"

def verifier_venv_build_system_commands(
    workspace: Path,
    *,
    venv_path: str | None = None,
    spec: VerifierSpec | None = None,
) -> list[str]:
    """Install build backends (+ ``editables``) into the verifier venv before editable replay."""
    segments = spec.editable_segments if spec is not None else None
    requires = _editable_offline_seed_specs(workspace, editable_segments=segments)
    if not requires:
        return []
    pip_bin = _verifier_pip(spec, venv_path=venv_path)
    pkgs = " ".join(shlex.quote(r) for r in requires)
    return [f"{shlex.quote(pip_bin)} install --no-cache-dir {pkgs}"]

def _plugin_closure_probe_python() -> str:
    return (
        "import importlib.metadata, sys\n"
        "ok, errors = [], []\n"
        "eps = importlib.metadata.entry_points()\n"
        "group = eps.select(group='pytest11') if hasattr(eps, 'select') else eps.get('pytest11', [])\n"
        "for ep in group:\n"
        "    try:\n"
        "        ep.load()\n"
        "        ok.append(ep.name)\n"
        "    except Exception as exc:\n"
        "        errors.append(f'{ep.name}: {type(exc).__name__}: {exc}')\n"
        "print('PLUGIN_OK:' + ','.join(ok))\n"
        "if errors:\n"
        "    print('PLUGIN_CONFLICTS:' + '; '.join(errors))\n"
        "    sys.exit(2)\n"
        "sys.exit(0)\n"
    )

def _parse_plugin_probe_names(stdout: str, *, prefix: str) -> tuple[str, ...]:
    """Parse ``PLUGIN_OK:a,b`` or conflict names from ``PLUGIN_CONFLICTS:name: Err; ...``."""
    for line in (stdout or "").splitlines():
        line = line.strip()
        if not line.startswith(prefix):
            continue
        payload = line[len(prefix) :].strip()
        if not payload:
            return ()
        if prefix.startswith("PLUGIN_CONFLICTS"):
            names: list[str] = []
            for part in payload.split(";"):
                part = part.strip()
                if not part:
                    continue
                names.append(part.split(":", 1)[0].strip())
            return tuple(n for n in names if n)
        return tuple(n for n in payload.split(",") if n.strip())
    return ()

def _materialize_harbor_probe_tree(tests_dir: Path | None, dest: Path) -> tuple[str, ...]:
    """Write Harbor hidden ``.py`` sources from ``test.patch`` hunks into *dest*.

    Prefer parse-added-hunks (plan Q6). *dest* must be outside ``/app`` so agent
    remounts never see the files. Returns relative paths written.
    """
    if tests_dir is None:
        return ()
    written: list[str] = []
    patch_path = tests_dir / "test.patch"
    for rel, body in added_python_sources_from_patch(patch_path).items():
        target = dest / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        text = body if body.endswith("\n") else body + "\n"
        target.write_text(text, encoding="utf-8")
        written.append(rel)
    return tuple(written)

_MISSING_MODULE_RE = re.compile(
    r"No module named ['\"]([^'\"]+)['\"]"
)
_CANNOT_IMPORT_FROM_RE = re.compile(
    r"cannot import name ['\"][^'\"]+['\"] from ['\"]([^'\"]+)['\"]"
)

def _missing_module_from_import_error(err: str) -> str | None:
    """Best-effort module path extracted from a pytest collect ImportError."""
    match = _MISSING_MODULE_RE.search(err)
    if match:
        return match.group(1)
    match = _CANNOT_IMPORT_FROM_RE.search(err)
    if match:
        return match.group(1)
    
    match = re.search(
        r"^\s*from\s+([A-Za-z_][\w.]*)\s+import\b",
        err,
        re.MULTILINE,
    )
    if match:
        return match.group(1)
    
    match = re.search(r"^\s*from\s+([A-Za-z_][\w.]*)\s*$", err, re.MULTILINE)
    if match:
        return match.group(1)
    match = re.search(r"^\s*import\s+([A-Za-z_][\w.]*)\b", err, re.MULTILINE)
    if match:
        return match.group(1)
    return None

def collect_import_error_is_editable_feature_gap(
    err: str,
    provided_roots: set[str],
) -> bool:
    """True when collect ImportError is a missing workspace submodule (pre-solution).

    Top-level missing packages (``No module named 'pwnlib'``) remain prep failures
    when detected explicitly. Missing feature submodules and truncated
    ``from <editable_root>...`` traces soft-succeed after a prior top-level import
    probe has already confirmed the editable root is importable.

    Explicit ``No module named '<third_party>'`` always fails closed, even when the
    traceback also shows ``from <editable_root>`` frames (e.g. pwntools → socks).
    """
    if not provided_roots:
        return False
    roots = {r.replace("-", "_").lower() for r in provided_roots} | {
        r.lower() for r in provided_roots
    }
    
    for match in _MISSING_MODULE_RE.finditer(err):
        missing_mod = match.group(1)
        missing_root = missing_mod.split(".", 1)[0].replace("-", "_").lower()
        if missing_root not in roots:
            return False
        
        if "." not in missing_mod:
            return False
    missing = _missing_module_from_import_error(err)
    if missing is not None:
        parts = [p for p in missing.split(".") if p]
        if parts:
            root = parts[0].replace("-", "_").lower()
            if root in roots and len(parts) > 1:
                return True
    
    
    for root in roots:
        if re.search(rf"(?m)^\s*from\s+{re.escape(root)}\.", err):
            return True
        if re.search(rf"(?m)^\s*from\s+{re.escape(root)}\s+import\b", err):
            return True
        if re.search(rf"(?m)^\s*from\s+{re.escape(root)}\s*$", err):
            return True
    return False

def _probe_editable_roots_importable(
    python_bin: str,
    provided_roots: set[str],
    *,
    workspace: Path,
    harbor_imports: tuple[str, ...] = (),
    env: dict[str, str] | None = None,
) -> str | None:
    """Return an error detail when Harbor-needed editable roots cannot be imported.

    Only probes import roots that Harbor tests actually import and that editable
    discovery claims to provide (e.g. ``pwnlib``, not the ``pwntools`` dist name).

    Import spelling comes from Harbor AST (``IPython``), not from the distribution
    name (``ipython``): ``import_roots_provided_by_project`` may list both, and
    case folding would otherwise probe the wrong module.
    """
    harbor_original: dict[str, str] = {}
    for raw in harbor_imports:
        key = raw.replace("-", "_").lower()
        
        prev = harbor_original.get(key)
        if prev is None or (prev.lower() == prev and raw.lower() != raw):
            harbor_original[key] = raw
    harbor = set(harbor_original)
    provided_norm = {
        r.replace("-", "_").lower() for r in provided_roots if "-" not in r
    }
    candidates = sorted(
        {
            harbor_original[h]
            for h in harbor
            if h in provided_norm and harbor_original[h].isidentifier()
        }
    )
    if not candidates:
        return None
    script = (
        "import importlib, sys\n"
        f"roots = {candidates!r}\n"
        "errors = []\n"
        "for r in roots:\n"
        "    try:\n"
        "        importlib.import_module(r)\n"
        "    except Exception as exc:\n"
        "        errors.append(f'{r}: {type(exc).__name__}: {exc}')\n"
        "if errors:\n"
        "    print('; '.join(errors))\n"
        "    sys.exit(1)\n"
        "sys.exit(0)\n"
    )
    proc = subprocess.run(
        [python_bin, "-c", script],
        cwd=str(workspace),
        text=True,
        capture_output=True,
        check=False,
        env=env,
    )
    if proc.returncode == 0:
        return None
    missing = (proc.stdout or proc.stderr or "").strip() or "unknown"
    return f"editable import roots not importable in verifier venv: {missing}"

def probe_verifier_env(
    spec: VerifierSpec,
    *,
    workspace: Path,
    task_id: str = "unknown",
    dry_run: bool = False,
    run_collect: bool = True,
    tests_dir: Path | None = None,
) -> tuple[bool, str | None, PluginPolicy | None]:
    """Probe verifier venv collect/import + pytest plugin closure.

    Returns ``(ok, error_message, plugin_policy)``. On plugin conflicts with declared
    pins, returns a grade-subprocess-only ``PluginPolicy`` that disables autoload.
    Does **not** run full Harbor ``test.sh`` (avoids reward / patch side effects).

    When ``tests_dir`` is set, materializes ``test.patch`` Python hunks into a temp
    tree outside ``/app`` before collect-only so Adaptix-class ImportErrors are not
    masked by pre-apply missing paths.
    """
    python_bin = f"{spec.venv_path}/bin/python"
    if dry_run:
        return True, None, None
    if not Path(python_bin).is_file():
        return (
            False,
            format_prep_error(
                task_id,
                phase="verifier prep",
                detail=(
                    f"verifier venv missing at {spec.venv_path} "
                    "(no system-Python fallback)"
                ),
            ),
            None,
        )

    if spec.unmapped_imports and not run_collect:
        
        
        return (
            False,
            format_prep_error(
                task_id,
                phase="verifier prep",
                detail=(
                    "unmapped Harbor imports (no DeclaredDeps pin): "
                    + ", ".join(spec.unmapped_imports)
                ),
            ),
            None,
        )

    policy: PluginPolicy | None = None
    plugin_cmd = [python_bin, "-c", _plugin_closure_probe_python()]
    plugin_proc = subprocess.run(
        plugin_cmd,
        cwd=str(workspace),
        text=True,
        capture_output=True,
        check=False,
    )
    if plugin_proc.returncode == 2:
        detail = (plugin_proc.stdout or plugin_proc.stderr or "").strip()
        
        
        allow = _parse_plugin_probe_names(plugin_proc.stdout or "", prefix="PLUGIN_OK:")
        policy = PluginPolicy(disable_autoload=True, allowlist=allow)
        
    elif plugin_proc.returncode != 0:
        detail = (plugin_proc.stderr or plugin_proc.stdout or "plugin probe failed").strip()
        return (
            False,
            format_prep_error(task_id, phase="verifier prep", detail=detail),
            None,
        )

    if run_collect:
        provided = editable_provided_import_roots(
            workspace,
            spec.editable_segments,
            dockerfile=None,
        )
        
        if spec.grade_pythonpath:
            for entry in spec.grade_pythonpath:
                provided |= import_roots_provided_by_project(Path(entry))
                path = Path(entry)
                if path.name == "src" or (path / "src").is_dir():
                    provided |= _filesystem_package_roots(
                        path if path.name == "src" else path / "src"
                    )
        grade_env = verifier_grade_subprocess_env(spec, plugin_policy=policy)
        editable_err = _probe_editable_roots_importable(
            python_bin,
            provided,
            workspace=workspace,
            harbor_imports=spec.harbor_imports,
            env=grade_env,
        )
        if editable_err:
            return (
                False,
                format_prep_error(
                    task_id, phase="verifier prep", detail=editable_err
                ),
                policy,
            )
        
        
        if not test_sh_invokes_pytest(spec.test_sh_body):
            return True, None, policy
        collect_cmd = collect_only_pytest_command(python_bin, spec.test_sh_body)
        env = grade_env
        
        with tempfile.TemporaryDirectory(prefix="malvin-verifier-probe-") as tmp:
            probe_root = Path(tmp)
            written = _materialize_harbor_probe_tree(tests_dir, probe_root)
            collect_cwd = probe_root if written else workspace
            collect_proc = subprocess.run(
                ["bash", "-lc", collect_cmd],
                cwd=str(collect_cwd),
                text=True,
                capture_output=True,
                check=False,
                env=env,
            )
            if collect_proc.returncode != 0:
                err = (collect_proc.stderr or collect_proc.stdout or "").strip()
                if "ModuleNotFoundError" in err or "ImportError" in err:
                    if collect_import_error_is_editable_feature_gap(err, provided):
                        
                        return True, None, policy
                    missing = _missing_module_from_import_error(err)
                    if missing is not None:
                        missing_root = missing.split(".", 1)[0]
                        unmapped_norm = {
                            u.replace("-", "_").lower() for u in spec.unmapped_imports
                        } | {u.lower() for u in spec.unmapped_imports}
                        if (
                            missing_root.replace("-", "_").lower() in unmapped_norm
                            or missing_root.lower() in unmapped_norm
                        ):
                            return (
                                False,
                                format_prep_error(
                                    task_id,
                                    phase="verifier prep",
                                    detail=(
                                        "unmapped Harbor imports (no DeclaredDeps pin): "
                                        + ", ".join(spec.unmapped_imports)
                                    ),
                                ),
                                policy,
                            )
                    return (
                        False,
                        format_prep_error(
                            task_id, phase="verifier prep", detail=err[:800]
                        ),
                        policy,
                    )
                
                
                
                err_l = err.lower()
                missing_path = (
                    "file or directory not found" in err_l
                    or "no such file or directory" in err_l
                )
                if missing_path and not written:
                    return True, None, policy
                if missing_path and written:
                    return (
                        False,
                        format_prep_error(
                            task_id,
                            phase="verifier prep",
                            detail=(
                                "collect-only missing path after materializing "
                                f"test.patch hunks ({', '.join(written)}): {err[:600]}"
                            ),
                        ),
                        policy,
                    )
                
                
                return (
                    False,
                    format_prep_error(
                        task_id, phase="verifier prep", detail=err[:800]
                    ),
                    policy,
                )
    return True, None, policy

def verifier_grade_subprocess_env(
    spec: VerifierSpec,
    *,
    base_env: dict[str, str] | None = None,
    plugin_policy: PluginPolicy | None = None,
) -> dict[str, str]:
    """Subprocess env for Harbor ``test.sh`` inside ``/opt/malvin-verifier`` only."""
    env = dict(base_env) if base_env is not None else os.environ.copy()
    env["VIRTUAL_ENV"] = spec.venv_path
    env["PATH"] = f"{spec.venv_path}/bin:" + env.get("PATH", "")
    if spec.grade_pythonpath:
        
        
        existing = env.get("PYTHONPATH", "")
        merged = list(spec.grade_pythonpath)
        if existing:
            merged.extend(p for p in existing.split(":") if p)
        
        seen: set[str] = set()
        ordered: list[str] = []
        for part in merged:
            if part not in seen:
                seen.add(part)
                ordered.append(part)
        env["PYTHONPATH"] = ":".join(ordered)
    policy = plugin_policy if plugin_policy is not None else spec.plugin_policy
    if policy is not None:
        policy_env = policy.as_env()
        added_opts = policy_env.pop("PYTEST_ADDOPTS", None)
        env.update(policy_env)
        if added_opts:
            env["PYTEST_ADDOPTS"] = _merge_pytest_addopts(
                env.get("PYTEST_ADDOPTS"), added_opts
            )
    return env

@dataclass
class VerifierPrepResult:
    ok: bool
    error: str | None = None
    spec: VerifierSpec | None = None
    plugin_policy: PluginPolicy | None = None
    public_venv_present: bool = False

    def as_dict(self) -> dict[str, Any]:
        """Agent-safe status only (no rich grade-only VerifierSpec fields)."""
        return {
            "ok": self.ok,
            "error": self.error,
            "public_venv_present": self.public_venv_present,
            "venv_path": VERIFIER_VENV_PATH,
        }

def prepare_verifier_grade(
    workspace: Path,
    *,
    tests_dir: Path | None,
    dockerfile: Path | None = None,
    task_id: str = "unknown",
    dry_run: bool = False,
) -> VerifierPrepResult:
    """Grade-only prep: apply ``test.patch`` closure + probe. Not for pre-agent path."""
    if tests_dir is None or not tests_dir.exists():
        return VerifierPrepResult(
            ok=False,
            error=format_prep_error(
                task_id,
                phase="verifier prep",
                detail="tests_dir missing for grade prep",
            ),
        )
    spec = discover_verifier_spec(workspace, tests_dir=tests_dir, dockerfile=dockerfile)
    public_present = Path(f"{spec.venv_path}/bin/python").is_file()
    if dry_run:
        return VerifierPrepResult(
            ok=True, spec=spec, public_venv_present=public_present
        )
    
    
    
    if not public_present:
        for command in verifier_venv_materialize_public_commands(
            spec, workspace=workspace
        ):
            code, detail, _timed_out = _run_shell(command, workspace)
            if code != 0:
                return VerifierPrepResult(
                    ok=False,
                    error=format_prep_error(
                        task_id,
                        phase="verifier prep",
                        detail=detail or f"public venv materialize failed: {command}",
                    ),
                    spec=spec,
                    public_venv_present=False,
                )
        public_present = Path(f"{spec.venv_path}/bin/python").is_file()
        if not public_present:
            return VerifierPrepResult(
                ok=False,
                error=format_prep_error(
                    task_id,
                    phase="verifier prep",
                    detail=f"verifier venv missing after materialize at {spec.venv_path}",
                ),
                spec=spec,
                public_venv_present=False,
            )
    
    if spec.editable_segments:
        for command in verifier_venv_build_system_commands(workspace, spec=spec):
            code, detail, _timed_out = _run_shell(command, workspace)
            if code != 0:
                return VerifierPrepResult(
                    ok=False,
                    error=format_prep_error(
                        task_id,
                        phase="verifier prep",
                        detail=detail or f"build-system install failed: {command}",
                    ),
                    spec=spec,
                    public_venv_present=public_present,
                )
    
    for command in verifier_venv_replay_editable_commands(spec):
        code, detail, _timed_out = _run_shell(command, workspace)
        if code != 0:
            return VerifierPrepResult(
                ok=False,
                error=format_prep_error(
                    task_id,
                    phase="verifier prep",
                    detail=detail or f"editable replay failed: {command}",
                ),
                spec=spec,
                public_venv_present=public_present,
            )
    for command in verifier_venv_apply_grade_closure_commands(spec):
        code, detail, _timed_out = _run_shell(command, workspace)
        if code != 0:
            return VerifierPrepResult(
                ok=False,
                error=format_prep_error(
                    task_id,
                    phase="verifier prep",
                    detail=detail or f"closure install failed: {command}",
                ),
                spec=spec,
                public_venv_present=public_present,
            )
    ok, err, policy = probe_verifier_env(
        spec,
        workspace=workspace,
        tests_dir=tests_dir,
        task_id=task_id,
        dry_run=False,
    )
    if not ok:
        return VerifierPrepResult(
            ok=False,
            error=err,
            spec=spec,
            plugin_policy=policy,
            public_venv_present=public_present,
        )
    final_spec = VerifierSpec(
        declared=spec.declared,
        public_install_specs=spec.public_install_specs,
        editable_segments=spec.editable_segments,
        harbor_imports=spec.harbor_imports,
        grade_closure_install_specs=spec.grade_closure_install_specs,
        unmapped_imports=spec.unmapped_imports,
        test_sh_body=spec.test_sh_body,
        plugin_policy=policy,
        venv_path=spec.venv_path,
        grade_pythonpath=spec.grade_pythonpath,
    )
    return VerifierPrepResult(
        ok=True,
        spec=final_spec,
        plugin_policy=policy,
        public_venv_present=public_present,
    )

_PACKAGE_PROBE_IMPORT_ALIASES: dict[str, str] = {
    "beautifulsoup4": "bs4",
    "opencv-python": "cv2",
    "phonenumberslite": "phonenumbers",
    "pillow": "PIL",
    "pyelftools": "elftools",
    "pyserial": "serial",
    "pysocks": "socks",
    "python-dateutil": "dateutil",
    "pyyaml": "yaml",
    "scikit-image": "skimage",
    "scikit-learn": "sklearn",
}

def _probe_import_name(package_name: str) -> str:
    return _PACKAGE_PROBE_IMPORT_ALIASES.get(
        package_name, package_name.replace("-", "_")
    )

def _probe_checks_for_declared(declared: DeclaredDeps) -> list[tuple[str, str, str]]:
    """Return ``(import_name, expected_spec, display_name)`` probe tuples."""
    checks: list[tuple[str, str, str]] = []
    seen: set[str] = set()
    for name in sorted(declared.package_names()):
        if name in seen:
            continue
        spec = declared.effective_spec(name)
        if spec is None:
            continue
        import_name = _probe_import_name(name)
        checks.append((import_name, spec, name))
        seen.add(name)
    return checks

def _mandatory_probe_python(declared: DeclaredDeps) -> str:
    """Python source run by image-build and runtime verification probes.

    Prefer ``importlib.metadata.version(distribution)`` so packages whose import
    root differs from the distribution name (``pyelftools`` → ``elftools``) still
    pass when the pin is installed. Fall back to import-based discovery only when
    metadata is absent.
    """
    checks = _probe_checks_for_declared(declared)
    check_lines = [f"    ({import_name!r}, {spec!r}, {display!r})," for import_name, spec, display in checks]
    checks_literal = "\n".join(check_lines) if check_lines else ""
    return (
        "import importlib, importlib.util, sys\n"
        "errors = []\n"
        "checks = [\n"
        f"{checks_literal}\n"
        "]\n"
        "for import_name, spec_str, display_name in checks:\n"
        "    version = None\n"
        "    try:\n"
        "        from importlib.metadata import version as pkg_version\n"
        "        version = pkg_version(display_name)\n"
        "    except Exception:\n"
        "        version = None\n"
        "    if version is None:\n"
        "        try:\n"
        "            spec = importlib.util.find_spec(import_name)\n"
        "        except (ImportError, ModuleNotFoundError, ValueError) as exc:\n"
        "            errors.append(f'{display_name}: import check failed ({exc})')\n"
        "            continue\n"
        "        if spec is None:\n"
        "            errors.append(f'{display_name}: not installed (expected {spec_str})')\n"
        "            continue\n"
        "        mod = importlib.import_module(import_name)\n"
        "        version = getattr(mod, '__version__', None)\n"
        "    if version is None:\n"
        "        errors.append(f'{display_name}: installed but version unknown (expected {spec_str})')\n"
        "        continue\n"
        "    try:\n"
        "        from packaging.specifiers import SpecifierSet\n"
        "        from packaging.version import Version\n"
        "        _ops = ('==', '>=', '<=', '!=', '~=', '>', '<')\n"
        "        ver_spec = spec_str\n"
        "        if ver_spec.startswith('['):\n"
        "            end = ver_spec.find(']')\n"
        "            if end != -1:\n"
        "                ver_spec = ver_spec[end + 1 :].lstrip()\n"
        "        if not ver_spec:\n"
        "            continue\n"
        "        normalized = (\n"
        "            ver_spec if any(ver_spec.startswith(op) for op in _ops)\n"
        "            else f'=={ver_spec}'\n"
        "        )\n"
        "        if Version(str(version)) not in SpecifierSet(normalized):\n"
        "            errors.append(f'{display_name} {version} violates {spec_str}')\n"
        "    except Exception as exc:\n"
        "        if display_name == 'pydantic' and spec_str.startswith('>=2'):\n"
        "            if str(version).startswith('1.'):\n"
        "                errors.append(f'pydantic {version} violates {spec_str}')\n"
        "            continue\n"
        "        errors.append(f'{display_name}: version check failed ({version!r} vs {spec_str}: {exc})')\n"
        "if 'httpx' in "
        f"{sorted(declared.package_names())!r} and importlib.util.find_spec('httpx'):\n"
        "    import httpx\n"
        "    if httpx.__name__ != 'httpx':\n"
        "        errors.append(f'httpx namespace drift: {httpx.__name__}')\n"
        "if errors:\n"
        "    print('; '.join(errors), file=sys.stderr)\n"
        "    sys.exit(1)\n"
    )

def _mandatory_probe_command(declared: DeclaredDeps) -> str:
    body = _mandatory_probe_python(declared)
    return f"python3 -c {shlex.quote(body)}"

MANDATORY_PROBE_SCRIPT_PATH = "/tmp/malvin_mandatory_probe.py"

def mandatory_probe_script_write_command(declared: DeclaredDeps) -> str:
    """Write mandatory probe source to a fixed path (Modal/Docker image-build safe)."""
    encoded = base64.b64encode(_mandatory_probe_python(declared).encode()).decode()
    return f"echo {shlex.quote(encoded)} | base64 -d > {MANDATORY_PROBE_SCRIPT_PATH}"

def mandatory_probe_script_run_command() -> str:
    return f"python3 {MANDATORY_PROBE_SCRIPT_PATH}"

def mandatory_probe_script_commands(declared: DeclaredDeps) -> list[str]:
    """Return write-then-run shell steps for image-build mandatory probes."""
    return [
        mandatory_probe_script_write_command(declared),
        mandatory_probe_script_run_command(),
    ]

_HTTPX_DRIFT_FIX = "'starlette==1.0.0' 'click==8.3.1' 'typer==0.25.1'"
_HTTPX_DRIFT_PROBE_SCRIPT_PATH = "/tmp/malvin_httpx_drift_probe.py"

def _httpx_drift_probe_python() -> str:
    return (
        "import importlib.util, sys\n"
        "spec = importlib.util.find_spec('httpx')\n"
        "if spec is None:\n"
        "    raise SystemExit(0)\n"
        "import httpx\n"
        "raise SystemExit(1 if httpx.__name__ != 'httpx' else 0)\n"
    )

def _httpx_drift_probe_script_write_command() -> str:
    encoded = base64.b64encode(_httpx_drift_probe_python().encode()).decode()
    return f"echo {shlex.quote(encoded)} | base64 -d > {_HTTPX_DRIFT_PROBE_SCRIPT_PATH}"

def _httpx_drift_probe_script_run_command() -> str:
    return f"python3 {_HTTPX_DRIFT_PROBE_SCRIPT_PATH}"

def _httpx_drift_fix_command() -> str:
    """Run httpx namespace probe; on drift, reinstall starlette/click/typer pins."""
    return (
        f"{_httpx_drift_probe_script_run_command()} || "
        f"pip install --no-cache-dir --force-reinstall {_HTTPX_DRIFT_FIX}"
    )

_PROBE_VIOLATION_RE = re.compile(
    r"(?P<package>[a-zA-Z0-9][\w.-]*)\s+(?P<observed>[\d.]+)\s+violates\s+(?P<expected>.+)"
)

def _parse_probe_stderr_fragments(detail: str) -> list[tuple[str | None, str | None, str | None]]:
    """Return one ``(package, observed, expected)`` tuple per probe stderr fragment."""
    parsed: list[tuple[str | None, str | None, str | None]] = []
    for fragment in detail.replace(";", "\n").splitlines():
        fragment = fragment.strip()
        if not fragment:
            continue
        match = _PROBE_VIOLATION_RE.search(fragment)
        if match:
            parsed.append(
                (match.group("package"), match.group("observed"), match.group("expected"))
            )
            continue
        if "namespace drift" in fragment:
            parsed.append(("httpx", fragment, "httpx"))
            continue
        pkg_match = re.match(r"(\S+):", fragment)
        if pkg_match:
            pkg = pkg_match.group(1)
            if "not installed" in fragment:
                parsed.append((pkg, "not installed", fragment))
                continue
            if "import check failed" in fragment:
                parsed.append((pkg, "import failed", fragment))
                continue
            if "version unknown" in fragment:
                parsed.append((pkg, "unknown", fragment))
                continue
            if "version check failed" in fragment:
                parsed.append((pkg, "check failed", fragment))
    return parsed

def _parse_probe_stderr(detail: str) -> tuple[str | None, str | None, str | None]:
    """Return the first ``(package, observed, expected)`` parsed from mandatory-probe stderr."""
    fragments = _parse_probe_stderr_fragments(detail)
    if fragments:
        return fragments[0]
    return None, None, None

def _reconcile_declared_deps_commands(
    declared: DeclaredDeps,
    *,
    registry_pull: bool = False,
) -> list[str]:
    """Force-reinstall declared pins and pyproject/lockfile packages at image build."""
    cmds: list[str] = []
    if declared.bulk_pins and not registry_pull:
        pkg_args = [f"'{name}=={ver}'" for name, ver in sorted(declared.bulk_pins.items())]
        cmds.append("pip install --no-cache-dir --force-reinstall " + " ".join(pkg_args))
    reconcile_names = set(declared.constraints) | set(declared.lockfile_pins)
    if registry_pull:
        
        
        
        reconcile_names |= set(declared.bulk_pins)
    covered = {name.lower() for name in declared.bulk_pins} if not registry_pull else set()
    extras: list[str] = []
    for name in sorted(reconcile_names):
        if name in covered:
            continue
        pip_spec = declared.pip_install_spec(name)
        if pip_spec:
            extras.append(f"'{pip_spec}'")
    if extras:
        cmds.append("pip install --no-cache-dir --force-reinstall " + " ".join(extras))
    return cmds

def run_post_prep_probes(
    workspace: Path,
    declared: DeclaredDeps,
    *,
    task_id: str,
    phase: str = "runtime probe",
) -> list[str]:
    """Run verification probes; return human-readable errors (empty when ok)."""
    command = _mandatory_probe_command(declared)
    code, detail, _timed_out = _run_shell(command, workspace)
    if code == 0:
        return []
    observed_text = detail.strip() or "probe failed"
    fragments = _parse_probe_stderr_fragments(observed_text)
    if not fragments:
        return [
            format_prep_error(
                task_id,
                phase=phase,
                detail=observed_text,
                hint="check registry cache bust / pyproject.toml reconcile",
            )
        ]
    return [
        format_prep_error(
            task_id,
            phase=phase,
            package=package,
            observed=observed,
            expected=expected,
            detail=None if package is not None else observed_text,
            hint="check registry cache bust / pyproject.toml reconcile",
        )
        for package, observed, expected in fragments
    ]

def pydantic_pins_for_cache_bust(
    dockerfile: Path | None,
    workspace: Path | None = None,
) -> tuple[str | None, str | None]:
    """Return task pydantic pins when present in declared dependencies."""
    if dockerfile is None or not dockerfile.is_file() or workspace is None:
        return None, None
    workspace = workspace.resolve()
    declared = declared_python_dependencies(workspace, dockerfile)
    pydantic_spec = declared.effective_spec("pydantic")
    if pydantic_spec is not None and pydantic_spec.startswith("=="):
        return pydantic_spec[2:], declared.lockfile_pins.get("pydantic-core")
    for req_rel in requirements_paths_from_dockerfile(dockerfile):
        pydantic_ver, core_ver = read_pydantic_pins_from_requirements(workspace / req_rel)
        if pydantic_ver is not None:
            return pydantic_ver, core_ver
    return None, None

def _pydantic_v1_eviction_command() -> str:
    """Evict stale pydantic v1 when the image has pydantic but no task declaration."""
    return (
        "python3 -c \""
        "import importlib.util, sys; "
        "spec=importlib.util.find_spec('pydantic'); "
        "ver = None; "
        "exec('try:\\n from importlib.metadata import version as pkg_version\\n ver=pkg_version(\\\"pydantic\\\")\\nexcept Exception: pass') if spec else None; "
        "import pydantic; "
        "ver = ver or getattr(pydantic, '__version__', ''); "
        "sys.exit(1 if str(ver).startswith('1.') else 0)"
        "\" 2>/dev/null || "
        "pip install --no-cache-dir 'pydantic>=2,<3'"
    )

_LINT_GATE_TOOLS = ("ruff", "mypy", "pre-commit")
_TOX_RUNNER_TOOLS = ("tox", "invoke")
_TOX_VARS_RE = re.compile(r"\{\[vars\]([^\}]+)\}")

def _tox_ini_section_text(tox_text: str, header: str) -> str | None:
    """Return the body of a tox.ini section named *header* (e.g. ``[vars]``)."""
    lines = tox_text.splitlines()
    start: int | None = None
    for index, line in enumerate(lines):
        if line.strip() == header:
            start = index + 1
            break
    if start is None:
        return None
    section_lines: list[str] = []
    for line in lines[start:]:
        stripped = line.strip()
        if stripped.startswith("[") and stripped.endswith("]"):
            break
        section_lines.append(line)
    return "\n".join(section_lines) if section_lines else ""

def tox_lint_section_text(tox_text: str) -> str | None:
    """Return the body of ``[testenv:lint]`` from a ``tox.ini`` string."""
    return _tox_ini_section_text(tox_text, "[testenv:lint]")

def tox_ini_vars(tox_text: str) -> dict[str, str]:
    """Parse ``[vars]`` substitutions from a tox.ini string."""
    section = _tox_ini_section_text(tox_text, "[vars]")
    if section is None:
        return {}
    vars_map: dict[str, str] = {}
    for raw in section.splitlines():
        stripped = raw.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            continue
        key, value = stripped.split("=", 1)
        vars_map[key.strip()] = value.strip()
    return vars_map

def expand_tox_vars(command: str, vars_map: dict[str, str]) -> str:
    """Replace ``{[vars]name}`` placeholders using *vars_map*."""

    def _replace(match: re.Match[str]) -> str:
        return vars_map.get(match.group(1).strip(), match.group(0))

    return _TOX_VARS_RE.sub(_replace, command)

def workspace_has_justfile(workspace: Path) -> bool:
    return (workspace / "justfile").is_file() or (workspace / "Justfile").is_file()

def tox_lint_check_commands(workspace: Path) -> list[str]:
    """Return ``commands`` from ``[testenv:lint]`` when present (tox vars expanded)."""
    tox_path = workspace / "tox.ini"
    if not tox_path.is_file():
        return []
    tox_text = tox_path.read_text(encoding="utf-8")
    section = tox_lint_section_text(tox_text)
    if section is None:
        return []
    vars_map = tox_ini_vars(tox_text)
    commands: list[str] = []
    in_commands = False
    for raw in section.splitlines():
        line = raw.rstrip()
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        if re.match(r"^commands\s*=", stripped, re.I):
            in_commands = True
            continue
        if in_commands:
            if line and not line[0].isspace():
                in_commands = False
                continue
            if stripped:
                commands.append(expand_tox_vars(stripped, vars_map))
    return commands

def lint_gate_tool_pins(workspace: Path) -> dict[str, str]:
    """Return pinned lint-gate tool versions declared by the workspace."""
    candidates = (
        workspace / "requirements" / "lint.txt",
        workspace / "requirements" / "dev.txt",
        workspace / "requirements" / "raw" / "lint.txt",
    )
    for path in candidates:
        pins = _pins_from_requirements_file(path)
        tools = {name: pins[name] for name in _LINT_GATE_TOOLS if name in pins}
        if tools:
            return tools
    return {}

def tox_runner_tool_pins(workspace: Path) -> dict[str, str]:
    """Return pinned tox/invoke versions from workspace requirements, if any."""
    candidates = (
        workspace / "requirements" / "runner.txt",
        workspace / "requirements" / "dev.txt",
        workspace / "requirements" / "raw" / "runner.txt",
    )
    for path in candidates:
        pins = _pins_from_requirements_file(path)
        tools = {name: pins[name] for name in _TOX_RUNNER_TOOLS if name in pins}
        if tools:
            return tools
    return {}

def just_install_command(workspace: Path) -> str | None:
    """Install the ``just`` binary when the workspace has a justfile.

    Prefers a prebuilt GitHub release tarball over ``cargo install`` so image
    builds do not recompile the Rust crate on every warm layer.
    """
    if not workspace_has_justfile(workspace):
        return None
    
    just_version = "1.40.0"
    archive = f"just-{just_version}-x86_64-unknown-linux-musl.tar.gz"
    url = (
        "https://github.com/casey/just/releases/download/"
        f"{just_version}/{archive}"
    )
    return (
        "command -v just >/dev/null 2>&1 || "
        f"(curl -fsSL {shlex.quote(url)} -o /tmp/just.tgz && "
        "tar -xzf /tmp/just.tgz -C /usr/local/bin just && "
        "chmod +x /usr/local/bin/just && rm -f /tmp/just.tgz)"
    )

def tox_runner_install_command(workspace: Path) -> str | None:
    """Install tox/invoke when the workspace uses tox or just recipes that call them.

    Always installs (no soft ``command -v`` skip). Tox is clamped to
    :data:`tox_gates.MIN_TOX_FOR_SKIP_ENV_INSTALL` so offline agent checks that
    inject ``--skip-env-install`` resolve a capable runner under TOOLCHAIN_PATH.
    """
    from tox_gates import clamp_tox_version, image_build_pip_install_command

    needs_tox = (workspace / "tox.ini").is_file() or workspace_has_justfile(workspace)
    if not needs_tox:
        return None
    pins = dict(tox_runner_tool_pins(workspace))
    if "tox" in pins:
        pins["tox"] = clamp_tox_version(pins["tox"])
    if pins:
        args = " ".join(
            shlex.quote(f"{name}=={version}") for name, version in sorted(pins.items())
        )
    else:
        args = shlex.quote(f"tox=={clamp_tox_version(None)}")
    return image_build_pip_install_command(args)

def workspace_lint_tool_install_command(workspace: Path) -> str | None:
    """Install tox lint-gate CLIs at image build for offline malvin quality gates."""
    if (workspace / "uv.lock").is_file():
        return None
    if not tox_lint_check_commands(workspace):
        return None
    pins = lint_gate_tool_pins(workspace)
    if not pins:
        return None
    args = " ".join(shlex.quote(f"{name}=={version}") for name, version in sorted(pins.items()))
    return f"python3 -m pip install --no-cache-dir {args}"

PRECOMMIT_WARM_SCRIPT_PATH = "/tmp/malvin_precommit_warm.sh"

def _precommit_warm_script_body(workspace: Path) -> str:
    """Bash script to bootstrap ``pre-commit`` and warm hook environments.

    ``install-hooks`` is best-effort: configs often pin ``default_language_version``
    to interpreters absent from Harbor images (e.g. python3.8). Failing closed on
    that aborts image build even when ``--test`` only needs ecosystem smoke.
    """
    pin = _precommit_pin_from_workspace(workspace)
    pip_spec = f"pre-commit=={pin}" if pin else "pre-commit"
    venv_bin = f"{_UV_PROJECT_VENV}/bin/pre-commit"
    soft = ' || echo "malvin: pre-commit install-hooks failed (continuing)" >&2'
    return (
        "#!/usr/bin/env bash\n"
        "set -euo pipefail\n"
        "if command -v pre-commit >/dev/null 2>&1; then\n"
        f"  pre-commit install-hooks{soft}\n"
        f"elif test -x {shlex.quote(venv_bin)}; then\n"
        f"  PATH={shlex.quote(_UV_PROJECT_VENV + '/bin')}:\"$PATH\" "
        f"pre-commit install-hooks{soft}\n"
        "else\n"
        f"  python3 -m pip install --no-cache-dir {shlex.quote(pip_spec)}\n"
        f"  pre-commit install-hooks{soft}\n"
        "fi\n"
    )

def precommit_warm_script_write_command(workspace: Path) -> str | None:
    """Write pre-commit warm script to a fixed path (Modal/Docker image-build safe)."""
    if not (workspace / ".pre-commit-config.yaml").is_file():
        return None
    encoded = base64.b64encode(_precommit_warm_script_body(workspace).encode()).decode()
    return f"echo {shlex.quote(encoded)} | base64 -d > {PRECOMMIT_WARM_SCRIPT_PATH}"

def precommit_warm_script_run_command() -> str:
    return f"bash {PRECOMMIT_WARM_SCRIPT_PATH}"

def precommit_warm_script_commands(workspace: Path) -> list[str]:
    """Return write-then-run shell steps for image-build pre-commit hook warming."""
    write = precommit_warm_script_write_command(workspace)
    if write is None:
        return []
    return [write, precommit_warm_script_run_command()]

def precommit_install_hooks_command(workspace: Path) -> str | None:
    """Backward-compatible alias returning only the run step."""
    commands = precommit_warm_script_commands(workspace)
    return commands[-1] if commands else None

_UV_BOOTSTRAP_SHELL = (
    "command -v uv >/dev/null 2>&1 || python3 -m pip install --no-cache-dir uv"
)
_UV_PROJECT_VENV = ".venv"

def _pyproject_has_uv_dev_group(workspace: Path) -> bool:
    pyproject = workspace / "pyproject.toml"
    if not pyproject.is_file():
        return False
    raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    groups = raw.get("dependency-groups")
    return isinstance(groups, dict) and "dev" in groups

def _read_pyproject_build_system_requires(pyproject: Path) -> list[str]:
    """Return ``[build-system].requires`` entries from ``pyproject.toml``."""
    if not pyproject.is_file():
        return []
    raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    build_system = raw.get("build-system")
    if not isinstance(build_system, dict):
        return []
    requires = build_system.get("requires")
    if not isinstance(requires, list):
        return []
    return [req for req in requires if isinstance(req, str) and req.strip()]

def _workspace_has_ruff_signal(workspace: Path) -> bool:
    """True when ruff is likely used by malvin quality gates for this workspace."""
    pyproject = workspace / "pyproject.toml"
    if pyproject.is_file():
        raw = tomllib.loads(pyproject.read_text(encoding="utf-8"))
        groups = raw.get("dependency-groups")
        if isinstance(groups, dict):
            dev = groups.get("dev")
            if isinstance(dev, list) and any(
                isinstance(dep, str) and dep.split("[", 1)[0].strip() == "ruff" for dep in dev
            ):
                return True
    lockfile = workspace / "uv.lock"
    if lockfile.is_file():
        return 'name = "ruff"' in lockfile.read_text(encoding="utf-8")
    return False

_UV_OFFLINE_SMOKE_PREFIX = "UV_OFFLINE=1 UV_NO_SYNC=1"

def uv_sync_dev_command(workspace: Path) -> str | None:
    """Return shell steps to warm a uv venv when the workspace uses uv.

    Callers must run the returned command in ``/app`` during image build with network
    access so later offline ``uv sync`` / ``uv run`` gates can succeed.
    """
    if not (workspace / "uv.lock").is_file():
        return None
    sync = "uv sync --group dev" if _pyproject_has_uv_dev_group(workspace) else "uv sync"
    return f"{_UV_BOOTSTRAP_SHELL} && {sync}"

def uv_pip_build_system_command(workspace: Path) -> str | None:
    """Return shell steps to cache ``[build-system].requires`` for offline ``uv run``."""
    if not (workspace / "uv.lock").is_file():
        return None
    requires = _read_pyproject_build_system_requires(workspace / "pyproject.toml")
    if not requires:
        return None
    quoted = " ".join(shlex.quote(req) for req in requires)
    return (
        f"{_UV_BOOTSTRAP_SHELL} && uv pip install --python {_UV_PROJECT_VENV} {quoted}"
    )

def uv_editable_install_command(workspace: Path) -> str | None:
    """Return shell steps to pre-install the project editable for offline rebuilds.

    Hatchling editable installs need the ``editables`` package even when it is not
    listed in ``[build-system].requires``; install it before ``-e .``.
    """
    if not (workspace / "uv.lock").is_file():
        return None
    return (
        f"{_UV_BOOTSTRAP_SHELL} && "
        f"uv pip install --python {_UV_PROJECT_VENV} editables && "
        f"uv pip install --python {_UV_PROJECT_VENV} -e . --no-build-isolation"
    )

def uv_offline_smoke_commands(workspace: Path) -> list[str]:
    """Gate-equivalent offline checks to run at image build after cache warming.

    Lint smokes (``uv run ruff check``) soft-fail like pre-commit hook install:
    a missing console script must not abort the image build after deps warmed.
    """
    if not (workspace / "uv.lock").is_file():
        return []
    commands: list[str] = []
    sync = "uv sync --offline --group dev" if _pyproject_has_uv_dev_group(workspace) else "uv sync --offline"
    commands.append(f"{_UV_OFFLINE_SMOKE_PREFIX} {sync}")
    if _workspace_has_ruff_signal(workspace):
        commands.append(
            f"{_UV_OFFLINE_SMOKE_PREFIX} uv run ruff check "
            '|| echo "malvin: uv run ruff check failed (continuing)" >&2'
        )
    return commands

def workspace_declared_repin_command(
    workspace: Path,
    dockerfile: Path | None = None,
) -> str | None:
    """Force-reinstall declared pins after warm pip installs that may clobber them.

    Example: installing tox upgrades ``packaging``, which then fails the mandatory probe
    against Adaptix's ``packaging==24.2`` pin.

    Bulk pins and pyproject/lockfile constraints share one ``pip install`` so transitive
    deps of bulk packages cannot float past declared ranges (httpx: ``twine`` pulling
    ``rich`` 15 while ``rich>=10,<15`` is declared).
    """
    if dockerfile is None or not dockerfile.is_file():
        return None
    declared = declared_python_dependencies(workspace.resolve(), dockerfile)
    specs: list[str] = []
    covered: set[str] = set()
    for name, ver in sorted(declared.bulk_pins.items()):
        specs.append(f"'{name}=={ver}'")
        covered.add(name.lower())
    for name in sorted(set(declared.constraints) | set(declared.lockfile_pins)):
        key = name.lower()
        if key in covered:
            continue
        pip_spec = declared.pip_install_spec(name)
        if pip_spec:
            specs.append(f"'{pip_spec}'")
            covered.add(key)
    if not specs:
        return None
    return "pip install --no-cache-dir --force-reinstall " + " ".join(specs)

def workspace_image_warm_commands(
    workspace: Path,
    dockerfile: Path | None = None,
) -> list[str]:
    """Shell commands to warm offline agent quality gates at Modal image build."""
    commands: list[str] = []
    just_install = just_install_command(workspace)
    if just_install:
        commands.append(just_install)
    tox_runner = tox_runner_install_command(workspace)
    if tox_runner:
        commands.append(tox_runner)
    lint_install = workspace_lint_tool_install_command(workspace)
    if lint_install:
        commands.append(lint_install)
    
    
    pip_seed = default_pip_editable_seed_command(workspace, dockerfile)
    if pip_seed:
        commands.append(pip_seed)
    uv_sync = uv_sync_dev_command(workspace)
    if uv_sync:
        commands.append(uv_sync)
    build_system = uv_pip_build_system_command(workspace)
    if build_system:
        commands.append(build_system)
    editable = uv_editable_install_command(workspace)
    if editable:
        commands.append(editable)
    precommit_cmds = precommit_warm_script_commands(workspace)
    commands.extend(precommit_cmds)
    from tox_gates import tox_gate_env_warm_command, tox_gate_precommit_warm_command

    tox_gate_env = tox_gate_env_warm_command(workspace)
    if tox_gate_env:
        commands.append(tox_gate_env)
    elif tox_lint_check_commands(workspace):
        commands.append("tox -e lint --notest --skip-missing-interpreters true")
    tox_pc = tox_gate_precommit_warm_command(workspace)
    if tox_pc:
        commands.append(tox_pc)
    
    repin = workspace_declared_repin_command(workspace, dockerfile)
    if repin:
        commands.append(repin)
    smoke = uv_offline_smoke_commands(workspace)
    if smoke and build_system:
        
        
        commands.append(smoke[0])
        commands.append(build_system)
        commands.extend(smoke[1:])
    else:
        commands.extend(smoke)
    return commands

def registry_image_cache_bust_commands(
    dockerfile: Path | None = None,
    workspace: Path | None = None,
    *,
    registry_pull: bool = False,
) -> list[str]:
    """Modal registry cache bust: reconcile declared deps, drift fixes, mandatory probe.

    When ``pyproject.toml`` declares packages omitted from Dockerfile bulk pins (e.g.
    aiomonitor ``pydantic>=2.0.0``), reconcile commands install them unconditionally
    after bulk pin replay — not only when bulk pins are absent.

    With ``registry_pull=True``, skip Dockerfile bulk-pin replay (full ``RUN pip install``
    replay) because Harbor registry images already ship those pins; still reconcile
    declared bulk pins when Modal base-image layering may have clobbered them.
    """
    declared = (
        declared_python_dependencies(workspace.resolve(), dockerfile)
        if workspace is not None and dockerfile is not None and dockerfile.is_file()
        else DeclaredDeps({}, {}, (), {})
    )
    cmds: list[str] = []
    reconcile = _reconcile_declared_deps_commands(declared, registry_pull=registry_pull)
    cmds.extend(reconcile)
    if not declared.package_names():
        cmds.append(_pydantic_v1_eviction_command())
    cmds.append(_httpx_drift_probe_script_write_command())
    cmds.append(_httpx_drift_fix_command())
    
    if reconcile:
        cmds.extend(reconcile)
    cmds.extend(mandatory_probe_script_commands(declared))
    return cmds

def prepare_task_sandbox(
    spec: Any,
    workspace: Path,
    *,
    dry_run: bool = False,
    deadline: float | None = None,
    offline_editable: bool = True,
    verify_probes: bool = True,
) -> SandboxPrepResult:
    """Offline editable replay and declared-dependency verification probes."""
    workspace = workspace.resolve()
    task_id = getattr(spec, "task_id", "unknown")
    dockerfile = spec.dockerfile if getattr(spec, "dockerfile", None) and spec.dockerfile.is_file() else None
    declared = declared_python_dependencies(workspace, dockerfile)
    sync_commands = workspace_sync_commands_from_dockerfile(
        spec.dockerfile,
        offline_editable=offline_editable,
    )
    if sync_commands:
        click.echo(
            f"Preparing sandbox: replaying {len(sync_commands)} Dockerfile install step(s)"
        )
    sync_warnings: list[str] = []
    for command in sync_commands:
        click.echo(f"Prep sync: {command}")
        if dry_run:
            continue
        timeout_sec = _remaining_sec(deadline) if deadline is not None else None
        code, detail, timed_out = _run_shell(command, workspace, timeout_sec=timeout_sec)
        if timed_out:
            err = format_prep_error(
                task_id,
                phase="runtime sync",
                detail=f"sync timed out for {command!r}" + (f": {detail}" if detail else ""),
                hint="check offline editable replay",
            )
            click.echo(err, err=True)
            return SandboxPrepResult(
                sync_commands=tuple(sync_commands),
                sync_warnings=tuple(sync_warnings),
                probe_errors=(err,),
                ok=False,
                timed_out=True,
            )
        if code != 0:
            err = format_prep_error(
                task_id,
                phase="runtime sync",
                detail=f"exit {code} for {command!r}" + (f": {detail}" if detail else ""),
                hint="check offline editable replay",
            )
            sync_warnings.append(err)
            click.echo(err, err=True)
            return SandboxPrepResult(
                sync_commands=tuple(sync_commands),
                sync_warnings=tuple(sync_warnings),
                probe_errors=(err,),
                ok=False,
            )

    if dry_run or not verify_probes:
        return SandboxPrepResult(
            sync_commands=tuple(sync_commands),
            sync_warnings=tuple(sync_warnings),
            probe_errors=(),
            ok=True,
        )

    probe_errors = run_post_prep_probes(workspace, declared, task_id=task_id)
    if probe_errors:
        for err in probe_errors:
            click.echo(err, err=True)
        return SandboxPrepResult(
            sync_commands=tuple(sync_commands),
            sync_warnings=tuple(sync_warnings),
            probe_errors=tuple(probe_errors),
            ok=False,
        )

    return SandboxPrepResult(
        sync_commands=tuple(sync_commands),
        sync_warnings=tuple(sync_warnings),
        probe_errors=(),
        ok=True,
    )

def _test_parse_dockerfile_run_commands_multiline() -> None:
    text = """FROM base
RUN pip install --no-cache-dir pytest && \\
    pip install -e .
RUN git clone https://example.com/foo .
"""
    runs = parse_dockerfile_run_commands(text)
    assert len(runs) == 2, runs
    assert "pip install --no-cache-dir pytest" in runs[0]
    assert runs[1].startswith("git clone")

def _test_workspace_sync_commands_bandit() -> None:
    text = """RUN git clone https://github.com/PyCQA/bandit.git . && git checkout abc
RUN pip install pytest && pip install -e .
"""
    runs = parse_dockerfile_run_commands(text)
    sync = _sync_commands_from_runs(runs)
    assert len(sync) == 1, sync
    assert "-e" in sync[0] and "--no-deps" in sync[0]

def _test_workspace_sync_commands_fastapi() -> None:
    text = """RUN git clone https://github.com/fastapi/fastapi .
RUN pip install --no-cache-dir -e ".[all]" && pip install --no-cache-dir pytest
"""
    runs = parse_dockerfile_run_commands(text)
    sync = _sync_commands_from_runs(runs)
    assert len(sync) == 1, sync
    assert '-e ".[all]"' in sync[0] and "--no-deps" in sync[0]

def _test_bash_lc_pip_intents_ignore_shell_noise() -> None:
    text = (
        "FROM x\n"
        'RUN bash -lc "if [ -f requirements.txt ]; then pip install -r requirements.txt; fi; '
        'pip install --no-cache-dir -e . pytest pint"\n'
    )
    intents = collect_pip_install_intents(text)
    joined = " ".join(intents)
    assert "pip install --no-cache-dir -e . pytest pint" in joined
    unpinned = collect_unpinned_package_names(intents)
    assert "pytest" in unpinned
    assert "pint" in unpinned
    assert "fi" not in unpinned
    assert "if" not in unpinned

def _test_requirement_inline_comments_stripped_for_pip() -> None:
    """OpenStack-style ``pkg>=1 # MIT`` must not reach pip install args."""
    assert _strip_requirement_comment("beautifulsoup4>=4.8.0 # MIT") == "beautifulsoup4>=4.8.0"
    assert _requirement_line_package("beautifulsoup4>=4.8.0 # MIT") == (
        "beautifulsoup4",
        ">=4.8.0",
    )
    assert _parse_dependency_spec("PyYAML>=5.3.1 # MIT") == ("pyyaml", ">=5.3.1")
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "requirements.txt").write_text(
            "beautifulsoup4>=4.8.0 # MIT\nPyYAML>=5.3.1 # MIT\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install -r requirements.txt\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        soup = declared.pip_install_spec("beautifulsoup4")
        assert soup == "beautifulsoup4>=4.8.0"
        assert "#" not in soup
        cmds = registry_image_cache_bust_commands(
            dockerfile, workspace=root, registry_pull=True
        )
        joined = " ".join(cmds)
        assert "# MIT" not in joined
        assert "beautifulsoup4>=4.8.0" in joined

def _test_pep508_extras_preserved_in_pip_install_spec() -> None:
    """``fastapi-cli[standard] >=0.0.8`` must not become ``fastapi-cli==[standard]…``."""
    import tempfile

    assert _parse_dependency_spec("fastapi-cli[standard] >=0.0.8") == (
        "fastapi-cli",
        "[standard]>=0.0.8",
    )
    assert _parse_dependency_spec("uvicorn[standard] >=0.12.0") == (
        "uvicorn",
        "[standard]>=0.12.0",
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0"\n'
            "dependencies = [\n"
            '  "fastapi-cli[standard] >=0.0.8",\n'
            '  "uvicorn[standard] >=0.12.0",\n'
            "]\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text("FROM x\nRUN pip install -e .\n", encoding="utf-8")
        declared = declared_python_dependencies(root, dockerfile)
        assert declared.pip_install_spec("fastapi-cli") == "fastapi-cli[standard]>=0.0.8"
        assert declared.pip_install_spec("uvicorn") == "uvicorn[standard]>=0.12.0"
        cmds = registry_image_cache_bust_commands(
            dockerfile, workspace=root, registry_pull=True
        )
        joined = " ".join(cmds)
        assert "fastapi-cli==[" not in joined
        assert "uvicorn==[" not in joined
        assert "fastapi-cli[standard]>=0.0.8" in joined

def _test_requirements_editable_and_constraints_declared() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "requirements.txt").write_text(
            "-e .[cli]\nfixtures>=3.0.0\nrich\n",
            encoding="utf-8",
        )
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0"\n'
            'optional-dependencies = { cli = ["click>=8"] }\n',
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install -r requirements.txt\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        assert any("-e" in seg for seg in declared.editable_segments)
        assert "fixtures" in declared.constraints or "fixtures" in declared.package_names()
        assert "rich" in declared.package_names()
        assert "click" in declared.package_names()

def _test_poetry_extra_and_runtime_deps_declared() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "pyproject.toml").write_text(
            "[tool.poetry]\n"
            'name = "demo"\n'
            'version = "0"\n'
            'dependencies.python = "^3.10"\n'
            'dependencies.rich = ">=14"\n'
            'dependencies.pytest = { version = ">=8", optional = true }\n'
            'extras.check = [ "pytest" ]\n',
            encoding="utf-8",
        )
        (root / "demo").mkdir()
        (root / "demo" / "__init__.py").write_text("", encoding="utf-8")
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            'FROM x\nRUN pip install -e ".[check]"\n',
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        assert "rich" in declared.package_names()
        assert "pytest" in declared.package_names()

def _test_fixture_imports_not_unmapped_for_workspace_project() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        workspace = root / "ws"
        workspace.mkdir()
        (workspace / "pkg").mkdir()
        (workspace / "pkg" / "__init__.py").write_text("", encoding="utf-8")
        (workspace / "pyproject.toml").write_text(
            '[project]\nname = "pkg"\nversion = "0"\n',
            encoding="utf-8",
        )
        tests = root / "tests"
        tests.mkdir()
        (tests / "test.patch").write_text(
            "diff --git a/fixtures/sample.py b/fixtures/sample.py\n"
            "--- /dev/null\n"
            "+++ b/fixtures/sample.py\n"
            "@@ -0,0 +1,1 @@\n"
            "+import flask\n"
            "diff --git a/tests/test_pkg.py b/tests/test_pkg.py\n"
            "--- /dev/null\n"
            "+++ b/tests/test_pkg.py\n"
            "@@ -0,0 +1,1 @@\n"
            "+import pkg\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text("FROM x\nRUN pip install pytest\n", encoding="utf-8")
        spec = discover_verifier_spec(workspace, tests_dir=tests, dockerfile=dockerfile)
        assert "flask" not in spec.harbor_imports
        assert "pkg" not in spec.unmapped_imports
        assert any("-e" in seg for seg in spec.editable_segments)

def _test_editable_pip_segment_ignores_dirty_equals() -> None:
    bulk = (
        "pip install --no-cache-dir pytest dirty-equals>=0.9.0 inline-snapshot>=0.21.1"
    )
    assert not _is_editable_pip_segment(bulk)
    assert _is_editable_pip_segment('pip install --no-cache-dir -e ".[all]"')
    assert _is_editable_pip_segment('pip3 install -e ".[pandas]"')
    assert _is_bulk_pip_segment("pip3 install pytest covdefaults")

def _test_infra_abort_dockerfile_sync_is_offline() -> None:
    """Offline sync must not replay network-fetching bulk pip; editable gets --no-deps."""
    import tempfile

    text = """FROM base
RUN pip install --no-cache-dir pytest requests
RUN pip install --no-cache-dir -e ".[dev]"
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        sync = workspace_sync_commands_from_dockerfile(dockerfile)
        for cmd in sync:
            assert _is_editable_pip_segment(cmd) or not _is_bulk_pip_segment(cmd), cmd
            if _is_editable_pip_segment(cmd):
                assert "--no-deps" in cmd and "--no-build-isolation" in cmd, cmd
        bulk = dockerfile_bulk_pip_commands(dockerfile)
    assert bulk
    assert all(_is_bulk_pip_segment(cmd) for cmd in bulk), bulk

def _test_dockerfile_image_build_commands_fastapi() -> None:
    import tempfile

    text = """FROM base
RUN git clone https://github.com/fastapi/fastapi .
RUN pip install --no-cache-dir -e ".[all]" && pip install --no-cache-dir pytest dirty-equals>=0.9.0
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        build = dockerfile_image_build_commands(dockerfile)
    assert len(build) == 1, build
    assert '-e ".[all]"' in build[0]
    assert "pytest" not in build[0]

def _test_workspace_sync_commands_fastapi_task_dockerfile() -> None:
    import tempfile

    text = """FROM base
RUN git clone https://github.com/fastapi/fastapi .
RUN pip install --no-cache-dir -e ".[all]" && pip install --no-cache-dir pytest dirty-equals>=0.9.0
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        sync = workspace_sync_commands_from_dockerfile(dockerfile)
    assert len(sync) == 1, sync
    assert "-e" in sync[0] and "--no-deps" in sync[0]

def _test_should_replay_skips_apt_and_git() -> None:
    assert not should_replay_run_command("apt-get update && apt-get install -y build-essential")
    assert not should_replay_run_command("git clone https://github.com/foo .")
    assert should_replay_run_command("go mod download")

def _test_hybrid_poetry_runtime_sync_skipped() -> None:
    import tempfile

    text = """FROM base
RUN poetry install --no-interaction
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        sync = workspace_sync_commands_from_dockerfile(dockerfile)
    assert sync == [], sync

def _test_hybrid_pnpm_runtime_sync_skipped() -> None:
    import tempfile

    text = """FROM base
RUN pnpm install --frozen-lockfile
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        sync = workspace_sync_commands_from_dockerfile(dockerfile)
    assert sync == [], sync

def _test_tox_lint_check_commands() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert tox_lint_check_commands(root) == []
        (root / "tox.ini").write_text(
            "[vars]\n"
            "lint_all = src/ tests/\n"
            "lint_mypy = src/\n"
            "[testenv:lint]\n"
            "commands =\n"
            "  ruff check {[vars]lint_all} --fix\n"
            "  mypy {[vars]lint_mypy}\n",
            encoding="utf-8",
        )
        assert tox_lint_check_commands(root) == [
            "ruff check src/ tests/ --fix",
            "mypy src/",
        ]

def _test_just_and_tox_runner_install_commands() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert just_install_command(root) is None
        assert tox_runner_install_command(root) is None
        (root / "justfile").write_text("lint:\n    tox -e lint\n", encoding="utf-8")
        just_cmd = just_install_command(root)
        assert just_cmd is not None
        assert "github.com/casey/just/releases" in just_cmd
        assert "cargo install just" not in just_cmd
        tox_cmd = tox_runner_install_command(root)
        assert tox_cmd is not None
        assert "tox" in tox_cmd
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "runner.txt").write_text("tox==4.23.2\ninvoke==2.2.0\n", encoding="utf-8")
        pinned = tox_runner_install_command(root)
        assert pinned is not None
        
        assert "tox==4.42.0" in pinned
        assert "tox==4.23.2" not in pinned
        assert "invoke==2.2.0" in pinned
        assert "/opt/venv/bin/python -m pip install" in pinned
        assert "command -v tox" not in pinned
        (req_dir / "runner.txt").write_text("tox==4.50.0\n", encoding="utf-8")
        newer = tox_runner_install_command(root)
        assert newer is not None
        assert "tox==4.50.0" in newer

def _test_workspace_lint_tool_install_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert workspace_lint_tool_install_command(root) is None
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "lint.txt").write_text(
            "ruff==0.9.1\nmypy==1.14.0\npre-commit==4.0.1\n",
            encoding="utf-8",
        )
        (root / "tox.ini").write_text(
            "[testenv:lint]\n"
            "deps = -r requirements/lint.txt\n"
            "commands =\n"
            "  ruff check src/ --fix\n",
            encoding="utf-8",
        )
        cmd = workspace_lint_tool_install_command(root)
        assert cmd is not None
        assert "ruff==0.9.1" in cmd
        assert "mypy==1.14.0" in cmd
        assert "pre-commit==4.0.1" in cmd

def _test_precommit_install_hooks_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert precommit_install_hooks_command(root) is None
        assert precommit_warm_script_commands(root) == []
        (root / ".pre-commit-config.yaml").write_text("repos: []\n", encoding="utf-8")
        cmds = precommit_warm_script_commands(root)
        assert len(cmds) == 2
        assert "base64 -d" in cmds[0]
        assert cmds[1] == f"bash {PRECOMMIT_WARM_SCRIPT_PATH}"
        body = base64.b64decode(
            shlex.split(cmds[0].split("|")[0].removeprefix("echo ").strip())[0]
        ).decode()
        assert "pre-commit install-hooks" in body
        assert "pip install --no-cache-dir pre-commit" in body
        assert "PRE_COMMIT" not in body
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "lint.txt").write_text("pre-commit==4.0.1\n", encoding="utf-8")
        pinned_body = base64.b64decode(
            shlex.split(precommit_warm_script_commands(root)[0].split("|")[0].removeprefix("echo ").strip())[0]
        ).decode()
        assert "pre-commit==4.0.1" in pinned_body
        assert ".venv/bin/pre-commit" in pinned_body

def _test_precommit_pin_from_workspace_pyproject() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            "[dependency-groups]\ndev = [\"pre-commit==3.5.0\"]\n",
            encoding="utf-8",
        )
        assert _precommit_pin_from_workspace(root) == "3.5.0"

def _test_uv_sync_dev_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert uv_sync_dev_command(root) is None
        (root / "uv.lock").write_text("# lock\n", encoding="utf-8")
        cmd = uv_sync_dev_command(root)
        assert cmd is not None
        assert cmd.endswith("uv sync")
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n',
            encoding="utf-8",
        )
        cmd = uv_sync_dev_command(root)
        assert cmd is not None
        assert "pip install" in cmd and "uv" in cmd
        assert cmd.endswith("uv sync")
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            "[dependency-groups]\ndev = [\"pytest\"]\n",
            encoding="utf-8",
        )
        cmd = uv_sync_dev_command(root)
        assert cmd is not None
        assert "pip install" in cmd and "uv" in cmd
        assert cmd.endswith("uv sync --group dev")

def _test_uv_pip_build_system_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert uv_pip_build_system_command(root) is None
        (root / "uv.lock").write_text("# lock\n", encoding="utf-8")
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n',
            encoding="utf-8",
        )
        assert uv_pip_build_system_command(root) is None
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            '[build-system]\nrequires = ["setuptools>=69.2", "setuptools-scm[toml]>=8.0"]\n',
            encoding="utf-8",
        )
        cmd = uv_pip_build_system_command(root)
        assert cmd is not None
        assert "uv pip install --python .venv" in cmd
        assert shlex.quote("setuptools-scm[toml]>=8.0") in cmd

def _test_uv_editable_install_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert uv_editable_install_command(root) is None
        (root / "uv.lock").write_text("# lock\n", encoding="utf-8")
        cmd = uv_editable_install_command(root)
        assert cmd is not None
        assert "uv pip install --python .venv editables" in cmd
        assert "uv pip install --python .venv -e . --no-build-isolation" in cmd

def _test_default_pip_editable_seed_for_offline_sync() -> None:
    """Dockerfile ``pip install -e`` + hatchling ⇒ system pip gets editables at warm."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            'FROM x\nRUN pip install -e ".[diagrams]"\n',
            encoding="utf-8",
        )
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0"\n'
            '[build-system]\nrequires = ["hatchling"]\n'
            'build-backend = "hatchling.build"\n',
            encoding="utf-8",
        )
        seed = default_pip_editable_seed_command(root, dockerfile)
        assert seed is not None
        assert "pip install --no-cache-dir" in seed
        assert "hatchling" in seed
        assert "editables" in seed
        warm = workspace_image_warm_commands(root, dockerfile=dockerfile)
        assert seed in warm
        venv_cmds = verifier_venv_build_system_commands(root)
        assert len(venv_cmds) == 1
        assert "hatchling" in venv_cmds[0]
        assert "editables" in venv_cmds[0]
        
        bare = root / "Dockerfile.bare"
        bare.write_text("FROM x\nRUN pip install pytest\n", encoding="utf-8")
        assert default_pip_editable_seed_command(root, bare) is None

def _test_editable_seed_reads_monorepo_build_backends() -> None:
    """Editable targets under libs/*/pyproject.toml must contribute hatchling seeds."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        core = root / "libs" / "core"
        core.mkdir(parents=True)
        (core / "pyproject.toml").write_text(
            '[project]\nname = "langchain-core"\nversion = "0"\n'
            '[build-system]\nrequires = ["hatchling"]\n'
            'build-backend = "hatchling.build"\n',
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install -e libs/core\n",
            encoding="utf-8",
        )
        seed = default_pip_editable_seed_command(root, dockerfile)
        assert seed is not None
        assert "hatchling" in seed
        assert "editables" in seed
        specs = _editable_offline_seed_specs(root, dockerfile=dockerfile)
        assert any("hatchling" in s for s in specs)
        empty = DeclaredDeps({}, {}, (), {})
        venv_cmds = verifier_venv_build_system_commands(
            root,
            spec=VerifierSpec(
                declared=empty,
                public_install_specs=(),
                editable_segments=("pip install -e libs/core",),
            ),
        )
        assert venv_cmds and "hatchling" in venv_cmds[0]

def _test_editable_target_project_deps_enter_declared() -> None:
    """``pip install -e libs/core --no-deps`` still needs libs/core's pydantic pin."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        core = root / "libs" / "core"
        core.mkdir(parents=True)
        (core / "pyproject.toml").write_text(
            '[project]\nname = "langchain-core"\nversion = "0"\n'
            'dependencies = ["pydantic>=2.7.4,<3.0.0", "tenacity"]\n'
            '[build-system]\nrequires = ["hatchling"]\n'
            'build-backend = "hatchling.build"\n',
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install -e libs/core\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        assert declared.effective_spec("pydantic") == ">=2.7.4,<3.0.0"
        assert "tenacity" in declared.unpinned_names or declared.effective_spec("tenacity")
        specs = _public_install_specs(declared)
        assert any(s.startswith("pydantic") for s in specs)

def _test_uv_offline_smoke_commands() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert uv_offline_smoke_commands(root) == []
        (root / "uv.lock").write_text("# lock\n", encoding="utf-8")
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n',
            encoding="utf-8",
        )
        smoke = uv_offline_smoke_commands(root)
        assert smoke == ["UV_OFFLINE=1 UV_NO_SYNC=1 uv sync --offline"]
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            "[dependency-groups]\ndev = [\"ruff\"]\n",
            encoding="utf-8",
        )
        smoke = uv_offline_smoke_commands(root)
        assert len(smoke) == 2
        assert smoke[0] == "UV_OFFLINE=1 UV_NO_SYNC=1 uv sync --offline --group dev"
        assert smoke[1].startswith("UV_OFFLINE=1 UV_NO_SYNC=1 uv run ruff check")
        assert "continuing" in smoke[1]

def _test_workspace_declared_repin_command() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert workspace_declared_repin_command(root) is None
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "RUN pip install -r requirements/test_extra_new.txt\n",
            encoding="utf-8",
        )
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "test_extra_new.txt").write_text(
            "packaging==24.2\npydantic==2.10.3\n",
            encoding="utf-8",
        )
        cmd = workspace_declared_repin_command(root, dockerfile)
        assert cmd is not None
        assert "packaging==24.2" in cmd
        assert "pydantic==2.10.3" in cmd

        
        
        (root / "pyproject.toml").write_text(
            '[project]\nname = "httpx"\nversion = "0"\n'
            'dependencies = ["rich>=10,<15", "httpcore==1.*"]\n',
            encoding="utf-8",
        )
        (req_dir / "test_extra_new.txt").write_text(
            "twine==6.1.0\nmkdocs==1.6.1\n",
            encoding="utf-8",
        )
        cmd = workspace_declared_repin_command(root, dockerfile)
        assert cmd is not None
        assert "twine==6.1.0" in cmd
        assert "rich>=10,<15" in cmd
        assert "httpcore==1.*" in cmd
        assert cmd.count("pip install") == 1

def _test_workspace_image_warm_commands() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        assert workspace_image_warm_commands(root) == []
        (root / ".pre-commit-config.yaml").write_text("repos: []\n", encoding="utf-8")
        precommit_only = workspace_image_warm_commands(root)
        assert len(precommit_only) == 2
        assert "base64 -d" in precommit_only[0]
        assert precommit_only[1] == f"bash {PRECOMMIT_WARM_SCRIPT_PATH}"
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "lint.txt").write_text("ruff==0.9.1\nmypy==1.14.0\n", encoding="utf-8")
        (root / "tox.ini").write_text(
            "[testenv:lint]\ncommands =\n  ruff check src/ --fix\n",
            encoding="utf-8",
        )
        lint_warm = workspace_image_warm_commands(root)
        assert any("tox" in cmd for cmd in lint_warm)
        assert any("ruff==0.9.1" in cmd for cmd in lint_warm)
        assert any(
            cmd == "tox run -e lint --notest --skip-missing-interpreters true"
            for cmd in lint_warm
        )
        assert any(".tox/lint/bin/python" in cmd and "pre_commit" in cmd for cmd in lint_warm)
        assert len(lint_warm) == 6
        (root / "justfile").write_text("lint:\n    tox -e lint\n", encoding="utf-8")
        with_just = workspace_image_warm_commands(root)
        assert any("github.com/casey/just/releases" in cmd for cmd in with_just)
        assert len(with_just) == 7
        (root / "uv.lock").write_text("# lock\n", encoding="utf-8")
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            '[build-system]\nrequires = ["setuptools>=69.2"]\n'
            "[dependency-groups]\ndev = [\"ruff\"]\n",
            encoding="utf-8",
        )
        cmds = workspace_image_warm_commands(root)
        precommit_script = precommit_warm_script_commands(root)
        assert cmds[0] == just_install_command(root)
        assert "tox" in cmds[1]
        assert cmds[2:5] == [
            f"{_UV_BOOTSTRAP_SHELL} && uv sync --group dev",
            (
                f"{_UV_BOOTSTRAP_SHELL} && uv pip install --python {_UV_PROJECT_VENV} "
                f"{shlex.quote('setuptools>=69.2')}"
            ),
            (
                f"{_UV_BOOTSTRAP_SHELL} && "
                f"uv pip install --python {_UV_PROJECT_VENV} editables && "
                f"uv pip install --python {_UV_PROJECT_VENV} "
                "-e . --no-build-isolation"
            ),
        ]
        assert cmds[5:7] == precommit_script
        assert any("tox run -e lint --notest" in cmd for cmd in cmds)
        assert "uv run ruff check" in cmds[-1]
        assert "continuing" in cmds[-1]

def _test_setuptools_extra_requirement_files_not_extra_keys() -> None:
    """Kombu-style extras map to requirements files; extra keys are not PyPI names."""
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "setup.py").write_text(
            "from setuptools import setup\n"
            "setup(\n"
            "    name='demo',\n"
            "    extras_require={\n"
            "        'msgpack': extras('msgpack.txt'),\n"
            "        'redis': extras('redis.txt'),\n"
            "        'azureservicebus': extras('azureservicebus.txt'),\n"
            "    },\n"
            ")\n",
            encoding="utf-8",
        )
        extras_dir = root / "requirements" / "extras"
        extras_dir.mkdir(parents=True)
        (extras_dir / "msgpack.txt").write_text("msgpack==1.1.2\n", encoding="utf-8")
        (extras_dir / "redis.txt").write_text(
            "redis>=4.5.2,!=4.5.5,<7.1\n",
            encoding="utf-8",
        )
        (extras_dir / "azureservicebus.txt").write_text(
            "azure-servicebus>=7.12.0\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            'FROM x\nRUN pip install -e ".[msgpack,redis]"\n'
            "RUN pip install -r requirements/test.txt\n",
            encoding="utf-8",
        )
        (root / "requirements").mkdir(exist_ok=True)
        (root / "requirements" / "test.txt").write_text(
            "pytest==9.0.2\n",
            encoding="utf-8",
        )
        (root / "requirements" / "default.txt").write_text(
            "amqp>=5.1.1,<6.0.0\nvine==5.1.0\npackaging\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        names = declared.package_names()
        assert "msgpack" in names
        assert declared.pip_install_spec("msgpack") == "msgpack==1.1.2"
        assert declared.pip_install_spec("redis") == "redis>=4.5.2,!=4.5.5,<7.1"
        assert declared.pip_install_spec("vine") == "vine==5.1.0"
        assert "packaging" in names
        
        assert "azureservicebus" not in names
        
        scraped = _requirement_names_from_setup_py(root / "setup.py")
        assert "msgpack" not in scraped
        assert "redis" not in scraped
        assert "azureservicebus" not in scraped
        assert "demo" not in scraped

def _test_registry_image_cache_bust_commands() -> None:
    import tempfile

    text = """FROM base
RUN pip install --no-cache-dir -e ".[all]" && pip install --no-cache-dir pytest dirty-equals>=0.9.0
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        cmds = registry_image_cache_bust_commands(dockerfile)
    assert len(cmds) >= 4, cmds
    assert cmds[0].startswith("python3 -c") or cmds[0].startswith("pip install")
    joined = " ".join(cmds)
    assert "starlette==1.0.0" in joined
    assert "pydantic==2.13.4" not in joined
    assert cmds[-1] == f"python3 {MANDATORY_PROBE_SCRIPT_PATH}", cmds
    assert "base64 -d" in cmds[-2], cmds

def _test_registry_image_cache_bust_pydantic_v1_legitimate() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "RUN pip install --no-cache-dir pydantic==1.10.26 pytest\n",
            encoding="utf-8",
        )
        cmds = registry_image_cache_bust_commands(dockerfile, workspace=root)
    joined = " ".join(cmds)
    assert "pydantic==1.10.26" in joined, cmds
    assert "pydantic>=2" not in joined, cmds
    assert cmds[-1] == f"python3 {MANDATORY_PROBE_SCRIPT_PATH}", cmds

def _test_run_post_prep_probes_structured_error() -> None:
    import sys
    import tempfile
    from unittest.mock import patch

    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        declared = DeclaredDeps({}, {"pydantic": ">=2.0.0"}, (), {})
        mod = sys.modules[__name__]
        with patch.object(
            mod,
            "_run_shell",
            return_value=(1, "pydantic 1.10.26 violates >=2.0.0", False),
        ):
            errors = run_post_prep_probes(
                workspace, declared, task_id="probe-test", phase="runtime probe"
            )
    assert len(errors) == 1, errors
    assert "probe-test" in errors[0]
    assert "pydantic" in errors[0]
    assert "1.10.26" in errors[0]
    assert ">=2.0.0" in errors[0]

def _test_run_post_prep_probes_multi_violation_errors() -> None:
    import sys
    import tempfile
    from unittest.mock import patch

    stderr = (
        "pydantic 2.13.4 violates ==2.12.5; "
        "terminaltables 3.1.0 violates ==3.1.10"
    )
    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        declared = DeclaredDeps({}, {"pydantic": ">=2.0.0"}, (), {"terminaltables": "3.1.10"})
        mod = sys.modules[__name__]
        with patch.object(mod, "_run_shell", return_value=(1, stderr, False)):
            errors = run_post_prep_probes(
                workspace, declared, task_id="multi-probe", phase="runtime probe"
            )
    assert len(errors) == 2, errors
    assert any("pydantic" in err and "2.13.4" in err for err in errors), errors
    assert any("terminaltables" in err and "3.1.0" in err for err in errors), errors

def _test_run_post_prep_probes_mixed_import_and_violation_errors() -> None:
    import sys
    import tempfile
    from unittest.mock import patch

    stderr = (
        "backports.strenum: import check failed (No module named 'backports'); "
        "pydantic 1.10.26 violates >=2.0.0"
    )
    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        declared = DeclaredDeps(
            {},
            {"pydantic": ">=2.0.0", "backports.strenum": "==1.3.1"},
            (),
            {},
        )
        mod = sys.modules[__name__]
        with patch.object(mod, "_run_shell", return_value=(1, stderr, False)):
            errors = run_post_prep_probes(
                workspace, declared, task_id="mixed-probe", phase="runtime probe"
            )
    assert len(errors) == 2, errors
    assert any("backports.strenum" in err for err in errors), errors
    assert any("pydantic" in err and "1.10.26" in err for err in errors), errors

def _test_mandatory_probe_accepts_single_char_version_ops() -> None:
    """Constraints like ``>4.6`` / ``<7`` must not become ``==>4.6`` / ``==<7``."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        
        (workspace / "pkg_a.py").write_text("__version__ = '4.9.0'\n", encoding="utf-8")
        probe_body = _mandatory_probe_python(
            DeclaredDeps(
                {},
                {"pexpect": ">4.6", "hypothesis": "<7"},
                (),
                {},
            )
        )
        
        wrapped = (
            "import importlib.metadata as _im\n"
            "_orig = _im.version\n"
            "def _fake(name):\n"
            "    if name == 'pexpect':\n"
            "        return '4.9.0'\n"
            "    if name == 'hypothesis':\n"
            "        return '6.156.6'\n"
            "    return _orig(name)\n"
            "_im.version = _fake\n"
            + probe_body
        )
        proc = subprocess.run(
            [sys.executable, "-c", wrapped],
            cwd=str(workspace),
            capture_output=True,
            text=True,
            check=False,
        )
    assert proc.returncode == 0, proc.stderr

def _test_mandatory_probe_strips_pep508_extras_before_specifier() -> None:
    """Remainders like ``[standard]>=0.0.8`` must not become ``==[standard]…``."""
    probe_body = _mandatory_probe_python(
        DeclaredDeps(
            {},
            {
                "fastapi-cli": "[standard]>=0.0.8",
                "uvicorn": "[standard]>=0.12.0",
            },
            (),
            {},
        )
    )
    assert "ver_spec.startswith('[')" in probe_body
    wrapped = (
        "import importlib.metadata as _im\n"
        "def _fake(name):\n"
        "    if name == 'fastapi-cli':\n"
        "        return '0.0.29'\n"
        "    if name == 'uvicorn':\n"
        "        return '0.51.0'\n"
        "    raise _im.PackageNotFoundError(name)\n"
        "_im.version = _fake\n"
        + probe_body
    )
    proc = subprocess.run(
        [sys.executable, "-c", wrapped],
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc.returncode == 0, proc.stderr
    assert "Invalid specifier" not in proc.stderr

def _test_precommit_warm_soft_fails_install_hooks() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / ".pre-commit-config.yaml").write_text("repos: []\n", encoding="utf-8")
        body = _precommit_warm_script_body(root)
    assert "install-hooks" in body
    assert "continuing" in body
    assert "|| echo" in body

def _test_pythonpath_dockerfile_skips_synthetic_editable() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        src = root / "src" / "demo_pkg"
        src.mkdir(parents=True)
        (src / "__init__.py").write_text("", encoding="utf-8")
        (root / "pyproject.toml").write_text(
            "[project]\nname = 'demo-pkg'\nversion = '0.1.0'\n"
            "[build-system]\nrequires = ['setuptools', 'cython']\n"
            "build-backend = 'setuptools.build_meta'\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nENV PYTHONPATH=/app/src\n"
            "RUN pip install attrs numpy\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root, dockerfile)
        assert not any("-e" in s for s in declared.editable_segments), declared
        spec = discover_verifier_spec(root, tests_dir=None, dockerfile=dockerfile)
        assert not any("-e" in s for s in spec.editable_segments), spec
        assert any(str(root / "src") == p or p.endswith("/src") for p in spec.grade_pythonpath)
        env = verifier_grade_subprocess_env(spec, base_env={})
        assert "PYTHONPATH" in env
        assert "src" in env["PYTHONPATH"]

def _test_mandatory_probe_fails_on_invalid_version_string() -> None:
    import importlib.util
    import types
    from unittest.mock import patch

    fake_mod = types.ModuleType("badver")
    fake_mod.__version__ = "not-a-version"
    fake_mod.__spec__ = importlib.util.spec_from_loader("badver", loader=None)
    probe_body = _mandatory_probe_python(
        DeclaredDeps({}, {"badver": "==1.0.0"}, (), {})
    )
    real_find_spec = importlib.util.find_spec
    with (
        patch.dict(sys.modules, {"badver": fake_mod}),
        patch("importlib.metadata.version", return_value="not-a-version"),
        patch(
            "importlib.util.find_spec",
            side_effect=lambda name, *args, **kwargs: None
            if name == "httpx"
            else real_find_spec(name, *args, **kwargs),
        ),
    ):
        try:
            exec(probe_body, {})
            raise AssertionError("expected probe to exit 1 on invalid version")
        except SystemExit as exc:
            assert exc.code == 1, f"expected exit 1, got {exc.code}"

def _test_mandatory_probe_prefers_metadata_over_stale_module_version() -> None:
    body = _mandatory_probe_python(
        DeclaredDeps({}, {"terminaltables": "==3.1.10"}, (), {})
    )
    assert "pkg_version(display_name)" in body
    assert body.index("pkg_version(display_name)") < body.index("__version__")

def _test_mandatory_probe_runtime_metadata_wins_over_stale_version() -> None:
    import importlib.util
    import types
    from unittest.mock import patch

    fake_mod = types.ModuleType("terminaltables")
    fake_mod.__version__ = "3.1.0"
    fake_mod.__spec__ = importlib.util.spec_from_loader("terminaltables", loader=None)
    probe_body = _mandatory_probe_python(
        DeclaredDeps({}, {"terminaltables": "==3.1.10"}, (), {})
    )
    real_find_spec = importlib.util.find_spec
    with (
        patch.dict(sys.modules, {"terminaltables": fake_mod}),
        patch("importlib.metadata.version", return_value="3.1.10"),
        patch(
            "importlib.util.find_spec",
            side_effect=lambda name, *args, **kwargs: None
            if name == "httpx"
            else real_find_spec(name, *args, **kwargs),
        ),
    ):
        try:
            exec(probe_body, {})
        except SystemExit as exc:
            assert exc.code in (0, None), f"probe failed with exit {exc.code}"

def _test_effective_spec_prefers_pyproject_constraint_over_lockfile() -> None:
    declared = DeclaredDeps(
        {},
        {"pydantic": ">=2.0.0"},
        (),
        {"pydantic": "2.12.5"},
    )
    assert declared.effective_spec("pydantic") == ">=2.0.0"

def _test_effective_spec_exact_pyproject_beats_lockfile() -> None:
    declared = DeclaredDeps(
        {},
        {"pydantic": "==2.12.5"},
        (),
        {"pydantic": "2.13.4"},
    )
    assert declared.effective_spec("pydantic") == "==2.12.5"

def _test_mandatory_probe_fails_when_version_unknown() -> None:
    import importlib.util
    import types
    from unittest.mock import patch

    fake_mod = types.ModuleType("silentpkg")
    fake_mod.__spec__ = importlib.util.spec_from_loader("silentpkg", loader=None)
    probe_body = _mandatory_probe_python(
        DeclaredDeps({}, {"silentpkg": "==9.9.9"}, (), {})
    )
    real_find_spec = importlib.util.find_spec
    with (
        patch.dict(sys.modules, {"silentpkg": fake_mod}),
        patch("importlib.metadata.version", side_effect=Exception("no metadata")),
        patch(
            "importlib.util.find_spec",
            side_effect=lambda name, *args, **kwargs: None
            if name == "httpx"
            else real_find_spec(name, *args, **kwargs),
        ),
    ):
        try:
            exec(probe_body, {})
            raise AssertionError("expected probe to exit 1 when version unknown")
        except SystemExit as exc:
            assert exc.code == 1, f"expected exit 1, got {exc.code}"

def _test_httpx_drift_probe_script_write_roundtrip() -> None:
    write_cmd = _httpx_drift_probe_script_write_command()
    payload = shlex.split(write_cmd.split("|")[0].removeprefix("echo ").strip())[0]
    assert base64.b64decode(payload).decode() == _httpx_drift_probe_python(), write_cmd

def _test_probe_import_name_phonenumberslite() -> None:
    assert _probe_import_name("phonenumberslite") == "phonenumbers"
    assert _probe_import_name("pydantic-core") == "pydantic_core"
    assert _probe_import_name("pyelftools") == "elftools"
    assert _probe_import_name("pyserial") == "serial"

def _test_mandatory_probe_uses_metadata_before_import() -> None:
    """Distribution metadata satisfies probes when the import root differs from the dist name."""
    declared = DeclaredDeps({}, {"pyelftools": ">=0.32"}, (), {})
    body = _mandatory_probe_python(declared)
    meta_at = body.index("pkg_version(display_name)")
    import_at = body.index("find_spec(import_name)")
    assert meta_at < import_at, body[:400]

def _test_registry_image_cache_bust_reconciles_twice_after_httpx_fix() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        req_dir = root / "requirements"
        req_dir.mkdir()
        (req_dir / "dev.txt").write_text(
            "typing-extensions==4.12.2\nphonenumberslite==8.13.52\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text("RUN pip install -r requirements/dev.txt\n", encoding="utf-8")
        cmds = registry_image_cache_bust_commands(dockerfile, workspace=root, registry_pull=True)
    reconcile = [cmd for cmd in cmds if "typing-extensions==4.12.2" in cmd]
    assert len(reconcile) == 2, cmds
    assert _httpx_drift_probe_script_write_command() in cmds, cmds

def _test_mandatory_probe_script_commands_builder_safe() -> None:
    declared = DeclaredDeps(
        {"pytest": "8.0.0"},
        {"pydantic": ">=2.0.0", "aioconsole": "==0.8.1"},
        (),
        {},
    )
    cmds = mandatory_probe_script_commands(declared)
    joined = " ".join(cmds)
    assert "checks = [" not in joined, joined
    assert "base64 -d" in joined, joined
    assert cmds[-1] == f"python3 {MANDATORY_PROBE_SCRIPT_PATH}", cmds

def _test_mandatory_probe_script_write_roundtrip() -> None:
    declared = DeclaredDeps({}, {"pydantic": ">=2.0.0", "aiomonitor": "==0.7.1"}, (), {})
    write_cmd = mandatory_probe_script_write_command(declared)
    expected = _mandatory_probe_python(declared)
    payload = shlex.split(write_cmd.split("|")[0].removeprefix("echo ").strip())[0]
    assert base64.b64decode(payload).decode() == expected, write_cmd

def _test_declared_deps_skip_marker_gated_backports() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "pyproject.toml").write_text(
            '[project]\nname = "x"\ndependencies = [\n'
            '  "pydantic>=2.0.0",\n'
            '  "backports.strenum>=1.2.4; python_version<\'3.11\'",\n'
            "]\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(root)
    assert "pydantic" in declared.constraints, declared
    if sys.version_info >= (3, 11):
        assert "backports.strenum" not in declared.constraints, declared
    else:
        assert "backports.strenum" in declared.constraints, declared

def _test_mandatory_probe_no_crash_on_dotted_import_name() -> None:
    import tempfile
    from unittest.mock import patch

    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        declared = DeclaredDeps(
            {},
            {"backports.strenum": ">=1.2.4", "pydantic": ">=2.0.0"},
            (),
            {},
        )
        mod = sys.modules[__name__]
        with patch.object(
            mod,
            "_run_shell",
            return_value=(1, "backports.strenum: import check failed (No module named 'backports')", False),
        ):
            errors = run_post_prep_probes(
                workspace, declared, task_id="dotted-test", phase="runtime probe"
            )
    assert len(errors) == 1, errors
    assert "dotted-test" in errors[0]
    assert "backports" in errors[0]

def _test_registry_image_cache_bust_adaptix_pydantic_pin() -> None:
    import tempfile

    dockerfile = _FIXTURE_VERIFIER_ADAPTIX / "environment" / "Dockerfile"
    assert dockerfile.is_file(), dockerfile
    with tempfile.TemporaryDirectory() as tmp:
        workspace = Path(tmp)
        req_dir = workspace / "requirements"
        req_dir.mkdir()
        (req_dir / "test_extra_new.txt").write_text(
            "pydantic==2.10.3\npydantic-core==2.27.1\n",
            encoding="utf-8",
        )
        (req_dir / "lint.txt").write_text("pre-commit==4.0.1\n", encoding="utf-8")
        (workspace / ".pre-commit-config.yaml").write_text("repos: []\n", encoding="utf-8")
        cmds = registry_image_cache_bust_commands(dockerfile, workspace=workspace)
        precommit = precommit_warm_script_commands(workspace)
    assert any("pydantic==2.10.3" in c for c in cmds), cmds
    assert any("pydantic-core==2.27.1" in c for c in cmds), cmds
    assert not any("pydantic==2.13.4" in c for c in cmds), cmds
    assert precommit
    pinned_body = base64.b64decode(
        shlex.split(precommit[0].split("|")[0].removeprefix("echo ").strip())[0]
    ).decode()
    assert "pre-commit==4.0.1" in pinned_body

def _test_pydantic_pins_for_cache_bust_reads_requirements() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "RUN pip install -r requirements/dev.txt\n",
            encoding="utf-8",
        )
        (root / "requirements").mkdir()
        (root / "requirements" / "dev.txt").write_text("pydantic==1.2.3\n", encoding="utf-8")
        pins = pins_for_task(dockerfile, workspace=root)
    assert pins.get("pydantic") == "1.2.3"

def _test_collect_pip_install_intents_bash_lc() -> None:
    text = """FROM base
RUN bash -lc "if [ -f requirements.txt ]; then pip install -r requirements.txt; fi; pip install -e . pytest"
"""
    intents = collect_pip_install_intents(text)
    assert any("-r requirements.txt" in i for i in intents), intents
    assert any("-e ." in i for i in intents), intents

def _test_dockerfile_bulk_pip_commands_fastapi() -> None:
    import tempfile

    text = """FROM base
RUN git clone https://github.com/fastapi/fastapi .
RUN pip install --no-cache-dir -e ".[all]" && pip install --no-cache-dir pytest dirty-equals>=0.9.0
"""
    with tempfile.TemporaryDirectory() as tmp:
        dockerfile = Path(tmp) / "Dockerfile"
        dockerfile.write_text(text, encoding="utf-8")
        bulk = dockerfile_bulk_pip_commands(dockerfile)
    assert bulk, bulk
    assert all("pip install" in cmd for cmd in bulk)
    assert all('-e "' not in cmd for cmd in bulk)

_FIXTURE_VERIFIER_ADAPTIX = malvin_repo_root() / "tests" / "fixtures" / "verifier_adaptix"

def _test_discover_verifier_spec_public_vs_grade() -> None:
    fixture = _FIXTURE_VERIFIER_ADAPTIX
    workspace = fixture / "workspace"
    tests_dir = fixture / "tests"
    dockerfile = fixture / "environment" / "Dockerfile"
    public = discover_verifier_spec(workspace, tests_dir=None, dockerfile=dockerfile)
    assert public.harbor_imports == ()
    assert public.grade_closure_install_specs == ()
    assert "typing-extensions==4.12.2" in public.public_install_specs or any(
        s.startswith("typing-extensions") for s in public.public_install_specs
    )
    
    public_joined = " ".join(public.public_install_specs)
    assert "NoExtraItems" not in public_joined
    assert "test_aliases" not in public_joined
    assert "test.patch" not in public_joined
    
    grade = discover_verifier_spec(workspace, tests_dir=tests_dir, dockerfile=dockerfile)
    assert "pytest" in grade.harbor_imports
    assert "typeguard" in grade.harbor_imports
    assert "typing_extensions" in grade.harbor_imports
    assert "os" not in grade.harbor_imports
    view = public.public_view()
    assert "harbor_imports" not in view
    assert "grade_closure_install_specs" not in view

def _test_verifier_venv_materialize_public_no_patch_only_names() -> None:
    fixture = _FIXTURE_VERIFIER_ADAPTIX
    workspace = fixture / "workspace"
    tests_dir = fixture / "tests"
    dockerfile = fixture / "environment" / "Dockerfile"
    
    grade = discover_verifier_spec(workspace, tests_dir=tests_dir, dockerfile=dockerfile)
    public = discover_verifier_spec(workspace, tests_dir=None, dockerfile=dockerfile)
    cmds = verifier_venv_materialize_public_commands(public)
    joined = "\n".join(cmds)
    assert VERIFIER_VENV_PATH in joined
    assert "venv" in joined
    
    public_names = {
        s.split("==", 1)[0].split("[", 1)[0].lower() for s in public.public_install_specs
    }
    for line in cmds:
        if "install" not in line or "--upgrade" in line or " -e " in f" {line} ":
            continue
        for token in line.split():
            if "==" not in token:
                continue
            pkg = token.split("==", 1)[0].split("[", 1)[0].lower()
            assert pkg in public_names, (pkg, public_names, line)
    for secret_name in ("NoExtraItems", "test_aliases", "test.patch"):
        assert secret_name not in joined
    
    for name in grade.unmapped_imports:
        assert f" {name} " not in f" {joined} "
        assert f"/{name}" not in joined
        assert not any(
            tok == name or tok.startswith(f"{name}==") for tok in joined.split()
        )

def _test_verifier_grade_closure_commands_include_mapped() -> None:
    fixture = _FIXTURE_VERIFIER_ADAPTIX
    grade = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=fixture / "tests",
        dockerfile=fixture / "environment" / "Dockerfile",
    )
    
    assert grade.grade_closure_install_specs, grade.harbor_imports
    closure_cmds = verifier_venv_apply_grade_closure_commands(grade)
    assert closure_cmds, grade.grade_closure_install_specs
    joined = "\n".join(closure_cmds)
    assert "typeguard" in joined or any(
        "typeguard" in s for s in grade.grade_closure_install_specs
    )
    assert "typing-extensions" in joined or any(
        "typing-extensions" in s for s in grade.grade_closure_install_specs
    )
    public_cmds = "\n".join(verifier_venv_materialize_public_commands(grade))
    assert "typing-extensions" in public_cmds or any(
        "typing-extensions" in s for s in grade.public_install_specs
    )
    assert "harbor_imports" not in public_cmds
    assert "PLUGIN_CONFLICTS" not in public_cmds

def _test_probe_verifier_env_plugin_conflict_reports_verifier_prep() -> None:
    """Missing verifier venv fails closed (no system-Python fallback)."""
    import tempfile

    declared = DeclaredDeps(
        bulk_pins={"typing-extensions": "4.12.2"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    spec = VerifierSpec(
        declared=declared,
        public_install_specs=("typing-extensions==4.12.2",),
        editable_segments=(),
        harbor_imports=("typeguard",),
        test_sh_body="python -m pytest -q\n",
        venv_path="/tmp/malvin-verifier-does-not-exist",
    )
    with tempfile.TemporaryDirectory() as tmp:
        ok, err, policy = probe_verifier_env(
            spec,
            workspace=Path(tmp),
            task_id="fixture-adaptix",
            dry_run=False,
            run_collect=False,
        )
    assert ok is False
    assert err is not None
    assert "verifier prep" in err
    assert "missing" in err.lower() or "no system-python" in err.lower()
    assert policy is None

def _test_prepare_verifier_grade_materialize_when_missing() -> None:
    """Missing ``/opt/malvin-verifier``: materialize before probe; fail closed if absent."""
    import sys
    import tempfile
    from unittest.mock import patch

    fixture = _FIXTURE_VERIFIER_ADAPTIX
    workspace = fixture / "workspace"
    tests_dir = fixture / "tests"
    dockerfile = fixture / "environment" / "Dockerfile"
    mod = sys.modules[__name__]
    real_discover = discover_verifier_spec

    with tempfile.TemporaryDirectory() as tmp:
        venv_path = Path(tmp) / "malvin-verifier"
        calls: list[str] = []

        def discover_with_tmp_venv(
            ws: Path,
            tests_dir: Path | None = None,
            dockerfile: Path | None = None,
        ) -> VerifierSpec:
            spec = real_discover(ws, tests_dir=tests_dir, dockerfile=dockerfile)
            return VerifierSpec(
                declared=spec.declared,
                public_install_specs=spec.public_install_specs,
                editable_segments=spec.editable_segments,
                harbor_imports=spec.harbor_imports,
                grade_closure_install_specs=spec.grade_closure_install_specs,
                unmapped_imports=spec.unmapped_imports,
                test_sh_body=spec.test_sh_body,
                plugin_policy=spec.plugin_policy,
                venv_path=str(venv_path),
            )

        def shell_ok_no_create(
            command: str, _workspace: Path, timeout_sec: float | None = None
        ) -> tuple[int, str, bool]:
            del timeout_sec
            calls.append(command)
            return 0, "", False

        with (
            patch.object(mod, "discover_verifier_spec", side_effect=discover_with_tmp_venv),
            patch.object(mod, "_run_shell", side_effect=shell_ok_no_create),
            patch.object(mod, "probe_verifier_env") as probe,
        ):
            result = prepare_verifier_grade(
                workspace,
                tests_dir=tests_dir,
                dockerfile=dockerfile,
                task_id="mat-missing",
            )
            probe.assert_not_called()
        assert result.ok is False
        assert result.error is not None
        assert "verifier prep" in result.error
        assert "missing" in result.error.lower()
        assert calls, "expected public materialize commands when venv absent"
        assert any(str(venv_path) in c for c in calls)
        assert not (venv_path / "bin" / "python").is_file()

        calls.clear()

        def shell_fail(
            command: str, _workspace: Path, timeout_sec: float | None = None
        ) -> tuple[int, str, bool]:
            del timeout_sec
            calls.append(command)
            return 1, "venv create failed", False

        with (
            patch.object(mod, "discover_verifier_spec", side_effect=discover_with_tmp_venv),
            patch.object(mod, "_run_shell", side_effect=shell_fail),
            patch.object(mod, "probe_verifier_env") as probe,
        ):
            result = prepare_verifier_grade(
                workspace,
                tests_dir=tests_dir,
                dockerfile=dockerfile,
                task_id="mat-fail",
            )
            probe.assert_not_called()
        assert result.ok is False
        assert result.error is not None
        assert "verifier prep" in result.error
        assert calls, "expected materialize attempt before fail-closed"

def _test_probe_verifier_env_unmapped_imports_fail_closed() -> None:
    """Q7: unmapped Harbor imports abort at verifier prep (no invented PyPI pins)."""
    import tempfile

    declared = DeclaredDeps(
        bulk_pins={"pytest": "8.0.0"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "venv"
        _clone_cached_venv(venv)
        spec = VerifierSpec(
            declared=declared,
            public_install_specs=("pytest==8.0.0",),
            editable_segments=(),
            unmapped_imports=("only_in_patch",),
            test_sh_body="python -m pytest -q\n",
            venv_path=str(venv),
        )
        ok, err, _policy = probe_verifier_env(
            spec,
            workspace=root,
            task_id="unmapped",
            dry_run=False,
            run_collect=False,
        )
    assert ok is False
    assert err is not None
    assert "verifier prep" in err
    assert "only_in_patch" in err

def _test_prepare_task_sandbox_does_not_call_probe_verifier() -> None:
    import inspect

    source = inspect.getsource(prepare_task_sandbox)
    assert "probe_verifier_env" not in source
    assert "prepare_verifier_grade" not in source
    assert "discover_verifier_spec" not in source

def _test_probe_verifier_env_missing_collect_path_does_not_abort() -> None:
    """Collect-only against paths absent from disk *and* ``test.patch`` must not abort."""
    from unittest.mock import MagicMock, patch

    declared = DeclaredDeps(
        bulk_pins={"pytest": "8.0.0"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "venv"
        _clone_cached_venv(venv)
        spec = VerifierSpec(
            declared=declared,
            public_install_specs=("pytest==8.0.0",),
            editable_segments=(),
            test_sh_body="python -m pytest tests/missing_hidden_from_patch.py -q\n",
            venv_path=str(venv),
        )
        plugin_out = MagicMock(returncode=0, stdout="PLUGIN_OK:\n", stderr="")
        collect_out = MagicMock(
            returncode=2,
            stdout="",
            stderr="ERROR: file or directory not found: tests/missing_hidden_from_patch.py\n",
        )

        def fake_run(cmd, **kwargs):
            if isinstance(cmd, list) and len(cmd) >= 3 and cmd[1] == "-c":
                return plugin_out
            return collect_out

        with patch("subprocess.run", side_effect=fake_run):
            ok, err, _policy = probe_verifier_env(
                spec,
                workspace=root,
                task_id="probe-missing-path",
                dry_run=False,
                run_collect=True,
                tests_dir=None,
            )
    assert ok is True, err
    assert err is None

def _test_probe_plugin_conflict_failed_collect_aborts() -> None:
    """PLUGIN_CONFLICTS must not soft-succeed when collect-only still fails."""
    from unittest.mock import MagicMock, patch

    declared = DeclaredDeps(
        bulk_pins={"pytest": "8.0.0"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "malvin-verifier"
        _clone_cached_venv(venv)
        spec = VerifierSpec(
            declared=declared,
            public_install_specs=("pytest==8.0.0",),
            editable_segments=(),
            test_sh_body="python -m pytest tests/test_aliases.py -q\n",
            venv_path=str(venv),
        )
        plugin_out = MagicMock(
            returncode=2,
            stdout=(
                "PLUGIN_OK:\n"
                "PLUGIN_CONFLICTS:typeguard: ImportError: NoExtraItems\n"
            ),
            stderr="",
        )
        collect_out = MagicMock(
            returncode=1,
            stdout="",
            stderr="INTERNALERROR> collection failed for unknown reason\n",
        )

        def fake_run(cmd, **kwargs):
            if isinstance(cmd, list) and len(cmd) >= 3 and cmd[1] == "-c":
                return plugin_out
            return collect_out

        with patch("subprocess.run", side_effect=fake_run):
            ok, err, policy = probe_verifier_env(
                spec,
                workspace=root,
                task_id="plugin-softpass",
                dry_run=False,
                run_collect=True,
                tests_dir=None,
            )
    assert ok is False, "plugin conflict + failed collect must fail closed"
    assert err is not None and "verifier prep" in err
    assert "INTERNALERROR" in err or "collection failed" in err
    assert policy is not None
    assert policy.disable_autoload is True

def _test_modified_hunk_context_imports_in_verifier_spec() -> None:
    """Modified test.patch hunks must surface context-line third-party imports."""
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        workspace = root / "workspace"
        workspace.mkdir()
        (workspace / "pyproject.toml").write_text(
            "[project]\nname='x'\nversion='0'\n"
            "dependencies=['only-in-context-pkg==1.0.0']\n",
            encoding="utf-8",
        )
        tests = root / "tests"
        tests.mkdir()
        (tests / "test.patch").write_text(
            "diff --git a/tests/test_mod.py b/tests/test_mod.py\n"
            "--- a/tests/test_mod.py\n"
            "+++ b/tests/test_mod.py\n"
            "@@ -1,3 +1,5 @@\n"
            " import only_in_context_pkg\n"
            " def test_a():\n"
            "     assert True\n"
            "+def test_b():\n"
            "+    assert True\n",
            encoding="utf-8",
        )
        (tests / "test.sh").write_text(
            "#!/bin/bash\npython -m pytest tests/test_mod.py -q\n",
            encoding="utf-8",
        )
        grade = discover_verifier_spec(workspace, tests_dir=tests, dockerfile=None)
        public = discover_verifier_spec(workspace, tests_dir=None, dockerfile=None)
    assert "only_in_context_pkg" in grade.harbor_imports
    assert "only_in_context_pkg" not in public.harbor_imports
    assert any("only-in-context-pkg" in s for s in grade.grade_closure_install_specs)
    assert "only_in_context_pkg" in grade.grade_view()["harbor_imports"]
    assert "harbor_imports" not in grade.public_view()
    assert "unmapped_imports" not in grade.public_view()

def _test_adaptix_prepatch_materialize_catches_importerror() -> None:
    """Production Harbor timing: no test file on disk; patch hunks must fail prep."""
    from unittest.mock import MagicMock, patch

    fixture = _FIXTURE_VERIFIER_ADAPTIX
    dockerfile = fixture / "environment" / "Dockerfile"
    tests_dir = fixture / "tests"
    grade = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=tests_dir,
        dockerfile=dockerfile,
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "malvin-verifier"
        workspace = root / "app"
        workspace.mkdir()
        _clone_cached_venv(venv)
        conflict_spec = VerifierSpec(
            declared=grade.declared,
            public_install_specs=grade.public_install_specs,
            editable_segments=(),
            harbor_imports=grade.harbor_imports,
            grade_closure_install_specs=grade.grade_closure_install_specs,
            unmapped_imports=(),
            test_sh_body=grade.test_sh_body
            or "python -m pytest tests/test_aliases.py -q\n",
            venv_path=str(venv),
        )
        plugin_out = MagicMock(returncode=0, stdout="PLUGIN_OK:\n", stderr="")
        collect_out = MagicMock(
            returncode=1,
            stdout="",
            stderr="ImportError: NoExtraItems is missing from typing_extensions\n",
        )

        def fake_run(cmd, **kwargs):
            if isinstance(cmd, list) and len(cmd) >= 3 and cmd[1] == "-c":
                return plugin_out
            return collect_out

        with patch("subprocess.run", side_effect=fake_run):
            ok, err, policy = probe_verifier_env(
                conflict_spec,
                workspace=workspace,
                tests_dir=tests_dir,
                task_id="adaptix-prepatch",
                dry_run=False,
                run_collect=True,
            )
        if ok:
            assert err is None
            if policy is not None:
                assert policy.disable_autoload is True
            grade_env = verifier_grade_subprocess_env(
                conflict_spec, plugin_policy=policy
            )
            assert grade_env.get("VIRTUAL_ENV") == str(venv)
        else:
            assert err is not None and "verifier prep" in err

def _test_verifier_pip_honors_spec_venv_path() -> None:
    declared = DeclaredDeps(
        bulk_pins={"pytest": "8.0.0"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    spec = VerifierSpec(
        declared=declared,
        public_install_specs=("pytest==8.0.0",),
        editable_segments=(),
        venv_path="/tmp/custom-malvin-verifier",
    )
    cmds = "\n".join(verifier_venv_materialize_public_commands(spec))
    assert "/tmp/custom-malvin-verifier/bin/pip" in cmds
    assert "/opt/malvin-verifier/bin/pip" not in cmds
    closure = VerifierSpec(
        declared=declared,
        public_install_specs=("pytest==8.0.0",),
        editable_segments=(),
        grade_closure_install_specs=("pytest==8.0.0",),
        venv_path="/tmp/custom-malvin-verifier",
    )
    assert all(
        "/tmp/custom-malvin-verifier/bin/pip" in c
        for c in verifier_venv_apply_grade_closure_commands(closure)
    )

def _test_prepare_verifier_grade_materialize_creates_real_venv() -> None:
    """End-to-end: missing venv → materialize commands produce ``bin/python``.

    ``python -m venv`` / pip upgrade are multi-second; under unit tests those shell
    steps are served from the process venv cache while still driving
    ``prepare_verifier_grade`` through ``_run_shell``.
    """
    from unittest.mock import patch

    fixture = _FIXTURE_VERIFIER_ADAPTIX
    with tempfile.TemporaryDirectory() as tmp:
        venv_path = Path(tmp) / "malvin-verifier"
        workspace = fixture / "workspace"
        tests_dir = fixture / "tests"
        dockerfile = fixture / "environment" / "Dockerfile"
        mod = sys.modules[__name__]

        def discover_tmp(
            ws: Path,
            tests_dir: Path | None = None,
            dockerfile: Path | None = None,
        ) -> VerifierSpec:
            _ = (ws, tests_dir, dockerfile)
            
            return VerifierSpec(
                declared=DeclaredDeps({}, {}, (), {}),
                public_install_specs=(),
                editable_segments=(),
                harbor_imports=(),
                grade_closure_install_specs=(),
                unmapped_imports=(),
                test_sh_body="python -m pytest -q\n",
                venv_path=str(venv_path),
            )

        def fast_run_shell(
            command: str,
            ws: Path,
            *,
            timeout_sec: float | None = None,
        ) -> tuple[int, str, bool]:
            _ = timeout_sec
            if " -m venv " in command or command.strip().startswith("python3 -m venv"):
                _clone_cached_venv(venv_path)
                return 0, "", False
            if "install --upgrade pip" in command:
                return 0, "", False
            return _run_shell(command, ws)

        with (
            patch.object(mod, "discover_verifier_spec", side_effect=discover_tmp),
            patch.object(
                mod,
                "probe_verifier_env",
                return_value=(True, None, None),
            ),
            patch.object(mod, "_run_shell", side_effect=fast_run_shell),
        ):
            result = prepare_verifier_grade(
                workspace,
                tests_dir=tests_dir,
                dockerfile=dockerfile,
                task_id="mat-e2e",
            )
        assert (venv_path / "bin" / "python").is_file(), result.error
        assert result.ok is True
        assert result.public_venv_present is True

def _test_discover_grade_closure_records_declared_harbor_imports() -> None:
    """Mapped Harbor imports fill grade_closure; unmapped stay out of install commands."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        workspace = root / "ws"
        workspace.mkdir()
        tests_dir = root / "tests"
        tests_dir.mkdir()
        (tests_dir / "test.patch").write_text(
            "diff --git a/t.py b/t.py\n"
            "--- /dev/null\n"
            "+++ b/t.py\n"
            "@@ -0,0 +1,2 @@\n"
            "+import requests\n"
            "+import only_in_patch\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install --no-cache-dir requests==2.31.0\n",
            encoding="utf-8",
        )
        grade = discover_verifier_spec(
            workspace, tests_dir=tests_dir, dockerfile=dockerfile
        )
        public = discover_verifier_spec(workspace, tests_dir=None, dockerfile=dockerfile)
    assert any(s.startswith("requests==") for s in grade.grade_closure_install_specs)
    assert "only_in_patch" in grade.unmapped_imports
    assert "only_in_patch" not in "\n".join(
        verifier_venv_apply_grade_closure_commands(grade)
    )
    assert public.grade_closure_install_specs == ()
    assert public.harbor_imports == ()
    assert any(s.startswith("requests==") for s in grade.public_install_specs)

def _test_editable_project_satisfies_harbor_import() -> None:
    """Dockerfile ``pip install -e .`` provides Harbor imports without DeclaredDeps pins."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        workspace = root / "ws"
        workspace.mkdir()
        (workspace / "mypkg").mkdir()
        (workspace / "mypkg" / "__init__.py").write_text("", encoding="utf-8")
        (workspace / "pyproject.toml").write_text(
            '[project]\nname = "my-pkg"\nversion = "0.1.0"\n',
            encoding="utf-8",
        )
        tests_dir = root / "tests"
        tests_dir.mkdir()
        (tests_dir / "test.patch").write_text(
            "diff --git a/t.py b/t.py\n"
            "--- /dev/null\n"
            "+++ b/t.py\n"
            "@@ -0,0 +1,1 @@\n"
            "+import mypkg\n",
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install -e .\n",
            encoding="utf-8",
        )
        grade = discover_verifier_spec(
            workspace, tests_dir=tests_dir, dockerfile=dockerfile
        )
    assert "mypkg" in grade.harbor_imports
    assert grade.unmapped_imports == ()
    assert grade.editable_segments
    assert any("-e" in seg for seg in grade.editable_segments)

def _test_probe_editable_roots_prefers_harbor_import_case() -> None:
    """Dist name ``ipython`` must not override Harbor import spelling ``IPython``."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "IPython").mkdir()
        (root / "IPython" / "__init__.py").write_text("x = 1\n", encoding="utf-8")
        python = sys.executable
        err = _probe_editable_roots_importable(
            python,
            {"ipython", "IPython"},
            workspace=root,
            harbor_imports=("IPython",),
        )
        assert err is None, err

def _test_non_pytest_test_sh_skips_collect_probe() -> None:
    assert not test_sh_invokes_pytest("#!/bin/bash\nbash /app/test.sh base\n")
    assert test_sh_invokes_pytest("python -m pytest tests/ -q\n")

def _test_unpinned_dockerfile_package_declared() -> None:
    """Bare ``pip install pytest`` becomes an unpinned DeclaredDeps name."""
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        workspace = root / "ws"
        workspace.mkdir()
        (workspace / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n',
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text(
            "FROM x\nRUN pip install --no-cache-dir pytest\nRUN pip install -e .\n",
            encoding="utf-8",
        )
        declared = declared_python_dependencies(workspace, dockerfile)
        tests_dir = root / "tests"
        tests_dir.mkdir()
        (tests_dir / "test.patch").write_text(
            "diff --git a/t.py b/t.py\n"
            "--- /dev/null\n"
            "+++ b/t.py\n"
            "@@ -0,0 +1,2 @@\n"
            "+import pytest\n"
            "+import demo\n",
            encoding="utf-8",
        )
        grade = discover_verifier_spec(
            workspace, tests_dir=tests_dir, dockerfile=dockerfile
        )
    assert "pytest" in declared.unpinned_names
    assert declared.pip_install_spec("pytest") == "pytest"
    assert "pytest" in grade.public_install_specs
    assert grade.unmapped_imports == ()

def _test_cargo_and_go_mod_skipped_in_offline_sync() -> None:
    """Network language package fetches are not replayed in offline sandbox sync."""
    cargo_runs = parse_dockerfile_run_commands("FROM x\nRUN cargo fetch\n")
    go_runs = parse_dockerfile_run_commands("FROM x\nRUN go mod download\n")
    assert _sync_commands_from_runs(cargo_runs, offline_editable=False) == []
    assert _sync_commands_from_runs(go_runs, offline_editable=False) == []
    assert _sync_commands_from_runs(cargo_runs, offline_editable=True) == []

def _test_collect_import_error_editable_feature_gap() -> None:
    provided = {"pwnlib", "pwn", "pwntools"}
    assert collect_import_error_is_editable_feature_gap(
        "ModuleNotFoundError: No module named 'pwnlib.tubes.mux'",
        provided,
    )
    assert not collect_import_error_is_editable_feature_gap(
        "ModuleNotFoundError: No module named 'pwnlib'",
        provided,
    )
    assert collect_import_error_is_editable_feature_gap(
        "tests/test_mux.py:17: in <module>\n    from pwnlib\n",
        provided,
    )
    
    assert not collect_import_error_is_editable_feature_gap(
        "File \"/app/pwnlib/context/__init__.py\", line 21, in <module>\n"
        "    import socks\n"
        "ModuleNotFoundError: No module named 'socks'\n",
        provided,
    )

def _test_bare_pyproject_deps_become_unpinned() -> None:
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "pyproject.toml").write_text(
            '[project]\nname = "demo"\nversion = "0.1.0"\n'
            'dependencies = ["pysocks", "requests>=2.0"]\n',
            encoding="utf-8",
        )
        dockerfile = root / "Dockerfile"
        dockerfile.write_text("FROM x\nRUN pip install -e .\n", encoding="utf-8")
        declared = declared_python_dependencies(root, dockerfile)
    assert "pysocks" in declared.unpinned_names
    assert declared.constraints.get("requests") == ">=2.0"
    assert declared.pip_install_spec("pysocks") == "pysocks"

def _test_adaptix_conflict_fixture_yields_plugin_policy_or_verifier_prep() -> None:
    """Adaptix pin conflict: collect ImportError fails verifier prep (or plugin policy)."""
    import tempfile
    from unittest.mock import MagicMock, patch

    fixture = _FIXTURE_VERIFIER_ADAPTIX
    dockerfile = fixture / "environment" / "Dockerfile"
    grade = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=fixture / "tests",
        dockerfile=dockerfile,
    )
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "malvin-verifier"
        workspace = root / "app"
        tests = workspace / "tests"
        tests.mkdir(parents=True)
        (tests / "test_aliases.py").write_text(
            "from typing_extensions import NoExtraItems\n"
            "import typeguard\n"
            "import pytest\n"
            "def test_smoke():\n"
            "    assert NoExtraItems is not None\n",
            encoding="utf-8",
        )
        _clone_cached_venv(venv)
        conflict_spec = VerifierSpec(
            declared=grade.declared,
            public_install_specs=grade.public_install_specs,
            editable_segments=(),
            harbor_imports=grade.harbor_imports,
            grade_closure_install_specs=grade.grade_closure_install_specs,
            unmapped_imports=(),
            test_sh_body="python -m pytest tests/test_aliases.py -q\n",
            venv_path=str(venv),
        )
        plugin_out = MagicMock(
            returncode=2,
            stdout=(
                "PLUGIN_OK:\n"
                "PLUGIN_CONFLICTS:typeguard: ImportError: NoExtraItems\n"
            ),
            stderr="",
        )
        collect_out = MagicMock(returncode=0, stdout="", stderr="")

        def fake_run(cmd, **kwargs):
            if isinstance(cmd, list) and len(cmd) >= 3 and cmd[1] == "-c":
                return plugin_out
            return collect_out

        with patch("subprocess.run", side_effect=fake_run):
            ok, err, policy = probe_verifier_env(
                conflict_spec,
                workspace=workspace,
                tests_dir=fixture / "tests",
                task_id="adaptix-fixture",
                dry_run=False,
                run_collect=True,
            )
        if ok:
            assert err is None
            if policy is not None:
                assert policy.disable_autoload is True
                assert policy.as_env().get("PYTEST_DISABLE_PLUGIN_AUTOLOAD") == "1"
            assert conflict_spec.venv_path != ""
            assert Path(f"{conflict_spec.venv_path}/bin/python").is_file()
            grade_env = verifier_grade_subprocess_env(
                conflict_spec, plugin_policy=policy
            )
            assert grade_env.get("VIRTUAL_ENV") == conflict_spec.venv_path
            assert grade_env.get("VIRTUAL_ENV") != sys.prefix
        else:
            assert err is not None and "verifier prep" in err

def _test_adaptix_import_error_never_soft_succeeds_on_system_python() -> None:
    """Adaptix-class ImportError: never ok=True when verifier venv is absent (system Python)."""
    import tempfile

    fixture = _FIXTURE_VERIFIER_ADAPTIX
    dockerfile = fixture / "environment" / "Dockerfile"
    grade = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=fixture / "tests",
        dockerfile=dockerfile,
    )
    
    missing = VerifierSpec(
        declared=grade.declared,
        public_install_specs=grade.public_install_specs,
        editable_segments=(),
        harbor_imports=grade.harbor_imports,
        grade_closure_install_specs=grade.grade_closure_install_specs,
        unmapped_imports=(),
        test_sh_body="python -m pytest tests/test_aliases.py -q\n",
        venv_path="/tmp/malvin-verifier-adaptix-missing-venv",
    )
    with tempfile.TemporaryDirectory() as tmp:
        ok, err, policy = probe_verifier_env(
            missing,
            workspace=Path(tmp),
            task_id="adaptix-no-system",
            dry_run=False,
            run_collect=True,
        )
    assert ok is False
    assert err is not None and "verifier prep" in err
    assert "no system-python" in err.lower() or "missing" in err.lower()
    assert policy is None
    
    with tempfile.TemporaryDirectory() as tmp:
        venv_path = Path(tmp) / "absent-verifier"
        calls: list[str] = []
        mod = sys.modules[__name__]
        real_discover = discover_verifier_spec

        def discover_missing(
            ws: Path,
            tests_dir: Path | None = None,
            dockerfile: Path | None = None,
        ) -> VerifierSpec:
            spec = real_discover(ws, tests_dir=tests_dir, dockerfile=dockerfile)
            return VerifierSpec(
                declared=spec.declared,
                public_install_specs=spec.public_install_specs,
                editable_segments=spec.editable_segments,
                harbor_imports=spec.harbor_imports,
                grade_closure_install_specs=spec.grade_closure_install_specs,
                unmapped_imports=(),
                test_sh_body=spec.test_sh_body,
                venv_path=str(venv_path),
            )

        def shell_noop(
            command: str, _workspace: Path, timeout_sec: float | None = None
        ) -> tuple[int, str, bool]:
            del timeout_sec
            calls.append(command)
            return 0, "", False

        from unittest.mock import patch

        with (
            patch.object(mod, "discover_verifier_spec", side_effect=discover_missing),
            patch.object(mod, "_run_shell", side_effect=shell_noop),
        ):
            prep = prepare_verifier_grade(
                fixture / "workspace",
                tests_dir=fixture / "tests",
                dockerfile=dockerfile,
                task_id="adaptix-grade-no-system",
            )
    assert prep.ok is False
    assert prep.error is not None and "verifier prep" in prep.error
    assert not (venv_path / "bin" / "python").is_file()
    
    assert prep.public_venv_present is False

def _test_plugin_policy_as_env_allowlist_wiring() -> None:
    policy = PluginPolicy(disable_autoload=True, allowlist=("xdist", "timeout"))
    env = policy.as_env()
    assert env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] == "1"
    assert "-p xdist" in env["PYTEST_ADDOPTS"]
    assert "-p timeout" in env["PYTEST_ADDOPTS"]
    assert env["MALVIN_VERIFIER_PLUGIN_ALLOWLIST"] == "xdist,timeout"
    declared = DeclaredDeps({}, {}, (), {})
    spec = VerifierSpec(
        declared=declared,
        public_install_specs=(),
        editable_segments=(),
        plugin_policy=policy,
    )
    grade_env = verifier_grade_subprocess_env(
        spec, base_env={"PATH": "/usr/bin", "PYTEST_ADDOPTS": "-q --maxfail=1"}
    )
    assert grade_env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] == "1"
    assert "VIRTUAL_ENV" in grade_env
    
    assert "-q" in grade_env["PYTEST_ADDOPTS"]
    assert "--maxfail=1" in grade_env["PYTEST_ADDOPTS"]
    assert "-p xdist" in grade_env["PYTEST_ADDOPTS"]
    assert "-p timeout" in grade_env["PYTEST_ADDOPTS"]

def _test_plugin_disable_policy_lets_collect_boot() -> None:
    """Broken pytest11 entry point: disable-autoload policy → collect-only boots."""
    import tempfile
    from unittest.mock import MagicMock, patch

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        venv = root / "malvin-verifier"
        workspace = root / "app"
        tests = workspace / "tests"
        tests.mkdir(parents=True)
        (tests / "test_smoke.py").write_text(
            "def test_ok():\n    assert True\n",
            encoding="utf-8",
        )
        _clone_cached_venv(venv)
        declared = DeclaredDeps(
            bulk_pins={"pytest": "8.3.4"},
            constraints={},
            editable_segments=(),
            lockfile_pins={},
        )
        spec = VerifierSpec(
            declared=declared,
            public_install_specs=("pytest==8.3.4",),
            editable_segments=(),
            test_sh_body="python -m pytest tests/test_smoke.py -q\n",
            venv_path=str(venv),
        )
        plugin_out = MagicMock(
            returncode=2,
            stdout=(
                "PLUGIN_OK:\n"
                "PLUGIN_CONFLICTS:broken: ImportError: NoExtraItems is missing "
                "from typing_extensions\n"
            ),
            stderr="",
        )
        collect_out = MagicMock(
            returncode=0,
            stdout="tests/test_smoke.py::test_ok\n",
            stderr="",
        )

        def fake_run(cmd, **kwargs):
            if isinstance(cmd, list) and len(cmd) >= 3 and cmd[1] == "-c":
                return plugin_out
            return collect_out

        with patch("subprocess.run", side_effect=fake_run):
            ok, err, policy = probe_verifier_env(
                spec,
                workspace=workspace,
                task_id="plugin-disable-boot",
                dry_run=False,
                run_collect=True,
            )
    assert ok is True, err
    assert err is None
    assert policy is not None
    assert policy.disable_autoload is True
    assert "broken" not in policy.allowlist
    grade_env = verifier_grade_subprocess_env(spec, plugin_policy=policy)
    assert grade_env.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD") == "1"

def _test_verifier_prep_result_as_dict_excludes_secrets() -> None:
    """Behavioral spy: agent-safe as_dict never carries grade-only VerifierSpec fields."""
    declared = DeclaredDeps(
        bulk_pins={"pytest": "8.3.4"},
        constraints={},
        editable_segments=(),
        lockfile_pins={},
    )
    policy = PluginPolicy(disable_autoload=True, allowlist=("timeout",))
    spec = VerifierSpec(
        declared=declared,
        public_install_specs=("pytest==8.3.4",),
        editable_segments=(),
        harbor_imports=("typeguard", "secret_mod"),
        grade_closure_install_specs=("typeguard==4.4.1",),
        unmapped_imports=("secret_mod",),
        test_sh_body="python -m pytest -q\n",
        plugin_policy=policy,
    )
    result = VerifierPrepResult(
        ok=True, spec=spec, plugin_policy=policy, public_venv_present=True
    )
    payload = result.as_dict()
    dumped = str(payload)
    for forbidden in (
        "harbor_imports",
        "grade_closure",
        "unmapped",
        "plugin_policy",
        "test_sh_body",
        "typeguard",
        "secret_mod",
        "PYTEST_DISABLE",
        "NoExtraItems",
    ):
        assert forbidden not in dumped, dumped
    assert payload["ok"] is True
    assert payload["public_venv_present"] is True
    assert payload["venv_path"] == VERIFIER_VENV_PATH

def _test_leakage_public_view_excludes_patch_only_imports() -> None:
    fixture = _FIXTURE_VERIFIER_ADAPTIX
    public = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=None,
        dockerfile=fixture / "environment" / "Dockerfile",
    )
    grade = discover_verifier_spec(
        fixture / "workspace",
        tests_dir=fixture / "tests",
        dockerfile=fixture / "environment" / "Dockerfile",
    )
    view = public.public_view()
    for key in (
        "harbor_imports",
        "grade_closure_install_specs",
        "unmapped_imports",
        "plugin_policy",
        "test_sh_body",
    ):
        assert key not in view
    assert "NoExtraItems" not in str(view)
    assert grade.harbor_imports
    assert public.harbor_imports == ()

_SELF_TEST_FNS = (
    _test_parse_dockerfile_run_commands_multiline,
    _test_workspace_sync_commands_bandit,
    _test_workspace_sync_commands_fastapi,
    _test_bash_lc_pip_intents_ignore_shell_noise,
    _test_requirement_inline_comments_stripped_for_pip,
    _test_pep508_extras_preserved_in_pip_install_spec,
    _test_requirements_editable_and_constraints_declared,
    _test_poetry_extra_and_runtime_deps_declared,
    _test_fixture_imports_not_unmapped_for_workspace_project,
    _test_editable_pip_segment_ignores_dirty_equals,
    _test_infra_abort_dockerfile_sync_is_offline,
    _test_dockerfile_image_build_commands_fastapi,
    _test_hybrid_poetry_runtime_sync_skipped,
    _test_hybrid_pnpm_runtime_sync_skipped,
    _test_tox_lint_check_commands,
    _test_just_and_tox_runner_install_commands,
    _test_workspace_lint_tool_install_command,
    _test_precommit_install_hooks_command,
    _test_precommit_pin_from_workspace_pyproject,
    _test_uv_sync_dev_command,
    _test_uv_pip_build_system_command,
    _test_uv_editable_install_command,
    _test_default_pip_editable_seed_for_offline_sync,
    _test_editable_seed_reads_monorepo_build_backends,
    _test_editable_target_project_deps_enter_declared,
    _test_uv_offline_smoke_commands,
    _test_setuptools_extra_requirement_files_not_extra_keys,
    _test_workspace_declared_repin_command,
    _test_workspace_image_warm_commands,
    _test_registry_image_cache_bust_commands,
    _test_registry_image_cache_bust_pydantic_v1_legitimate,
    _test_declared_deps_skip_marker_gated_backports,
    _test_mandatory_probe_no_crash_on_dotted_import_name,
    _test_run_post_prep_probes_structured_error,
    _test_run_post_prep_probes_multi_violation_errors,
    _test_run_post_prep_probes_mixed_import_and_violation_errors,
    _test_mandatory_probe_prefers_metadata_over_stale_module_version,
    _test_mandatory_probe_runtime_metadata_wins_over_stale_version,
    _test_mandatory_probe_fails_on_invalid_version_string,
    _test_mandatory_probe_accepts_single_char_version_ops,
    _test_mandatory_probe_strips_pep508_extras_before_specifier,
    _test_precommit_warm_soft_fails_install_hooks,
    _test_pythonpath_dockerfile_skips_synthetic_editable,
    _test_effective_spec_prefers_pyproject_constraint_over_lockfile,
    _test_effective_spec_exact_pyproject_beats_lockfile,
    _test_mandatory_probe_fails_when_version_unknown,
    _test_httpx_drift_probe_script_write_roundtrip,
    _test_probe_import_name_phonenumberslite,
    _test_mandatory_probe_uses_metadata_before_import,
    _test_registry_image_cache_bust_reconciles_twice_after_httpx_fix,
    _test_mandatory_probe_script_commands_builder_safe,
    _test_mandatory_probe_script_write_roundtrip,
    _test_registry_image_cache_bust_adaptix_pydantic_pin,
    _test_pydantic_pins_for_cache_bust_reads_requirements,
    _test_collect_pip_install_intents_bash_lc,
    _test_dockerfile_bulk_pip_commands_fastapi,
    _test_workspace_sync_commands_fastapi_task_dockerfile,
    _test_should_replay_skips_apt_and_git,
    _test_discover_verifier_spec_public_vs_grade,
    _test_verifier_venv_materialize_public_no_patch_only_names,
    _test_verifier_grade_closure_commands_include_mapped,
    _test_probe_verifier_env_plugin_conflict_reports_verifier_prep,
    _test_prepare_verifier_grade_materialize_when_missing,
    _test_probe_verifier_env_unmapped_imports_fail_closed,
    _test_prepare_task_sandbox_does_not_call_probe_verifier,
    _test_probe_verifier_env_missing_collect_path_does_not_abort,
    _test_probe_plugin_conflict_failed_collect_aborts,
    _test_modified_hunk_context_imports_in_verifier_spec,
    _test_adaptix_prepatch_materialize_catches_importerror,
    _test_verifier_pip_honors_spec_venv_path,
    _test_prepare_verifier_grade_materialize_creates_real_venv,
    _test_discover_grade_closure_records_declared_harbor_imports,
    _test_editable_project_satisfies_harbor_import,
    _test_probe_editable_roots_prefers_harbor_import_case,
    _test_non_pytest_test_sh_skips_collect_probe,
    _test_unpinned_dockerfile_package_declared,
    _test_cargo_and_go_mod_skipped_in_offline_sync,
    _test_collect_import_error_editable_feature_gap,
    _test_bare_pyproject_deps_become_unpinned,
    _test_adaptix_conflict_fixture_yields_plugin_policy_or_verifier_prep,
    _test_adaptix_import_error_never_soft_succeeds_on_system_python,
    _test_plugin_policy_as_env_allowlist_wiring,
    _test_plugin_disable_policy_lets_collect_boot,
    _test_verifier_prep_result_as_dict_excludes_secrets,
    _test_leakage_public_view_excludes_patch_only_imports,
)

def run_self_tests() -> None:
    if _clone_cached_venv is None:
        raise RuntimeError("inject sandbox_prep._clone_cached_venv before run_self_tests")
    for fn in _SELF_TEST_FNS:
        fn()
    click.echo("sandbox_prep self-tests passed")

if __name__ == "__main__":
    raise SystemExit(
        "Run unit tests via pytest tests/test_sandbox_prep_unit.py "
        "(injects venv cache) rather than python -m sandbox_prep."
    )