All files / src review.service.ts

90.77% Statements 1083/1193
81.13% Branches 800/986
95.13% Functions 137/144
90.9% Lines 1010/1111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                              1x 1x   1x                                                                                           223x 223x 223x 223x 223x 223x 223x 223x   223x                                   15x 15x 15x   15x 5x     15x 15x   3x 3x 2x 2x 1x 1x             15x 2x     13x 13x 1x     12x 12x   12x   12x 1x       12x 12x 5x 5x 4x 3x 3x 1x       1x 1x         12x       12x 1x   12x 1x       12x 12x 12x 6x 6x 6x 1x         12x                                                                                               15x   2x 2x 4x   1x   3x                           21x 14x   7x   2x   2x   2x   1x                   3x 3x 1x     2x 2x 2x       2x                                                                   19x     19x   19x 4x 4x 4x 4x       19x 1x       18x 2x     16x     16x 16x   16x 13x 4x   13x 12x 12x 12x 4x 4x 4x   3x   2x 1x     1x   1x     1x 1x 1x           1x     1x       14x 14x 14x 14x   14x         14x 2x 3x 2x           14x 1x 2x 1x         1x 1x 1x 1x 1x 1x   2x 1x           14x 1x 2x 1x 2x 1x       1x 1x 1x 1x 1x 1x 1x     1x 1x           14x 14x 4x     14x 1x       1x                 1x     1x                   13x 19x                 13x         13x 13x 3x 3x 2x       13x 19x 4x     13x             13x               13x     13x 13x   13x 13x   13x 4x     13x     13x       13x 4x     13x 13x 4x     13x             13x           13x 10x     10x           10x     3x 1x         13x       13x 4x     13x 13x 4x     13x 13x   13x 2x 2x 2x 2x       2x       2x 2x       2x                   2x 1x         1x 1x       2x       2x     2x 2x         13x 12x       13x 4x 2x     4x                   4x 2x         13x 1x                         1x     1x 1x     1x                   1x           13x           13x   13x               6x   6x 1x     6x 1x       5x 5x 2x 2x                 3x 1x       3x 3x                 3x     3x     3x 3x                   3x 3x     3x     3x 1x 1x   1x 1x 1x       3x             16x 4x   16x 16x 1x     16x 16x 16x 16x   16x 4x     16x 16x 16x 16x       16x                         4x 4x   4x       4x 3x 1x   3x     1x             1x 1x           1x 1x 1x                                 1x                           5x 9x 9x 9x 5x 5x 5x 5x             6x   6x 2x     6x 1x     5x                             5x 5x 5x 4x 4x 1x 1x 1x       5x 2x 1x 2x     5x     5x                   5x           5x 2x 1x   2x 2x 1x           5x   5x                     5x 5x     5x 5x                     3x 3x                             6x 4x 4x   2x                                 10x 10x         10x 1x     10x 10x 8x   8x 7x   1x   7x     7x           7x     8x 5x 2x             7x 1x 1x 1x 1x               1x         1x           7x 20x   20x 20x   7x   1x         10x 1x   10x               2x   2x 2x 2x     2x                                                               20x 20x   19x   20x 1x       19x 2x       17x               17x                                                                 17x 17x   16x 16x 16x 14x             2x 2x   3x 3x       2x 2x 3x 1x     2x 1x 1x     2x   1x     16x     17x   16x     16x 16x   16x 16x 1x 1x 1x 1x   1x 1x 1x 1x         1x   1x     1x     16x                                         16x 16x 16x   16x       17x             18x 7x 7x 3x   5x 4x 4x 7x 2x   2x   3x 2x 2x                             21x 1x       21x 21x 18x 18x 12x 12x 12x         21x 21x 4x 4x 4x 2x 2x 2x                   21x 21x   18x 18x 18x 1x       18x 18x 18x 6x       12x     2x   2x 1x 1x   1x         21x 1x       21x 21x 21x   21x 6x 15x     2x   2x     21x 1x     21x   13x 1x     1x     12x   13x 13x           12x         17x 17x   17x 16x     1x 1x   1x           1x   1x                         1x                 2x 2x 2x       2x           2x     2x             2x   2x 2x     2x 2x   2x 2x 1x 1x   1x                 2x 2x   2x                     5x             5x                                           5x     5x 5x 1x     5x 3x     2x 2x         3x 3x         5x                               4x 4x   3x 3x   3x 1x     2x   4x                                     3x 3x   3x   3x     3x 3x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x       1x 1x     3x                             3x 3x     3x 3x 3x 2x 1x 1x       2x 2x 3x 3x   1x     1x                     24x   20x     24x   22x   24x                       24x 24x     24x 24x 4x 3x 1x 1x     4x   20x               24x 24x                   22x   22x 22x 18x   18x   18x 18x     22x 21x 21x 21x 19x 19x 19x 19x 19x   22x             35x   35x   35x 19x               16x                     12x     12x 1x 1x 1x             12x     12x     12x     12x 12x             12x               12x             12x 12x     12x 12x   1x 1x   1x                 11x 10x     1x       12x 12x 12x 1x   1x         1x 1x 1x   12x 1x 1x 1x 1x           1x                                                                                                     14x 14x 13x 1x     1x 1x 2x           13x 3x 2x   1x 1x                             23x 23x 22x 18x     4x 4x 5x   4x 4x 4x     3x 2x 2x 2x       3x 1x   1x     3x 3x 3x 3x         3x             1x               12x 11x 11x 9x 9x 9x                               26x 26x 25x 25x 17x 1x   17x       8x     8x 10x 2x     8x 3x           8x 8x   7x 2x 2x     6x 1x 1x   1x         6x 1x 1x 1x 1x 1x 1x     1x 1x 1x                         8x 3x       8x             8x   8x 5x   4x   4x   4x 4x   4x 4x         4x   3x 3x 5x 5x 5x 5x   5x     4x         3x 5x 5x 2x 2x                 8x   1x                   16x 16x               14x   13x   12x 10x                                                   14x   14x 14x 11x     14x 14x 18x 17x 17x 18x 18x     14x 10x   5x 7x 7x 7x     5x 5x 11x 11x 11x   4x 4x     7x 1x     6x   11x 3x     3x       5x   5x 3x   5x                     1x                           5x   5x 5x 4x   2x   4x 1x 1x 1x 1x             1x     5x 5x 4x 4x 2x 2x 2x 1x   1x         1x   5x 2x                         6x 4x 4x 6x   4x 4x 4x 4x 4x   4x 4x 4x 1x   3x           4x 8x 1x 4x 4x 1x 4x   1x 1x 1x     1x 1x 1x 1x 1x 1x 1x       4x             6x 6x 1x   5x     5x 6x 6x 6x 6x 6x 1x   5x 6x 6x 1x 1x 1x 1x 1x 1x   5x                 31x       6x 6x 1x   5x                                       13x 3x 1x   3x     10x 7x     10x   10x 8x   8x 3x 2x   3x       3x 3x         3x 3x   7x 2x       5x 3x 3x 2x   3x     2x     3x 2x     3x   4x 3x   4x                                   13x 13x 13x   15x 5x     10x 10x   2x     8x 8x       8x 8x 8x     8x 8x   3x 3x 1x   3x         5x 3x   2x 2x   1x   1x         5x 5x 5x 1x   5x           13x 2x 2x 2x 2x     13x                         22x   22x 3x     22x 22x 18x 18x   5x 1x   5x     13x 13x 2x 1x   2x       11x 15x 15x 15x 15x 6x 1x       6x           5x 2x   5x             5x   22x 2x   22x                     4x 4x 5x   4x 4x               7x   7x 6x 6x 4x     1x   3x       4x 4x   2x 2x 2x     2x   1x                                     3x     3x 3x   2x 2x     2x 2x 1x     1x   2x   2x   1x     1x 1x   1x     1x 1x         3x      
import {
  GitProviderService,
  PullRequest,
  PullRequestCommit,
  ChangedFile,
  CreatePullReviewComment,
  REVIEW_STATE,
  type CiConfig,
  type LLMMode,
  LlmProxyService,
  logStreamEvent,
  createStreamLoggerState,
  type VerboseLevel,
  shouldLog,
  normalizeVerbose,
  type LlmJsonPutSchema,
  LlmJsonPut,
  parallel,
  GitSdkService,
  parseChangedLinesFromPatch,
  parseDiffText,
  parseHunksFromPatch,
  calculateNewLineNumber,
} from "@spaceflow/core";
import type { IConfigReader } from "@spaceflow/core";
import { type AnalyzeDeletionsMode, type ReviewConfig } from "./review.config";
import {
  ReviewSpecService,
  ReviewSpec,
  ReviewIssue,
  ReviewResult,
  ReviewStats,
  FileSummary,
  FileContentsMap,
  FileContentLine,
  type UserInfo,
} from "./review-spec";
import { MarkdownFormatter, ReviewReportService, type ReportFormat } from "./review-report";
import { execSync } from "child_process";
import { readFile, readdir } from "fs/promises";
import { join, dirname, extname, relative, isAbsolute } from "path";
import micromatch from "micromatch";
import { ReviewOptions } from "./review.config";
import { IssueVerifyService } from "./issue-verify.service";
import { DeletionImpactService } from "./deletion-impact.service";
import { parseTitleOptions } from "./parse-title-options";
import { homedir } from "os";
 
export interface ReviewContext extends ReviewOptions {
  owner: string;
  repo: string;
  prNumber?: number;
  baseRef?: string;
  headRef?: string;
  specSources: string[];
  verbose?: VerboseLevel;
  includes?: string[];
  files?: string[];
  commits?: string[];
  concurrency?: number;
  timeout?: number;
  retries?: number;
  retryDelay?: number;
  /** 仅执行删除代码分析,跳过常规代码审查 */
  deletionOnly?: boolean;
  /** 删除代码分析模式:openai 使用标准模式,claude-agent 使用 Agent 模式 */
  deletionAnalysisMode?: LLMMode;
  /** 输出格式:markdown, terminal, json。不指定则智能选择 */
  outputFormat?: ReportFormat;
  /** 是否使用 AI 生成 PR 功能描述 */
  generateDescription?: boolean;
  /** 显示所有问题,不过滤非变更行的问题 */
  showAll?: boolean;
  /** PR 事件类型(opened, synchronize, closed 等) */
  eventAction?: string;
}
 
export interface FileReviewPrompt {
  filename: string;
  systemPrompt: string;
  userPrompt: string;
}
 
export interface ReviewPrompt {
  filePrompts: FileReviewPrompt[];
}
 
export interface LLMReviewOptions {
  verbose?: VerboseLevel;
  concurrency?: number;
  timeout?: number;
  retries?: number;
  retryDelay?: number;
}
 
const REVIEW_COMMENT_MARKER = "<!-- spaceflow-review -->";
const REVIEW_LINE_COMMENTS_MARKER = "<!-- spaceflow-review-lines -->";
 
const REVIEW_SCHEMA: LlmJsonPutSchema = {
  type: "object",
  properties: {
    issues: {
      type: "array",
      items: {
        type: "object",
        properties: {
          file: { type: "string", description: "发生问题的文件路径" },
          line: {
            type: "string",
            description:
              "问题所在的行号,只支持单行或多行 (如 123 或 123-125),不允许使用 `,` 分隔多个行号",
          },
          ruleId: { type: "string", description: "违反的规则 ID(如 JsTs.FileName.UpperCamel)" },
          specFile: {
            type: "string",
            description: "规则来源的规范文件名(如 js&ts.file-name.md)",
          },
          reason: { type: "string", description: "问题的简要概括" },
          suggestion: {
            type: "string",
            description:
              "修改后的完整代码片段。要求以代码为主体,并在代码中使用详细的中文注释解释逻辑改进点。不要包含 Markdown 反引号。",
          },
          commit: { type: "string", description: "相关的 7 位 commit SHA" },
          severity: {
            type: "string",
            description: "问题严重程度,根据规则文档中的 severity 标记确定",
            enum: ["error", "warn"],
          },
        },
        required: ["file", "line", "ruleId", "specFile", "reason"],
        additionalProperties: false,
      },
    },
    summary: { type: "string", description: "本次代码审查的整体总结" },
  },
  required: ["issues", "summary"],
  additionalProperties: false,
};
 
export class ReviewService {
  protected readonly llmJsonPut: LlmJsonPut<ReviewResult>;
 
  constructor(
    protected readonly gitProvider: GitProviderService,
    protected readonly config: IConfigReader,
    protected readonly reviewSpecService: ReviewSpecService,
    protected readonly llmProxyService: LlmProxyService,
    protected readonly reviewReportService: ReviewReportService,
    protected readonly issueVerifyService: IssueVerifyService,
    protected readonly deletionImpactService: DeletionImpactService,
    protected readonly gitSdk: GitSdkService,
  ) {
    this.llmJsonPut = new LlmJsonPut(REVIEW_SCHEMA, {
      llmRequest: async (prompt) => {
        const response = await this.llmProxyService.chat(
          [
            { role: "system", content: prompt.systemPrompt },
            { role: "user", content: prompt.userPrompt },
          ],
          { adapter: "openai" },
        );
        if (!response.content) {
          throw new Error("LLM 返回了空内容");
        }
        return response.content;
      },
    });
  }
 
