difflore-cli 0.2.0

Your AI coding agent learned public code, not your team's private decisions. difflore turns past PR reviews into source-backed local rules.
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
use difflore_core::infra::git::RepoScope;
use difflore_core::ingest::github::{ImportOptions, ImportProgress};
use difflore_core::ingest::provider::ReviewProvider;
use sqlx::SqlitePool;

use crate::cli::{ImportDistillArg, ImportProviderArg};
use crate::runtime::CommandContext;
use crate::style;
use crate::support::util::{ensure_project, project_path, validate_owner_repo};

#[cfg(test)]
mod fixtures;
mod github;
mod gitlab;
mod local_agent_distill;
mod local_candidates;
mod scope;
mod upload;

pub(crate) use github::format_github_import_err;
use github::verify_source_repo_access;
use gitlab::{run_gitlab_import, verify_gitlab_project_access};
use local_agent_distill::run_local_agent_candidates;
use local_candidates::{
    LocalCandidateProgress, local_candidate_budget, print_local_candidate_next_steps,
    run_local_candidates,
};
use upload::{ensure_cloud_session_for_upload, run_upload};

/// Args bundle for `difflore import-reviews`; keeps dispatcher calls from
/// growing a long positional parameter list.
pub(crate) struct ImportArgs {
    pub repo: Option<String>,
    pub from_upstream: Option<String>,
    /// Explicit `--provider` override; `None` → detect from the git remote.
    pub provider: Option<ImportProviderArg>,
    /// Explicit `--gitlab-host` for self-managed instances; implies the
    /// gitlab provider.
    pub gitlab_host: Option<String>,
    pub max_prs: usize,
    pub pr_numbers: Vec<i32>,
    /// PR numbers to exclude from import (parsed from `--exclude-prs`). Any PR
    /// whose number is in this set contributes zero rules. Used for leak-free
    /// recall evaluation.
    pub exclude_prs: Vec<i32>,
    pub since: Option<String>,
    pub include_open: bool,
    pub upload: bool,
    pub distill: ImportDistillArg,
    pub dry_run: bool,
    pub json: bool,
    pub wall_timeout_secs: Option<u64>,
}

impl From<crate::cli::ImportReviewsCliArgs> for ImportArgs {
    fn from(args: crate::cli::ImportReviewsCliArgs) -> Self {
        Self {
            repo: args.repo,
            from_upstream: args.from_upstream,
            provider: args.provider,
            gitlab_host: args.gitlab_host,
            max_prs: args.max_prs,
            pr_numbers: args.pr_numbers,
            exclude_prs: args.exclude_prs,
            since: args.since,
            include_open: args.include_open,
            upload: args.upload,
            distill: args.distill,
            dry_run: args.dry_run,
            json: args.json,
            wall_timeout_secs: args.wall_timeout_secs,
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct ImportRunOutcome;

struct ValidatedArgs {
    repo: Option<String>,
    from_upstream: Option<String>,
    provider: Option<ImportProviderArg>,
    gitlab_host: Option<String>,
    requested_max_prs: usize,
    max_prs: usize,
    pr_numbers: Vec<i32>,
    /// PR numbers to exclude from import, deduped into a set. Any PR whose
    /// number is in this set contributes zero rules.
    exclude_prs: std::collections::HashSet<i32>,
    since: Option<String>,
    include_open: bool,
    upload: bool,
    distill: ImportDistillArg,
    local_candidates: bool,
    dry_run: bool,
    json: bool,
}

/// Provider-neutral argument validation. `--repo` / `--from-upstream` shape
/// checks are deliberately NOT here: their grammar differs per provider
/// (GitHub `owner/repo` vs GitLab nested namespace paths), so they run after
/// provider resolution.
fn validate_args(args: ImportArgs) -> Result<ValidatedArgs, String> {
    let ImportArgs {
        repo,
        from_upstream,
        provider,
        gitlab_host,
        max_prs,
        pr_numbers,
        exclude_prs,
        since,
        include_open,
        upload,
        distill,
        dry_run,
        json,
        wall_timeout_secs: _,
    } = args;

    let requested_max_prs = max_prs;
    let max_prs = max_prs.clamp(1, 1000);
    if !json && requested_max_prs != max_prs {
        eprintln!(
            "{} --max-prs capped at {max_prs} (requested {requested_max_prs}; valid range 1..=1000)",
            style::amber(style::sym::WARN)
        );
    }
    if let Some(s) = since.as_deref()
        && chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").is_err()
    {
        return Err(format!(
            "--since '{s}' is not a valid YYYY-MM-DD date (e.g. 2026-01-15)."
        ));
    }
    if pr_numbers.iter().any(|n| *n <= 0) {
        return Err("--pr must be a positive PR number.".to_owned());
    }
    if exclude_prs.iter().any(|n| *n <= 0) {
        return Err("--exclude-prs must list positive PR numbers.".to_owned());
    }
    if upload && distill == ImportDistillArg::LocalAgent {
        return Err(
            "--distill local-agent cannot be combined with --upload; upload uses cloud extraction."
                .to_owned(),
        );
    }
    let exclude_prs: std::collections::HashSet<i32> = exclude_prs.into_iter().collect();

    let local_candidates = !upload;

    Ok(ValidatedArgs {
        repo,
        from_upstream,
        provider,
        gitlab_host,
        requested_max_prs,
        max_prs,
        pr_numbers,
        exclude_prs,
        since,
        include_open,
        upload,
        distill,
        local_candidates,
        dry_run,
        json,
    })
}

/// Which provider this run targets, after flags + remote detection settle.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ResolvedProvider {
    Github,
    Gitlab { host: String },
}

/// Resolve the review provider from explicit flags first, then the git
/// remote. Detection is conservative (`ingest::provider`): github.com →
/// GitHub, gitlab.com or a PAT-configured host → GitLab, any other host →
/// error demanding an explicit `--provider` instead of guessing — a wrong
/// guess would import review history from the wrong API surface.
fn resolve_provider(
    provider: Option<ImportProviderArg>,
    gitlab_host: Option<&str>,
    remote_url: Option<&str>,
    configured_gitlab_hosts: &[String],
) -> Result<ResolvedProvider, String> {
    use difflore_core::ingest::gitlab::auth as gitlab_auth;
    use difflore_core::ingest::provider as ingest_provider;

    if let Some(host_input) = gitlab_host {
        if provider == Some(ImportProviderArg::Github) {
            return Err(
                "--gitlab-host conflicts with --provider github; drop one of the two.".to_owned(),
            );
        }
        let host = gitlab_auth::normalize_gitlab_host(host_input).map_err(|e| e.to_string())?;
        return Ok(ResolvedProvider::Gitlab { host });
    }

    match provider {
        Some(ImportProviderArg::Github) => Ok(ResolvedProvider::Github),
        Some(ImportProviderArg::Gitlab) => {
            // Forced GitLab without --gitlab-host: adopt the remote's host
            // when it plausibly is the instance, else default to gitlab.com.
            let host = remote_url
                .and_then(ingest_provider::remote_url_host)
                .filter(|host| host != "github.com")
                .unwrap_or_else(|| gitlab_auth::DEFAULT_GITLAB_HOST.to_owned());
            Ok(ResolvedProvider::Gitlab { host })
        }
        None => {
            // No remote (or a local-path remote): keep the long-standing
            // GitHub default — that path already reports a clear "--repo
            // required" error when nothing is detectable.
            let Some(url) = remote_url else {
                return Ok(ResolvedProvider::Github);
            };
            match ingest_provider::detect_provider_from_remote_url(url, configured_gitlab_hosts) {
                Some(ReviewProvider::Github) => Ok(ResolvedProvider::Github),
                Some(ReviewProvider::Gitlab) => {
                    let host = ingest_provider::remote_url_host(url)
                        .unwrap_or_else(|| gitlab_auth::DEFAULT_GITLAB_HOST.to_owned());
                    Ok(ResolvedProvider::Gitlab { host })
                }
                None => ingest_provider::remote_url_host(url).map_or(
                    Ok(ResolvedProvider::Github),
                    |host| {
                        Err(format!(
                            "Could not infer the review provider for remote host '{host}'.\n  \
                             Pass --provider github, or --provider gitlab --gitlab-host {host} for a self-managed GitLab.\n  \
                             Tip: `difflore auth gitlab --host {host}` stores a PAT and makes detection automatic next time."
                        ))
                    },
                ),
            }
        }
    }
}

fn resolve_local_repo(
    repo: Option<String>,
    from_upstream: Option<&str>,
    pp: &str,
) -> Result<String, String> {
    repo.or_else(|| difflore_core::ingest::github::detect_repo_from_remote(pp).ok())
        .ok_or_else(|| {
            let from_upstream_hint = if from_upstream.is_some() {
                "\n  · `--from-upstream` is set, but --repo is still required to declare the local target. \
                 Pass --repo to the same value if you want this repo to inherit the upstream's memory directly."
            } else {
                ""
            };
            format!(
                "Could not detect GitHub repo from git remote. \
                 Pass `--repo owner/repo` (the local repo to attach memory to).{from_upstream_hint}"
            )
        })
}

fn run_dry_run(v: &ValidatedArgs, local_repo: &str, source_repo: &str) {
    if v.json {
        println!(
            "{}",
            crate::support::util::json_or(&dry_run_payload(v, local_repo, source_repo), "{}")
        );
        return;
    }

    let label = if v.from_upstream.is_some() {
        format!("{source_repo} -> attach to {local_repo}")
    } else {
        local_repo.to_owned()
    };
    let open_part = if v.include_open {
        " (including open PRs)"
    } else {
        ""
    };
    style::println_wrapped(&format!(
        "{} Dry run | would import up to {} PRs from {label}{open_part}.",
        style::ok(style::sym::TIP),
        v.max_prs,
    ));
    if v.upload {
        style::println_wrapped(
            "  Would upload to cloud for extraction; `difflore cloud sync` then pulls rules down.",
        );
    }
    if v.local_candidates {
        let distill_label = distill_label(v.distill);
        style::println_wrapped(&format!(
            "  Would draft local rule candidates from high-signal review comments via {distill_label}; no cloud needed.",
        ));
        println!(
            "  Up to {} rule drafts would be created.",
            local_candidate_budget(v)
        );
    }
    println!(
        "  {}",
        style::pewter("(no DB writes, no network calls performed)")
    );
}

/// Deterministically order the exclude set for JSON output. The set itself is
/// unordered, so sorting keeps `--json` payloads stable for snapshot tests and
/// for an eval harness that diffs successive runs.
fn sorted_exclude_prs(exclude_prs: &std::collections::HashSet<i32>) -> Vec<i32> {
    let mut out: Vec<i32> = exclude_prs.iter().copied().collect();
    out.sort_unstable();
    out
}

const fn distill_wire(distill: ImportDistillArg) -> &'static str {
    match distill {
        ImportDistillArg::Heuristic => "heuristic",
        ImportDistillArg::LocalAgent => "local-agent",
    }
}

const fn distill_label(distill: ImportDistillArg) -> &'static str {
    match distill {
        ImportDistillArg::Heuristic => "local heuristics",
        ImportDistillArg::LocalAgent => "local-agent",
    }
}

fn dry_run_payload(v: &ValidatedArgs, local_repo: &str, source_repo: &str) -> serde_json::Value {
    serde_json::json!({
        "dryRun": true,
        "provider": "github",
        "repo": local_repo,
        "sourceRepo": source_repo,
        "fromUpstream": v.from_upstream.as_deref(),
        "maxPrs": v.max_prs,
        "requestedMaxPrs": v.requested_max_prs,
        "maxPrsClamped": v.requested_max_prs != v.max_prs,
        "prNumbers": v.pr_numbers,
        "excludePrs": sorted_exclude_prs(&v.exclude_prs),
        "includeOpen": v.include_open,
        "upload": v.upload,
        "localCandidates": v.local_candidates,
        "distill": distill_wire(v.distill),
        "localCandidateBudget": if v.local_candidates {
            Some(local_candidate_budget(v))
        } else {
            None
        },
        "writes": false,
        "networkCalls": false,
    })
}

fn run_gitlab_dry_run(v: &ValidatedArgs, host: &str, gitlab_project: &str) {
    if v.json {
        println!(
            "{}",
            crate::support::util::json_or(&gitlab_dry_run_payload(v, host, gitlab_project), "{}")
        );
        return;
    }
    style::println_wrapped(&format!(
        "{} Dry run | would import up to {} merged MRs from {host}/{gitlab_project}.",
        style::ok(style::sym::TIP),
        v.max_prs,
    ));
    if v.upload {
        style::println_wrapped(
            "  Would upload to cloud for extraction; `difflore cloud sync` then pulls rules down.",
        );
    }
    if v.local_candidates {
        let distill_label = distill_label(v.distill);
        style::println_wrapped(&format!(
            "  Would draft local rule candidates from high-signal review comments via {distill_label}; no cloud needed.",
        ));
        println!(
            "  Up to {} rule drafts would be created.",
            local_candidate_budget(v)
        );
    }
    println!(
        "  {}",
        style::pewter("(no DB writes, no network calls performed)")
    );
}