  async getContextFromEnv(options: ReviewOptions): Promise<ReviewContext> {
    const reviewConf = this.config.getPluginConfig<ReviewConfig>("review");
    const ciConf = this.config.get<CiConfig>("ci");
    const repository = ciConf?.repository;
 
    if (options.ci) {
      this.gitProvider.validateConfig();
    }
 
    let repoPath = repository;
    if (!repoPath) {
      // 非 CI 模式下,从 git remote 获取仓库信息
      const remoteUrl = this.gitSdk.getRemoteUrl();
      if (remoteUrl) {
        const parsed = this.gitSdk.parseRepositoryFromRemoteUrl(remoteUrl);
        if (parsed) {
          repoPath = `${parsed.owner}/${parsed.repo}`;
          Iif (shouldLog(options.verbose, 1)) {
            console.log(`📦 从 git remote 获取仓库: ${repoPath}`);
          }
        }
      }
    }
 
    if (!repoPath) {
      throw new Error("缺少配置 ci.repository");
    }
 
    const parts = repoPath.split("/");
    if (parts.length < 2) {
      throw new Error("ci.repository 格式不正确");
    }
 
    const owner = parts[0];
    const repo = parts[1];
 
    let prNumber = options.prNumber;
 
    if (!prNumber && options.ci) {
      prNumber = await this.getPrNumberFromEvent();
    }
 
    // 从 PR 标题解析命令参数(命令行参数优先,标题参数作为补充)
    let titleOptions: ReturnType<typeof parseTitleOptions> = {};
    if (prNumber && options.ci) {
      try {
        const pr = await this.gitProvider.getPullRequest(owner, repo, prNumber);
        if (pr?.title) {
          titleOptions = parseTitleOptions(pr.title);
          if (Object.keys(titleOptions).length > 0 && shouldLog(options.verbose, 1)) {
            console.log(`📋 从 PR 标题解析到参数:`, titleOptions);
          }
        }
      } catch (error) {
        Eif (shouldLog(options.verbose, 1)) {
          console.warn(`⚠️ 获取 PR 标题失败:`, error);
        }
      }
    }
 
    const specSources = [
      join(homedir(), ".spaceflow", "deps"),
      join(process.cwd(), ".spaceflow", "deps"),
    ];
    if (options.references?.length) {
      specSources.push(...options.references);
    }
    if (reviewConf.references?.length) {
      specSources.push(...reviewConf.references);
    }
 
    // 当没有 PR 且没有指定 base/head 时,自动获取默认值
    let baseRef = options.base;
    let headRef = options.head;
    if (!prNumber && !baseRef && !headRef) {
      headRef = this.gitSdk.getCurrentBranch() ?? "HEAD";
      baseRef = this.gitSdk.getDefaultBranch();
      if (shouldLog(options.verbose, 1)) {
        console.log(`📌 自动检测分支: base=${baseRef}, head=${headRef}`);
      }
    }
 
    // 合并参数优先级:命令行 > PR 标题 > 配置文件 > 默认值
    return {
      owner,
      repo,
      prNumber,
      baseRef,
      headRef,
      specSources,
      dryRun: options.dryRun || titleOptions.dryRun || false,
      ci: options.ci ?? false,
      verbose: normalizeVerbose(options.verbose ?? titleOptions.verbose),
      includes: options.includes ?? titleOptions.includes ?? reviewConf.includes,
      llmMode: options.llmMode ?? titleOptions.llmMode ?? reviewConf.llmMode,
      files: this.normalizeFilePaths(options.files),
      commits: options.commits,
      verifyFixes:
        options.verifyFixes ?? titleOptions.verifyFixes ?? reviewConf.verifyFixes ?? true,
      verifyConcurrency: options.verifyConcurrency ?? reviewConf.verifyFixesConcurrency ?? 10,
      analyzeDeletions: this.resolveAnalyzeDeletions(
        options.analyzeDeletions ??
          options.deletionOnly ??
          titleOptions.analyzeDeletions ??
          titleOptions.deletionOnly ??
          reviewConf.analyzeDeletions ??
          false,
        { ci: options.ci, hasPrNumber: !!prNumber },
      ),
      deletionOnly: options.deletionOnly || titleOptions.deletionOnly || false,
      deletionAnalysisMode:
        options.deletionAnalysisMode ??
        titleOptions.deletionAnalysisMode ??
        reviewConf.deletionAnalysisMode ??
        "openai",
      concurrency: options.concurrency ?? reviewConf.concurrency ?? 5,
      timeout: options.timeout ?? reviewConf.timeout,
      retries: options.retries ?? reviewConf.retries ?? 0,
      retryDelay: options.retryDelay ?? reviewConf.retryDelay ?? 1000,
      generateDescription: options.generateDescription ?? reviewConf.generateDescription ?? false,
      showAll: options.showAll ?? false,
      flush: options.flush ?? false,
      eventAction: options.eventAction,
    };
  }
 
  /**
   * 将文件路径规范化为相对于仓库根目录的路径
   * 支持绝对路径和相对路径输入
   */
  protected normalizeFilePaths(files?: string[]): string[] | undefined {
    if (!files || files.length === 0) return files;
 
    const cwd = process.cwd();
    return files.map((file) => {
      if (isAbsolute(file)) {
        // 绝对路径转换为相对路径
        return relative(cwd, file);
      }
      return file;
    });
  }
 
  /**
   * 根据 AnalyzeDeletionsMode 和当前环境解析是否启用删除代码分析
   * @param mode 配置的模式值
   * @param env 当前环境信息
   * @returns 是否启用删除代码分析
   */
  protected resolveAnalyzeDeletions(
    mode: AnalyzeDeletionsMode,
    env: { ci: boolean; hasPrNumber: boolean },
  ): boolean {
    if (typeof mode === "boolean") {
      return mode;
    }
    switch (mode) {
      case "ci":
        return env.ci;
      case "pr":
        return env.hasPrNumber;
      case "terminal":
        return !env.ci;
      default:
        return false;
    }
  }
 
  /**
   * 从 CI 事件文件中解析 PR 编号
   * 在 CI 环境中,GitHub/Gitea Actions 会将事件信息写入 GITHUB_EVENT_PATH / GITEA_EVENT_PATH 指向的文件
   * @returns PR 编号,如果无法解析则返回 undefined
   */
  protected async getPrNumberFromEvent(): Promise<number | undefined> {
    const eventPath = process.env.GITHUB_EVENT_PATH || process.env.GITEA_EVENT_PATH;
    if (!eventPath) {
      return undefined;
    }
 
    try {
      const eventContent = await readFile(eventPath, "utf-8");
      const event = JSON.parse(eventContent);
      // 支持多种事件类型:
      // - pull_request 事件: event.pull_request.number 或 event.number
      // - issue_comment 事件: event.issue.number
      return event.pull_request?.number || event.issue?.number || event.number;
    } catch {
      return undefined;
    }
  }
 
  /**
   * 执行代码审查的主方法
   * 该方法负责协调整个审查流程,包括:
   * 1. 加载审查规范(specs)
   * 2. 获取 PR/分支的变更文件和提交记录
   * 3. 调用 LLM 进行代码审查
   * 4. 处理历史 issue(更新行号、验证修复状态)
   * 5. 生成并发布审查报告
   *
   * @param context 审查上下文,包含 owner、repo、prNumber 等信息
   * @returns 审查结果,包含发现的问题列表和统计信息
   */
  async execute(context: ReviewContext): Promise<ReviewResult> {
    const {
      owner,
      repo,
      prNumber,
      baseRef,
      headRef,
      specSources,
      dryRun,
      ci,
      verbose,
      includes,
      llmMode,
      files,
      commits: filterCommits,
      deletionOnly,
    } = context;
 
    // 直接审查文件模式:指定了 -f 文件且 base=head
    const isDirectFileMode = files && files.length > 0 && baseRef === headRef;
 
    if (shouldLog(verbose, 1)) {
      console.log(`🔍 Review 启动`);
      console.log(`   DRY-RUN mode: ${dryRun ? "enabled" : "disabled"}`);
      console.log(`   CI mode: ${ci ? "enabled" : "disabled"}`);
      console.log(`   Verbose: ${verbose}`);
    }
 
    // 如果是 deletionOnly 模式,直接执行删除代码分析
    if (deletionOnly) {
      return this.executeDeletionOnly(context);
    }
 
    // 如果是 closed 事件或 flush 模式,仅收集 review 状态
    if (context.eventAction === "closed" || context.flush) {
      return this.executeCollectOnly(context);
    }
 
    const specs = await this.loadSpecs(specSources, verbose);
 
    let pr: PullRequest | undefined;
    let commits: PullRequestCommit[] = [];
    let changedFiles: ChangedFile[] = [];
 
    if (prNumber) {
      if (shouldLog(verbose, 1)) {
        console.log(`📥 获取 PR #${prNumber} 信息 (owner: ${owner}, repo: ${repo})`);
      }
      pr = await this.gitProvider.getPullRequest(owner, repo, prNumber);
      commits = await this.gitProvider.getPullRequestCommits(owner, repo, prNumber);
      changedFiles = await this.gitProvider.getPullRequestFiles(owner, repo, prNumber);
      if (shouldLog(verbose, 1)) {
        console.log(`   PR: ${pr?.title}`);
        console.log(`   Commits: ${commits.length}`);
        console.log(`   Changed files: ${changedFiles.length}`);
      }
    } else if (baseRef && headRef) {
      // 如果指定了 -f 文件且 base=head(无差异模式),直接审查指定文件
      if (files && files.length > 0 && baseRef === headRef) {
        Iif (shouldLog(verbose, 1)) {
          console.log(`📥 直接审查指定文件模式 (${files.length} 个文件)`);
        }
        changedFiles = files.map((f) => ({ filename: f, status: "modified" as const }));
      } else {
        Iif (shouldLog(verbose, 1)) {
          console.log(`📥 获取 ${baseRef}...${headRef} 的差异 (owner: ${owner}, repo: ${repo})`);
        }
        changedFiles = await this.getChangedFilesBetweenRefs(owner, repo, baseRef, headRef);
        commits = await this.getCommitsBetweenRefs(baseRef, headRef);
        Iif (shouldLog(verbose, 1)) {
          console.log(`   Changed files: ${changedFiles.length}`);
          console.log(`   Commits: ${commits.length}`);
        }
      }
    } else {
      Iif (shouldLog(verbose, 1)) {
        console.log(`❌ 错误: 缺少 prNumber 或 baseRef/headRef`, { prNumber, baseRef, headRef });
      }
      throw new Error("必须指定 PR 编号或者 base/head 分支");
    }
 
    // 0. 过滤掉 merge commit(消息以 "Merge branch" 开头的 commit)
    const beforeMergeFilterCount = commits.length;
    commits = commits.filter((c) => {
      const message = c.commit?.message || "";
      return !message.startsWith("Merge branch ");
    });
    Iif (beforeMergeFilterCount !== commits.length && shouldLog(verbose, 1)) {
      console.log(`   跳过 Merge Commits: ${beforeMergeFilterCount} -> ${commits.length} 个`);
    }
 
    // 1. 按指定的 files 过滤
    if (files && files.length > 0) {
      const beforeFilesCount = changedFiles.length;
      changedFiles = changedFiles.filter((f) => files.includes(f.filename || ""));
      Iif (shouldLog(verbose, 1)) {
        console.log(`   Files 过滤文件: ${beforeFilesCount} -> ${changedFiles.length} 个文件`);
      }
    }
 
    // 2. 按指定的 commits 过滤
    if (filterCommits && filterCommits.length > 0) {
      const beforeCommitsCount = commits.length;
      commits = commits.filter((c) => filterCommits.some((fc) => fc && c.sha?.startsWith(fc)));
      Iif (shouldLog(verbose, 1)) {
        console.log(`   Commits 过滤: ${beforeCommitsCount} -> ${commits.length} 个`);
      }
 
      // 同时也过滤变更文件,仅保留属于这些 commit 的文件
      const beforeFilesCount = changedFiles.length;
      const commitFilenames = new Set<string>();
      for (const commit of commits) {
        Iif (!commit.sha) continue;
        const commitFiles = await this.getFilesForCommit(owner, repo, commit.sha, prNumber);
        commitFiles.forEach((f) => commitFilenames.add(f));
      }
      changedFiles = changedFiles.filter((f) => commitFilenames.has(f.filename || ""));
      Iif (shouldLog(verbose, 1)) {
        console.log(`   按 Commits 过滤文件: ${beforeFilesCount} -> ${changedFiles.length} 个文件`);
      }
    }
 
    // 3. 使用 includes 过滤文件和 commits
    if (includes && includes.length > 0) {
      const beforeFilesCount = changedFiles.length;
      const filenames = changedFiles.map((file) => file.filename || "");
      const matchedFilenames = micromatch(filenames, includes);
      changedFiles = changedFiles.filter((file) => matchedFilenames.includes(file.filename || ""));
      Iif (shouldLog(verbose, 1)) {
        console.log(`   Includes 过滤文件: ${beforeFilesCount} -> ${changedFiles.length} 个文件`);
      }
 
      const beforeCommitsCount = commits.length;
      const filteredCommits: PullRequestCommit[] = [];
      for (const commit of commits) {
        Iif (!commit.sha) continue;
        const commitFiles = await this.getFilesForCommit(owner, repo, commit.sha, prNumber);
        Eif (micromatch.some(commitFiles, includes)) {
          filteredCommits.push(commit);
        }
      }
      commits = filteredCommits;
      Iif (shouldLog(verbose, 1)) {
        console.log(`   Includes 过滤 Commits: ${beforeCommitsCount} -> ${commits.length} 个`);
      }
    }
 
    // 只按扩展名过滤规则,includes 和 override 在 LLM 审查后处理
    const applicableSpecs = this.reviewSpecService.filterApplicableSpecs(specs, changedFiles);
    if (shouldLog(verbose, 1)) {
      console.log(`   适用的规则文件: ${applicableSpecs.length}`);
    }
 
    if (applicableSpecs.length === 0 || changedFiles.length === 0) {
      Iif (shouldLog(verbose, 1)) {
        console.log("✅ 没有需要审查的文件或规则");
      }
      // 即使没有适用的规则,也为每个变更文件生成摘要
      const summary: FileSummary[] = changedFiles
        .filter((f) => f.filename && f.status !== "deleted")
        .map((f) => ({
          file: f.filename!,
          resolved: 0,
          unresolved: 0,
          summary: applicableSpecs.length === 0 ? "无适用的审查规则" : "已跳过",
        }));
      const prInfo =
        context.generateDescription && llmMode
          ? await this.generatePrDescription(commits, changedFiles, llmMode, undefined, verbose)
          : await this.buildFallbackDescription(commits, changedFiles);
      return {
        success: true,
        title: prInfo.title,
        description: prInfo.description,
        issues: [],
        summary,
        round: 1,
      };
    }
 
    const headSha = pr?.head?.sha || headRef || "HEAD";
    const fileContents = await this.getFileContents(
      owner,
      repo,
      changedFiles,
      commits,
      headSha,
      prNumber,
      verbose,
    );
    Iif (!llmMode) {
      throw new Error("必须指定 LLM 类型");
    }
 
    // 获取上一次的审查结果(用于提示词优化)
    let existingResult: ReviewResult | null = null;
    if (ci && prNumber) {
      existingResult = await this.getExistingReviewResult(owner, repo, prNumber);
      if (existingResult && shouldLog(verbose, 1)) {
        console.log(`📋 获取到上一次审查结果,包含 ${existingResult.issues.length} 个问题`);
      }
    }
    // 计算当前轮次:基于已有结果的轮次 + 1
    const currentRound = (existingResult?.round ?? 0) + 1;
    if (shouldLog(verbose, 1)) {
      console.log(`🔄 当前审查轮次: ${currentRound}`);
    }
 
    const reviewPrompt = await this.buildReviewPrompt(
      specs,
      changedFiles,
      fileContents,
      commits,
      existingResult,
    );
    const result = await this.runLLMReview(llmMode, reviewPrompt, {
      verbose,
      concurrency: context.concurrency,
      timeout: context.timeout,
      retries: context.retries,
      retryDelay: context.retryDelay,
    });
    // 填充 PR 功能描述和标题
    const prInfo = context.generateDescription
      ? await this.generatePrDescription(commits, changedFiles, llmMode, fileContents, verbose)
      : await this.buildFallbackDescription(commits, changedFiles);
    result.title = prInfo.title;
    result.description = prInfo.description;
    // 更新 round 并为新 issues 赋值 round
    result.round = currentRound;
    result.issues = result.issues.map((issue) => ({ ...issue, round: currentRound }));
 
    if (shouldLog(verbose, 1)) {
      console.log(`📝 LLM 审查完成,发现 ${result.issues.length} 个问题`);
    }
 
    result.issues = await this.fillIssueCode(result.issues, fileContents);
 
    // 在 LLM 审查后应用 includes 和 override 过滤
    let filteredIssues = this.reviewSpecService.filterIssuesByIncludes(
      result.issues,
      applicableSpecs,
    );
    if (shouldLog(verbose, 1)) {
      console.log(`   应用 includes 过滤后: ${filteredIssues.length} 个问题`);
    }
 
    filteredIssues = this.reviewSpecService.filterIssuesByRuleExistence(filteredIssues, specs);
    if (shouldLog(verbose, 1)) {
      console.log(`   应用规则存在性过滤后: ${filteredIssues.length} 个问题`);
    }
 
    filteredIssues = this.reviewSpecService.filterIssuesByOverrides(
      filteredIssues,
      applicableSpecs,
      verbose,
    );
 
    // 过滤掉不属于本次 PR commits 的问题(排除 merge commit 引入的代码)
    Iif (shouldLog(verbose, 3)) {
      console.log(`   🔍 变更行过滤条件检查:`);
      console.log(
        `      showAll=${context.showAll}, isDirectFileMode=${isDirectFileMode}, commits.length=${commits.length}`,
      );
    }
    if (!context.showAll && !isDirectFileMode && commits.length > 0) {
      Iif (shouldLog(verbose, 2)) {
        console.log(`   🔍 开始变更行过滤,当前 ${filteredIssues.length} 个问题`);
      }
      filteredIssues = this.filterIssuesByValidCommits(
        filteredIssues,
        commits,
        fileContents,
        verbose,
      );
      Iif (shouldLog(verbose, 2)) {
        console.log(`   🔍 变更行过滤完成,剩余 ${filteredIssues.length} 个问题`);
      }
    } else if (shouldLog(verbose, 1)) {
      console.log(
        `   跳过变更行过滤 (${context.showAll ? "showAll=true" : isDirectFileMode ? "直接审查文件模式" : "commits.length=0"})`,
      );
    }
 
    filteredIssues = this.reviewSpecService.formatIssues(filteredIssues, {
      specs,
      changedFiles,
    });
    if (shouldLog(verbose, 1)) {
      console.log(`   应用格式化后: ${filteredIssues.length} 个问题`);
    }
 
    result.issues = filteredIssues;
    if (shouldLog(verbose, 1)) {
      console.log(`📝 最终发现 ${result.issues.length} 个问题`);
    }
 
    let existingIssues: ReviewIssue[] = [];
    let allIssues = result.issues;
 
    if (ci && prNumber && existingResult) {
      existingIssues = existingResult.issues ?? [];
      Eif (existingIssues.length > 0) {
        Eif (shouldLog(verbose, 1)) {
          console.log(`📋 已有评论中存在 ${existingIssues.length} 个问题`);
        }
 
        // 先同步最新的 resolved 状态,确保后续 invalidate/verify 能正确跳过已解决的问题
        await this.syncResolvedComments(owner, repo, prNumber, existingResult);
 
        // 如果文件有变更,将该文件的历史问题标记为无效
        // 简化策略:避免复杂的行号更新逻辑
        const reviewConf = this.config.getPluginConfig<ReviewConfig>("review");
        Eif (
          reviewConf.invalidateChangedFiles !== "off" &&
          reviewConf.invalidateChangedFiles !== "keep"
        ) {
          existingIssues = await this.invalidateIssuesForChangedFiles(
            existingIssues,
            pr?.head?.sha,
            owner,
            repo,
            verbose,
          );
        }
 
        // 验证历史问题是否已修复
        if (context.verifyFixes) {
          existingIssues = await this.verifyAndUpdateIssues(context, existingIssues, commits, {
            specs,
            fileContents,
          });
        } else {
          Eif (shouldLog(verbose, 1)) {
            console.log(`   ⏭️  跳过历史问题验证 (verifyFixes=false)`);
          }
        }
 
        const { filteredIssues: newIssues, skippedCount } = this.filterDuplicateIssues(
          result.issues,
          existingIssues,
        );
        Iif (skippedCount > 0 && shouldLog(verbose, 1)) {
          console.log(`   跳过 ${skippedCount} 个重复问题,新增 ${newIssues.length} 个问题`);
        }
        result.issues = newIssues;
        allIssues = [...existingIssues, ...newIssues];
      }
    }
 
    // 统一填充所有问题的 author 信息(仅在有 commits 时)
    if (commits.length > 0) {
      allIssues = await this.fillIssueAuthors(allIssues, commits, owner, repo, verbose);
    }
 
    // 第一次提交报告:审查问题完成
    if (prNumber && !dryRun) {
      if (shouldLog(verbose, 1)) {
        console.log(`💬 提交 PR 评论 (代码审查完成)...`);
      }
 
      await this.postOrUpdateReviewComment(
        owner,
        repo,
        prNumber,
        {
          ...result,
          issues: allIssues,
        },
        verbose,
      );
      if (shouldLog(verbose, 1)) {
        console.log(`✅ 评论已提交`);
      }
    }
 
    // 如果启用了删除代码影响分析
    if (context.analyzeDeletions && llmMode) {
      const deletionImpact = await this.deletionImpactService.analyzeDeletionImpact(
        {
          owner,
          repo,
          prNumber,
          baseRef,
          headRef,
          analysisMode: context.deletionAnalysisMode,
          includes,
        },
        llmMode,
        verbose,
      );
      result.deletionImpact = deletionImpact;
 
      // 第二次更新报告:删除代码分析完成
      Eif (prNumber && !dryRun) {
        Iif (shouldLog(verbose, 1)) {
          console.log(`💬 更新 PR 评论 (删除代码分析完成)...`);
        }
        await this.postOrUpdateReviewComment(
          owner,
          repo,
          prNumber,
          {
            ...result,
            issues: allIssues,
          },
          verbose,
        );
        Iif (shouldLog(verbose, 1)) {
          console.log(`✅ 评论已更新`);
        }
      }
    }
 
    const reviewComment = this.formatReviewComment(
      { ...result, issues: allIssues },
      { prNumber, outputFormat: context.outputFormat, ci },
    );
 
    // 终端输出(根据 outputFormat 或智能选择)
    console.log(MarkdownFormatter.clearReviewData(reviewComment, "<hidden>"));
 
    return result;
  }
 
  /**
   * 仅收集 review 状态模式(用于 PR 关闭或 --flush 指令)
   * 从现有的 AI review 评论中读取问题状态,同步已解决/无效状态,输出统计信息
   */
  protected async executeCollectOnly(context: ReviewContext): Promise<ReviewResult> {
    const { owner, repo, prNumber, verbose, ci, dryRun } = context;
 
    if (shouldLog(verbose, 1)) {
      console.log(`📊 仅收集 review 状态模式`);
    }
 
    if (!prNumber) {
      throw new Error("collectOnly 模式必须指定 PR 编号");
    }
 
    // 1. 从现有的 AI review 评论中读取问题
    const existingResult = await this.getExistingReviewResult(owner, repo, prNumber);
    if (!existingResult) {
      console.log(`ℹ️  PR #${prNumber} 没有找到 AI review 评论`);
      return {
        success: true,
        description: "",
        issues: [],
        summary: [],
        round: 0,
      };
    }
 
    if (shouldLog(verbose, 1)) {
      console.log(`📋 找到 ${existingResult.issues.length} 个历史问题`);
    }
 
    // 2. 获取 commits 并填充 author 信息
    const commits = await this.gitProvider.getPullRequestCommits(owner, repo, prNumber);
    existingResult.issues = await this.fillIssueAuthors(
      existingResult.issues,
      commits,
      owner,
      repo,
      verbose,
    );
 
    // 3. 同步已解决的评论状态
    await this.syncResolvedComments(owner, repo, prNumber, existingResult);
 
    // 4. 同步评论 reactions(👍/👎)
    await this.syncReactionsToIssues(owner, repo, prNumber, existingResult, verbose);
 
    // 5. LLM 验证历史问题是否已修复
    try {
      existingResult.issues = await this.verifyAndUpdateIssues(
        context,
        existingResult.issues,
        commits,
      );
    } catch (error) {
      console.warn("⚠️ LLM 验证修复状态失败,跳过:", error);
    }
 
    // 6. 统计问题状态并设置到 result
    const stats = this.calculateIssueStats(existingResult.issues);
    existingResult.stats = stats;
 
    // 7. 输出统计信息
    console.log(this.reviewReportService.formatStatsTerminal(stats, prNumber));
 
    // 8. 更新 PR 评论(如果不是 dry-run)
    if (ci && !dryRun) {
      Eif (shouldLog(verbose, 1)) {
        console.log(`💬 更新 PR 评论...`);
      }
      await this.postOrUpdateReviewComment(owner, repo, prNumber, existingResult, verbose);
      Eif (shouldLog(verbose, 1)) {
        console.log(`✅ 评论已更新`);
      }
    }
 
    return existingResult;
  }
 
  /**
   * 加载并去重审查规则
   */
  protected async loadSpecs(specSources: string[], verbose?: VerboseLevel): Promise<ReviewSpec[]> {
    if (shouldLog(verbose, 1)) {
      console.log(`📂 解析规则来源: ${specSources.length} 个`);
    }
    const specDirs = await this.reviewSpecService.resolveSpecSources(specSources);
    if (shouldLog(verbose, 2)) {
      console.log(`   解析到 ${specDirs.length} 个规则目录`, specDirs);
    }
 
    let specs: ReviewSpec[] = [];
    for (const specDir of specDirs) {
      const dirSpecs = await this.reviewSpecService.loadReviewSpecs(specDir);
      specs.push(...dirSpecs);
    }
    if (shouldLog(verbose, 1)) {
      console.log(`   找到 ${specs.length} 个规则文件`);
    }
 
    const beforeDedup = specs.reduce((sum, s) => sum + s.rules.length, 0);
    specs = this.reviewSpecService.deduplicateSpecs(specs);
    const afterDedup = specs.reduce((sum, s) => sum + s.rules.length, 0);
    Iif (beforeDedup !== afterDedup && shouldLog(verbose, 1)) {
      console.log(`   去重规则: ${beforeDedup} -> ${afterDedup} 条`);
    }
 
    return specs;
  }
 
  /**
   * LLM 验证历史问题是否已修复
   * 如果传入 preloaded(specs/fileContents),直接使用;否则从 PR 获取
   */
  protected async verifyAndUpdateIssues(
    context: ReviewContext,
    issues: ReviewIssue[],
    commits: PullRequestCommit[],
    preloaded?: { specs: ReviewSpec[]; fileContents: FileContentsMap },
  ): Promise<ReviewIssue[]> {
    const { owner, repo, prNumber, llmMode, specSources, verbose } = context;
    const unfixedIssues = issues.filter((i) => i.valid !== "false" && !i.fixed);
 
    Iif (unfixedIssues.length === 0) {
      return issues;
    }
 
    if (!llmMode) {
      if (shouldLog(verbose, 1)) {
        console.log(`   ⏭️  跳过 LLM 验证(缺少 llmMode)`);
      }
      return issues;
    }
 
    Iif (!preloaded && (!specSources?.length || !prNumber)) {
      if (shouldLog(verbose, 1)) {
        console.log(`   ⏭️  跳过 LLM 验证(缺少 specSources 或 prNumber)`);
      }
      return issues;
    }
 
    Eif (shouldLog(verbose, 1)) {
      console.log(`\n🔍 开始 LLM 验证 ${unfixedIssues.length} 个未修复问题...`);
    }
 
    let specs: ReviewSpec[];
    let fileContents: FileContentsMap;
 
    if (preloaded) {
      specs = preloaded.specs;
      fileContents = preloaded.fileContents;
    } else E{
      const pr = await this.gitProvider.getPullRequest(owner, repo, prNumber!);
      const changedFiles = await this.gitProvider.getPullRequestFiles(owner, repo, prNumber!);
      const headSha = pr?.head?.sha || "HEAD";
      specs = await this.loadSpecs(specSources, verbose);
      fileContents = await this.getFileContents(
        owner,
        repo,
        changedFiles,
        commits,
        headSha,
        prNumber!,
        verbose,
      );
    }
 
    return this.issueVerifyService.verifyIssueFixes(
      issues,
      fileContents,
      specs,
      llmMode,
      verbose,
      context.verifyConcurrency,
    );
  }
 
  /**
   * 计算问题状态统计
   */
  protected calculateIssueStats(issues: ReviewIssue[]): ReviewStats {
    const total = issues.length;
    const fixed = issues.filter((i) => i.fixed).length;
    const resolved = issues.filter((i) => i.resolved && !i.fixed).length;
    const invalid = issues.filter((i) => i.valid === "false" && !i.fixed && !i.resolved).length;
    const pending = total - fixed - resolved - invalid;
    const fixRate = total > 0 ? Math.round((fixed / total) * 100 * 10) / 10 : 0;
    const resolveRate = total > 0 ? Math.round(((fixed + resolved) / total) * 100 * 10) / 10 : 0;
    return { total, fixed, resolved, invalid, pending, fixRate, resolveRate };
  }
 