fn gitlab_dry_run_payload(
    v: &ValidatedArgs,
    host: &str,
    gitlab_project: &str,
) -> serde_json::Value {
    serde_json::json!({
        "dryRun": true,
        "provider": "gitlab",
        "gitlabHost": host,
        "repo": gitlab_project,
        "sourceRepo": gitlab_project,
        "maxPrs": v.max_prs,
        "requestedMaxPrs": v.requested_max_prs,
        "maxPrsClamped": v.requested_max_prs != v.max_prs,
        "prNumbers": v.pr_numbers,
        "excludePrs": sorted_exclude_prs(&v.exclude_prs),
        "upload": v.upload,
        "localCandidates": v.local_candidates,
        "distill": distill_wire(v.distill),
        "localCandidateBudget": if v.local_candidates {
            Some(local_candidate_budget(v))
        } else {
            None
        },
        "writes": false,
        "networkCalls": false,
    })
}

fn print_gitlab_import_plan(v: &ValidatedArgs, host: &str, gitlab_project: &str) {
    if v.json {
        return;
    }
    style::println_wrapped(&format!(
        "{} Import plan: scan {} from {host}/{gitlab_project}.",
        style::ok(style::sym::TIP),
        if v.pr_numbers.is_empty() {
            format!("up to {} merged MRs", v.max_prs)
        } else {
            format!(
                "MR {}",
                v.pr_numbers
                    .iter()
                    .map(|n| format!("!{n}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        },
    ));
    if !v.exclude_prs.is_empty() {
        let excluded = sorted_exclude_prs(&v.exclude_prs)
            .iter()
            .map(|n| format!("!{n}"))
            .collect::<Vec<_>>()
            .join(", ");
        style::println_wrapped(&format!(
            "  {} excluding {} (contributes zero rules)",
            style::pewter(style::sym::BULLET),
            excluded,
        ));
    }
    style::println_wrapped(&format!(
        "  {} preview only: {}",
        style::pewter(style::sym::BULLET),
        style::cmd("difflore import-reviews --dry-run"),
    ));
    style::println_wrapped(&format!(
        "  {} recovery: if GitLab throttles, retry with {} or {}.",
        style::pewter(style::sym::BULLET),
        style::cmd("--max-prs 20"),
        style::cmd("--since YYYY-MM-DD"),
    ));
}

fn print_import_plan(v: &ValidatedArgs, local_repo: &str, source_repo: &str) {
    if v.json {
        return;
    }
    let label = if v.from_upstream.is_some() {
        format!("{source_repo} -> attach to {local_repo}")
    } else {
        local_repo.to_owned()
    };
    style::println_wrapped(&format!(
        "{} Import plan: scan {} from {label}.",
        style::ok(style::sym::TIP),
        if v.pr_numbers.is_empty() {
            let pr_kind = if v.include_open {
                "merged/open PRs"
            } else {
                "merged PRs"
            };
            format!("up to {} {pr_kind}", v.max_prs)
        } else {
            format!(
                "PR {}",
                v.pr_numbers
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        },
    ));
    if !v.exclude_prs.is_empty() {
        let excluded = sorted_exclude_prs(&v.exclude_prs)
            .iter()
            .map(|n| format!("#{n}"))
            .collect::<Vec<_>>()
            .join(", ");
        style::println_wrapped(&format!(
            "  {} excluding {} (contributes zero rules)",
            style::pewter(style::sym::BULLET),
            excluded,
        ));
    }
    style::println_wrapped(&format!(
        "  {} preview only: {}",
        style::pewter(style::sym::BULLET),
        style::cmd("difflore import-reviews --dry-run"),
    ));
    style::println_wrapped(&format!(
        "  {} recovery: if GitHub throttles, retry with {} or {}.",
        style::pewter(style::sym::BULLET),
        style::cmd("--max-prs 20"),
        style::cmd("--since YYYY-MM-DD"),
    ));
}

async fn run_import(
    db: &SqlitePool,
    opts: ImportOptions,
    repo: &str,
    source_repo: &str,
    upload: bool,
    json: bool,
) -> Result<ImportProgress, String> {
    if json {
        let result = match difflore_core::ingest::github::import_pr_reviews(db, opts, None).await {
            Ok(r) => r,
            Err(e) => return Err(format_github_import_err("Import failed", &e.to_string())),
        };
        return Ok(result);
    }

    let spinner_label = format!("Importing PR reviews from {source_repo}");
    let spinner = style::Spinner::new(&spinner_label);
    let spinner_progress = spinner.handle();

    let empty_pr_kind = if opts.include_open {
        "merged/open PRs"
    } else {
        "merged PRs"
    };
    let direct_pr_mode = !opts.pr_numbers.is_empty();
    let progress_cb: Box<dyn Fn(&ImportProgress) + Send> = Box::new(move |p| {
        if p.prs_total > 0 && p.prs_fetched > 0 {
            let skipped_part = if p.comments_skipped > 0 {
                format!(" ({} skipped)", p.comments_skipped)
            } else {
                String::new()
            };
            spinner_progress.println(&format!(
                "  [{}/{}] {} comments imported{}",
                p.prs_fetched, p.prs_total, p.comments_imported, skipped_part
            ));
        } else if p.prs_total > 0 {
            spinner_progress.println(&format!(
                "  {} PRs with review activity to import",
                p.prs_total
            ));
        } else if direct_pr_mode && p.prs_missing > 0 {
            spinner_progress.println(&format!(
                "  No requested PRs with review activity found ({} missing/inaccessible).",
                p.prs_missing
            ));
        } else {
            spinner_progress.println(&format!("  No {empty_pr_kind} with review activity found."));
        }
    });

    let result =
        match difflore_core::ingest::github::import_pr_reviews(db, opts, Some(progress_cb)).await {
            Ok(r) => r,
            Err(e) => {
                spinner.finish_err("Import failed");
                return Err(format_github_import_err("Import failed", &e.to_string()));
            }
        };

    spinner.finish_ok(&format!(
        "Imported {} PRs from {}",
        result.prs_fetched, source_repo,
    ));
    if source_repo != repo {
        println!("  attached to local repo: {}", style::pewter(repo));
    }
    println!("  review comments:        {}", result.comments_imported);
    if result.comments_skipped > 0 {
        println!("  skipped:                {}", result.comments_skipped);
    }
    if result.prs_missing > 0 {
        let missing = result
            .missing_pr_numbers
            .iter()
            .map(|n| format!("#{n}"))
            .collect::<Vec<_>>()
            .join(", ");
        println!("  missing PRs:            {missing}");
    }
    // Phrase as "requested": upload runs after this summary, so a later
    // failure must not contradict an earlier "uploaded: yes".
    println!(
        "  upload requested:       {}",
        if upload { "yes" } else { "no" }
    );
    println!();
    if upload {
        println!(
            "  {} Uploading imported comments for extraction...",
            style::emerald(style::sym::TIP),
        );
    } else if result.comments_imported > 0 {
        println!(
            "  {} Imports stayed local.",
            style::emerald(style::sym::TIP),
        );
        style::println_wrapped("    Drafting review candidates from high-signal comments...");
    }
    Ok(result)
}

async fn run_local_candidate_distillation(
    db: &SqlitePool,
    source: &str,
    repo: &str,
    source_repo: &RepoScope,
    v: &ValidatedArgs,
) -> LocalCandidateProgress {
    let budget = local_candidate_budget(v);
    if v.distill == ImportDistillArg::LocalAgent {
        match run_local_agent_candidates(
            db,
            source,
            repo,
            source_repo,
            budget,
            &v.pr_numbers,
            &v.exclude_prs,
        )
        .await
        {
            Ok(progress) => return progress,
            Err(e) => {
                if difflore_core::infra::env::debug_telemetry() {
                    eprintln!(
                        "[difflore.import_reviews] local-agent distill failed; falling back to heuristic: {e}"
                    );
                }
            }
        }
    }

    run_local_candidates(
        db,
        source,
        repo,
        source_repo,
        budget,
        &v.pr_numbers,
        &v.exclude_prs,
    )
    .await
}

/// The fields rendered into the `--json` import report. Built once at the call
/// site and passed by reference so the (formerly duplicated) 10-argument list
/// can't be reordered: several fields share a type (`provider`/`repo`/
/// `source_repo` are all `&str`; `max_prs`/`requested_max_prs`/
/// `uploaded_reviews` are all `usize`), where a positional swap compiles
/// silently.
struct ImportReport<'a> {
    provider: &'a str,
    gitlab_host: Option<&'a str>,
    repo: &'a str,
    source_repo: &'a str,
    max_prs: usize,
    requested_max_prs: usize,
    result: &'a ImportProgress,
    distill: ImportDistillArg,
    local_candidates: Option<&'a LocalCandidateProgress>,
    uploaded_reviews: usize,
}

fn print_import_json(report: &ImportReport<'_>) {
    let payload = import_json_payload(report);
    println!("{}", crate::support::util::json_or(&payload, "{}"));
}

fn import_json_payload(report: &ImportReport<'_>) -> serde_json::Value {
    let result = report.result;
    serde_json::json!({
        "provider": report.provider,
        "gitlabHost": report.gitlab_host,
        "repo": report.repo,
        "sourceRepo": report.source_repo,
        "maxPrs": report.max_prs,
        "requestedMaxPrs": report.requested_max_prs,
        "maxPrsClamped": report.requested_max_prs != report.max_prs,
        "prsFetched": result.prs_fetched,
        "prsTotal": result.prs_total,
        "commentsImported": result.comments_imported,
        "commentsSkipped": result.comments_skipped,
        "prsMissing": result.prs_missing,
        "missingPrNumbers": &result.missing_pr_numbers,
        "uploadedReviews": report.uploaded_reviews,
        "cloudUploadQueued": report.uploaded_reviews > 0,
        "localCandidates": report.local_candidates.map(|p| serde_json::json!({
            "distill": distill_wire(report.distill),
            "commentsConsidered": p.comments_considered,
            "candidatesCreated": p.candidates_created,
            "candidatesActivated": p.candidates_activated,
            "candidatesPending": p.candidates_pending,
            "candidatesDeduped": p.candidates_deduped,
            "candidatesMatchedActive": p.candidates_matched_active,
            "candidatesSuppressedRejected": p.candidates_suppressed_rejected,
            "candidateBudget": p.budget,
            "commentsSkipped": p.comments_skipped,
            "capped": p.capped,
        })),
    })
}

pub(crate) async fn handle(ctx: &CommandContext, args: ImportArgs) -> anyhow::Result<()> {
    if let Some(timeout_secs) = args.wall_timeout_secs {
        let timeout_secs = timeout_secs.max(1);
        let run = try_handle(ctx, args);
        match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run).await {
            Ok(result) => {
                result.map_err(anyhow::Error::msg)?;
            }
            Err(_) => {
                return Err(anyhow::Error::msg(format!(
                    "import-reviews timed out after {timeout_secs}s"
                )));
            }
        }
    } else {
        try_handle(ctx, args).await.map_err(anyhow::Error::msg)?;
    }
    Ok(())
}

pub(crate) async fn try_handle(
    ctx: &CommandContext,
    args: ImportArgs,
) -> Result<ImportRunOutcome, String> {
    let v = validate_args(args)?;

    let pp = project_path();
    let remote_url = difflore_core::ingest::provider::git_remote_origin_url(&pp);
    // PAT-configured self-managed hosts only matter for auto-detection, so
    // skip the auth-db read when an explicit flag already decides.
    let configured_hosts = if v.provider.is_none() && v.gitlab_host.is_none() {
        difflore_core::ingest::gitlab::auth::configured_hosts().await
    } else {
        Vec::new()
    };
    let provider = resolve_provider(
        v.provider,
        v.gitlab_host.as_deref(),
        remote_url.as_deref(),
        &configured_hosts,
    )?;

    match provider {
        ResolvedProvider::Github => try_handle_github(ctx, &pp, v).await,
        ResolvedProvider::Gitlab { host } => {
            try_handle_gitlab(ctx, &pp, remote_url.as_deref(), &host, v).await
        }
    }
}

async fn try_handle_github(
    ctx: &CommandContext,
    pp: &str,
    v: ValidatedArgs,
) -> Result<ImportRunOutcome, String> {
    if let Some(r) = v.repo.as_deref()
        && let Err(msg) = validate_owner_repo(r)
    {
        return Err(format!("--repo '{r}' is invalid: {msg}"));
    }
    if let Some(r) = v.from_upstream.as_deref()
        && let Err(msg) = validate_owner_repo(r)
    {
        return Err(format!("--from-upstream '{r}' is invalid: {msg}"));
    }

    let db = &ctx.db;
    let project = ensure_project(db, pp).await.map_err(|e| e.to_string())?;

    let local_repo = resolve_local_repo(v.repo.clone(), v.from_upstream.as_deref(), pp)?;
    let source_repo = v
        .from_upstream
        .clone()
        .unwrap_or_else(|| local_repo.clone());
    let source_repo_scope = RepoScope::github(&source_repo)
        .ok_or_else(|| format!("--from-upstream '{source_repo}' is invalid for GitHub"))?;

    if v.dry_run {
        run_dry_run(&v, &local_repo, &source_repo);
        return Ok(ImportRunOutcome);
    }

    if v.upload {
        ensure_cloud_session_for_upload(ctx).await?;
    }

    print_import_plan(&v, &local_repo, &source_repo);

    if let Err(e) = verify_source_repo_access(&source_repo) {
        return Err(format_github_import_err("Import failed", &e));
    }

    let opts = ImportOptions {
        repo: local_repo.clone(),
        source_repo: source_repo.clone(),
        project_id: project.id,
        max_prs: v.max_prs,
        pr_numbers: v.pr_numbers.clone(),
        exclude_prs: v.exclude_prs.clone(),
        since: v.since.clone(),
        upload_to_cloud: v.upload,
        include_open: v.include_open,
    };

    let import_result = run_import(db, opts, &local_repo, &source_repo, v.upload, v.json).await?;

    let local_candidate_progress = if v.local_candidates {
        let progress =
            run_local_candidate_distillation(db, "github", &local_repo, &source_repo_scope, &v)
                .await;
        if !v.json {
            print_local_candidate_next_steps(&progress, &local_repo);
        }
        if progress.candidates_pending > 0 {
            crate::commands::memory::mark_memory_autopilot_dirty_best_effort(db, "import_reviews")
                .await;
            crate::commands::memory::schedule_memory_autopilot_best_effort(
                db,
                "import_reviews",
                difflore_core::memory_autopilot_schedule::EXPLICIT_AUTOPILOT_COOLDOWN_SECS,
            )
            .await;
        }
        Some(progress)
    } else {
        None
    };

    let uploaded_reviews = if v.upload {
        run_upload(ctx, db, "github", &local_repo, None, &import_result, v.json).await?
    } else {
        0
    };

    if v.json {
        print_import_json(&ImportReport {
            provider: "github",
            gitlab_host: None,
            repo: &local_repo,
            source_repo: &source_repo,
            max_prs: v.max_prs,
            requested_max_prs: v.requested_max_prs,
            result: &import_result,
            distill: v.distill,
            local_candidates: local_candidate_progress.as_ref(),
            uploaded_reviews,
        });
    }
    Ok(ImportRunOutcome)
}

async fn try_handle_gitlab(
    ctx: &CommandContext,
    pp: &str,
    remote_url: Option<&str>,
    host: &str,
    v: ValidatedArgs,
) -> Result<ImportRunOutcome, String> {
    // Flags whose semantics don't exist in the GitLab v1 importer fail loud
    // instead of being silently ignored.
    if v.from_upstream.is_some() {
        return Err(
            "--from-upstream is GitHub-only for now; GitLab imports read the project directly \
             (pass --repo group/project)."
                .to_owned(),
        );
    }
    if v.include_open {
        return Err(
            "--include-open is not supported for GitLab yet; the GitLab importer reads merged \
             MRs only."
                .to_owned(),
        );
    }

    let gitlab_project = resolve_gitlab_project_path(v.repo.clone(), remote_url, host)?;
    difflore_core::ingest::provider::validate_gitlab_project_path(&gitlab_project)
        .map_err(|msg| format!("--repo is invalid for GitLab: {msg}"))?;
    let gitlab_repo_scope = RepoScope::gitlab(host, &gitlab_project)
        .ok_or_else(|| format!("--repo is invalid for GitLab: {gitlab_project}"))?;

    if v.dry_run {
        run_gitlab_dry_run(&v, host, &gitlab_project);
        return Ok(ImportRunOutcome);
    }

    if v.upload {
        ensure_cloud_session_for_upload(ctx).await?;
    }

    print_gitlab_import_plan(&v, host, &gitlab_project);

    let Some((token, _source)) = difflore_core::ingest::gitlab::auth::resolve_token(host).await
    else {
        return Err(missing_gitlab_token_error(host));
    };

    verify_gitlab_project_access(host, &token, &gitlab_project).await?;

    let db = &ctx.db;
    let project = ensure_project(db, pp).await.map_err(|e| e.to_string())?;
    let opts = difflore_core::ingest::gitlab::ImportOptions {
        host: host.to_owned(),
        project_path: gitlab_project.clone(),
        project_id: project.id,
        token,
        max_mrs: v.max_prs,
        // `--pr` carries MR IIDs in the GitLab context (flag reuse by design).
        mr_iids: v.pr_numbers.clone(),
        exclude_mrs: v.exclude_prs.clone(),
        since: v.since.clone(),
    };

    let import_result = run_gitlab_import(db, opts, v.upload, v.json).await?;

    let local_candidate_progress = if v.local_candidates {
        let progress =
            run_local_candidate_distillation(db, "gitlab", &gitlab_project, &gitlab_repo_scope, &v)
                .await;
        if !v.json {
            print_local_candidate_next_steps(&progress, &gitlab_project);
        }
        if progress.candidates_pending > 0 {
            crate::commands::memory::mark_memory_autopilot_dirty_best_effort(db, "import_reviews")
                .await;
            crate::commands::memory::schedule_memory_autopilot_best_effort(
                db,
                "import_reviews",
                difflore_core::memory_autopilot_schedule::EXPLICIT_AUTOPILOT_COOLDOWN_SECS,
            )
            .await;
        }
        Some(progress)
    } else {
        None
    };

    let uploaded_reviews = if v.upload {
        run_upload(
            ctx,
            db,
            "gitlab",
            &gitlab_project,
            Some(host),
            &import_result,
            v.json,
        )
        .await?
    } else {
        0
    };

    if v.json {
        print_import_json(&ImportReport {
            provider: "gitlab",
            gitlab_host: Some(host),
            repo: &gitlab_project,
            source_repo: gitlab_repo_scope.as_str(),
            max_prs: v.max_prs,
            requested_max_prs: v.requested_max_prs,
            result: &import_result,
            distill: v.distill,
            local_candidates: local_candidate_progress.as_ref(),
            uploaded_reviews,
        });
    }
    Ok(ImportRunOutcome)
}

/// `--repo` wins; otherwise the namespace path comes from the git remote,
/// but only when the remote actually points at the resolved host — silently
/// importing `group/project` from the wrong instance would be worse than
/// asking for the flag.
fn resolve_gitlab_project_path(
    repo: Option<String>,
    remote_url: Option<&str>,
    host: &str,
) -> Result<String, String> {
    if let Some(repo) = repo {
        return Ok(repo);
    }
    remote_url
        .and_then(difflore_core::ingest::provider::remote_url_host_and_path)
        .filter(|(remote_host, _)| remote_host.eq_ignore_ascii_case(host))
        .map(|(_, path)| path)
        .filter(|path| !path.is_empty())
        .ok_or_else(|| {
            format!(
                "Could not detect the GitLab project path from the git remote for {host}.\n  \
                 Pass `--repo group/project` (subgroups allowed, e.g. group/subgroup/project)."
            )
        })
}

fn missing_gitlab_token_error(host: &str) -> String {
    format!(
        "No GitLab token found for {host}.\n  \
         Store one first: echo \"<TOKEN>\" | difflore auth gitlab --host {host}\n  \
         Or set DIFFLORE_GITLAB_TOKEN / GITLAB_TOKEN in this shell.\n  \
         Mint a PAT with the read_api scope at https://{host}/-/user_settings/personal_access_tokens"
    )
}

#[cfg(test)]
#[allow(unsafe_code)] // reason: test home is pinned once so remember_as_candidate never writes to the user's real home.
mod tests {

    use std::collections::HashSet;

    use crate::cli::ImportDistillArg;
    use crate::support::review_text::strip_review_markdown_noise;
    use difflore_core::infra::git::RepoScope;
    use difflore_core::ingest::github::ImportProgress;

    use super::fixtures::{
        fresh_import_pool, imported_item, review, seed_gitlab_pr_with_directive,
        seed_imported_review_comments, seed_imported_review_comments_with_resolution,
        seed_pr_with_directive,
    };
    use super::github::{format_github_import_err, gh_repo_view_failure_detail};
    use super::gitlab::format_gitlab_import_err;
    use super::local_candidates::{
        CAPTURE_CONFIDENCE_HIGH, CAPTURE_CONFIDENCE_LOW, CaptureRoute,
        active_candidate_next_step_commands, candidate_title, clean_review_comment,
        distilled_rule_statement, is_high_signal_review_comment_for_paths, local_candidate_budget,
        local_candidate_budget_reached, local_candidate_input,
        pending_candidate_next_step_commands, pending_drafts_review_hint, route_for_confidence,
        run_local_candidates,
    };
    use super::scope::file_pattern_from_path;
    use super::upload::{
        build_upload_batches, cloud_upload_next_step_commands, comment_event_type,
        comment_file_path_from_metadata, gitlab_host_from_metadata, imported_review_upload,
        matches_upload_target,
    };
    use super::{ImportArgs, ImportReport, dry_run_payload, import_json_payload, validate_args};

    fn github_scope(repo: &str) -> RepoScope {
        RepoScope::github(repo).expect("test GitHub repo scope")
    }

    fn gitlab_scope(host: &str, repo: &str) -> RepoScope {
        RepoScope::gitlab(host, repo).expect("test GitLab repo scope")
    }

    #[test]
    fn strip_review_markdown_noise_drops_severity_banners_and_emphasis() {
        let raw = "_⚠️ Potential issue_ | _🟡 Minor_ Wait for the async submit \
                   path before asserting state.";
        let out = strip_review_markdown_noise(raw);
        assert!(!out.contains('_'), "underscores remain: {out}");
        assert!(!out.contains(''), "emoji remain: {out}");
        assert!(
            !out.to_ascii_lowercase().contains("potential issue"),
            "banner: {out}"
        );
        assert!(
            !out.to_ascii_lowercase().contains("minor"),
            "severity: {out}"
        );
        assert!(out.starts_with("Wait for the async submit"), "got: {out}");
    }

    #[test]
    fn strip_review_markdown_noise_keeps_real_prose() {
        let raw = "**Use** `errors.Is` rather than `==` when comparing wrapped errors.";
        let out = strip_review_markdown_noise(raw);
        assert!(out.contains("Use"));
        assert!(out.contains("errors.Is"));
        assert!(!out.contains('*'));
    }

    #[test]
    fn clean_review_comment_strips_coderabbit_summary_wrappers() {
        let raw = "<details>\n<summary>Actionable comments posted: 3</summary>\n\n\
                   _⚠️ Potential issue_ | _🟡 Minor_\n\n\
                   Wait for the async submit path before asserting state.\n\
                   </details>";
        let out = clean_review_comment(raw);
        assert!(!out.contains("details"), "html residue: {out}");
        assert!(!out.contains("Actionable"), "banner: {out}");
        assert!(!out.contains('_'), "emphasis: {out}");
        assert!(out.starts_with("Wait for the async submit"), "got: {out}");
    }

    #[test]
    fn clean_review_comment_strips_outside_diff_platform_warning_lines() {
        let raw = "[!CAUTION]\n\
                   Some comments are outside the diff and cannot be posted inline.\n\
                   Outside diff range comments (14)\n\
                   Prefer checking the parsed header before indexing into it.";
        let out = clean_review_comment(raw);

        assert!(!out.contains("[!CAUTION]"), "caution residue: {out}");
        assert!(!out.contains("outside the diff"), "platform residue: {out}");
        assert!(
            out.starts_with("Prefer checking the parsed header"),
            "got: {out}"
        );
    }

    #[test]
    fn candidate_title_uses_clean_first_sentence() {
        let raw = "_⚠️ Potential issue_ | _🟡 Minor_ Wait for the async submit \
                   path before asserting state. The current code races.";
        let title = candidate_title(raw, "form-core/src/index.ts");
        assert!(
            title.starts_with("Review: Wait for the async submit"),
            "got: {title}"
        );
        assert!(!title.contains(''));
        assert!(!title.contains('_'));
    }

    #[test]
    fn candidate_title_normalizes_review_chatter_for_dedup() {
        let a = candidate_title(
            "Please prefer Mapping[str, str] here instead of dict[str, str]. It keeps callers flexible.",
            "src/http/headers.py",
        );
        let b = candidate_title(
            "We should prefer Mapping[str, str] here instead of dict[str, str]. It keeps callers flexible.",
            "src/http/headers.py",
        );

        assert_eq!(
            a,
            "Review: Prefer Mapping[str, str] here instead of dict[str, str]"
        );
        assert_eq!(a, b);
    }

    #[test]
    fn format_github_import_err_classifies_known_and_falls_through_unknown() {
        // (raw, must-contain): one row per branch in format_github_import_err.
        let cases: &[(&str, &str)] = &[
            ("GitHub CLI (gh) is not installed", "cli.github.com"),
            (
                "gh api graphql error: HTTP 401: Bad credentials",
                "auth missing or expired",
            ),
            (
                "GraphQL errors: Could not resolve to a Repository with the name 'foo/bar'.",
                "gh repo view",
            ),
            (
                "GraphQL errors: Resource not accessible by personal access token",
                "gh auth refresh",
            ),
            (
                "gh api graphql error: API rate limit exceeded",
                "rate limit",
            ),
        ];
        for (raw, expect) in cases {
            let out = format_github_import_err("Import failed", raw);
            assert!(
                out.contains(expect),
                "want {expect:?} for {raw:?}, got: {out}"
            );
        }

        let rate_limited =
            format_github_import_err("Import failed", "gh api graphql error: rate limit exceeded");
        assert!(rate_limited.contains("--max-prs 20"));
        assert!(rate_limited.contains("--dry-run"));

        // All branches except the trivially-actionable "gh not installed" one
        // must retain the raw stderr at the tail. The actionable framing is
        // the prefix; raw is the suffix that keeps bug reports debuggable.
        let raw_required: &[&str] = &[
            "gh api graphql error: HTTP 401: Bad credentials",
            "GraphQL errors: Could not resolve to a Repository with the name 'foo/bar'.",
            "GraphQL errors: Resource not accessible by personal access token",
            "gh api graphql error: API rate limit exceeded",
            "request failed: connection refused",
            "request timed out after 30s",
        ];
        for raw in raw_required {
            let out = format_github_import_err("Import failed", raw);
            assert!(
                out.contains(raw) && out.contains("raw:"),
                "raw input {raw:?} not retained at tail in: {out}"
            );
        }

        // Unknown errors fall through verbatim — never silently swallowed.
        assert_eq!(
            format_github_import_err("Import failed", "novel github error xyz"),
            "Import failed: novel github error xyz"
        );
    }

    #[test]
    fn format_gitlab_import_err_classifies_statuses_with_actionable_recovery() {
        let host = "gitlab.corp.example";
        // (raw, must-contain): one row per branch in format_gitlab_import_err.
        let cases: &[(&str, &str)] = &[
            (
                "GitLab API error: HTTP 401 Unauthorized for GET /api/v4/projects/g%2Fp",
                "read_api",
            ),
            (
                "GitLab API error: HTTP 404 Not Found for GET /api/v4/projects/g%2Fp",
                "404 — not 403",
            ),
            (
                "GitLab API error: HTTP 403 Forbidden for GET /api/v4/projects/g%2Fp",
                "IP allowlists",
            ),
            (
                "GitLab API error: HTTP 429 Too Many Requests for GET /api/v4/projects/g%2Fp",
                "--max-prs 20",
            ),
            (
                "GitLab API error: HTTP 503 Service Unavailable for GET /api/v4/projects/g%2Fp",
                "rerun the same command",
            ),
            (
                "GitLab API request failed for GET /api/v4/projects/g%2Fp: invalid peer certificate",
                "trusted at the OS level",
            ),
            (
                "GitLab API request failed for GET /api/v4/projects/g%2Fp: operation timed out",
                "VPN/proxy",
            ),
            (
                "GitLab API request failed for GET /api/v4/projects/g%2Fp: dns error: failed to lookup address",
                "--gitlab-host",
            ),
            // Windows connection reset, rendered through the reqwest source
            // chain (observed live against an unreachable host).
            (
                "GitLab API request failed for GET /api/v4/projects/g%2Fp: error sending request for url (https://h/): client error (Connect): An existing connection was forcibly closed by the remote host. (os error 10054)",
                "--gitlab-host",
            ),
        ];
        for (raw, expect) in cases {
            let out = format_gitlab_import_err("Import failed", host, raw);
            assert!(
                out.contains(expect),
                "want {expect:?} for {raw:?}, got: {out}"
            );
            assert!(
                out.contains(raw) && out.contains("raw:"),
                "raw input {raw:?} not retained at tail in: {out}"
            );
        }

        // Auth-shaped errors must point at the instance's PAT settings page.
        let unauthorized = format_gitlab_import_err(
            "Import failed",
            host,
            "GitLab API error: HTTP 401 Unauthorized for GET /api/v4/projects/g%2Fp",
        );
        assert!(unauthorized.contains(&format!(
            "https://{host}/-/user_settings/personal_access_tokens"
        )));
        assert!(unauthorized.contains(&format!("difflore auth gitlab --host {host}")));

        // The 404 path must explain the GitLab quirk (no-access private
        // projects answer 404, not 403) so users check BOTH path and scope.
        let missing = format_gitlab_import_err(
            "Import failed",
            host,
            "GitLab API error: HTTP 404 Not Found for GET /api/v4/projects/g%2Fp",
        );
        assert!(missing.contains("wrong project path or a permission gap"));

        // Unknown errors fall through to the generic core mapper, never
        // silently swallowed.
        assert_eq!(
            format_gitlab_import_err("Import failed", host, "novel gitlab error xyz"),
            "Import failed: novel gitlab error xyz"
        );
    }

    #[test]
    fn provider_resolution_prefers_flags_then_remote_then_errors_on_unknown_hosts() {
        use super::{ImportProviderArg, ResolvedProvider, resolve_provider};

        let gitlab = |host: &str| ResolvedProvider::Gitlab {
            host: host.to_owned(),
        };

        // Explicit --gitlab-host wins and implies the gitlab provider.
        assert_eq!(
            resolve_provider(
                None,
                Some("GitLab.Corp.Example"),
                Some("https://github.com/o/r.git"),
                &[],
            ),
            Ok(gitlab("gitlab.corp.example"))
        );
        // ...but conflicts with an explicit github provider.
        assert!(
            resolve_provider(
                Some(ImportProviderArg::Github),
                Some("gitlab.corp.example"),
                None,
                &[],
            )
            .is_err()
        );

        // Explicit provider flags decide without a remote.
        assert_eq!(
            resolve_provider(Some(ImportProviderArg::Github), None, None, &[]),
            Ok(ResolvedProvider::Github)
        );
        assert_eq!(
            resolve_provider(Some(ImportProviderArg::Gitlab), None, None, &[]),
            Ok(gitlab("gitlab.com"))
        );
        // Forced gitlab adopts a plausible remote host...
        assert_eq!(
            resolve_provider(
                Some(ImportProviderArg::Gitlab),
                None,
                Some("git@gitlab.corp.example:group/project.git"),
                &[],
            ),
            Ok(gitlab("gitlab.corp.example"))
        );
        // ...but never adopts github.com as a GitLab instance.
        assert_eq!(
            resolve_provider(
                Some(ImportProviderArg::Gitlab),
                None,
                Some("https://github.com/o/r.git"),
                &[],
            ),
            Ok(gitlab("gitlab.com"))
        );

        // Auto-detection: known hosts map to their provider.
        assert_eq!(
            resolve_provider(None, None, Some("git@github.com:o/r.git"), &[]),
            Ok(ResolvedProvider::Github)
        );
        assert_eq!(
            resolve_provider(None, None, Some("https://gitlab.com/g/p.git"), &[]),
            Ok(gitlab("gitlab.com"))
        );
        // PAT-configured self-managed hosts detect automatically.
        assert_eq!(
            resolve_provider(
                None,
                None,
                Some("https://gitlab.corp.example/g/p.git"),
                &["gitlab.corp.example".to_owned()],
            ),
            Ok(gitlab("gitlab.corp.example"))
        );

        // Unknown host: refuse to guess, demand an explicit provider.
        let err = resolve_provider(None, None, Some("https://gitea.corp.example/o/r.git"), &[])
            .expect_err("unknown host must not be guessed");
        assert!(err.contains("--provider gitlab --gitlab-host gitea.corp.example"));
        assert!(err.contains("--provider github"));

        // No remote / local-path remote: legacy GitHub default.
        assert_eq!(
            resolve_provider(None, None, None, &[]),
            Ok(ResolvedProvider::Github)
        );
        assert_eq!(
            resolve_provider(None, None, Some("/srv/git/repo.git"), &[]),
            Ok(ResolvedProvider::Github)
        );
    }

    #[test]
    fn gitlab_project_path_comes_from_flag_or_matching_remote_only() {
        use super::resolve_gitlab_project_path;

        // --repo wins unconditionally.
        assert_eq!(
            resolve_gitlab_project_path(
                Some("group/sub/project".to_owned()),
                Some("https://elsewhere.example/x/y.git"),
                "gitlab.com",
            ),
            Ok("group/sub/project".to_owned())
        );
        // Remote path is used when the remote host matches the instance.
        assert_eq!(
            resolve_gitlab_project_path(
                None,
                Some("git@gitlab.com:group/sub/project.git"),
                "gitlab.com",
            ),
            Ok("group/sub/project".to_owned())
        );
        // Host mismatch → require the flag instead of importing from the
        // wrong instance.
        let err = resolve_gitlab_project_path(
            None,
            Some("git@gitlab.com:group/project.git"),
            "gitlab.corp.example",
        )
        .expect_err("mismatched remote host must not leak a project path");
        assert!(err.contains("--repo group/project"));
        assert!(
            resolve_gitlab_project_path(None, None, "gitlab.com").is_err(),
            "no remote and no flag must error"
        );
    }

    #[test]
    fn gh_repo_view_failure_detail_ignores_stdout_warnings() {
        let detail = gh_repo_view_failure_detail(
            "acme/widgets",
            "exit status: 1",
            b"warning: extension update available\n{\"nameWithOwner\":\"acme/widgets\"}\n",
            b"GraphQL: Could not resolve to a Repository with the name 'acme/widgets'.\n",
        );

        assert_eq!(
            detail,
            "GraphQL: Could not resolve to a Repository with the name 'acme/widgets'."
        );

        let fallback = gh_repo_view_failure_detail(
            "acme/widgets",
            "exit status: 1",
            b"warning: extension update available\n",
            b"",
        );
        assert_eq!(
            fallback,
            "gh repo view acme/widgets failed with status exit status: 1"
        );
    }

    #[test]
    fn upload_batches_split_large_reviews_by_comment_count() {
        let batches = build_upload_batches(&[review(1, 181)]);
        let counts: Vec<usize> = batches
            .iter()
            .flat_map(|batch| batch.iter().map(|r| r.comments.len()))
            .collect();
        assert_eq!(counts, vec![20, 20, 20, 20, 20, 20, 20, 20, 20, 1]);
    }

    #[test]
    fn upload_batches_keep_small_reviews_under_batch_limits() {
        let reviews = (1..=25).map(|pr| review(pr, 1)).collect::<Vec<_>>();
        let batches = build_upload_batches(&reviews);
        assert_eq!(batches.len(), 2);
        assert_eq!(batches[0].len(), 20);
        assert_eq!(batches[1].len(), 5);
    }

    #[test]
    fn import_upload_payload_attaches_to_local_repo_and_keeps_upstream_source() {
        let item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(upload.repo_full_name, "user/fork");
        assert_eq!(
            upload.source_repo_full_name.as_deref(),
            Some("upstream/project")
        );
        assert_eq!(upload.pr_number, 7);
        assert_eq!(upload.comments.len(), 1);
    }

    #[test]
    fn import_upload_payload_preserves_gitlab_provider_and_host() {
        let mut item = imported_item(
            Some("group/sub/project"),
            Some(
                r#"{"gitlabHost":"GitLab.Corp.Example","sourceRepoFullName":"group/sub/project"}"#,
            ),
        );
        item.item.source = "gitlab".to_owned();

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(upload.provider.as_deref(), Some("gitlab"));
        assert_eq!(upload.provider_host.as_deref(), Some("gitlab.corp.example"));
        assert_eq!(
            upload.repo_full_name,
            "gitlab.corp.example/group/sub/project"
        );
        assert_eq!(upload.source_repo_full_name, None);
        assert_eq!(
            gitlab_host_from_metadata(Some(r#"{"gitlabHost":"https://gitlab.corp.example/"}"#))
                .as_deref(),
            Some("gitlab.corp.example")
        );
        assert_eq!(
            gitlab_host_from_metadata(Some(r#"{"gitlabHost":"https://gitlab.corp.example/g/p"}"#)),
            None
        );
    }

    #[test]
    fn upload_target_filters_gitlab_reviews_by_host_dimension() {
        let mut corp_item = imported_item(
            Some("group/project"),
            Some(r#"{"gitlabHost":"gitlab.corp.example"}"#),
        );
        corp_item.item.source = "gitlab".to_owned();
        let mut dotcom_item = imported_item(
            Some("group/project"),
            Some(r#"{"gitlabHost":"gitlab.com"}"#),
        );
        dotcom_item.item.source = "gitlab".to_owned();

        assert!(matches_upload_target(
            &corp_item,
            "gitlab",
            "group/project",
            Some("gitlab.corp.example"),
        ));
        assert!(!matches_upload_target(
            &dotcom_item,
            "gitlab",
            "group/project",
            Some("gitlab.corp.example"),
        ));
        assert!(matches_upload_target(
            &dotcom_item,
            "gitlab",
            "group/project",
            Some("https://gitlab.com/"),
        ));
        assert!(
            !matches_upload_target(&corp_item, "gitlab", "group/project", None),
            "GitLab upload filtering must fail closed without the requested host"
        );
    }

    #[test]
    fn import_upload_payload_does_not_invent_source_repo_without_metadata() {
        let item = imported_item(Some("user/fork"), None);

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(upload.repo_full_name, "user/fork");
        assert_eq!(upload.source_repo_full_name, None);
    }

    #[test]
    fn import_upload_payload_canonicalizes_gitlab_source_repo() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"gitlabHost":"gitlab.com","sourceRepoFullName":"upstream/project"}"#),
        );
        item.item.source = "gitlab".to_owned();

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(upload.repo_full_name, "gitlab.com/user/fork");
        assert_eq!(
            upload.source_repo_full_name.as_deref(),
            Some("gitlab.com/upstream/project")
        );
    }

    #[test]
    fn import_upload_payload_preserves_inline_comment_file_path() {
        let mut item = imported_item(Some("user/fork"), None);
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","sourceRepoFullName":"user/fork","attachedRepoFullName":"user/fork","resolved":true}"#
                .to_owned(),
        );

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(
            upload.comments[0].file_path.as_deref(),
            Some("src/http/request.rs"),
            "the inline comment's path must flow into the cloud payload so extraction can derive file_patterns"
        );
    }

    #[test]
    fn import_upload_payload_leaves_file_path_none_without_a_recorded_path() {
        // Legacy rows / top-level review bodies carry no per-comment metadata.
        let item = imported_item(Some("user/fork"), None);
        let upload = imported_review_upload(&item).expect("review with comments should upload");
        assert_eq!(upload.comments[0].file_path, None);

        // Explicit null, blank, and unparseable metadata all degrade to None
        // rather than erroring or uploading an empty-string path.
        assert_eq!(
            comment_file_path_from_metadata(Some(r#"{"filePath":null}"#)),
            None
        );
        assert_eq!(
            comment_file_path_from_metadata(Some(r#"{"filePath":"  "}"#)),
            None
        );
        assert_eq!(comment_file_path_from_metadata(Some("not json")), None);
        assert_eq!(comment_file_path_from_metadata(None), None);
    }

    #[test]
    fn import_upload_payload_labels_inline_comments_as_review_comments() {
        use difflore_core::contract::ImportedCommentEventType;

        let mut item = imported_item(Some("user/fork"), None);
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","sourceRepoFullName":"user/fork","attachedRepoFullName":"user/fork"}"#
                .to_owned(),
        );

        let upload = imported_review_upload(&item).expect("review with comments should upload");

        assert_eq!(
            upload.comments[0].event_type,
            Some(ImportedCommentEventType::PullRequestReviewComment),
            "a recorded filePath means the comment was inline on a diff"
        );
    }

    #[test]
    fn import_upload_payload_labels_discussion_comments_as_issue_comments() {
        use difflore_core::contract::ImportedCommentEventType;

        // GitHub PR discussion comments are anchored to the first changed
        // file at import time, so they carry BOTH `sourceKind: issue_comment`
        // and a borrowed filePath. The sourceKind must win, or the cloud
        // would label them as inline review comments.
        let mut item = imported_item(Some("user/fork"), None);
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/lib.rs","sourceRepoFullName":"user/fork","attachedRepoFullName":"user/fork","sourceKind":"issue_comment"}"#
                .to_owned(),
        );
        item.comments[0].comment_url =
            Some("https://github.com/user/fork/pull/7#issuecomment-99".to_owned());

        let upload = imported_review_upload(&item).expect("review with comments should upload");
        assert_eq!(
            upload.comments[0].event_type,
            Some(ImportedCommentEventType::IssueComment),
            "sourceKind=issue_comment outranks the anchored filePath"
        );
        assert_eq!(
            upload.comments[0].file_path.as_deref(),
            Some("src/lib.rs"),
            "the anchored path still flows into the payload for file-pattern extraction"
        );

        // GitLab MR-level discussion notes carry `sourceKind: mr_comment`
        // and map to the same webhook bucket.
        assert_eq!(
            comment_event_type(
                Some(r#"{"filePath":null,"sourceKind":"mr_comment"}"#),
                None,
                "https://gitlab.com/group/project/-/merge_requests/4#note_200",
            ),
            Some(ImportedCommentEventType::IssueComment),
        );
    }

    #[test]
    fn import_upload_payload_labels_review_bodies_as_pull_request_review() {
        use difflore_core::contract::ImportedCommentEventType;

        // Top-level review bodies carry no filePath/sourceKind metadata
        // (durability signal only, or nothing) — the GitHub URL fragment is
        // the local marker.
        let mut item = imported_item(Some("user/fork"), None);
        item.comments[0].metadata = Some(r#"{"resolved":true,"reactionsTotal":1}"#.to_owned());
        item.comments[0].comment_url =
            Some("https://github.com/user/fork/pull/7#pullrequestreview-42".to_owned());
        item.comments[0].line_number = None;

        let upload = imported_review_upload(&item).expect("review with comments should upload");
        assert_eq!(
            upload.comments[0].event_type,
            Some(ImportedCommentEventType::PullRequestReview),
        );
    }

    #[test]
    fn comment_event_type_is_omitted_when_locally_unknown() {
        use difflore_core::contract::ImportedCommentEventType;

        // No metadata + unrecognized URL: stay silent so the cloud's own
        // derivation (which sees the same inputs) decides — explicit wrong
        // labels would override it.
        assert_eq!(
            comment_event_type(
                None,
                None,
                "https://gitlab.example/p/-/merge_requests/4#note_7"
            ),
            None,
        );
        assert_eq!(comment_event_type(Some("not json"), None, ""), None);
        // Legacy inline rows that lost filePath metadata are still recognized
        // by their GitHub fragment, mirroring the cloud's derivation.
        assert_eq!(
            comment_event_type(None, None, "https://github.com/u/r/pull/7#discussion_r100"),
            Some(ImportedCommentEventType::PullRequestReviewComment),
        );

        // The optional field must vanish from the wire payload (not serialize
        // as null) so pre-eventType cloud deployments see an unchanged shape,
        // and the serialized values must match the cloud zod enum exactly.
        let mut wire = review(7, 1);
        wire.comments[0].event_type = None;
        let json = serde_json::to_string(&wire).expect("serialize upload payload");
        assert!(!json.contains("eventType"), "omitted, got: {json}");

        wire.comments[0].event_type = Some(ImportedCommentEventType::IssueComment);
        let json = serde_json::to_string(&wire).expect("serialize upload payload");
        assert!(
            json.contains(r#""eventType":"issue_comment""#),
            "got: {json}"
        );
        assert_eq!(
            serde_json::to_string(&ImportedCommentEventType::PullRequestReviewComment).unwrap(),
            r#""pull_request_review_comment""#
        );
        assert_eq!(
            serde_json::to_string(&ImportedCommentEventType::PullRequestReview).unwrap(),
            r#""pull_request_review""#
        );
    }

    #[test]
    fn local_candidate_gate_keeps_review_rules_and_skips_chatter() {
        assert!(is_high_signal_review_comment_for_paths(
            "We should validate the header before parsing because otherwise malformed requests panic.",
            &[],
        ));
        assert!(!is_high_signal_review_comment_for_paths("LGTM", &[]));
        assert!(!is_high_signal_review_comment_for_paths(
            "nit: spacing",
            &[]
        ));
        assert!(!is_high_signal_review_comment_for_paths(
            "Thanks for fixing this.",
            &[],
        ));
        assert!(!is_high_signal_review_comment_for_paths(
            "Agree with u. If we add some conditions to check the param in advance, there should be a little slowdown than before.",
            &[],
        ));
        assert!(!is_high_signal_review_comment_for_paths(
            "Because this operation removes indices to prevent prefix checking.",
            &[],
        ));
        assert!(!is_high_signal_review_comment_for_paths(
            "// Copyright 2026 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style license.",
            &[],
        ));
        assert!(!is_high_signal_review_comment_for_paths(
            "## Pull request overview This PR updates CI workflows to use newer versions of tools and standardizes YAML string formatting.",
            &[".github/workflows/gin.yml".to_owned()],
        ));
    }

    #[test]
    fn local_candidate_title_and_file_pattern_are_stable() {
        let title = candidate_title(
            "Please prefer Mapping[str, str] here instead of dict[str, str]. It keeps callers flexible.",
            "src/http/headers.py",
        );
        assert_eq!(
            title,
            "Review: Prefer Mapping[str, str] here instead of dict[str, str]"
        );
        assert_eq!(
            file_pattern_from_path("src/http/headers.py").as_deref(),
            Some("src/http/**/*.py")
        );
        assert_eq!(
            file_pattern_from_path("README.md").as_deref(),
            Some("**/README.md")
        );
        assert_eq!(
            file_pattern_from_path("UPGRADE-6.4.md").as_deref(),
            Some("**/UPGRADE-6.4.md")
        );
        assert_eq!(
            file_pattern_from_path("acceptance/testdata/workflow/run-view.txtar").as_deref(),
            Some("acceptance/testdata/workflow/**/*.txtar")
        );
        assert_eq!(
            file_pattern_from_path("go.mod").as_deref(),
            Some("**/go.mod")
        );
        assert_eq!(
            file_pattern_from_path("package-lock.json").as_deref(),
            Some("**/package-lock.json")
        );
        assert_eq!(file_pattern_from_path("Context.PDF"), None);
        assert_eq!(file_pattern_from_path("maps.Copy"), None);
        assert_eq!(file_pattern_from_path("Handle body-size errors"), None);
    }

    #[test]
    fn local_candidate_body_starts_with_distilled_rule_before_raw_review() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].content =
            "Please prefer Mapping[str, str] here instead of dict[str, str]. It keeps callers flexible."
                .to_owned();
        item.comments[0].metadata = Some(r#"{"filePath":"src/http/headers.py"}"#.to_owned());

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(
            input
                .body
                .starts_with("Rule:\nPrefer Mapping[str, str] here instead of dict[str, str].")
        );
        assert!(
            input
                .body
                .contains("Source evidence:\nSource: upstream/project#7")
        );
        assert!(input.body.contains("Reviewer said:\n"));
    }

    #[test]
    fn local_candidate_skips_pr_overview_bot_summary() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "ci: update workflows and dependencies".to_owned();
        item.comments[0].content = "## Pull request overview\nThis PR should ensure CI uses current action versions and dependency manifests stay in sync.\n\n| File | Description |\n| ---- | ----------- |\n| .github/workflows/gin.yml | Updates the lint action version. |\n| `go.mod` | Bumps module dependencies. |"
            .to_owned();
        item.comments[0].metadata = None;

        assert!(
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .is_none()
        );
    }

    #[test]
    fn local_candidate_skips_coverage_and_ai_review_reports() {
        for (author, content) in [
            (
                Some("codecov[bot]"),
                "## Codecov Report\nPatch coverage is 72.31% and project coverage changed by -0.03%.",
            ),
            (
                None,
                "Codecov Report: patch coverage should improve before merge because uncovered lines changed.",
            ),
            (
                Some("coderabbitai"),
                "## Walkthrough\nThis automated review should ensure the new route handler validates input.",
            ),
            (
                None,
                "Actionable comments posted: 0. Review skipped because this PR only updates generated files.",
            ),
        ] {
            let mut item = imported_item(
                Some("user/fork"),
                Some(
                    r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#,
                ),
            );
            item.comments[0].author = author.map(str::to_owned);
            item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
            item.comments[0].content = content.to_owned();

            assert!(
                local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                    .is_none(),
                "content should be skipped: {content}"
            );
        }
    }

    #[test]
    fn local_candidate_skips_acknowledgements_and_weak_questions() {
        for content in [
            "I updated the test to use msw and verify the request body.",
            "Fixed in the latest push; the regression test now covers this.",
            "I tested this in the beta.6 version now and can confirm it works. Nice work.",
            "I don't have any suggestions for fixes, etc. Thanks for the great work.",
            "In the end, we use `any`, but it's good. Thank you for your contribution.",
            "Do we need to support this edge case?",
            "Is there a reason this should live in the public API?",
        ] {
            let mut item = imported_item(
                Some("user/fork"),
                Some(
                    r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#,
                ),
            );
            item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
            item.comments[0].content = content.to_owned();

            assert!(
                local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                    .is_none(),
                "content should be skipped: {content}"
            );
        }
    }

    #[test]
    fn local_candidate_keeps_directive_questions() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
        item.comments[0].content =
            "Could you add a regression test that verifies malformed headers return 400 instead of panicking?"
                .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(input.body.contains("add a regression test"));
    }

    #[test]
    fn local_candidate_keeps_copilot_as_product_or_path_name() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("human-reviewer".to_owned());
        item.comments[0].metadata = Some(r#"{"filePath":"pkg/cmd/copilot/copilot.go"}"#.to_owned());
        item.comments[0].content =
            "Also `copilot` should be replaced with the const to keep this command consistent."
                .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        let patterns = input.file_patterns.as_deref().unwrap_or_default();
        assert!(patterns.contains(&"pkg/cmd/copilot/**/*.go".to_owned()));
        assert!(!input.body.contains("`pkg/cmd/copilot/**/*.go`"));
        assert!(
            input
                .body
                .contains("`copilot` should be replaced with the const")
        );
    }

    #[test]
    fn local_candidate_skips_non_english_docs_translation_wording() {
        for content in [
            "This should be translated as a more natural Korean sentence for this paragraph.",
            "This sentence reads awkwardly and should be rewritten by a native speaker.",
        ] {
            let mut item = imported_item(
                Some("user/fork"),
                Some(
                    r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#,
                ),
            );
            item.comments[0].metadata =
                Some(r#"{"filePath":"docs/ko/docs/tutorial/response-status-code.md"}"#.to_owned());
            item.comments[0].content = content.to_owned();

            assert!(
                local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                    .is_none(),
                "content should be skipped: {content}"
            );
        }
    }

    #[test]
    fn local_candidate_keeps_localized_docs_api_symbol_rule() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata =
            Some(r#"{"filePath":"docs/ko/docs/tutorial/response-status-code.md"}"#.to_owned());
        item.comments[0].content =
            "Please keep `HTTPException` untranslated because it is a FastAPI API symbol."
                .to_owned();
        assert!(
            is_high_signal_review_comment_for_paths(
                &item.comments[0].content,
                &["docs/ko/docs/tutorial/response-status-code.md".to_owned()]
            ),
            "clean: {}",
            clean_review_comment(&item.comments[0].content)
        );

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(input.body.contains("keep `HTTPException` untranslated"));
    }

    #[test]
    fn local_candidate_extracts_later_directive_after_greeting() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata = Some(r#"{"filePath":"src/jsx/streaming.test.tsx"}"#.to_owned());
        item.comments[0].content = "Hi @alice, thank you for the correction. That's a great help. Please add the following test for the fallback path."
            .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(input.title.contains("Add the following test"));
        assert!(
            input
                .body
                .contains("Add the following test for the fallback path.")
        );
        assert!(!input.body.contains("thank you for the correction."));
    }

    #[test]
    fn local_candidate_extracts_directive_after_positive_ack() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata =
            Some(r#"{"filePath":"packages/vite/src/node/cli.ts"}"#.to_owned());
        item.comments[0].content =
            "This works great! As suggested, we should add the `-w` option as webpack does."
                .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(input.body.contains("add the `-w` option as webpack does."));
        assert!(!input.title.contains("This works great"));
    }

    #[test]
    fn local_candidate_skips_pr_process_chatter() {
        for content in [
            "@airhorns would you merge main to this branch? Tests should be green after that.",
            "Can I make changes to this PR? Or should I fork your repo?",
            "Please don't comment on years old PRs, open a new issue with a minimal reproduction.",
            "A test is failing (+ rebase needed).",
            ":/ Could you update the PR base branch before merging this?",
        ] {
            let mut item = imported_item(
                Some("user/fork"),
                Some(
                    r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#,
                ),
            );
            item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
            item.comments[0].content = content.to_owned();

            assert!(
                local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                    .is_none(),
                "content should be skipped: {content}"
            );
        }
    }

    #[test]
    fn local_candidate_ignores_bare_code_filenames_from_review_tables() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "ci summary".to_owned();
        item.comments[0].metadata = None;
        item.comments[0].content =
            "Please ensure workflow versions stay consistent across CI files.\n\n\
| File | Description |\n\
| ---- | ----------- |\n\
| .github/workflows/gin.yml | Updates the lint action version. |\n\
| ConsumerGroup.java | Bare generated table filename without a directory. |"
                .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;
        let patterns = input.file_patterns.expect("file patterns");

        assert_eq!(patterns, vec![".github/workflows/**/*.yml".to_owned()]);
        assert!(!input.body.contains("Related files: ConsumerGroup.java"));
    }

    #[test]
    fn local_candidate_caps_large_pr_summary_file_patterns() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "module00/src/Foo00.java".to_owned();
        item.comments[0].metadata = Some(r#"{"filePath":"module00/src/Foo00.java"}"#.to_owned());
        let rows = (0..40)
            .map(|n| format!("| module{n:02}/src/Foo{n:02}.java | keep validation aligned |"))
            .collect::<Vec<_>>()
            .join("\n");
        item.comments[0].content = format!(
            "Please validate serializer state and keep behavior consistent across these modules.\n\n| File | Comment |\n| ---- | ------- |\n{rows}"
        );

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;
        let patterns = input.file_patterns.expect("file patterns");

        assert_eq!(
            patterns.len(),
            difflore_core::skills::REMEMBER_FILE_PATTERN_LIMIT
        );
        assert_eq!(patterns[0], "module00/src/**/*.java");
    }

    #[test]
    fn local_candidate_caps_related_files_body_line() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "module00/src/Foo00.java".to_owned();
        item.comments[0].metadata = Some(r#"{"filePath":"module00/src/Foo00.java"}"#.to_owned());
        let rows = (0..48)
            .map(|n| format!("| module{n:02}/src/Foo{n:02}.java | keep validation aligned |"))
            .collect::<Vec<_>>()
            .join("\n");
        item.comments[0].content = format!(
            "Please validate serializer state and keep behavior consistent across these modules.\n\n| File | Comment |\n| ---- | ------- |\n{rows}"
        );

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;

        assert!(
            input
                .body
                .contains("Related files: module01/src/Foo01.java")
        );
        assert!(input.body.contains("and 35 more"));
        assert!(!input.body.contains("module47/src/Foo47.java"));
        assert!(
            input.body.chars().count() <= difflore_core::skills::REMEMBER_BODY_CHAR_LIMIT,
            "candidate body should fit remember_rule limit"
        );
    }

    #[test]
    fn local_candidate_skips_coderabbit_outside_diff_aggregate() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "review summary".to_owned();
        item.comments[0].metadata = None;
        item.comments[0].content = "[!CAUTION]\n\
Some comments are outside the diff and cannot be posted inline due to platform limitations.\n\n\
<details>\n\
<summary>Outside diff range comments (14)</summary>\n\n\
| File | Comment |\n\
| ---- | ------- |\n\
| `src/lib.rs` | We should validate the header before parsing because malformed requests panic. |\n\
| +14 more | Additional outside-diff comments. |\n\
</details>"
            .to_owned();

        assert!(
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .is_none()
        );
    }

    #[test]
    fn local_candidate_skips_platform_review_table_wrapper() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
        item.comments[0].content = "<details>\n\
<summary>Review details</summary>\n\n\
| Reviewable files | 18 |\n\
| Additional comments | 14 |\n\n\
We should validate the header before parsing because malformed requests panic.\n\
</details>"
            .to_owned();

        assert!(
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .is_none()
        );
    }

    #[test]
    fn local_candidate_ignores_plus_more_scope_markers() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.file_path = "ci summary".to_owned();
        item.comments[0].metadata = None;
        item.comments[0].content =
            "Please ensure workflow versions stay consistent across CI files.\n\n\
| File | Description |\n\
| ---- | ----------- |\n\
| .github/workflows/gin.yml | Updates the lint action version. |\n\
| +14 more | Additional files hidden by the review UI. |"
                .to_owned();

        let input =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("candidate")
                .input;
        let patterns = input.file_patterns.expect("file patterns");

        assert_eq!(patterns, vec![".github/workflows/**/*.yml".to_owned()]);
        assert!(input.body.contains("File: .github/workflows/gin.yml"));
        assert!(!input.body.contains("+14 more"));
    }

    #[test]
    fn local_candidate_skips_pr_author_thread_replies() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.item.author = Some("alice".to_owned());
        item.comments[0].author = Some("Alice".to_owned());
        item.comments[0].content =
            "Fixed - now asserting found=false for all the non-matching paths, not just checking for panics."
                .to_owned();
        item.comments[0].metadata = Some(r#"{"filePath":"tree_test.go"}"#.to_owned());

        assert!(
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .is_none()
        );
    }

    #[test]
    fn local_candidate_uses_pr_discussion_comment_with_changed_file_scope() {
        let mut item = imported_item(
            Some("difflore-fixtures/terminal"),
            Some(
                r#"{"sourceRepoFullName":"microsoft/terminal","attachedRepoFullName":"difflore-fixtures/terminal"}"#,
            ),
        );
        item.item.file_path = "tools/ReleaseEngineering/Draft-TerminalReleases.ps1".to_owned();
        item.comments[0].author = Some("DHowett".to_owned());
        item.comments[0].comment_url = Some(
            "https://github.com/microsoft/terminal/pull/13629#issuecomment-1644692454".to_owned(),
        );
        item.comments[0].metadata = Some(
            r#"{"filePath":"tools/ReleaseEngineering/Draft-TerminalReleases.ps1","sourceKind":"issue_comment"}"#
                .to_owned(),
        );
        item.comments[0].content =
            "This is great and amazing, but it needs to be fixed for portable/zip builds and stuff too."
                .to_owned();

        let input = local_candidate_input(
            &item,
            &item.comments[0],
            &github_scope("microsoft/terminal"),
        )
        .expect("candidate")
        .input;

        assert_eq!(
            input.file_patterns.as_deref(),
            Some(&["tools/ReleaseEngineering/**/*.ps1".to_owned()][..])
        );
        assert!(input.body.contains("Source: microsoft/terminal#7"));
        assert!(input.body.contains("Fixed for portable/zip builds"));
    }

    #[test]
    fn local_candidate_does_not_auto_activate_unadopted_bot_directive() {
        // A bot directive with no adoption signal (unresolved, no reactions)
        // must land as a medium-confidence pending draft: not dropped, not
        // auto-active.
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("github-actions[bot]".to_owned());
        item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
        item.comments[0].content =
            "Please ensure workflow versions stay consistent across CI files.".to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("unadopted bot directive should draft a candidate, not be vetoed");
        assert_eq!(
            candidate.route,
            CaptureRoute::Candidate,
            "unadopted bot directive must stay pending, got confidence {}",
            candidate.confidence,
        );
        assert!(candidate.confidence < CAPTURE_CONFIDENCE_HIGH);
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_LOW);
    }

    #[test]
    fn local_candidate_auto_activates_resolved_bot_directive() {
        // A bot directive that WAS adopted (resolved thread) earns the
        // resolved bonus and clears the HIGH threshold, so it auto-activates.
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("coderabbitai[bot]".to_owned());
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","resolved":true,"thumbsUp":1,"thumbsDown":0,"reactionsTotal":1}"#
                .to_owned(),
        );
        item.comments[0].content =
            "Please validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("resolved bot directive should draft a candidate");
        assert_eq!(
            candidate.route,
            CaptureRoute::Active,
            "resolved+approved bot directive must auto-activate, got confidence {}",
            candidate.confidence,
        );
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_HIGH);
    }

    #[test]
    fn local_candidate_auto_activates_resolved_human_directive() {
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("human-reviewer".to_owned());
        item.comments[0].metadata =
            Some(r#"{"filePath":"src/http/request.rs","resolved":true}"#.to_owned());
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("resolved human directive should draft a candidate");
        assert_eq!(candidate.route, CaptureRoute::Active);
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_HIGH);
    }

    #[test]
    fn local_candidate_leaves_unadopted_human_directive_pending() {
        // A strong human directive with no adoption signal becomes a pending
        // candidate the user must accept, not auto-active.
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata = Some(r#"{"filePath":"src/http/request.rs"}"#.to_owned());
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("unadopted human directive should still draft a candidate");
        assert_eq!(candidate.route, CaptureRoute::Candidate);
        assert!(candidate.confidence < CAPTURE_CONFIDENCE_HIGH);
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_LOW);
    }

    #[test]
    fn local_candidate_drops_contradicted_directive() {
        // A later reply retracting the suggestion is a strong negative —
        // even a strong directive must be dropped (route below LOW → None).
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","laterReplies":["Actually no, disregard that — the framework already handles it."]}"#
                .to_owned(),
        );
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        assert!(
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .is_none(),
            "a contradicted directive must be dropped, not drafted"
        );
    }

    #[test]
    fn local_candidate_demotes_resolved_but_downvoted_directive_to_pending() {
        // A resolved thread alone clears HIGH, but a strict 👎-majority is a
        // correctness signal: the directive demotes to a pending candidate
        // (still ≥ LOW so it is reviewed, not dropped), not auto-active.
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("human-reviewer".to_owned());
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","resolved":true,"thumbsUp":1,"thumbsDown":4,"reactionsTotal":5}"#
                .to_owned(),
        );
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect(
                    "resolved-but-downvoted directive should draft a candidate, not be dropped",
                );
        assert_eq!(
            candidate.route,
            CaptureRoute::Candidate,
            "net-downvoted resolved directive must stay pending, got confidence {}",
            candidate.confidence,
        );
        assert!(candidate.confidence < CAPTURE_CONFIDENCE_HIGH);
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_LOW);
    }

    #[test]
    fn local_candidate_keeps_resolved_directive_active_despite_single_downvote() {
        // A tied 👍/👎 is not a veto: only a strict 👎-majority penalizes, so
        // the resolved bonus still carries the directive to active.
        let mut item = imported_item(
            Some("user/fork"),
            Some(r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#),
        );
        item.comments[0].author = Some("human-reviewer".to_owned());
        item.comments[0].metadata = Some(
            r#"{"filePath":"src/http/request.rs","resolved":true,"thumbsUp":1,"thumbsDown":1,"reactionsTotal":2}"#
                .to_owned(),
        );
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let candidate =
            local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                .expect("resolved directive should draft a candidate");
        assert_eq!(
            candidate.route,
            CaptureRoute::Active,
            "a tied 👍/👎 must not penalize a resolved directive, got confidence {}",
            candidate.confidence,
        );
        assert!(candidate.confidence >= CAPTURE_CONFIDENCE_HIGH);
    }

    #[test]
    fn capture_confidence_routes_at_named_thresholds() {
        assert_eq!(
            route_for_confidence(CAPTURE_CONFIDENCE_HIGH),
            CaptureRoute::Active
        );
        assert_eq!(
            route_for_confidence(CAPTURE_CONFIDENCE_HIGH - 0.01),
            CaptureRoute::Candidate
        );
        assert_eq!(
            route_for_confidence(CAPTURE_CONFIDENCE_LOW),
            CaptureRoute::Candidate
        );
        assert_eq!(
            route_for_confidence(CAPTURE_CONFIDENCE_LOW - 0.01),
            CaptureRoute::Drop
        );
    }

    #[test]
    fn local_candidate_skips_greeting_only_review_verdicts() {
        for content in [
            "Hi, thanks for the PR.",
            "@m1a2st : Thanks for the updated PR.",
            "Hi @matt-welch, thanks for working on this.",
            "@junrao You're right.",
            "Overall LGTM",
            "Be fine as-is",
        ] {
            let mut item = imported_item(
                Some("user/fork"),
                Some(
                    r#"{"sourceRepoFullName":"upstream/project","attachedRepoFullName":"user/fork"}"#,
                ),
            );
            item.comments[0].metadata = Some(r#"{"filePath":"src/lib.rs"}"#.to_owned());
            item.comments[0].content = content.to_owned();

            assert!(
                local_candidate_input(&item, &item.comments[0], &github_scope("upstream/project"))
                    .is_none(),
                "content should be skipped: {content}"
            );
        }
    }

    #[test]
    fn distilled_rule_statement_removes_review_chatter_prefixes() {
        assert_eq!(
            distilled_rule_statement(
                "We should validate the header before parsing because otherwise malformed requests panic.",
                "src/http/request.rs",
            ),
            "Validate the header before parsing because otherwise malformed requests panic."
        );
    }

    #[test]
    fn distilled_rule_statement_keeps_dotted_code_identifiers_intact() {
        assert_eq!(
            distilled_rule_statement(
                "The test should verify that `http.ErrAbortHandler` is actually being treated as a broken pipe error by asserting that the output does NOT contain \"panic recovered\".",
                "recovery_test.go",
            ),
            "The test should verify that `http.ErrAbortHandler` is actually being treated as a broken pipe error by asserting that the output does NOT contain \"panic recovered\"."
        );
    }

    #[test]
    fn gitlab_same_repo_local_candidate_does_not_widen_file_patterns() {
        let mut item = imported_item(Some("group/project"), None);
        item.item.source = "gitlab".to_owned();
        item.comments[0].metadata = Some(
            serde_json::json!({
                "filePath": "src/http/request.rs",
                "gitlabHost": "gitlab.com",
                "sourceRepoFullName": "group/project",
                "attachedRepoFullName": "group/project",
                "resolved": true,
            })
            .to_string(),
        );
        item.comments[0].content =
            "We should validate the header before parsing because otherwise malformed requests panic."
                .to_owned();

        let input = local_candidate_input(
            &item,
            &item.comments[0],
            &gitlab_scope("gitlab.com", "group/project"),
        )
        .expect("candidate")
        .input;

        assert_eq!(
            input.file_patterns.as_deref(),
            Some(
                [
                    String::from("src/http/**/*.rs"),
                    String::from("src/**/*.rs"),
                ]
                .as_slice()
            )
        );
        assert!(
            !input
                .file_patterns
                .as_deref()
                .unwrap_or_default()
                .contains(&String::from("**/*.rs"))
        );
    }

    #[test]
    fn import_next_steps_are_value_proof_first() {
        assert_eq!(
            active_candidate_next_step_commands(),
            &[
                "difflore status",
                "difflore memory active",
                "difflore recall --diff",
                "difflore review --diff all",
            ],
        );
        assert_eq!(
            pending_candidate_next_step_commands("acme/widgets"),
            vec![
                "difflore memory review".to_owned(),
                "difflore drafts list --repo acme/widgets --json".to_owned(),
                "difflore drafts approve --all --repo acme/widgets --yes".to_owned(),
            ],
        );

        let cloud_commands = cloud_upload_next_step_commands()
            .iter()
            .map(|(cmd, _)| *cmd)
            .collect::<Vec<_>>();
        assert_eq!(
            cloud_commands,
            vec![
                "difflore cloud sync",
                "difflore status",
                "difflore recall --diff",
                "difflore cloud impact",
                "difflore review --diff all",
            ],
        );
    }

    #[test]
    fn pending_drafts_hint_points_at_memory_review_not_removed_candidates_verb() {
        // The drafts hint must name an existing command and never resurrect
        // the removed `difflore candidates` verb.
        for count in [1usize, 8] {
            let (prefix, command, suffix) = pending_drafts_review_hint(count);
            let full = format!("{prefix}{command}{suffix}");

            assert_eq!(
                command, "difflore memory review",
                "hint must steer to a real command"
            );
            assert!(
                !full.contains("difflore candidates"),
                "hint must not name the removed `difflore candidates` verb: {full}"
            );
            assert!(
                full.contains("agent inspect"),
                "hint should point at the agent inspection flow: {full}"
            );
            assert!(
                full.contains("held for review"),
                "hint should read as a review prompt: {full}"
            );
        }

        // Plain singular/plural agreement on the draft noun.
        assert!(
            pending_drafts_review_hint(1)
                .0
                .contains("1 medium-confidence draft held")
        );
        assert!(
            pending_drafts_review_hint(8)
                .0
                .contains("8 medium-confidence drafts held")
        );
    }

    #[tokio::test]
    async fn local_candidate_budget_ignores_deduped_comments_between_new_rules() {
        let db = fresh_import_pool().await;
        seed_imported_review_comments(
            &db,
            &[
                (
                    "Please validate the header before parsing because otherwise malformed requests panic.",
                    "src/http/request.rs",
                ),
                (
                    "We should validate the header before parsing because otherwise malformed requests panic.",
                    "src/http/request.rs",
                ),
                (
                    "Please prefer Mapping[str, str] here instead of dict[str, str]. It keeps callers flexible.",
                    "src/http/headers.py",
                ),
            ],
        )
        .await;

        let source_scope = github_scope("acme/widgets");
        let progress = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            2,
            &[],
            &HashSet::new(),
        )
        .await;

        assert_eq!(progress.candidates_created, 2);
        // Seeded comments are resolved threads, so the gate auto-activates
        // both — none stay pending.
        assert_eq!(progress.candidates_activated, 2);
        assert_eq!(progress.candidates_pending, 0);
        assert_eq!(progress.candidates_duplicate_in_run, 1);
        assert!(local_candidate_budget_reached(&progress));
        assert!(progress.capped);

        let memories = difflore_core::skills::list_all_skills(&db)
            .await
            .expect("list active memories");
        assert_eq!(memories.len(), 2);
        assert!(
            memories
                .iter()
                .any(|c| c.name.contains("Validate the header")),
            "memories: {memories:?}"
        );
        assert!(
            memories.iter().any(|c| c.name.contains("Prefer Mapping")),
            "memories: {memories:?}"
        );
    }

    #[tokio::test]
    async fn gitlab_local_import_recalls_and_stays_isolated_from_same_github_namespace() {
        let db = fresh_import_pool().await;
        seed_gitlab_pr_with_directive(
            &db,
            "gitlab.com",
            "group/project",
            7,
            "We should validate the header before parsing because otherwise malformed requests panic.",
            "src/http/request.rs",
        )
        .await;
        seed_pr_with_directive(
            &db,
            "group/project",
            8,
            "We should prefer Mapping[str, str] here instead of dict[str, str] to keep callers flexible.",
            "src/http/headers.py",
        )
        .await;

        let gitlab_source_scope = gitlab_scope("gitlab.com", "group/project");
        let gitlab_progress = run_local_candidates(
            &db,
            "gitlab",
            "group/project",
            &gitlab_source_scope,
            25,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(gitlab_progress.candidates_created, 1);
        assert_eq!(gitlab_progress.candidates_activated, 1);

        let github_source_scope = github_scope("group/project");
        let github_progress = run_local_candidates(
            &db,
            "github",
            "group/project",
            &github_source_scope,
            25,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(github_progress.candidates_created, 1);
        assert_eq!(github_progress.candidates_activated, 1);

        let source_repos = difflore_core::skills::list_source_repos(&db)
            .await
            .expect("load source repos");
        let mut source_repo_values = source_repos
            .values()
            .filter_map(|repo| repo.as_deref())
            .collect::<Vec<_>>();
        source_repo_values.sort_unstable();
        assert_eq!(
            source_repo_values,
            vec!["gitlab.com/group/project", "group/project"]
        );

        let gitlab_patterns: Option<String> =
            sqlx::query_scalar("SELECT file_patterns FROM skills WHERE source_repo = ?1")
                .bind(gitlab_source_scope.as_str())
                .fetch_one(&db)
                .await
                .expect("load gitlab file patterns");
        let gitlab_patterns: Vec<String> =
            serde_json::from_str(&gitlab_patterns.expect("gitlab file patterns"))
                .expect("parse gitlab file patterns");
        assert_eq!(gitlab_patterns, vec!["src/http/**/*.rs"]);

        let gitlab_export = difflore_core::export::collect_rules_for_export_with_scopes(
            &db,
            &[gitlab_source_scope.as_str().to_owned()],
            difflore_core::export::ExportCollectOptions::default(),
        )
        .await
        .expect("collect gitlab export");
        assert_eq!(gitlab_export.rules.len(), 1);
        assert!(
            gitlab_export.rules[0].name.contains("Validate the header"),
            "gitlab export: {:?}",
            gitlab_export.rules
        );

        let github_export = difflore_core::export::collect_rules_for_export_with_scopes(
            &db,
            &[github_source_scope.as_str().to_owned()],
            difflore_core::export::ExportCollectOptions::default(),
        )
        .await
        .expect("collect github export");
        assert_eq!(github_export.rules.len(), 1);
        assert!(
            github_export.rules[0].name.contains("Prefer Mapping"),
            "github export: {:?}",
            github_export.rules
        );

        let gitlab_project_path: String = sqlx::query_scalar(
            "SELECT p.path FROM projects p \
             INNER JOIN review_items ri ON ri.project_id = p.id \
             WHERE ri.source = ?1 LIMIT 1",
        )
        .bind("gitlab")
        .fetch_one(&db)
        .await
        .expect("load gitlab project path");
        let project_hash = difflore_core::infra::db::project_hash_from_root(std::path::Path::new(
            &gitlab_project_path,
        ));
        let index_pool = difflore_core::context::index_db::get_pool_for_project(&project_hash)
            .await
            .expect("open test index pool");
        let repo_scopes = vec![
            gitlab_source_scope.as_str().to_owned(),
            github_source_scope.as_str().to_owned(),
        ];
        difflore_core::context::orchestrator::ensure_rules_indexed_for_repo_scopes_with_embedding_timeout(
            &db,
            &index_pool,
            &repo_scopes,
            Some(std::time::Duration::from_millis(0)),
        )
        .await
        .expect("index scoped rules");

        let gitlab_filter = difflore_core::context::index_db::QueryFilter {
            language: Some("rust".to_owned()),
            repo_scope: Some(gitlab_source_scope.as_str().to_owned()),
        };
        let gitlab_hits = difflore_core::context::retrieval::retrieve_rules_with_confidence(
            &index_pool,
            "validate header parsing malformed requests",
            difflore_core::context::retrieval::RetrievalOptions {
                top_k: Some(5),
                target_scope: Some(difflore_core::context::retrieval::TargetScope::File(
                    "src/http/request.rs",
                )),
                filter: Some(&gitlab_filter),
                ann_enabled: false,
                ..Default::default()
            },
        )
        .await
        .expect("retrieve gitlab rules");
        assert!(
            gitlab_hits
                .iter()
                .any(|rule| rule.content.contains("Validate the header")),
            "gitlab recall hits: {gitlab_hits:?}"
        );
        assert!(
            !gitlab_hits
                .iter()
                .any(|rule| rule.content.contains("Prefer Mapping")),
            "gitlab recall leaked github rule: {gitlab_hits:?}"
        );

        let github_filter = difflore_core::context::index_db::QueryFilter {
            language: Some("python".to_owned()),
            repo_scope: Some(github_source_scope.as_str().to_owned()),
        };
        let github_hits = difflore_core::context::retrieval::retrieve_rules_with_confidence(
            &index_pool,
            "prefer mapping strings flexible callers",
            difflore_core::context::retrieval::RetrievalOptions {
                top_k: Some(5),
                target_scope: Some(difflore_core::context::retrieval::TargetScope::File(
                    "src/http/headers.py",
                )),
                filter: Some(&github_filter),
                ann_enabled: false,
                ..Default::default()
            },
        )
        .await
        .expect("retrieve github rules");
        assert!(
            github_hits
                .iter()
                .any(|rule| rule.content.contains("Prefer Mapping")),
            "github recall hits: {github_hits:?}"
        );
        assert!(
            !github_hits
                .iter()
                .any(|rule| rule.content.contains("Validate the header")),
            "github recall leaked gitlab rule: {github_hits:?}"
        );
    }

    #[tokio::test]
    async fn run_local_candidates_leaves_unresolved_directives_pending() {
        // End-to-end routing: an unresolved (un-adopted) directive must NOT
        // be served by the MCP active-rule path; it lands as a pending
        // candidate the user can review and accept.
        let db = fresh_import_pool().await;
        seed_imported_review_comments_with_resolution(
            &db,
            &[(
                "We should validate the header before parsing because otherwise malformed requests panic.",
                "src/http/request.rs",
            )],
            false,
        )
        .await;

        let source_scope = github_scope("acme/widgets");
        let progress = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;

        assert_eq!(progress.candidates_created, 1);
        assert_eq!(progress.candidates_activated, 0);
        assert_eq!(progress.candidates_pending, 1);

        // Not active → not surfaced by list_all_skills.
        let active = difflore_core::skills::list_all_skills(&db)
            .await
            .expect("list active memories");
        assert!(
            active.is_empty(),
            "unresolved directive must not auto-activate"
        );

        // But it IS a pending candidate awaiting review.
        let pending = difflore_core::skills::count_pending_candidates(&db, None)
            .await
            .expect("count pending");
        assert_eq!(pending, 1);
    }

    #[tokio::test]
    async fn rejected_candidate_is_not_resurrected_on_reimport() {
        // Regression for the resurrection bug: rejecting a pending candidate
        // must tombstone its content so a subsequent `import-reviews` (which
        // re-reads every stored comment) does NOT re-create the rejected draft.
        let db = fresh_import_pool().await;
        seed_imported_review_comments_with_resolution(
            &db,
            &[(
                "We should validate the header before parsing because otherwise malformed requests panic.",
                "src/http/request.rs",
            )],
            false,
        )
        .await;

        let source_scope = github_scope("acme/widgets");

        // First import: one pending candidate is created.
        let first = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(first.candidates_created, 1);
        assert_eq!(first.candidates_pending, 1);
        assert_eq!(first.candidates_suppressed_rejected, 0);

        let pending = difflore_core::skills::list_candidates(&db, None, None)
            .await
            .expect("list pending candidates");
        assert_eq!(pending.len(), 1, "expected exactly one pending candidate");
        let candidate_id = pending[0].id.clone();

        // The user rejects it.
        difflore_core::skills::reject_candidate(&db, &candidate_id)
            .await
            .expect("reject candidate");
        assert_eq!(
            difflore_core::skills::count_pending_candidates(&db, None)
                .await
                .expect("count pending after reject"),
            0,
        );

        // Second import re-reads the same comment but must NOT resurrect it.
        let second = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(
            second.candidates_created, 0,
            "rejected candidate must not be re-created on re-import"
        );
        assert_eq!(
            second.candidates_suppressed_rejected, 1,
            "the re-import must record the suppressed rejected suggestion"
        );
        assert_eq!(
            difflore_core::skills::count_pending_candidates(&db, None)
                .await
                .expect("count pending after reimport"),
            0,
            "no pending candidate should exist after a suppressed re-import"
        );
    }

    #[tokio::test]
    async fn reimport_of_auto_promoted_rule_matches_active_without_duplicating() {
        // Companion to the rejection regression: a HIGH-confidence (resolved-
        // thread) comment auto-promotes to `active` on first import. The next
        // import re-reads the same comment and must dedup into the approved
        // rule — counted as matched-active (NOT a strengthened dedup) and never
        // forking a fresh draft, which would trip promote_candidate's
        // "duplicates active rule" guard and abort the whole import.
        let db = fresh_import_pool().await;
        seed_imported_review_comments_with_resolution(
            &db,
            &[(
                "We should validate the header before parsing because otherwise malformed requests panic.",
                "src/http/request.rs",
            )],
            true,
        )
        .await;

        let source_scope = github_scope("acme/widgets");

        // First import: resolved thread auto-promotes to an active rule.
        let first = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(first.candidates_created, 1);
        assert_eq!(
            first.candidates_activated, 1,
            "a resolved thread should auto-activate"
        );

        // Second import re-reads the same comment.
        let second = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(
            second.candidates_created, 0,
            "re-import of an active rule must not create a new row"
        );
        assert_eq!(
            second.candidates_deduped, 0,
            "an untouched active match must not be reported as a strengthened dedup"
        );
        assert_eq!(
            second.candidates_matched_active, 1,
            "re-import must record the already-active match"
        );
        assert_eq!(
            difflore_core::skills::count_pending_candidates(&db, None)
                .await
                .expect("count pending after active re-import"),
            0,
            "re-import must not fork a pending duplicate of the active rule"
        );
    }

    #[tokio::test]
    async fn rejected_comment_does_not_suppress_later_same_signature_evidence() {
        // Order-independence regression: a rejected comment must be skipped
        // WITHOUT consuming the in-run dedupe signature, so a second comment
        // that distills to the same rule but carries different (non-rejected)
        // source evidence still produces a draft on re-import.
        let db = fresh_import_pool().await;
        seed_imported_review_comments_with_resolution(
            &db,
            &[
                (
                    "Please validate the header before parsing because otherwise malformed requests panic.",
                    "src/http/request.rs",
                ),
                (
                    "We should validate the header before parsing because otherwise malformed requests panic.",
                    "src/http/request.rs",
                ),
            ],
            false,
        )
        .await;

        let source_scope = github_scope("acme/widgets");

        // First import: both comments distill to the same signature, so one
        // pending draft is created and the other is an in-run dedupe.
        let first = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(first.candidates_created, 1);
        assert_eq!(first.candidates_duplicate_in_run, 1);

        let pending = difflore_core::skills::list_candidates(&db, None, None)
            .await
            .expect("list pending candidates");
        assert_eq!(pending.len(), 1, "expected exactly one pending draft");
        let candidate_id = pending[0].id.clone();

        // Reject the created draft — this tombstones only THAT comment's
        // content hash, not the shared distilled signature.
        difflore_core::skills::reject_candidate(&db, &candidate_id)
            .await
            .expect("reject candidate");

        // Re-import: the rejected comment is suppressed, but the OTHER
        // same-signature comment's distinct evidence must still create a draft.
        let second = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            5,
            &[],
            &HashSet::new(),
        )
        .await;
        assert_eq!(
            second.candidates_suppressed_rejected, 1,
            "the rejected comment must be suppressed on re-import"
        );
        assert_eq!(
            second.candidates_created, 1,
            "the non-rejected same-signature comment must still create a draft (order-independent)"
        );
        assert_eq!(
            difflore_core::skills::count_pending_candidates(&db, None)
                .await
                .expect("count pending after reimport"),
            1,
            "exactly one fresh draft should exist after the suppressed re-import"
        );
    }

    #[test]
    fn import_local_candidate_budget_scales_with_pr_window() {
        let defaults = validate_args(import_args_with_budget(10)).expect("valid args");
        assert_eq!(local_candidate_budget(&defaults), 25);

        let larger_window = validate_args(import_args_with_budget(100)).expect("valid args");
        assert_eq!(local_candidate_budget(&larger_window), 200);
    }

    #[test]
    fn import_dry_run_json_describes_plan_without_side_effects() {
        let args = validate_args(ImportArgs {
            repo: Some("acme/fork".to_owned()),
            from_upstream: Some("acme/upstream".to_owned()),
            provider: None,
            gitlab_host: None,
            max_prs: 2,
            pr_numbers: vec![7, 8],
            exclude_prs: vec![9, 9, 10],
            since: None,
            include_open: true,
            upload: false,
            distill: ImportDistillArg::Heuristic,
            dry_run: true,
            json: true,
            wall_timeout_secs: None,
        })
        .expect("valid args");

        let payload = dry_run_payload(&args, "acme/fork", "acme/upstream");

        assert_eq!(payload["dryRun"], true);
        assert_eq!(payload["provider"], "github");
        assert_eq!(payload["repo"], "acme/fork");
        assert_eq!(payload["sourceRepo"], "acme/upstream");
        assert_eq!(payload["fromUpstream"], "acme/upstream");
        assert_eq!(payload["maxPrs"], 2);
        assert_eq!(payload["requestedMaxPrs"], 2);
        assert_eq!(payload["maxPrsClamped"], false);
        assert_eq!(payload["prNumbers"], serde_json::json!([7, 8]));
        // Deduped (the two 9s collapse) and sorted for stable JSON output.
        assert_eq!(payload["excludePrs"], serde_json::json!([9, 10]));
        assert_eq!(payload["includeOpen"], true);
        assert_eq!(payload["upload"], false);
        assert_eq!(payload["localCandidates"], true);
        assert_eq!(payload["distill"], "heuristic");
        assert_eq!(payload["localCandidateBudget"], 25);
        assert_eq!(payload["writes"], false);
        assert_eq!(payload["networkCalls"], false);
    }

    #[test]
    fn import_dry_run_json_reports_clamped_max_prs() {
        let args = validate_args(import_args_with_budget(0)).expect("valid args");
        let payload = dry_run_payload(&args, "acme/fork", "acme/upstream");

        assert_eq!(payload["maxPrs"], 1);
        assert_eq!(payload["requestedMaxPrs"], 0);
        assert_eq!(payload["maxPrsClamped"], true);
    }

    #[test]
    fn import_json_payload_reports_cloud_upload_queue_result() {
        let progress = ImportProgress {
            prs_total: 2,
            prs_fetched: 1,
            comments_imported: 13,
            comments_skipped: 0,
            prs_missing: 2,
            missing_pr_numbers: vec![404, 405],
        };
        let payload = import_json_payload(&ImportReport {
            provider: "github",
            gitlab_host: None,
            repo: "acme/fork",
            source_repo: "acme/upstream",
            max_prs: 1,
            requested_max_prs: 0,
            result: &progress,
            distill: ImportDistillArg::Heuristic,
            local_candidates: None,
            uploaded_reviews: 7,
        });

        assert_eq!(payload["provider"], "github");
        assert!(payload["gitlabHost"].is_null());
        assert_eq!(payload["repo"], "acme/fork");
        assert_eq!(payload["sourceRepo"], "acme/upstream");
        assert_eq!(payload["maxPrs"], 1);
        assert_eq!(payload["requestedMaxPrs"], 0);
        assert_eq!(payload["maxPrsClamped"], true);
        assert_eq!(payload["prsFetched"], 1);
        assert_eq!(payload["commentsImported"], 13);
        assert_eq!(payload["prsMissing"], 2);
        assert_eq!(payload["missingPrNumbers"], serde_json::json!([404, 405]));
        assert_eq!(payload["uploadedReviews"], 7);
        assert_eq!(payload["cloudUploadQueued"], true);
    }

    #[test]
    fn import_json_payload_names_the_gitlab_provider_and_host() {
        let progress = ImportProgress {
            prs_total: 1,
            prs_fetched: 1,
            comments_imported: 4,
            comments_skipped: 0,
            prs_missing: 0,
            missing_pr_numbers: Vec::new(),
        };
        let payload = import_json_payload(&ImportReport {
            provider: "gitlab",
            gitlab_host: Some("gitlab.corp.example"),
            repo: "group/sub/project",
            source_repo: "group/sub/project",
            max_prs: 10,
            requested_max_prs: 10,
            result: &progress,
            distill: ImportDistillArg::Heuristic,
            local_candidates: None,
            uploaded_reviews: 0,
        });

        assert_eq!(payload["provider"], "gitlab");
        assert_eq!(payload["gitlabHost"], "gitlab.corp.example");
        assert_eq!(payload["repo"], "group/sub/project");
        assert_eq!(payload["maxPrsClamped"], false);
        assert_eq!(payload["cloudUploadQueued"], false);
    }

    fn import_args_with_budget(max_prs: usize) -> ImportArgs {
        ImportArgs {
            repo: None,
            from_upstream: None,
            provider: None,
            gitlab_host: None,
            max_prs,
            pr_numbers: Vec::new(),
            exclude_prs: Vec::new(),
            since: None,
            include_open: false,
            upload: false,
            distill: ImportDistillArg::Heuristic,
            dry_run: false,
            json: true,
            wall_timeout_secs: None,
        }
    }

    #[tokio::test]
    async fn exclude_prs_yields_no_rules_from_the_excluded_pr() {
        // Leak-free recall eval relies on this: import a repo's review memory
        // while withholding the exact PR recall will be tested on. Seed two
        // PRs with distinct, high-signal directives; exclude one and assert it
        // contributes zero rules while the other still does.
        let db = fresh_import_pool().await;
        seed_pr_with_directive(
            &db,
            "acme/widgets",
            7,
            "We should validate the header before parsing because otherwise malformed requests panic.",
            "src/http/request.rs",
        )
        .await;
        seed_pr_with_directive(
            &db,
            "acme/widgets",
            8,
            "We should prefer Mapping[str, str] here instead of dict[str, str] to keep callers flexible.",
            "src/http/headers.py",
        )
        .await;

        let exclude: HashSet<i32> = std::iter::once(8).collect();
        let source_scope = github_scope("acme/widgets");
        let progress = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            25,
            &[],
            &exclude,
        )
        .await;

        // Only PR #7's directive survives — PR #8 produced no candidate.
        assert_eq!(
            progress.candidates_created, 1,
            "excluded PR #8 must contribute zero rules"
        );

        let memories = difflore_core::skills::list_all_skills(&db)
            .await
            .expect("list active memories");
        assert_eq!(memories.len(), 1, "memories: {memories:?}");
        assert!(
            memories
                .iter()
                .any(|m| m.name.contains("Validate the header")),
            "PR #7's rule should be present: {memories:?}"
        );
        assert!(
            !memories.iter().any(|m| m.name.contains("Prefer Mapping")),
            "PR #8 was excluded, so its rule must not appear: {memories:?}"
        );
    }

    #[tokio::test]
    async fn empty_exclude_set_keeps_every_prs_rules() {
        // Control for the exclude test: with no exclusions both seeded PRs
        // contribute their directive.
        let db = fresh_import_pool().await;
        seed_pr_with_directive(
            &db,
            "acme/widgets",
            7,
            "We should validate the header before parsing because otherwise malformed requests panic.",
            "src/http/request.rs",
        )
        .await;
        seed_pr_with_directive(
            &db,
            "acme/widgets",
            8,
            "We should prefer Mapping[str, str] here instead of dict[str, str] to keep callers flexible.",
            "src/http/headers.py",
        )
        .await;

        let source_scope = github_scope("acme/widgets");
        let progress = run_local_candidates(
            &db,
            "github",
            "acme/widgets",
            &source_scope,
            25,
            &[],
            &HashSet::new(),
        )
        .await;

        assert_eq!(
            progress.candidates_created, 2,
            "no exclusions means both PRs contribute rules"
        );
    }
}