  /**
   * 仅执行删除代码分析模式
   */
  protected async executeDeletionOnly(context: ReviewContext): Promise<ReviewResult> {
    const { owner, repo, prNumber, baseRef, headRef, dryRun, ci, verbose, llmMode } = context;
 
    if (shouldLog(verbose, 1)) {
      console.log(`🗑️  仅执行删除代码分析模式`);
    }
 
    if (!llmMode) {
      throw new Error("必须指定 LLM 类型");
    }
 
    const deletionImpact = await this.deletionImpactService.analyzeDeletionImpact(
      {
        owner,
        repo,
        prNumber,
        baseRef,
        headRef,
        analysisMode: context.deletionAnalysisMode,
        includes: context.includes,
      },
      llmMode,
      verbose,
    );
 
    // 获取 commits 和 changedFiles 用于生成描述
    let commits: PullRequestCommit[] = [];
    let changedFiles: ChangedFile[] = [];
    if (prNumber) {
      commits = await this.gitProvider.getPullRequestCommits(owner, repo, prNumber);
      changedFiles = await this.gitProvider.getPullRequestFiles(owner, repo, prNumber);
    } else Eif (baseRef && headRef) {
      changedFiles = await this.getChangedFilesBetweenRefs(owner, repo, baseRef, headRef);
      commits = await this.getCommitsBetweenRefs(baseRef, headRef);
    }
 
    // 使用 includes 过滤文件
    if (context.includes && context.includes.length > 0) {
      const filenames = changedFiles.map((file) => file.filename || "");
      const matchedFilenames = micromatch(filenames, context.includes);
      changedFiles = changedFiles.filter((file) => matchedFilenames.includes(file.filename || ""));
    }
 
    const prInfo = context.generateDescription
      ? await this.generatePrDescription(commits, changedFiles, llmMode, undefined, verbose)
      : await this.buildFallbackDescription(commits, changedFiles);
    const result: ReviewResult = {
      success: true,
      title: prInfo.title,
      description: prInfo.description,
      issues: [],
      summary: [],
      deletionImpact,
      round: 1,
    };
 
    const reviewComment = this.formatReviewComment(result, {
      prNumber,
      outputFormat: context.outputFormat,
      ci,
    });
 
    if (ci && prNumber && !dryRun) {
      if (shouldLog(verbose, 1)) {
        console.log(`💬 提交 PR 评论...`);
      }
      await this.postOrUpdateReviewComment(owner, repo, prNumber, result, verbose);
      if (shouldLog(verbose, 1)) {
        console.log(`✅ 评论已提交`);
      }
    }
 
    // 终端输出(根据 outputFormat 或智能选择)
 
    console.log(MarkdownFormatter.clearReviewData(reviewComment, "<hidden>"));
 
    return result;
  }
 
  protected async getChangedFilesBetweenRefs(
    _owner: string,
    _repo: string,
    baseRef: string,
    headRef: string,
  ): Promise<ChangedFile[]> {
    // 使用 getDiffBetweenRefs 获取包含 patch 的文件列表
    // 这样可以正确解析变更行号,用于过滤非变更行的问题
    const diffFiles = await this.gitSdk.getDiffBetweenRefs(baseRef, headRef);
    const statusFiles = await this.gitSdk.getChangedFilesBetweenRefs(baseRef, headRef);
 
    // 合并 status 和 patch 信息
    const statusMap = new Map(statusFiles.map((f) => [f.filename, f.status]));
    return diffFiles.map((f) => ({
      filename: f.filename,
      status: statusMap.get(f.filename) || "modified",
      patch: f.patch,
    }));
  }
 
  protected async getCommitsBetweenRefs(
    baseRef: string,
    headRef: string,
  ): Promise<PullRequestCommit[]> {
    const gitCommits = await this.gitSdk.getCommitsBetweenRefs(baseRef, headRef);
    return gitCommits.map((c) => ({
      sha: c.sha,
      commit: {
        message: c.message,
        author: c.author,
      },
    }));
  }
 
  protected async getFilesForCommit(
    owner: string,
    repo: string,
    sha: string,
    prNumber?: number,
  ): Promise<string[]> {
    if (prNumber) {
      const commit = await this.gitProvider.getCommit(owner, repo, sha);
      return commit.files?.map((f) => f.filename || "").filter(Boolean) || [];
    } else {
      return this.gitSdk.getFilesForCommit(sha);
    }
  }
 
  /**
   * 获取文件内容并构建行号到 commit hash 的映射
   * 返回 Map<filename, Array<[commitHash, lineCode]>>
   */
  protected async getFileContents(
    owner: string,
    repo: string,
    changedFiles: ChangedFile[],
    commits: PullRequestCommit[],
    ref: string,
    prNumber?: number,
    verbose?: VerboseLevel,
  ): Promise<FileContentsMap> {
    const contents: FileContentsMap = new Map();
    const latestCommitHash = commits[commits.length - 1]?.sha?.slice(0, 7) || "-------";
 
    // 优先使用 changedFiles 中的 patch 字段(来自 PR 的整体 diff base...head)
    // 这样行号是相对于最终文件的,而不是每个 commit 的父 commit
    // buildLineCommitMap 遍历每个 commit 的 diff,行号可能与最终文件不一致
    if (shouldLog(verbose, 1)) {
      console.log(`📊 正在构建行号到变更的映射...`);
    }
 
    for (const file of changedFiles) {
      if (file.filename && file.status !== "deleted") {
        try {
          let rawContent: string;
          if (prNumber) {
            rawContent = await this.gitProvider.getFileContent(owner, repo, file.filename, ref);
          } else {
            rawContent = await this.gitSdk.getFileContent(ref, file.filename);
          }
          const lines = rawContent.split("\n");
 
          // 优先使用 file.patch(PR 整体 diff),这是相对于最终文件的行号
          let changedLines = parseChangedLinesFromPatch(file.patch);
 
          // 如果 changedLines 为空,需要判断是否应该将所有行标记为变更
          // 情况1: 文件是新增的(status 为 added/A)
          // 情况2: patch 为空但文件有 additions(部分 Git Provider API 可能不返回完整 patch)
          const isNewFile =
            file.status === "added" ||
            file.status === "A" ||
            (file.additions && file.additions > 0 && file.deletions === 0 && !file.patch);
          if (changedLines.size === 0 && isNewFile) {
            changedLines = new Set(lines.map((_, i) => i + 1));
            Iif (shouldLog(verbose, 2)) {
              console.log(
                `   ℹ️ ${file.filename}: 新增文件无 patch,将所有 ${lines.length} 行标记为变更`,
              );
            }
          }
 
          if (shouldLog(verbose, 3)) {
            console.log(`   📄 ${file.filename}: ${lines.length} 行, ${changedLines.size} 行变更`);
            console.log(`      latestCommitHash: ${latestCommitHash}`);
            if (changedLines.size > 0 && changedLines.size <= 20) {
              console.log(
                `      变更行号: ${Array.from(changedLines)
                  .sort((a, b) => a - b)
                  .join(", ")}`,
              );
            } else Eif (changedLines.size > 20) {
              console.log(`      变更行号: (共 ${changedLines.size} 行,省略详情)`);
            }
            Iif (!file.patch) {
              console.log(
                `      ⚠️ 该文件没有 patch 信息 (status=${file.status}, additions=${file.additions}, deletions=${file.deletions})`,
              );
            } else {
              console.log(
                `      patch 前 200 字符: ${file.patch.slice(0, 200).replace(/\n/g, "\\n")}`,
              );
            }
          }
 
          const contentLines: FileContentLine[] = lines.map((line, index) => {
            const lineNum = index + 1;
            // 如果该行在 PR 的整体 diff 中被标记为变更,则使用最新 commit hash
            const hash = changedLines.has(lineNum) ? latestCommitHash : "-------";
            return [hash, line];
          });
          contents.set(file.filename, contentLines);
        } catch {
          console.warn(`警告: 无法获取文件内容: ${file.filename}`);
        }
      }
    }
 
    if (shouldLog(verbose, 1)) {
      console.log(`📊 映射构建完成,共 ${contents.size} 个文件`);
    }
    return contents;
  }
 
  protected async runLLMReview(
    llmMode: LLMMode,
    reviewPrompt: ReviewPrompt,
    options: LLMReviewOptions = {},
  ): Promise<ReviewResult> {
    console.log(`🤖 调用 ${llmMode} 进行代码审查...`);
 
    try {
      const result = await this.callLLM(llmMode, reviewPrompt, options);
      Iif (!result) {
        throw new Error("AI 未返回有效结果");
      }
      return {
        success: true,
        description: "", // 由 execute 方法填充
        issues: result.issues || [],
        summary: result.summary || [],
        round: 1, // 由 execute 方法根据 existingResult 更新
      };
    } catch (error) {
      if (error instanceof Error) {
        console.error("LLM 调用失败:", error.message);
        if (error.stack) {
          console.error("堆栈信息:\n" + error.stack);
        }
      } else {
        console.error("LLM 调用失败:", error);
      }
      return {
        success: false,
        description: "",
        issues: [],
        summary: [],
        round: 1,
      };
    }
  }
 
  /**
   * 根据文件过滤 specs,只返回与该文件匹配的规则
   * - 如果 spec 有 includes 配置,只有当文件名匹配 includes 模式时才包含该 spec
   * - 如果 spec 没有 includes 配置,则按扩展名匹配
   */
  protected filterSpecsForFile(specs: ReviewSpec[], filename: string): ReviewSpec[] {
    const ext = extname(filename).slice(1).toLowerCase();
    if (!ext) return [];
 
    return specs.filter((spec) => {
      // 先检查扩展名是否匹配
      if (!spec.extensions.includes(ext)) {
        return false;
      }
 
      // 如果有 includes 配置,检查文件名是否匹配 includes 模式
      if (spec.includes.length > 0) {
        return micromatch.isMatch(filename, spec.includes, { matchBase: true });
      }
 
      // 没有 includes 配置,扩展名匹配即可
      return true;
    });
  }
 
  /**
   * 构建 systemPrompt
   */
  protected buildSystemPrompt(specsSection: string): string {
    return `你是一个专业的代码审查专家,负责根据团队的编码规范对代码进行严格审查。
 
## 审查规范
 
${specsSection}
 
## 审查要求
 
1. **严格遵循规范**:只按照上述审查规范进行审查,不要添加规范之外的要求
2. **精准定位问题**:每个问题必须指明具体的行号,行号从文件内容中的 "行号|" 格式获取
3. **避免重复报告**:如果提示词中包含"上一次审查结果",请不要重复报告已存在的问题
4. **提供可行建议**:对于每个问题,提供具体的修改建议代码
 
## 注意事项
 
- 变更文件内容已在上下文中提供,无需调用读取工具
- 你可以读取项目中的其他文件以了解上下文
- 不要调用编辑工具修改文件,你的职责是审查而非修改
- 文件内容格式为 "CommitHash 行号| 代码",输出的 line 字段应对应原始行号
 
## 输出要求
 
- 发现问题时:在 issues 数组中列出所有问题,每个问题包含 file、line、ruleId、specFile、reason、suggestion、severity
- 无论是否发现问题:都必须在 summary 中提供该文件的审查总结,简要说明审查结果`;
  }
 
  protected async buildReviewPrompt(
    specs: ReviewSpec[],
    changedFiles: ChangedFile[],
    fileContents: FileContentsMap,
    commits: PullRequestCommit[],
    existingResult?: ReviewResult | null,
  ): Promise<ReviewPrompt> {
    const fileDataList = changedFiles
      .filter((f) => f.status !== "deleted" && f.filename)
      .map((file) => {
        const filename = file.filename!;
        const contentLines = fileContents.get(filename);
        if (!contentLines) {
          return {
            filename,
            file,
            linesWithNumbers: "(无法获取内容)",
            commitsSection: "- 无相关 commits",
          };
        }
        const padWidth = String(contentLines.length).length;
        const linesWithNumbers = contentLines
          .map(([hash, line], index) => {
            const lineNum = index + 1;
            return `${hash} ${String(lineNum).padStart(padWidth)}| ${line}`;
          })
          .join("\n");
        // 从 contentLines 中收集该文件相关的 commit hashes
        const fileCommitHashes = new Set<string>();
        for (const [hash] of contentLines) {
          if (hash !== "-------") {
            fileCommitHashes.add(hash);
          }
        }
        const relatedCommits = commits.filter((c) => {
          const shortHash = c.sha?.slice(0, 7) || "";
          return fileCommitHashes.has(shortHash);
        });
        const commitsSection =
          relatedCommits.length > 0
            ? relatedCommits
                .map((c) => `- \`${c.sha?.slice(0, 7)}\` ${c.commit?.message?.split("\n")[0]}`)
                .join("\n")
            : "- 无相关 commits";
        return { filename, file, linesWithNumbers, commitsSection };
      });
 
    const filePrompts: FileReviewPrompt[] = await Promise.all(
      fileDataList.map(async ({ filename, file, linesWithNumbers, commitsSection }) => {
        const fileDirectoryInfo = await this.getFileDirectoryInfo(filename);
 
        // 获取该文件上一次的审查结果
        const existingFileSummary = existingResult?.summary?.find((s) => s.file === filename);
        const existingFileIssues = existingResult?.issues?.filter((i) => i.file === filename) ?? [];
 
        let previousReviewSection = "";
        if (existingFileSummary || existingFileIssues.length > 0) {
          const parts: string[] = [];
          Eif (existingFileSummary?.summary) {
            parts.push(`**总结**:\n`);
            parts.push(`${existingFileSummary.summary}\n`);
          }
          Eif (existingFileIssues.length > 0) {
            parts.push(`**已发现的问题** (${existingFileIssues.length} 个):\n`);
            for (const issue of existingFileIssues) {
              const status = issue.fixed
                ? "✅ 已修复"
                : issue.valid === "false"
                  ? "❌ 无效"
                  : "⚠️ 待处理";
              parts.push(`- [${status}] 行 ${issue.line}: ${issue.reason} (规则: ${issue.ruleId})`);
            }
            parts.push("");
            // parts.push("请注意:不要重复报告上述已发现的问题,除非代码有新的变更导致问题复现。\n");
          }
          previousReviewSection = parts.join("\n");
        }
 
        const userPrompt = `## ${filename} (${file.status})
 
### 文件内容
 
\`\`\`
${linesWithNumbers}
\`\`\`
 
### 该文件的相关 Commits
 
${commitsSection}
 
### 该文件所在的目录树
 
${fileDirectoryInfo}
 
### 上一次审查结果
 
${previousReviewSection}`;
 
        // 根据文件过滤 specs,只注入与当前文件匹配的规则
        const fileSpecs = this.filterSpecsForFile(specs, filename);
        const specsSection = this.reviewSpecService.buildSpecsSection(fileSpecs);
        const systemPrompt = this.buildSystemPrompt(specsSection);
 
        return { filename, systemPrompt, userPrompt };
      }),
    );
 
    return { filePrompts };
  }
 
  protected async fillIssueCode(
    issues: ReviewIssue[],
    fileContents: FileContentsMap,
  ): Promise<ReviewIssue[]> {
    return issues.map((issue) => {
      const contentLines = fileContents.get(issue.file);
      if (!contentLines) {
        return issue;
      }
      const lineRange = issue.line.split("-").map((n) => parseInt(n, 10));
      const startLine = lineRange[0];
      const endLine = lineRange.length > 1 ? lineRange[1] : startLine;
      if (isNaN(startLine) || startLine < 1 || startLine > contentLines.length) {
        return issue;
      }
      const codeLines = contentLines
        .slice(startLine - 1, Math.min(endLine, contentLines.length))
        .map(([, line]) => line);
      const code = codeLines.join("\n").trim();
      return { ...issue, code };
    });
  }
 
  /**
   * 根据 commit 填充 issue 的 author 信息
   * 如果没有找到对应的 author,使用最后一次提交的人作为默认值
   */
  protected async fillIssueAuthors(
    issues: ReviewIssue[],
    commits: PullRequestCommit[],
    _owner: string,
    _repo: string,
    verbose?: VerboseLevel,
  ): Promise<ReviewIssue[]> {
    if (shouldLog(verbose, 2)) {
      console.log(`[fillIssueAuthors] issues=${issues.length}, commits=${commits.length}`);
    }
 
    // 收集需要查找的 Git 作者信息(email 或 name)
    const gitAuthorsToSearch = new Set<string>();
    for (const commit of commits) {
      const platformUser = commit.author || commit.committer;
      if (!platformUser?.login) {
        const gitAuthor = commit.commit?.author;
        if (gitAuthor?.email) gitAuthorsToSearch.add(gitAuthor.email);
        if (gitAuthor?.name) gitAuthorsToSearch.add(gitAuthor.name);
      }
    }
 
    // 通过 Git Provider API 查找用户,建立 email/name -> UserInfo 的映射
    const gitAuthorToUserMap = new Map<string, UserInfo>();
    for (const query of gitAuthorsToSearch) {
      try {
        const users = await this.gitProvider.searchUsers(query, 1);
        if (users.length > 0 && users[0].login) {
          const user: UserInfo = { id: String(users[0].id), login: users[0].login };
          gitAuthorToUserMap.set(query, user);
          Iif (shouldLog(verbose, 2)) {
            console.log(`[fillIssueAuthors] found user: ${query} -> ${user.login}`);
          }
        }
      } catch {
        // 忽略搜索失败
      }
    }
 
    // 构建 commit hash 到 author 的映射
    const commitAuthorMap = new Map<string, UserInfo>();
    for (const commit of commits) {
      // API 返回的 author/committer 可能为 null(未关联平台用户)
      const platformUser = commit.author || commit.committer;
      const gitAuthor = commit.commit?.author;
      if (shouldLog(verbose, 2)) {
        console.log(
          `[fillIssueAuthors] commit: sha=${commit.sha?.slice(0, 7)}, platformUser=${platformUser?.login}, gitAuthor=${gitAuthor?.name}`,
        );
      }
      Eif (commit.sha) {
        const shortHash = commit.sha.slice(0, 7);
        if (platformUser?.login) {
          commitAuthorMap.set(shortHash, {
            id: String(platformUser.id),
            login: platformUser.login,
          });
        } else if (gitAuthor) {
          // 尝试从平台用户映射中查找
          const foundUser =
            (gitAuthor.email && gitAuthorToUserMap.get(gitAuthor.email)) ||
            (gitAuthor.name && gitAuthorToUserMap.get(gitAuthor.name));
          if (foundUser) {
            commitAuthorMap.set(shortHash, foundUser);
          } else Eif (gitAuthor.name) {
            // 使用 Git 原始作者信息(name 作为 login)
            commitAuthorMap.set(shortHash, { id: "0", login: gitAuthor.name });
          }
        }
      }
    }
    if (shouldLog(verbose, 2)) {
      console.log(`[fillIssueAuthors] commitAuthorMap size: ${commitAuthorMap.size}`);
    }
 
    // 获取最后一次提交的 author 作为默认值
    const lastCommit = commits[commits.length - 1];
    const lastPlatformUser = lastCommit?.author || lastCommit?.committer;
    const lastGitAuthor = lastCommit?.commit?.author;
    let defaultAuthor: UserInfo | undefined;
    if (lastPlatformUser?.login) {
      defaultAuthor = { id: String(lastPlatformUser.id), login: lastPlatformUser.login };
    } else if (lastGitAuthor) {
      // 尝试从平台用户映射中查找
      const foundUser =
        (lastGitAuthor.email && gitAuthorToUserMap.get(lastGitAuthor.email)) ||
        (lastGitAuthor.name && gitAuthorToUserMap.get(lastGitAuthor.name));
      defaultAuthor =
        foundUser || (lastGitAuthor.name ? { id: "0", login: lastGitAuthor.name } : undefined);
    }
    if (shouldLog(verbose, 2)) {
      console.log(`[fillIssueAuthors] defaultAuthor: ${JSON.stringify(defaultAuthor)}`);
    }
    // 为每个 issue 填充 author
    return issues.map((issue) => {
      // 如果 issue 已有 author,保留原值
      if (issue.author) {
        Iif (shouldLog(verbose, 2)) {
          console.log(`[fillIssueAuthors] issue already has author: ${issue.author.login}`);
        }
        return issue;
      }
      // issue.commit 可能是 7 位短 hash
      const shortHash = issue.commit?.slice(0, 7);
      const author =
        shortHash && !shortHash.includes("---") ? commitAuthorMap.get(shortHash) : undefined;
      Iif (shouldLog(verbose, 2)) {
        console.log(
          `[fillIssueAuthors] issue: file=${issue.file}, commit=${issue.commit}, shortHash=${shortHash}, foundAuthor=${author?.login}, finalAuthor=${(author || defaultAuthor)?.login}`,
        );
      }
      // 优先使用 commit 对应的 author,否则使用默认 author
      return { ...issue, author: author || defaultAuthor };
    });
  }
 
  protected async getFileDirectoryInfo(filename: string): Promise<string> {
    const dir = dirname(filename);
    const currentFileName = filename.split("/").pop();
 
    if (dir === "." || dir === "") {
      return "(根目录)";
    }
 
    try {
      const entries = await readdir(dir, { withFileTypes: true });
 
      const sortedEntries = entries.sort((a, b) => {
        if (a.isDirectory() && !b.isDirectory()) return -1;
        if (!a.isDirectory() && b.isDirectory()) return 1;
        return a.name.localeCompare(b.name);
      });
 
      const lines: string[] = [`📁 ${dir}/`];
 
      for (let i = 0; i < sortedEntries.length; i++) {
        const entry = sortedEntries[i];
        const isLast = i === sortedEntries.length - 1;
        const isCurrent = entry.name === currentFileName;
        const branch = isLast ? "└── " : "├── ";
        const icon = entry.isDirectory() ? "📂" : "📄";
        const marker = isCurrent ? " ← 当前文件" : "";
 
        lines.push(`${branch}${icon} ${entry.name}${marker}`);
      }
 
      return lines.join("\n");
    } catch {
      return `📁 ${dir}/`;
    }
  }
 
  protected async callLLM(
    llmMode: LLMMode,
    reviewPrompt: ReviewPrompt,
    options: LLMReviewOptions = {},
  ): Promise<{ issues: ReviewIssue[]; summary: FileSummary[] } | null> {
    const { verbose, concurrency = 5, timeout, retries = 0, retryDelay = 1000 } = options;
    const fileCount = reviewPrompt.filePrompts.length;
    console.log(
      `📂 开始并行审查 ${fileCount} 个文件 (并发: ${concurrency}, 重试: ${retries}, 超时: ${timeout ?? "无"}ms)`,
    );
 
    const executor = parallel({
      concurrency,
      timeout,
      retries,
      retryDelay,
      onTaskStart: (taskId) => {
        console.log(`🚀 开始审查: ${taskId}`);
      },
      onTaskComplete: (taskId, success) => {
        console.log(`${success ? "✅" : "❌"} 完成审查: ${taskId}`);
      },
      onRetry: (taskId, attempt, error) => {
        console.log(`🔄 重试 ${taskId} (第 ${attempt} 次): ${error.message}`);
      },
    });
 
    const results = await executor.map(
      reviewPrompt.filePrompts,
      (filePrompt) => this.reviewSingleFile(llmMode, filePrompt, verbose),
      (filePrompt) => filePrompt.filename,
    );
 
    const allIssues: ReviewIssue[] = [];
    const fileSummaries: FileSummary[] = [];
 
    for (const result of results) {
      if (result.success && result.result) {
        allIssues.push(...result.result.issues);
        fileSummaries.push(result.result.summary);
      } else {
        fileSummaries.push({
          file: result.id,
          resolved: 0,
          unresolved: 0,
          summary: `❌ 审查失败: ${result.error?.message ?? "未知错误"}`,
        });
      }
    }
 
    const successCount = results.filter((r) => r.success).length;
    console.log(`🔍 审查完成: ${successCount}/${fileCount} 个文件成功`);
 
    return {
      issues: this.normalizeIssues(allIssues),
      summary: fileSummaries,
    };
  }
 
  protected async reviewSingleFile(
    llmMode: LLMMode,
    filePrompt: FileReviewPrompt,
    verbose?: VerboseLevel,
  ): Promise<{ issues: ReviewIssue[]; summary: FileSummary }> {
    Iif (shouldLog(verbose, 3)) {
      console.log(
        `\nsystemPrompt:\n----------------\n${filePrompt.systemPrompt}\n----------------`,
      );
      console.log(`\nuserPrompt:\n----------------\n${filePrompt.userPrompt}\n----------------`);
    }
 
    const stream = this.llmProxyService.chatStream(
      [
        { role: "system", content: filePrompt.systemPrompt },
        { role: "user", content: filePrompt.userPrompt },
      ],
      {
        adapter: llmMode,
        jsonSchema: this.llmJsonPut,
        verbose,
        allowedTools: [
          "Read",
          "Glob",
          "Grep",
          "WebSearch",
          "TodoWrite",
          "TodoRead",
          "Task",
          "Skill",
        ],
      },
    );
 
    const streamLoggerState = createStreamLoggerState();
    let fileResult: { issues?: ReviewIssue[]; summary?: string } | undefined;
 
    for await (const event of stream) {
      if (shouldLog(verbose, 2)) {
        logStreamEvent(event, streamLoggerState);
      }
 
      if (event.type === "result") {
        fileResult = event.response.structuredOutput as
          | { issues?: ReviewIssue[]; summary?: string }
          | undefined;
      } else Eif (event.type === "error") {
        throw new Error(event.message);
      }
    }
 
    // 在获取到问题时立即记录发现时间
    const now = new Date().toISOString();
    const issues = (fileResult?.issues ?? []).map((issue) => ({
      ...issue,
      date: issue.date ?? now,
    }));
 
    return {
      issues,
      summary: {
        file: filePrompt.filename,
        resolved: 0,
        unresolved: 0,
        summary: fileResult?.summary ?? "",
      },
    };
  }
 
  /**
   * 规范化 issues,拆分包含逗号的行号为多个独立 issue,并添加发现时间
   * 例如 "114, 122" 会被拆分成两个 issue,分别是 "114" 和 "122"
   */
  protected normalizeIssues(issues: ReviewIssue[]): ReviewIssue[] {
    const now = new Date().toISOString();
    return issues.flatMap((issue) => {
      // 确保 line 是字符串(LLM 可能返回数字)
      const lineStr = String(issue.line ?? "");
      const baseIssue = { ...issue, line: lineStr, date: issue.date ?? now };
 
      if (!lineStr.includes(",")) {
        return baseIssue;
      }
 
      const lines = lineStr.split(",");
 
      return lines.map((linePart, index) => ({
        ...baseIssue,
        line: linePart.trim(),
        suggestion: index === 0 ? issue.suggestion : `参考 ${issue.file}:${lines[0]}`,
      }));
    });
  }
 
  /**
   * 使用 AI 根据 commits、变更文件和代码内容总结 PR 实现的功能
   * @returns 包含 title 和 description 的对象
   */
  protected async generatePrDescription(
    commits: PullRequestCommit[],
    changedFiles: ChangedFile[],
    llmMode: LLMMode,
    fileContents?: FileContentsMap,
    verbose?: VerboseLevel,
  ): Promise<{ title: string; description: string }> {
    const commitMessages = commits
      .map((c) => `- ${c.sha?.slice(0, 7)}: ${c.commit?.message?.split("\n")[0]}`)
      .join("\n");
    const fileChanges = changedFiles
      .slice(0, 30)
      .map((f) => `- ${f.filename} (${f.status})`)
      .join("\n");
    // 构建代码变更内容(只包含变更行,限制总长度)
    let codeChangesSection = "";
    if (fileContents && fileContents.size > 0) {
      const codeSnippets: string[] = [];
      let totalLength = 0;
      const maxTotalLength = 8000; // 限制代码总长度
      for (const [filename, lines] of fileContents) {
        Iif (totalLength >= maxTotalLength) break;
        // 只提取有变更的行(commitHash 不是 "-------")
        const changedLines = lines
          .map(([hash, code], idx) => (hash !== "-------" ? `${idx + 1}: ${code}` : null))
          .filter(Boolean);
        Eif (changedLines.length > 0) {
          const snippet = `### ${filename}\n\`\`\`\n${changedLines.slice(0, 50).join("\n")}\n\`\`\``;
          Eif (totalLength + snippet.length <= maxTotalLength) {
            codeSnippets.push(snippet);
            totalLength += snippet.length;
          }
        }
      }
      Eif (codeSnippets.length > 0) {
        codeChangesSection = `\n\n## 代码变更内容\n${codeSnippets.join("\n\n")}`;
      }
    }
    const prompt = `请根据以下 PR 的 commit 记录、文件变更和代码内容,用简洁的中文总结这个 PR 实现了什么功能。
要求:
1. 第一行输出 PR 标题,格式必须是: Feat xxx 或 Fix xxx 或 Refactor xxx(根据变更类型选择,整体不超过 50 个字符)
2. 空一行后输出详细描述
3. 描述应该简明扼要,突出核心功能点
4. 使用 Markdown 格式
5. 不要逐条列出 commit,而是归纳总结
6. 重点分析代码变更的实际功能
 
## Commit 记录 (${commits.length} 个)
${commitMessages || "无"}
 
## 文件变更 (${changedFiles.length} 个文件)
${fileChanges || "无"}
${changedFiles.length > 30 ? `\n... 等 ${changedFiles.length - 30} 个文件` : ""}${codeChangesSection}`;
    try {
      const stream = this.llmProxyService.chatStream([{ role: "user", content: prompt }], {
        adapter: llmMode,
      });
      let content = "";
      for await (const event of stream) {
        if (event.type === "text") {
          content += event.content;
        } else Eif (event.type === "error") {
          throw new Error(event.message);
        }
      }
      // 解析标题和描述:第一行是标题,其余是描述
      const lines = content.trim().split("\n");
      const title = lines[0]?.replace(/^#+\s*/, "").trim() || "PR 更新";
      const description = lines.slice(1).join("\n").trim();
      return { title, description };
    } catch (error) {
      Iif (shouldLog(verbose, 1)) {
        console.warn("⚠️ AI 总结 PR 功能失败,使用默认描述:", error);
      }
      return this.buildFallbackDescription(commits, changedFiles);
    }
  }
 
  /**
   * 使用 LLM 生成 PR 标题
   */
  protected async generatePrTitle(
    commits: PullRequestCommit[],
    changedFiles: ChangedFile[],
  ): Promise<string> {
    const commitMessages = commits
      .slice(0, 10)
      .map((c) => c.commit?.message?.split("\n")[0])
      .filter(Boolean)
      .join("\n");
    const fileChanges = changedFiles
      .slice(0, 20)
      .map((f) => `${f.filename} (${f.status})`)
      .join("\n");
    const prompt = `请根据以下 commit 记录和文件变更,生成一个简短的 PR 标题。
要求:
1. 格式必须是: Feat: xxx 或 Fix: xxx 或 Refactor: xxx
2. 根据变更内容选择合适的前缀(新功能用 Feat,修复用 Fix,重构用 Refactor)
3. xxx 部分用简短的中文描述(整体不超过 50 个字符)
4. 只输出标题,不要加任何解释
 
Commit 记录:
${commitMessages || "无"}
 
文件变更:
${fileChanges || "无"}`;
    try {
      const stream = this.llmProxyService.chatStream([{ role: "user", content: prompt }], {
        adapter: "openai",
      });
      let title = "";
      for await (const event of stream) {
        if (event.type === "text") {
          title += event.content;
        } else Eif (event.type === "error") {
          throw new Error(event.message);
        }
      }
      return title.trim().slice(0, 50) || this.getFallbackTitle(commits);
    } catch {
      return this.getFallbackTitle(commits);
    }
  }
 
  /**
   * 获取降级标题(从第一个 commit 消息)
   */
  protected getFallbackTitle(commits: PullRequestCommit[]): string {
    const firstCommitMsg = commits[0]?.commit?.message?.split("\n")[0] || "PR 更新";
    return firstCommitMsg.slice(0, 50);
  }
 
  /**
   * 构建降级描述(当 AI 总结失败时使用)
   */
  protected async buildFallbackDescription(
    commits: PullRequestCommit[],
    changedFiles: ChangedFile[],
  ): Promise<{ title: string; description: string }> {
    const parts: string[] = [];
    // 使用 LLM 生成标题
    const title = await this.generatePrTitle(commits, changedFiles);
    if (commits.length > 0) {
      const messages = commits
        .slice(0, 5)
        .map((c) => `- ${c.commit?.message?.split("\n")[0]}`)
        .filter(Boolean);
      Eif (messages.length > 0) {
        parts.push(`**提交记录**: ${messages.join("; ")}`);
      }
    }
    if (changedFiles.length > 0) {
      const added = changedFiles.filter((f) => f.status === "added").length;
      const modified = changedFiles.filter((f) => f.status === "modified").length;
      const deleted = changedFiles.filter((f) => f.status === "deleted").length;
      const stats: string[] = [];
      if (added > 0) stats.push(`新增 ${added}`);
      Eif (modified > 0) stats.push(`修改 ${modified}`);
      if (deleted > 0) stats.push(`删除 ${deleted}`);
      parts.push(`**文件变更**: ${changedFiles.length} 个文件 (${stats.join(", ")})`);
    }
    return { title, description: parts.join("\n") };
  }
 
  protected formatReviewComment(
    result: ReviewResult,
    options: { prNumber?: number; outputFormat?: ReportFormat; ci?: boolean } = {},
  ): string {
    const { prNumber, outputFormat, ci } = options;
    // 智能选择格式:如果未指定,PR 模式用 markdown,终端用 terminal
    const format: ReportFormat = outputFormat || (ci && prNumber ? "markdown" : "terminal");
 
    if (format === "markdown") {
      return this.reviewReportService.formatMarkdown(result, {
        prNumber,
        includeReanalysisCheckbox: true,
        includeJsonData: true,
        reviewCommentMarker: REVIEW_COMMENT_MARKER,
      });
    }
 
    return this.reviewReportService.format(result, format);
  }
 
  protected async postOrUpdateReviewComment(
    owner: string,
    repo: string,
    prNumber: number,
    result: ReviewResult,
    verbose?: VerboseLevel,
  ): Promise<void> {
    // 获取配置
    const reviewConf = this.config.getPluginConfig<ReviewConfig>("review");
 
    // 如果配置启用且有 AI 生成的标题,只在第一轮审查时更新 PR 标题
    if (reviewConf.autoUpdatePrTitle && result.title && result.round === 1) {
      try {
        await this.gitProvider.editPullRequest(owner, repo, prNumber, { title: result.title });
        console.log(`📝 已更新 PR 标题: ${result.title}`);
      } catch (error) {
        console.warn("⚠️ 更新 PR 标题失败:", error);
      }
    }
 
    // 获取已解决的评论,同步 resolve 状态(在更新 review 之前)
    await this.syncResolvedComments(owner, repo, prNumber, result);
 
    // 获取评论的 reactions,同步 valid 状态(👎 标记为无效)
    await this.syncReactionsToIssues(owner, repo, prNumber, result, verbose);
 
    // 查找已有的 AI 评论(Issue Comment),可能存在多个重复评论
    Iif (shouldLog(verbose, 2)) {
      console.log(`[postOrUpdateReviewComment] owner=${owner}, repo=${repo}, prNumber=${prNumber}`);
    }
    const existingComments = await this.findExistingAiComments(owner, repo, prNumber, verbose);
    Iif (shouldLog(verbose, 2)) {
      console.log(
        `[postOrUpdateReviewComment] found ${existingComments.length} existing AI comments`,
      );
    }
 
    // 调试:检查 issues 是否有 author
    Iif (shouldLog(verbose, 3)) {
      for (const issue of result.issues.slice(0, 3)) {
        console.log(
          `[postOrUpdateReviewComment] issue: file=${issue.file}, commit=${issue.commit}, author=${issue.author?.login}`,
        );
      }
    }
 
    const reviewBody = this.formatReviewComment(result, {
      prNumber,
      outputFormat: "markdown",
      ci: true,
    });
 
    // 获取 PR 信息以获取 head commit SHA
    const pr = await this.gitProvider.getPullRequest(owner, repo, prNumber);
    const commitId = pr.head?.sha;
 
    // 1. 发布或更新主评论(使用 Issue Comment API,支持删除和更新)
    try {
      if (existingComments.length > 0) {
        // 更新第一个 AI 评论
        await this.gitProvider.updateIssueComment(owner, repo, existingComments[0].id, reviewBody);
        console.log(`✅ 已更新 AI Review 评论`);
        // 删除多余的重复 AI 评论
        for (const duplicate of existingComments.slice(1)) {
          try {
            await this.gitProvider.deleteIssueComment(owner, repo, duplicate.id);
            console.log(`🗑️ 已删除重复的 AI Review 评论 (id: ${duplicate.id})`);
          } catch {
            console.warn(`⚠️ 删除重复评论失败 (id: ${duplicate.id})`);
          }
        }
      } else {
        await this.gitProvider.createIssueComment(owner, repo, prNumber, { body: reviewBody });
        console.log(`✅ 已发布 AI Review 评论`);
      }
    } catch (error) {
      console.warn("⚠️ 发布/更新 AI Review 评论失败:", error);
    }
 
    // 2. 发布本轮新发现的行级评论(使用 PR Review API,不删除旧的 review,保留历史)
    let lineIssues: ReviewIssue[] = [];
    let comments: CreatePullReviewComment[] = [];
    if (reviewConf.lineComments) {
      lineIssues = result.issues.filter(
        (issue) =>
          issue.round === result.round &&
          !issue.fixed &&
          !issue.resolved &&
          issue.valid !== "false",
      );
      comments = lineIssues
        .map((issue) => this.issueToReviewComment(issue))
        .filter((comment): comment is CreatePullReviewComment => comment !== null);
    }
    if (reviewConf.lineComments) {
      const reviewBody = this.buildLineReviewBody(lineIssues, result.round, result.issues);
      if (comments.length > 0) {
        try {
          await this.gitProvider.createPullReview(owner, repo, prNumber, {
            event: REVIEW_STATE.COMMENT,
            body: reviewBody,
            comments,
            commit_id: commitId,
          });
          console.log(`✅ 已发布 ${comments.length} 条行级评论`);
        } catch {
          // 批量失败时逐条发布,跳过无法定位的评论
          console.warn("⚠️ 批量发布行级评论失败,尝试逐条发布...");
          let successCount = 0;
          for (const comment of comments) {
            try {
              await this.gitProvider.createPullReview(owner, repo, prNumber, {
                event: REVIEW_STATE.COMMENT,
                body: successCount === 0 ? reviewBody : undefined,
                comments: [comment],
                commit_id: commitId,
              });
              successCount++;
            } catch {
              console.warn(`⚠️ 跳过无法定位的评论: ${comment.path}:${comment.new_position}`);
            }
          }
          if (successCount > 0) {
            console.log(`✅ 逐条发布成功 ${successCount}/${comments.length} 条行级评论`);
          } else {
            console.warn("⚠️ 所有行级评论均无法定位,已跳过");
          }
        }
      } else E{
        // 本轮无新问题,仍发布 Round 状态(含上轮回顾)
        try {
          await this.gitProvider.createPullReview(owner, repo, prNumber, {
            event: REVIEW_STATE.COMMENT,
            body: reviewBody,
            comments: [],
            commit_id: commitId,
          });
          console.log(`✅ 已发布 Round ${result.round} 审查状态(无新问题)`);
        } catch (error) {
          console.warn("⚠️ 发布审查状态失败:", error);
        }
      }
    }
  }
 
  /**
   * 查找已有的所有 AI 评论(Issue Comment)
   * 返回所有包含 REVIEW_COMMENT_MARKER 的评论,用于更新第一个并清理重复项
   */
  protected async findExistingAiComments(
    owner: string,
    repo: string,
    prNumber: number,
    verbose?: VerboseLevel,
  ): Promise<{ id: number }[]> {
    try {
      const comments = await this.gitProvider.listIssueComments(owner, repo, prNumber);
      if (shouldLog(verbose, 2)) {
        console.log(
          `[findExistingAiComments] listIssueComments returned ${Array.isArray(comments) ? comments.length : typeof comments} comments`,
        );
        Eif (Array.isArray(comments)) {
          for (const c of comments.slice(0, 5)) {
            console.log(
              `[findExistingAiComments] comment id=${c.id}, body starts with: ${c.body?.slice(0, 80) ?? "(no body)"}`,
            );
          }
        }
      }
      return comments
        .filter((c) => c.body?.includes(REVIEW_COMMENT_MARKER) && c.id)
        .map((c) => ({ id: c.id! }));
    } catch (error) {
      console.warn("[findExistingAiComments] error:", error);
      return [];
    }
  }
 
  /**
   * 从 PR 的所有 resolved review threads 中同步 resolved 状态到 result.issues
   * 用户手动点击 resolve 的记录写入 resolved/resolvedBy 字段(区别于 AI 验证的 fixed/fixedBy)
   * 优先通过评论 body 中的 issue key 精确匹配,回退到 path+line 匹配
   */
  protected async syncResolvedComments(
    owner: string,
    repo: string,
    prNumber: number,
    result: ReviewResult,
  ): Promise<void> {
    try {
      const resolvedThreads = await this.gitProvider.listResolvedThreads(owner, repo, prNumber);
      if (resolvedThreads.length === 0) {
        return;
      }
      // 构建 issue key → issue 的映射,用于精确匹配
      const issueByKey = new Map<string, ReviewResult["issues"][0]>();
      for (const issue of result.issues) {
        issueByKey.set(this.generateIssueKey(issue), issue);
      }
      const now = new Date().toISOString();
      for (const thread of resolvedThreads) {
        if (!thread.path) continue;
        // 优先通过 issue key 精确匹配
        let matchedIssue: ReviewResult["issues"][0] | undefined;
        if (thread.body) {
          const issueKey = this.extractIssueKeyFromBody(thread.body);
          Eif (issueKey) {
            matchedIssue = issueByKey.get(issueKey);
          }
        }
        // 回退:path:line 匹配
        if (!matchedIssue) {
          matchedIssue = result.issues.find(
            (issue) =>
              issue.file === thread.path && this.lineMatchesPosition(issue.line, thread.line),
          );
        }
        Eif (matchedIssue && !matchedIssue.resolved) {
          matchedIssue.resolved = now;
          Eif (thread.resolvedBy) {
            matchedIssue.resolvedBy = {
              id: thread.resolvedBy.id?.toString(),
              login: thread.resolvedBy.login,
            };
          }
          console.log(
            `🟢 问题已标记为已解决: ${matchedIssue.file}:${matchedIssue.line}` +
              (thread.resolvedBy?.login ? ` (by @${thread.resolvedBy.login})` : ""),
          );
        }
      }
    } catch (error) {
      console.warn("⚠️ 同步已解决评论失败:", error);
    }
  }
 
  /**
   * 检查 issue 的行号是否匹配评论的 position
   */
  protected lineMatchesPosition(issueLine: string, position?: number): boolean {
    if (!position) return false;
    const lines = this.reviewSpecService.parseLineRange(issueLine);
    if (lines.length === 0) return false;
    const startLine = lines[0];
    const endLine = lines[lines.length - 1];
    return position >= startLine && position <= endLine;
  }
 
  /**
   * 从旧的 AI review 评论中获取 reactions 和回复,同步到 result.issues
   * - 存储所有 reactions 到 issue.reactions 字段
   * - 存储评论回复到 issue.replies 字段
   * - 如果评论有 👎 (-1) reaction,将对应的问题标记为无效
   */
  protected async syncReactionsToIssues(
    owner: string,
    repo: string,
    prNumber: number,
    result: ReviewResult,
    verbose?: VerboseLevel,
  ): Promise<void> {
    try {
      const reviews = await this.gitProvider.listPullReviews(owner, repo, prNumber);
      const aiReview = reviews.find((r) => r.body?.includes(REVIEW_LINE_COMMENTS_MARKER));
      if (!aiReview?.id) {
        if (shouldLog(verbose, 2)) {
          console.log(`[syncReactionsToIssues] No AI review found`);
        }
        return;
      }
 
      // 收集所有评审人
      const reviewers = new Set<string>();
 
      // 1. 从已提交的 review 中获取评审人(排除 AI bot)
      for (const review of reviews) {
        if (review.user?.login && !review.body?.includes(REVIEW_LINE_COMMENTS_MARKER)) {
          reviewers.add(review.user.login);
        }
      }
      if (shouldLog(verbose, 2)) {
        console.log(
          `[syncReactionsToIssues] reviewers from reviews: ${Array.from(reviewers).join(", ")}`,
        );
      }
 
      // 2. 从 PR 指定的评审人中获取(包括团队成员)
      try {
        const pr = await this.gitProvider.getPullRequest(owner, repo, prNumber);
        // 添加指定的个人评审人
        for (const reviewer of pr.requested_reviewers || []) {
          Eif (reviewer.login) {
            reviewers.add(reviewer.login);
          }
        }
        if (shouldLog(verbose, 2)) {
          console.log(
            `[syncReactionsToIssues] requested_reviewers: ${(pr.requested_reviewers || []).map((r) => r.login).join(", ")}`,
          );
          console.log(
            `[syncReactionsToIssues] requested_reviewers_teams: ${JSON.stringify(pr.requested_reviewers_teams || [])}`,
          );
        }
        // 添加指定的团队成员(需要通过 API 获取团队成员列表)
        for (const team of pr.requested_reviewers_teams || []) {
          Eif (team.id) {
            try {
              const members = await this.gitProvider.getTeamMembers(team.id);
              Eif (shouldLog(verbose, 2)) {
                console.log(
                  `[syncReactionsToIssues] team ${team.name}(${team.id}) members: ${members.map((m) => m.login).join(", ")}`,
                );
              }
              for (const member of members) {
                Eif (member.login) {
                  reviewers.add(member.login);
                }
              }
            } catch (e) {
              if (shouldLog(verbose, 2)) {
                console.log(`[syncReactionsToIssues] failed to get team ${team.id} members: ${e}`);
              }
            }
          }
        }
      } catch {
        // 获取 PR 信息失败,继续使用已有的评审人列表
      }
      if (shouldLog(verbose, 2)) {
        console.log(`[syncReactionsToIssues] final reviewers: ${Array.from(reviewers).join(", ")}`);
      }
 
      // 获取该 review 的所有行级评论
      const reviewComments = await this.gitProvider.listPullReviewComments(
        owner,
        repo,
        prNumber,
        aiReview.id,
      );
      // 构建评论 ID 到 issue 的映射,用于后续匹配回复
      const commentIdToIssue = new Map<number, (typeof result.issues)[0]>();
      // 遍历每个评论,获取其 reactions
      for (const comment of reviewComments) {
        if (!comment.id) continue;
        // 找到对应的 issue
        const matchedIssue = result.issues.find(
          (issue) =>
            issue.file === comment.path && this.lineMatchesPosition(issue.line, comment.position),
        );
        Eif (matchedIssue) {
          commentIdToIssue.set(comment.id, matchedIssue);
        }
        try {
          const reactions = await this.gitProvider.getPullReviewCommentReactions(
            owner,
            repo,
            comment.id,
          );
          if (reactions.length === 0 || !matchedIssue) continue;
          // 按 content 分组,收集每种 reaction 的用户列表
          const reactionMap = new Map<string, string[]>();
          for (const r of reactions) {
            Iif (!r.content) continue;
            const users = reactionMap.get(r.content) || [];
            Eif (r.user?.login) {
              users.push(r.user.login);
            }
            reactionMap.set(r.content, users);
          }
          // 存储到 issue.reactions
          matchedIssue.reactions = Array.from(reactionMap.entries()).map(([content, users]) => ({
            content,
            users,
          }));
          // 检查是否有评审人的 👎 (-1) reaction,标记为无效
          const thumbsDownUsers = reactionMap.get("-1") || [];
          const reviewerThumbsDown = thumbsDownUsers.filter((u) => reviewers.has(u));
          if (reviewerThumbsDown.length > 0 && matchedIssue.valid !== "false") {
            matchedIssue.valid = "false";
            console.log(
              `👎 问题已标记为无效: ${matchedIssue.file}:${matchedIssue.line} (by 评审人: ${reviewerThumbsDown.join(", ")})`,
            );
          }
        } catch {
          // 单个评论获取 reactions 失败,继续处理其他评论
        }
      }
      // 获取 PR 上的所有 Issue Comments(包含对 review 评论的回复)
      await this.syncRepliesToIssues(owner, repo, prNumber, reviewComments, result);
    } catch (error) {
      console.warn("⚠️ 同步评论 reactions 失败:", error);
    }
  }
 
  /**
   * 从评论 body 中提取 issue key(AI 行级评论末尾的 HTML 注释标记)
   * 格式:`<!-- issue-key: file:line:ruleId -->`
   * 返回 null 表示非 AI 评论(即用户真实回复)
   */
  protected extractIssueKeyFromBody(body: string): string | null {
    const match = body.match(/<!-- issue-key: (.+?) -->/);
    return match ? match[1] : null;
  }
 
  /**
   * 判断评论是否为 AI 生成的评论(非用户真实回复)
   * 除 issue-key 标记外,还通过结构化格式特征识别
   */
  protected isAiGeneratedComment(body: string): boolean {
    if (!body) return false;
    // 含 issue-key 标记
    if (body.includes("<!-- issue-key:")) return true;
    // 含 AI 评论的结构化格式特征(同时包含「规则」和「文件」字段)
    if (body.includes("- **规则**:") && body.includes("- **文件**:")) return true;
    return false;
  }
 
  /**
   * 同步评论回复到对应的 issues
   * review 评论回复是通过同一个 review 下的后续评论实现的
   *
   * 通过 AI 评论 body 中嵌入的 issue key(`<!-- issue-key: file:line:ruleId -->`)精确匹配 issue:
   * - 含 issue key 的评论是 AI 自身评论,过滤掉不作为回复
   * - 不含 issue key 但匹配 AI 格式特征的评论也视为 AI 评论,过滤掉
   * - 其余评论是用户真实回复,归到其前面最近的 AI 评论对应的 issue
   */
  protected async syncRepliesToIssues(
    _owner: string,
    _repo: string,
    _prNumber: number,
    reviewComments: {
      id?: number;
      path?: string;
      position?: number;
      body?: string;
      user?: { id?: number; login?: string };
      created_at?: string;
    }[],
    result: ReviewResult,
  ): Promise<void> {
    try {
      // 构建 issue key → issue 的映射,用于快速查找
      const issueByKey = new Map<string, ReviewResult["issues"][0]>();
      for (const issue of result.issues) {
        issueByKey.set(this.generateIssueKey(issue), issue);
      }
      // 按文件路径和行号分组评论
      const commentsByLocation = new Map<string, typeof reviewComments>();
      for (const comment of reviewComments) {
        if (!comment.path || !comment.position) continue;
        const key = `${comment.path}:${comment.position}`;
        const comments = commentsByLocation.get(key) || [];
        comments.push(comment);
        commentsByLocation.set(key, comments);
      }
      // 遍历每个位置的评论
      for (const [, comments] of commentsByLocation) {
        if (comments.length <= 1) continue;
        // 按创建时间排序
        comments.sort((a, b) => {
          const timeA = a.created_at ? new Date(a.created_at).getTime() : 0;
          const timeB = b.created_at ? new Date(b.created_at).getTime() : 0;
          return timeA - timeB;
        });
        // 遍历评论,用 issue key 精确匹配
        let lastIssueKey: string | null = null;
        for (const comment of comments) {
          const commentBody = comment.body || "";
          const issueKey = this.extractIssueKeyFromBody(commentBody);
          if (issueKey) {
            // AI 自身评论(含 issue-key),记录 issue key 但不作为回复
            lastIssueKey = issueKey;
            continue;
          }
          // 跳过不含 issue-key 但匹配 AI 格式特征的评论(如其他轮次的 bot 评论)
          if (this.isAiGeneratedComment(commentBody)) {
            continue;
          }
          // 用户真实回复,通过前面最近的 AI 评论的 issue key 精确匹配
          let matchedIssue = lastIssueKey ? (issueByKey.get(lastIssueKey) ?? null) : null;
          // 回退:如果 issue key 匹配失败,使用 path:position 匹配
          if (!matchedIssue) {
            matchedIssue =
              result.issues.find(
                (issue) =>
                  issue.file === comment.path &&
                  this.lineMatchesPosition(issue.line, comment.position),
              ) ?? null;
          }
          Iif (!matchedIssue) continue;
          // 追加回复(而非覆盖,同一 issue 可能有多条用户回复)
          if (!matchedIssue.replies) {
            matchedIssue.replies = [];
          }
          matchedIssue.replies.push({
            user: {
              id: comment.user?.id?.toString(),
              login: comment.user?.login || "unknown",
            },
            body: comment.body || "",
            createdAt: comment.created_at || "",
          });
        }
      }
    } catch (error) {
      console.warn("⚠️ 同步评论回复失败:", error);
    }
  }
 
  /**
   * 删除已有的 AI review(通过 marker 识别)
   * - 删除行级评论的 PR Review(带 REVIEW_LINE_COMMENTS_MARKER)
   * - 删除主评论的 Issue Comment(带 REVIEW_COMMENT_MARKER)
   */
  protected async deleteExistingAiReviews(
    owner: string,
    repo: string,
    prNumber: number,
  ): Promise<void> {
    let deletedCount = 0;
    // 删除行级评论的 PR Review
    try {
      const reviews = await this.gitProvider.listPullReviews(owner, repo, prNumber);
      const aiReviews = reviews.filter(
        (r) =>
          r.body?.includes(REVIEW_LINE_COMMENTS_MARKER) || r.body?.includes(REVIEW_COMMENT_MARKER),
      );
      for (const review of aiReviews) {
        Eif (review.id) {
          try {
            await this.gitProvider.deletePullReview(owner, repo, prNumber, review.id);
            deletedCount++;
          } catch {
            // 已提交的 review 无法删除,忽略
          }
        }
      }
    } catch (error) {
      console.warn("⚠️ 列出 PR reviews 失败:", error);
    }
    // 删除主评论的 Issue Comment
    try {
      const comments = await this.gitProvider.listIssueComments(owner, repo, prNumber);
      const aiComments = comments.filter((c) => c.body?.includes(REVIEW_COMMENT_MARKER));
      for (const comment of aiComments) {
        Eif (comment.id) {
          try {
            await this.gitProvider.deleteIssueComment(owner, repo, comment.id);
            deletedCount++;
          } catch (error) {
            console.warn(`⚠️ 删除评论 ${comment.id} 失败:`, error);
          }
        }
      }
    } catch (error) {
      console.warn("⚠️ 列出 issue comments 失败:", error);
    }
    if (deletedCount > 0) {
      console.log(`🗑️ 已删除 ${deletedCount} 个旧的 AI review`);
    }
  }
 
  /**
   * 构建行级评论 Review 的 body(marker + 本轮统计 + 上轮回顾)
   */
  protected buildLineReviewBody(
    issues: ReviewIssue[],
    round: number,
    allIssues: ReviewIssue[],
  ): string {
    // 只统计待处理的问题(未修复且未解决)
    const pendingIssues = issues.filter((i) => !i.fixed && !i.resolved && i.valid !== "false");
    const pendingErrors = pendingIssues.filter((i) => i.severity === "error").length;
    const pendingWarns = pendingIssues.filter((i) => i.severity === "warn").length;
    const fileCount = new Set(issues.map((i) => i.file)).size;
 
    const totalPending = pendingErrors + pendingWarns;
    const badges: string[] = [];
    if (totalPending > 0) badges.push(`⚠️ ${totalPending}`);
    if (pendingErrors > 0) badges.push(`🔴 ${pendingErrors}`);
    Iif (pendingWarns > 0) badges.push(`🟡 ${pendingWarns}`);
 
    const parts: string[] = [REVIEW_LINE_COMMENTS_MARKER];
    parts.push(`### 🚀 Spaceflow Review · Round ${round}`);
    if (issues.length === 0) {
      parts.push(`> ✅ 未发现新问题`);
    } else {
      parts.push(
        `> **${issues.length}** 个新问题 · **${fileCount}** 个文件${badges.length > 0 ? " · " + badges.join(" ") : ""}`,
      );
    }
 
    // 上轮回顾
    if (round > 1) {
      const prevIssues = allIssues.filter((i) => i.round === round - 1);
      Eif (prevIssues.length > 0) {
        const prevFixed = prevIssues.filter((i) => i.fixed).length;
        const prevResolved = prevIssues.filter((i) => i.resolved && !i.fixed).length;
        const prevInvalid = prevIssues.filter(
          (i) => i.valid === "false" && !i.fixed && !i.resolved,
        ).length;
        const prevPending = prevIssues.length - prevFixed - prevResolved - prevInvalid;
        parts.push("");
        parts.push(
          `<details><summary>📊 Round ${round - 1} 回顾 (${prevIssues.length} 个问题)</summary>\n`,
        );
        parts.push(`| 状态 | 数量 |`);
        parts.push(`|------|------|`);
        Eif (prevFixed > 0) parts.push(`| 🟢 已修复 | ${prevFixed} |`);
        Eif (prevResolved > 0) parts.push(`| ⚪ 已解决 | ${prevResolved} |`);
        Eif (prevInvalid > 0) parts.push(`| ❌ 无效 | ${prevInvalid} |`);
        Eif (prevPending > 0) parts.push(`| ⚠️ 待处理 | ${prevPending} |`);
        parts.push(`\n</details>`);
      }
    }
 
    return parts.join("\n");
  }
 
  /**
   * 将单个 ReviewIssue 转换为 CreatePullReviewComment
   */
  protected issueToReviewComment(issue: ReviewIssue): CreatePullReviewComment | null {
    const lineNums = this.reviewSpecService.parseLineRange(issue.line);
    if (lineNums.length === 0) {
      return null;
    }
    const lineNum = lineNums[0];
    // 构建评论内容,参照 markdown.formatter.ts 的格式
    const severityEmoji =
      issue.severity === "error" ? "🔴" : issue.severity === "warn" ? "🟡" : "⚪";
    const lines: string[] = [];
    lines.push(`${severityEmoji} **${issue.reason}**`);
    lines.push(`- **文件**: \`${issue.file}:${issue.line}\``);
    lines.push(`- **规则**: \`${issue.ruleId}\` (来自 \`${issue.specFile}\`)`);
    if (issue.commit) {
      lines.push(`- **Commit**: ${issue.commit}`);
    }
    lines.push(`- **开发人员**: ${issue.author ? "@" + issue.author.login : "未知"}`);
    lines.push(`<!-- issue-key: ${this.generateIssueKey(issue)} -->`);
    if (issue.suggestion) {
      const ext = extname(issue.file).slice(1) || "";
      const cleanSuggestion = issue.suggestion.replace(/```/g, "//").trim();
      lines.push(`- **建议**:`);
      lines.push(`\`\`\`${ext}`);
      lines.push(cleanSuggestion);
      lines.push("```");
    }
    return {
      path: issue.file,
      body: lines.join("\n"),
      new_position: lineNum,
      old_position: 0,
    };
  }
 
  protected generateIssueKey(issue: ReviewIssue): string {
    return `${issue.file}:${issue.line}:${issue.ruleId}`;
  }
 
  protected parseExistingReviewResult(commentBody: string): ReviewResult | null {
    const parsed = this.reviewReportService.parseMarkdown(commentBody);
    if (!parsed) {
      return null;
    }
    return parsed.result;
  }
 
  /**
   * 将有变更文件的历史 issue 标记为无效
   * 简化策略:如果文件在最新 commit 中有变更,则将该文件的所有历史问题标记为无效
   * @param issues 历史 issue 列表
   * @param headSha 当前 PR head 的 SHA
   * @param owner 仓库所有者
   * @param repo 仓库名
   * @param verbose 日志级别
   * @returns 更新后的 issue 列表
   */
  protected async invalidateIssuesForChangedFiles(
    issues: ReviewIssue[],
    headSha: string | undefined,
    owner: string,
    repo: string,
    verbose?: VerboseLevel,
  ): Promise<ReviewIssue[]> {
    if (!headSha) {
      if (shouldLog(verbose, 1)) {
        console.log(`   ⚠️ 无法获取 PR head SHA,跳过变更文件检查`);
      }
      return issues;
    }
 
    if (shouldLog(verbose, 1)) {
      console.log(`   📊 获取最新 commit 变更文件: ${headSha.slice(0, 7)}`);
    }
 
    try {
      // 使用 Git Provider API 获取最新一次 commit 的 diff
      const diffText = await this.gitProvider.getCommitDiff(owner, repo, headSha);
      const diffFiles = parseDiffText(diffText);
 
      if (diffFiles.length === 0) {
        if (shouldLog(verbose, 1)) {
          console.log(`   ⏭️ 最新 commit 无文件变更`);
        }
        return issues;
      }
 
      // 构建变更文件集合
      const changedFileSet = new Set(diffFiles.map((f) => f.filename));
      Iif (shouldLog(verbose, 2)) {
        console.log(`   [invalidateIssues] 变更文件: ${[...changedFileSet].join(", ")}`);
      }
 
      // 将变更文件的历史 issue 标记为无效
      let invalidatedCount = 0;
      const updatedIssues = issues.map((issue) => {
        // 如果 issue 已修复、已解决或已无效,不需要处理
        if (issue.fixed || issue.resolved || issue.valid === "false") {
          return issue;
        }
 
        // 如果 issue 所在文件有变更,标记为无效
        if (changedFileSet.has(issue.file)) {
          invalidatedCount++;
          if (shouldLog(verbose, 1)) {
            console.log(`   🗑️ Issue ${issue.file}:${issue.line} 所在文件有变更,标记为无效`);
          }
          return { ...issue, valid: "false", originalLine: issue.originalLine ?? issue.line };
        }
 
        return issue;
      });
 
      if (invalidatedCount > 0 && shouldLog(verbose, 1)) {
        console.log(`   📊 共标记 ${invalidatedCount} 个历史问题为无效(文件有变更)`);
      }
 
      return updatedIssues;
    } catch (error) {
      if (shouldLog(verbose, 1)) {
        console.log(`   ⚠️ 获取最新 commit 变更文件失败: ${error}`);
      }
      return issues;
    }
  }
 
  /**
   * 根据代码变更更新历史 issue 的行号
   * 当代码发生变化时,之前发现的 issue 行号可能已经不准确
   * 此方法通过分析 diff 来计算新的行号
   * @param issues 历史 issue 列表
   * @param filePatchMap 文件名到 patch 的映射
   * @param verbose 日志级别
   * @returns 更新后的 issue 列表
   */
  protected updateIssueLineNumbers(
    issues: ReviewIssue[],
    filePatchMap: Map<string, string>,
    verbose?: VerboseLevel,
  ): ReviewIssue[] {
    let updatedCount = 0;
    let invalidatedCount = 0;
    const updatedIssues = issues.map((issue) => {
      // 如果 issue 已修复、已解决或无效,不需要更新行号
      if (issue.fixed || issue.resolved || issue.valid === "false") {
        return issue;
      }
 
      const patch = filePatchMap.get(issue.file);
      if (!patch) {
        // 文件没有变更,行号不变
        return issue;
      }
 
      const lines = this.reviewSpecService.parseLineRange(issue.line);
      Iif (lines.length === 0) {
        return issue;
      }
 
      const startLine = lines[0];
      const endLine = lines[lines.length - 1];
      const hunks = parseHunksFromPatch(patch);
 
      // 计算新的起始行号
      const newStartLine = calculateNewLineNumber(startLine, hunks);
      if (newStartLine === null) {
        // 起始行被删除,直接标记为无效问题
        invalidatedCount++;
        if (shouldLog(verbose, 1)) {
          console.log(`📍 Issue ${issue.file}:${issue.line} 对应的代码已被删除,标记为无效`);
        }
        return { ...issue, valid: "false", originalLine: issue.originalLine ?? issue.line };
      }
 
      // 如果是范围行号,计算新的结束行号
      let newLine: string;
      if (startLine === endLine) {
        newLine = String(newStartLine);
      } else {
        const newEndLine = calculateNewLineNumber(endLine, hunks);
        if (newEndLine === null || newEndLine === newStartLine) {
          // 结束行被删除或范围缩小为单行,使用起始行
          newLine = String(newStartLine);
        } else {
          newLine = `${newStartLine}-${newEndLine}`;
        }
      }
 
      // 如果行号发生变化,更新 issue
      Eif (newLine !== issue.line) {
        updatedCount++;
        if (shouldLog(verbose, 1)) {
          console.log(`📍 Issue 行号更新: ${issue.file}:${issue.line} -> ${issue.file}:${newLine}`);
        }
        return { ...issue, line: newLine, originalLine: issue.originalLine ?? issue.line };
      }
 
      return issue;
    });
 
    if ((updatedCount > 0 || invalidatedCount > 0) && shouldLog(verbose, 1)) {
      const parts: string[] = [];
      if (updatedCount > 0) parts.push(`更新 ${updatedCount} 个行号`);
      if (invalidatedCount > 0) parts.push(`标记 ${invalidatedCount} 个无效`);
      console.log(`📊 Issue 行号处理: ${parts.join(",")}`);
    }
 
    return updatedIssues;
  }
 
  /**
   * 过滤掉不属于本次 PR commits 的问题(排除 merge commit 引入的代码)
   * 根据 fileContents 中问题行的实际 commit hash 进行验证,而不是依赖 LLM 填写的 commit
   */
  protected filterIssuesByValidCommits(
    issues: ReviewIssue[],
    commits: PullRequestCommit[],
    fileContents: FileContentsMap,
    verbose?: VerboseLevel,
  ): ReviewIssue[] {
    const validCommitHashes = new Set(commits.map((c) => c.sha?.slice(0, 7)).filter(Boolean));
 
    if (shouldLog(verbose, 3)) {
      console.log(`   🔍 有效 commit hashes: ${Array.from(validCommitHashes).join(", ")}`);
    }
 
    const beforeCount = issues.length;
    const filtered = issues.filter((issue) => {
      const contentLines = fileContents.get(issue.file);
      if (!contentLines) {
        // 文件不在 fileContents 中,保留 issue
        if (shouldLog(verbose, 3)) {
          console.log(`   ✅ Issue ${issue.file}:${issue.line} - 文件不在 fileContents 中,保留`);
        }
        return true;
      }
 
      const lineNums = this.reviewSpecService.parseLineRange(issue.line);
      if (lineNums.length === 0) {
        if (shouldLog(verbose, 3)) {
          console.log(`   ✅ Issue ${issue.file}:${issue.line} - 无法解析行号,保留`);
        }
        return true;
      }
 
      // 检查问题行范围内是否有任意一行属于本次 PR 的有效 commits
      for (const lineNum of lineNums) {
        const lineData = contentLines[lineNum - 1];
        Eif (lineData) {
          const [actualHash] = lineData;
          if (actualHash !== "-------" && validCommitHashes.has(actualHash)) {
            if (shouldLog(verbose, 3)) {
              console.log(
                `   ✅ Issue ${issue.file}:${issue.line} - 行 ${lineNum} hash=${actualHash} 匹配,保留`,
              );
            }
            return true;
          }
        }
      }
 
      // 问题行都不属于本次 PR 的有效 commits
      if (shouldLog(verbose, 2)) {
        console.log(`   Issue ${issue.file}:${issue.line} 不在本次 PR 变更行范围内,跳过`);
      }
      Iif (shouldLog(verbose, 3)) {
        const hashes = lineNums.map((ln) => {
          const ld = contentLines[ln - 1];
          return ld ? `${ln}:${ld[0]}` : `${ln}:N/A`;
        });
        console.log(`   ❌ Issue ${issue.file}:${issue.line} - 行号 hash: ${hashes.join(", ")}`);
      }
      return false;
    });
    if (beforeCount !== filtered.length && shouldLog(verbose, 1)) {
      console.log(`   过滤非本次 PR commits 问题后: ${beforeCount} -> ${filtered.length} 个问题`);
    }
    return filtered;
  }
 
  protected filterDuplicateIssues(
    newIssues: ReviewIssue[],
    existingIssues: ReviewIssue[],
  ): { filteredIssues: ReviewIssue[]; skippedCount: number } {
    // 所有历史问题(无论 valid 状态)都阻止新问题重复添加
    // valid='false' 的问题已被评审人标记为无效,不应再次报告
    // valid='true' 的问题已存在,无需重复
    // fixed 的问题已解决,无需重复
    const existingKeys = new Set(existingIssues.map((issue) => this.generateIssueKey(issue)));
    const filteredIssues = newIssues.filter(
      (issue) => !existingKeys.has(this.generateIssueKey(issue)),
    );
    const skippedCount = newIssues.length - filteredIssues.length;
    return { filteredIssues, skippedCount };
  }
 
  protected async getExistingReviewResult(
    owner: string,
    repo: string,
    prNumber: number,
  ): Promise<ReviewResult | null> {
    try {
      // 从 Issue Comment 获取已有的审查结果
      const comments = await this.gitProvider.listIssueComments(owner, repo, prNumber);
      const existingComment = comments.find((c) => c.body?.includes(REVIEW_COMMENT_MARKER));
      if (existingComment?.body) {
        return this.parseExistingReviewResult(existingComment.body);
      }
    } catch (error) {
      console.warn("⚠️ 获取已有评论失败:", error);
    }
    return null;
  }
 
  protected async ensureClaudeCli(): Promise<void> {
    try {
      execSync("claude --version", { stdio: "ignore" });
    } catch {
      console.log("🔧 Claude CLI 未安装,正在安装...");
      try {
        execSync("npm install -g @anthropic-ai/claude-code", {
          stdio: "inherit",
        });
        console.log("✅ Claude CLI 安装完成");
      } catch (installError) {
        throw new Error(
          `Claude CLI 安装失败: ${installError instanceof Error ? installError.message : String(installError)}`,
        );
      }
    }
  }
 
  /**
   * 构建文件行号到 commit hash 的映射
   * 遍历每个 commit,获取其修改的文件和行号
   * 优先使用 API,失败时回退到 git 命令
   */
  protected async buildLineCommitMap(
    owner: string,
    repo: string,
    commits: PullRequestCommit[],
    verbose?: VerboseLevel,
  ): Promise<Map<string, Map<number, string>>> {
    // Map<filename, Map<lineNumber, commitHash>>
    const fileLineMap = new Map<string, Map<number, string>>();
 
    // 按时间顺序遍历 commits(早的在前),后面的 commit 会覆盖前面的
    for (const commit of commits) {
      if (!commit.sha) continue;
 
      const shortHash = commit.sha.slice(0, 7);
      let files: Array<{ filename: string; patch: string }> = [];
 
      // 优先使用 getCommitDiff API 获取 diff 文本
      try {
        const diffText = await this.gitProvider.getCommitDiff(owner, repo, commit.sha);
        files = parseDiffText(diffText);
      } catch {
        // API 失败,回退到 git 命令
        files = this.gitSdk.getCommitDiff(commit.sha);
      }
      Iif (shouldLog(verbose, 2)) console.log(`   commit ${shortHash}: ${files.length} 个文件变更`);
 
      for (const file of files) {
        // 解析这个 commit 修改的行号
        const changedLines = parseChangedLinesFromPatch(file.patch);
 
        // 获取或创建文件的行号映射
        Eif (!fileLineMap.has(file.filename)) {
          fileLineMap.set(file.filename, new Map());
        }
        const lineMap = fileLineMap.get(file.filename)!;
 
        // 记录每行对应的 commit hash
        for (const lineNum of changedLines) {
          lineMap.set(lineNum, shortHash);
        }
      }
    }
 
    return fileLineMap;
  }
}