weave-core 0.3.2

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

use serde::Serialize;
use sem_core::model::change::ChangeType;
use sem_core::model::entity::SemanticEntity;
use sem_core::model::identity::match_entities;
use sem_core::parser::plugins::create_default_registry;
use sem_core::parser::registry::ParserRegistry;

/// Static parser registry shared across all merge operations.
/// Avoids recreating 11 tree-sitter language parsers per merge call.
static PARSER_REGISTRY: LazyLock<ParserRegistry> = LazyLock::new(create_default_registry);

use crate::conflict::{classify_conflict, ConflictComplexity, ConflictKind, EntityConflict, MarkerFormat, MergeStats};
use crate::region::{extract_regions, EntityRegion, FileRegion};
use crate::validate::SemanticWarning;
use crate::reconstruct::reconstruct;

/// How an individual entity was resolved during merge.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResolutionStrategy {
    Unchanged,
    OursOnly,
    TheirsOnly,
    ContentEqual,
    DiffyMerged,
    DecoratorMerged,
    InnerMerged,
    ConflictBothModified,
    ConflictModifyDelete,
    ConflictBothAdded,
    ConflictRenameRename,
    ConflictRenameModify,
    AddedOurs,
    AddedTheirs,
    Deleted,
    Renamed { from: String, to: String },
    Fallback,
}

/// Audit record for a single entity's merge resolution.
#[derive(Debug, Clone, Serialize)]
pub struct EntityAudit {
    pub name: String,
    #[serde(rename = "type")]
    pub entity_type: String,
    pub resolution: ResolutionStrategy,
}

/// Result of a merge operation.
#[derive(Debug)]
pub struct MergeResult {
    pub content: String,
    pub conflicts: Vec<EntityConflict>,
    pub warnings: Vec<SemanticWarning>,
    pub stats: MergeStats,
    pub audit: Vec<EntityAudit>,
}

impl MergeResult {
    pub fn is_clean(&self) -> bool {
        self.conflicts.is_empty()
            && !self.content.lines().any(|l| l.starts_with("<<<<<<< ours"))
    }
}

/// The resolved content for a single entity after merging.
#[derive(Debug, Clone)]
pub enum ResolvedEntity {
    /// Clean resolution — use this content.
    Clean(EntityRegion),
    /// Conflict — render conflict markers.
    Conflict(EntityConflict),
    /// Inner merge with per-member scoped conflicts.
    /// Content already contains per-member conflict markers; emit as-is.
    ScopedConflict {
        content: String,
        conflict: EntityConflict,
    },
    /// Entity was deleted.
    Deleted,
}

/// Perform entity-level 3-way merge.
///
/// Falls back to line-level merge (via diffy) when:
/// - No parser matches the file type
/// - Parser returns 0 entities for non-empty content
/// - File exceeds 1MB
pub fn entity_merge(
    base: &str,
    ours: &str,
    theirs: &str,
    file_path: &str,
) -> MergeResult {
    entity_merge_fmt(base, ours, theirs, file_path, &MarkerFormat::default())
}

/// Perform entity-level 3-way merge with configurable marker format.
pub fn entity_merge_fmt(
    base: &str,
    ours: &str,
    theirs: &str,
    file_path: &str,
    marker_format: &MarkerFormat,
) -> MergeResult {
    let timeout_secs = std::env::var("WEAVE_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(5);

    // Timeout: if entity merge takes too long, diffy is likely hitting
    // pathological input. Fall back to git merge-file which always terminates.
    let base_owned = base.to_string();
    let ours_owned = ours.to_string();
    let theirs_owned = theirs.to_string();
    let path_owned = file_path.to_string();
    let fmt_owned = marker_format.clone();

    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let result = entity_merge_with_registry(&base_owned, &ours_owned, &theirs_owned, &path_owned, &PARSER_REGISTRY, &fmt_owned);
        let _ = tx.send(result);
    });

    match rx.recv_timeout(Duration::from_secs(timeout_secs)) {
        Ok(result) => result,
        Err(_) => {
            eprintln!("weave: merge timed out after {}s for {}, falling back to git merge-file", timeout_secs, file_path);
            let mut stats = MergeStats::default();
            stats.used_fallback = true;
            git_merge_file(base, ours, theirs, &mut stats)
        }
    }
}

pub fn entity_merge_with_registry(
    base: &str,
    ours: &str,
    theirs: &str,
    file_path: &str,
    registry: &ParserRegistry,
    marker_format: &MarkerFormat,
) -> MergeResult {
    // Guard: if any input already contains conflict markers (e.g. AU/AA conflicts
    // where git bakes markers into stage blobs), report as conflict immediately.
    // We can't do a meaningful 3-way merge on pre-conflicted content.
    if has_conflict_markers(base) || has_conflict_markers(ours) || has_conflict_markers(theirs) {
        let mut stats = MergeStats::default();
        stats.entities_conflicted = 1;
        stats.used_fallback = true;
        // Use whichever input has markers as the merged content (preserves
        // the conflict for the user to resolve manually).
        let content = if has_conflict_markers(ours) {
            ours
        } else if has_conflict_markers(theirs) {
            theirs
        } else {
            base
        };
        let complexity = classify_conflict(Some(base), Some(ours), Some(theirs));
        return MergeResult {
            content: content.to_string(),
            conflicts: vec![EntityConflict {
                entity_name: "(file)".to_string(),
                entity_type: "file".to_string(),
                kind: ConflictKind::BothModified,
                complexity,
                ours_content: Some(ours.to_string()),
                theirs_content: Some(theirs.to_string()),
                base_content: Some(base.to_string()),
            }],
            warnings: vec![],
            stats,
            audit: vec![],
        };
    }

    // Fast path: if ours == theirs, no merge needed
    if ours == theirs {
        return MergeResult {
            content: ours.to_string(),
            conflicts: vec![],
            warnings: vec![],
            stats: MergeStats::default(),
            audit: vec![],
        };
    }

    // Fast path: if base == ours, take theirs entirely
    if base == ours {
        return MergeResult {
            content: theirs.to_string(),
            conflicts: vec![],
            warnings: vec![],
            stats: MergeStats {
                entities_theirs_only: 1,
                ..Default::default()
            },
            audit: vec![],
        };
    }

    // Fast path: if base == theirs, take ours entirely
    if base == theirs {
        return MergeResult {
            content: ours.to_string(),
            conflicts: vec![],
            warnings: vec![],
            stats: MergeStats {
                entities_ours_only: 1,
                ..Default::default()
            },
            audit: vec![],
        };
    }

    // Binary file detection: if any version has null bytes, use git merge-file directly
    if is_binary(base) || is_binary(ours) || is_binary(theirs) {
        let mut stats = MergeStats::default();
        stats.used_fallback = true;
        return git_merge_file(base, ours, theirs, &mut stats);
    }

    // Large file fallback
    if base.len() > 1_000_000 || ours.len() > 1_000_000 || theirs.len() > 1_000_000 {
        return line_level_fallback(base, ours, theirs, file_path);
    }

    // If the file type isn't natively supported, the registry returns the fallback
    // plugin (20-line chunks). Entity merge on arbitrary chunks produces WORSE
    // results than line-level merge (confirmed on GitButler's .svelte files where
    // chunk boundaries don't align with structural boundaries). So we skip entity
    // merge entirely for fallback-plugin files and go straight to line-level merge.
    let plugin = match registry.get_plugin(file_path) {
        Some(p) if p.id() != "fallback" => p,
        _ => return line_level_fallback(base, ours, theirs, file_path),
    };

    // Extract entities from all three versions. Keep unfiltered lists for inner merge
    // (child entities provide tree-sitter-based method decomposition for classes).
    let base_all = plugin.extract_entities(base, file_path);
    let ours_all = plugin.extract_entities(ours, file_path);
    let theirs_all = plugin.extract_entities(theirs, file_path);

    // Filter out nested entities for top-level matching and region extraction
    let base_entities = filter_nested_entities(base_all.clone());
    let ours_entities = filter_nested_entities(ours_all.clone());
    let theirs_entities = filter_nested_entities(theirs_all.clone());

    // Fallback if parser returns nothing for non-empty content
    if base_entities.is_empty() && !base.trim().is_empty() {
        return line_level_fallback(base, ours, theirs, file_path);
    }
    // When base is empty (file newly added in both branches), entity-level
    // reconstruction can produce invalid output for structured formats like JSON
    // (e.g. content appended after closing delimiter). Fall back to line-level
    // merge which handles this case correctly.
    if base.trim().is_empty() && !ours.trim().is_empty() && !theirs.trim().is_empty() {
        return line_level_fallback(base, ours, theirs, file_path);
    }
    // Allow empty entities if content is actually empty
    if ours_entities.is_empty() && !ours.trim().is_empty() && theirs_entities.is_empty() && !theirs.trim().is_empty() {
        return line_level_fallback(base, ours, theirs, file_path);
    }

    // Fallback if too many duplicate entity names. Entity matching is O(n*m) on
    // same-named entities which can hang on files with many `var app = ...` etc.
    if has_excessive_duplicates(&base_entities) || has_excessive_duplicates(&ours_entities) || has_excessive_duplicates(&theirs_entities) {
        return line_level_fallback(base, ours, theirs, file_path);
    }

    // Extract regions from all three
    let base_regions = extract_regions(base, &base_entities);
    let ours_regions = extract_regions(ours, &ours_entities);
    let theirs_regions = extract_regions(theirs, &theirs_entities);

    // Build region content maps (entity_id → content from file lines, preserving
    // surrounding syntax like `export` that sem-core's entity.content may strip)
    let base_region_content = build_region_content_map(&base_regions);
    let ours_region_content = build_region_content_map(&ours_regions);
    let theirs_region_content = build_region_content_map(&theirs_regions);

    // Match entities: base↔ours and base↔theirs
    let ours_changes = match_entities(&base_entities, &ours_entities, file_path, None, None, None);
    let theirs_changes = match_entities(&base_entities, &theirs_entities, file_path, None, None, None);

    // Build lookup maps
    let base_entity_map: HashMap<&str, &SemanticEntity> =
        base_entities.iter().map(|e| (e.id.as_str(), e)).collect();
    let ours_entity_map: HashMap<&str, &SemanticEntity> =
        ours_entities.iter().map(|e| (e.id.as_str(), e)).collect();
    let theirs_entity_map: HashMap<&str, &SemanticEntity> =
        theirs_entities.iter().map(|e| (e.id.as_str(), e)).collect();

    // Classify what happened to each entity in each branch
    let mut ours_change_map: HashMap<String, ChangeType> = HashMap::new();
    for change in &ours_changes.changes {
        ours_change_map.insert(change.entity_id.clone(), change.change_type);
    }
    let mut theirs_change_map: HashMap<String, ChangeType> = HashMap::new();
    for change in &theirs_changes.changes {
        theirs_change_map.insert(change.entity_id.clone(), change.change_type);
    }

    // Detect renames using structural_hash (RefFilter / IntelliMerge-inspired).
    // When one branch renames an entity, connect the old and new IDs so the merge
    // treats it as the same entity rather than a delete+add.
    let ours_rename_to_base = build_rename_map(&base_entities, &ours_entities);
    let theirs_rename_to_base = build_rename_map(&base_entities, &theirs_entities);
    // Reverse maps: base_id → renamed_id in that branch
    let base_to_ours_rename: HashMap<String, String> = ours_rename_to_base
        .iter()
        .map(|(new, old)| (old.clone(), new.clone()))
        .collect();
    let base_to_theirs_rename: HashMap<String, String> = theirs_rename_to_base
        .iter()
        .map(|(new, old)| (old.clone(), new.clone()))
        .collect();

    // Collect all entity IDs across all versions
    let mut all_entity_ids: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    // Track renamed IDs so we don't process them twice
    let mut skip_ids: HashSet<String> = HashSet::new();
    // The "new" IDs from renames should be skipped — they'll be handled via the base ID
    for new_id in ours_rename_to_base.keys() {
        skip_ids.insert(new_id.clone());
    }
    for new_id in theirs_rename_to_base.keys() {
        skip_ids.insert(new_id.clone());
    }

    // Start with ours ordering (skeleton)
    for entity in &ours_entities {
        if skip_ids.contains(&entity.id) {
            continue;
        }
        if seen.insert(entity.id.clone()) {
            all_entity_ids.push(entity.id.clone());
        }
    }
    // Add theirs-only entities
    for entity in &theirs_entities {
        if skip_ids.contains(&entity.id) {
            continue;
        }
        if seen.insert(entity.id.clone()) {
            all_entity_ids.push(entity.id.clone());
        }
    }
    // Add base-only entities (deleted in both → skip, deleted in one → handled below)
    for entity in &base_entities {
        if seen.insert(entity.id.clone()) {
            all_entity_ids.push(entity.id.clone());
        }
    }

    let mut stats = MergeStats::default();
    let mut conflicts: Vec<EntityConflict> = Vec::new();
    let mut audit: Vec<EntityAudit> = Vec::new();
    let mut resolved_entities: HashMap<String, ResolvedEntity> = HashMap::new();

    // Detect rename/rename conflicts: same base entity renamed differently in both branches.
    // These must be flagged before the entity resolution loop, which would otherwise silently
    // pick ours and also include theirs as an unmatched entity.
    let mut rename_conflict_ids: HashSet<String> = HashSet::new();
    for (base_id, ours_new_id) in &base_to_ours_rename {
        if let Some(theirs_new_id) = base_to_theirs_rename.get(base_id) {
            if ours_new_id != theirs_new_id {
                rename_conflict_ids.insert(base_id.clone());
            }
        }
    }

    for entity_id in &all_entity_ids {
        // Handle rename/rename conflicts: both branches renamed this base entity differently
        if rename_conflict_ids.contains(entity_id) {
            let ours_new_id = &base_to_ours_rename[entity_id];
            let theirs_new_id = &base_to_theirs_rename[entity_id];
            let base_entity = base_entity_map.get(entity_id.as_str());
            let ours_entity = ours_entity_map.get(ours_new_id.as_str());
            let theirs_entity = theirs_entity_map.get(theirs_new_id.as_str());
            let base_name = base_entity.map(|e| e.name.as_str()).unwrap_or(entity_id);
            let ours_name = ours_entity.map(|e| e.name.as_str()).unwrap_or(ours_new_id);
            let theirs_name = theirs_entity.map(|e| e.name.as_str()).unwrap_or(theirs_new_id);

            let base_rc = base_entity.map(|e| base_region_content.get(e.id.as_str()).map(|s| s.to_string()).unwrap_or_else(|| e.content.clone()));
            let ours_rc = ours_entity.map(|e| ours_region_content.get(e.id.as_str()).map(|s| s.to_string()).unwrap_or_else(|| e.content.clone()));
            let theirs_rc = theirs_entity.map(|e| theirs_region_content.get(e.id.as_str()).map(|s| s.to_string()).unwrap_or_else(|| e.content.clone()));

            stats.entities_conflicted += 1;
            let conflict = EntityConflict {
                entity_name: base_name.to_string(),
                entity_type: base_entity.map(|e| e.entity_type.clone()).unwrap_or_default(),
                kind: ConflictKind::RenameRename {
                    base_name: base_name.to_string(),
                    ours_name: ours_name.to_string(),
                    theirs_name: theirs_name.to_string(),
                },
                complexity: crate::conflict::ConflictComplexity::Syntax,
                ours_content: ours_rc,
                theirs_content: theirs_rc,
                base_content: base_rc,
            };
            conflicts.push(conflict.clone());
            audit.push(EntityAudit {
                name: base_name.to_string(),
                entity_type: base_entity.map(|e| e.entity_type.clone()).unwrap_or_default(),
                resolution: ResolutionStrategy::ConflictRenameRename,
            });
            let resolution = ResolvedEntity::Conflict(conflict);
            resolved_entities.insert(entity_id.clone(), resolution.clone());
            resolved_entities.insert(ours_new_id.clone(), resolution);
            // Mark theirs renamed ID as Deleted so reconstruct doesn't emit the conflict twice
            // (once from ours skeleton, once from theirs-only insertion)
            resolved_entities.insert(theirs_new_id.clone(), ResolvedEntity::Deleted);
            continue;
        }

        let in_base = base_entity_map.get(entity_id.as_str());
        // Follow rename chains: if base entity was renamed in ours/theirs, use renamed version
        let ours_id = base_to_ours_rename.get(entity_id.as_str()).map(|s| s.as_str()).unwrap_or(entity_id.as_str());
        let theirs_id = base_to_theirs_rename.get(entity_id.as_str()).map(|s| s.as_str()).unwrap_or(entity_id.as_str());
        let in_ours = ours_entity_map.get(ours_id).or_else(|| ours_entity_map.get(entity_id.as_str()));
        let in_theirs = theirs_entity_map.get(theirs_id).or_else(|| theirs_entity_map.get(entity_id.as_str()));

        let ours_change = ours_change_map.get(entity_id);
        let theirs_change = theirs_change_map.get(entity_id);

        let (resolution, strategy) = resolve_entity(
            entity_id,
            in_base,
            in_ours,
            in_theirs,
            ours_change,
            theirs_change,
            &base_region_content,
            &ours_region_content,
            &theirs_region_content,
            &base_all,
            &ours_all,
            &theirs_all,
            &mut stats,
            marker_format,
        );

        // Build audit entry from entity info
        let entity_name = in_ours.map(|e| e.name.as_str())
            .or_else(|| in_theirs.map(|e| e.name.as_str()))
            .or_else(|| in_base.map(|e| e.name.as_str()))
            .unwrap_or(entity_id)
            .to_string();
        let entity_type = in_ours.map(|e| e.entity_type.as_str())
            .or_else(|| in_theirs.map(|e| e.entity_type.as_str()))
            .or_else(|| in_base.map(|e| e.entity_type.as_str()))
            .unwrap_or("")
            .to_string();
        audit.push(EntityAudit {
            name: entity_name,
            entity_type,
            resolution: strategy,
        });

        match &resolution {
            ResolvedEntity::Conflict(ref c) => conflicts.push(c.clone()),
            ResolvedEntity::ScopedConflict { conflict, .. } => conflicts.push(conflict.clone()),
            _ => {}
        }

        resolved_entities.insert(entity_id.clone(), resolution.clone());
        // Also store under renamed IDs so reconstruct can find them
        if let Some(ours_renamed_id) = base_to_ours_rename.get(entity_id.as_str()) {
            resolved_entities.insert(ours_renamed_id.clone(), resolution.clone());
        }
        if let Some(theirs_renamed_id) = base_to_theirs_rename.get(entity_id.as_str()) {
            resolved_entities.insert(theirs_renamed_id.clone(), resolution);
        }
    }

    // Merge interstitial regions
    let (merged_interstitials, interstitial_conflicts) =
        merge_interstitials(&base_regions, &ours_regions, &theirs_regions, marker_format);
    stats.entities_conflicted += interstitial_conflicts.len();
    conflicts.extend(interstitial_conflicts);

    // Collect base IDs that were renamed in ours — these should not be treated
    // as "theirs-only additions" during reconstruction.
    let theirs_rename_base_ids: HashSet<String> = base_to_ours_rename.keys().cloned().collect();

    // Reconstruct the file
    let content = reconstruct(
        &ours_regions,
        &theirs_regions,
        &theirs_entities,
        &ours_entity_map,
        &resolved_entities,
        &merged_interstitials,
        marker_format,
        &theirs_rename_base_ids,
    );

    // Post-merge cleanup: remove duplicate lines and normalize blank lines
    let content = post_merge_cleanup(&content);

    // Post-merge validation: verify the merged result is structurally sound.
    // Catches silent data loss from entity merge / reconstruction bugs.
    let mut warnings = vec![];
    if conflicts.is_empty() && stats.entities_both_changed_merged > 0 {
        let merged_entities = plugin.extract_entities(&content, file_path);
        if merged_entities.is_empty() && !content.trim().is_empty() {
            warnings.push(crate::validate::SemanticWarning {
                entity_name: "(file)".to_string(),
                entity_type: "file".to_string(),
                file_path: file_path.to_string(),
                kind: crate::validate::WarningKind::ParseFailedAfterMerge,
                related: vec![],
            });
        }

        // Entity coverage check: every resolved-clean entity's content should
        // appear in the merged output. If it doesn't, reconstruct dropped it.
        if conflicts.is_empty() {
            for (_, resolved) in &resolved_entities {
                if let ResolvedEntity::Clean(region) = resolved {
                    let trimmed = region.content.trim();
                    if !trimmed.is_empty() && trimmed.len() > 20 && !content.contains(trimmed) {
                        // Entity resolved cleanly but its content is missing from output.
                        // Fall back to git merge-file to avoid silent data loss.
                        return git_merge_file(base, ours, theirs, &mut stats);
                    }
                }
            }
        }

        // Entity count check: re-parsed merged output should have at least as many
        // entities as the minimum of ours/theirs (minus deletions). A significant
        // drop means entities were silently lost.
        if conflicts.is_empty() && !merged_entities.is_empty() {
            let merged_top = filter_nested_entities(merged_entities);
            let deleted_count = resolved_entities.values()
                .filter(|r| matches!(r, ResolvedEntity::Deleted))
                .count();
            let expected_min = ours_entities.len().min(theirs_entities.len()).saturating_sub(deleted_count);
            if expected_min > 3 && merged_top.len() < expected_min * 80 / 100 {
                return git_merge_file(base, ours, theirs, &mut stats);
            }
        }

    }

    // Line-level drop detection: lines present in all 3 inputs (unchanged by
    // either branch) must appear in the output. Dropping them is always wrong.
    // This runs on ALL clean merges, not just those with both-changed entities.
    if conflicts.is_empty() {
        let base_lines: HashSet<&str> = base.lines()
            .map(|l| l.trim())
            .filter(|l| l.len() > 15 && !is_import_line_trimmed(l))
            .collect();
        let ours_lines: HashSet<&str> = ours.lines()
            .map(|l| l.trim())
            .filter(|l| l.len() > 15 && !is_import_line_trimmed(l))
            .collect();
        let theirs_lines: HashSet<&str> = theirs.lines()
            .map(|l| l.trim())
            .filter(|l| l.len() > 15 && !is_import_line_trimmed(l))
            .collect();
        let output_lines: HashSet<&str> = content.lines()
            .map(|l| l.trim())
            .collect();

        // Unchanged lines (in all 3) must be in output
        let missing_unchanged = base_lines.iter()
            .filter(|l| ours_lines.contains(*l) && theirs_lines.contains(*l))
            .filter(|l| !output_lines.contains(*l))
            .count();

        if missing_unchanged > 0 {
            return git_merge_file(base, ours, theirs, &mut stats);
        }

        // Lines added by either branch (not in base) shouldn't be dropped either.
        // Split into two tiers:
        // - "Significant" lines (> 40 chars): even 1 missing is likely a bug, since
        //   long lines are unique enough that reformatting won't change them completely
        // - Shorter lines (16-40 chars): use threshold > 3, since these could be
        //   structural lines reformatted by the import merger or brace placement
        let mut missing_added_significant = 0;
        let mut missing_added_short = 0;
        for l in ours_lines.iter().chain(theirs_lines.iter()) {
            if base_lines.contains(l) || output_lines.contains(l) {
                continue;
            }
            // Also check if the core content appears as a substring in any output line
            // (handles reformatting like `Foo {` becoming `Foo\n{`)
            if l.len() > 25 && content.contains(*l) {
                continue;
            }
            if l.len() > 40 {
                missing_added_significant += 1;
            } else {
                missing_added_short += 1;
            }
        }

        if missing_added_significant > 0 || missing_added_short > 3 {
            return git_merge_file(base, ours, theirs, &mut stats);
        }
    }

    let entity_result = MergeResult {
        content,
        conflicts,
        warnings,
        stats: stats.clone(),
        audit,
    };

    // Floor: never produce more conflict markers than git merge-file.
    // Entity merge can split one git conflict into multiple per-entity conflicts,
    // or interstitial merges can produce conflicts not tracked in the conflicts vec.
    let entity_markers = entity_result.content.lines().filter(|l| l.starts_with("<<<<<<<")).count();
    if entity_markers > 0 {
        let git_result = git_merge_file(base, ours, theirs, &mut stats);
        let git_markers = git_result.content.lines().filter(|l| l.starts_with("<<<<<<<")).count();
        if entity_markers > git_markers {
            return git_result;
        }
    }

    // Safety net: detect silent data loss from entity merge.
    // If the merged result is significantly shorter than expected, fall back to git.
    if entity_markers == 0 {
        let merged_len = entity_result.content.len();
        let max_input_len = ours.len().max(theirs.len());
        let min_input_len = ours.len().min(theirs.len());
        // Expected length: at least 90% of the shorter input (both branches
        // contribute content, so the merge should be at least as long as the
        // shorter one minus some deletions).
        if min_input_len > 200 && merged_len < min_input_len * 90 / 100 {
            return git_merge_file(base, ours, theirs, &mut stats);
        }
        // Also check: merged shouldn't be much shorter than max input unless
        // there were intentional deletions from one branch
        if max_input_len > 500 && merged_len < max_input_len * 70 / 100 {
            // Check if the length reduction is explained by one branch deleting content
            let base_len = base.len();
            let ours_deleted = base_len > ours.len() && (base_len - ours.len()) > max_input_len * 20 / 100;
            let theirs_deleted = base_len > theirs.len() && (base_len - theirs.len()) > max_input_len * 20 / 100;
            if !ours_deleted && !theirs_deleted {
                return git_merge_file(base, ours, theirs, &mut stats);
            }
        }
    }

    entity_result
}

fn resolve_entity(
    _entity_id: &str,
    in_base: Option<&&SemanticEntity>,
    in_ours: Option<&&SemanticEntity>,
    in_theirs: Option<&&SemanticEntity>,
    _ours_change: Option<&ChangeType>,
    _theirs_change: Option<&ChangeType>,
    base_region_content: &HashMap<&str, &str>,
    ours_region_content: &HashMap<&str, &str>,
    theirs_region_content: &HashMap<&str, &str>,
    base_all: &[SemanticEntity],
    ours_all: &[SemanticEntity],
    theirs_all: &[SemanticEntity],
    stats: &mut MergeStats,
    marker_format: &MarkerFormat,
) -> (ResolvedEntity, ResolutionStrategy) {
    // Helper: get region content (from file lines) for an entity, falling back to entity.content
    let region_content = |entity: &SemanticEntity, map: &HashMap<&str, &str>| -> String {
        map.get(entity.id.as_str()).map(|s| s.to_string()).unwrap_or_else(|| entity.content.clone())
    };

    match (in_base, in_ours, in_theirs) {
        // Entity exists in all three versions
        (Some(base), Some(ours), Some(theirs)) => {
            // Check modification status via structural hash AND region content.
            // Region content may differ even when structural hash is the same
            // (e.g., doc comment added/changed but function body unchanged).
            let base_rc_lazy = || region_content(base, base_region_content);
            let ours_rc_lazy = || region_content(ours, ours_region_content);
            let theirs_rc_lazy = || region_content(theirs, theirs_region_content);

            let ours_modified = ours.content_hash != base.content_hash
                || ours_rc_lazy() != base_rc_lazy();
            let theirs_modified = theirs.content_hash != base.content_hash
                || theirs_rc_lazy() != base_rc_lazy();

            match (ours_modified, theirs_modified) {
                (false, false) => {
                    // Neither changed
                    stats.entities_unchanged += 1;
                    (ResolvedEntity::Clean(entity_to_region_with_content(ours, &region_content(ours, ours_region_content))), ResolutionStrategy::Unchanged)
                }
                (true, false) => {
                    // Only ours changed
                    stats.entities_ours_only += 1;
                    (ResolvedEntity::Clean(entity_to_region_with_content(ours, &region_content(ours, ours_region_content))), ResolutionStrategy::OursOnly)
                }
                (false, true) => {
                    // Only theirs changed
                    stats.entities_theirs_only += 1;
                    (ResolvedEntity::Clean(entity_to_region_with_content(theirs, &region_content(theirs, theirs_region_content))), ResolutionStrategy::TheirsOnly)
                }
                (true, true) => {
                    // Both changed — try intra-entity merge
                    if ours.content_hash == theirs.content_hash {
                        // Same change in both — take ours
                        stats.entities_both_changed_merged += 1;
                        (ResolvedEntity::Clean(entity_to_region_with_content(ours, &region_content(ours, ours_region_content))), ResolutionStrategy::ContentEqual)
                    } else {
                        // Try diffy 3-way merge on region content (preserves full syntax)
                        let base_rc = region_content(base, base_region_content);
                        let ours_rc = region_content(ours, ours_region_content);
                        let theirs_rc = region_content(theirs, theirs_region_content);

                        // Rename-aware merge: when one side renamed an entity and the
                        // other modified it, normalize names before 3-way merge so diffy
                        // only sees the structural changes, not name conflicts.
                        let ours_renamed = base.name != ours.name;
                        let theirs_renamed = base.name != theirs.name;
                        let (merge_base_rc, merge_ours_rc, merge_theirs_rc, _final_name) =
                            if ours_renamed && !theirs_renamed {
                                // Ours renamed: normalize base+theirs to use ours' name
                                let nb = replace_at_word_boundaries(&base_rc, &base.name, &ours.name);
                                let nt = replace_at_word_boundaries(&theirs_rc, &theirs.name, &ours.name);
                                (nb, ours_rc.clone(), nt, Some(&ours.name))
                            } else if theirs_renamed && !ours_renamed {
                                // Theirs renamed: normalize base+ours to use theirs' name
                                let nb = replace_at_word_boundaries(&base_rc, &base.name, &theirs.name);
                                let no = replace_at_word_boundaries(&ours_rc, &ours.name, &theirs.name);
                                (nb, no, theirs_rc.clone(), Some(&theirs.name))
                            } else {
                                (base_rc.clone(), ours_rc.clone(), theirs_rc.clone(), None)
                            };

                        // Rename + modify: if one side renamed and the other modified
                        // the body, conflict. The modifying developer didn't know about
                        // the rename, so the merge needs human/agent review.
                        if (ours_renamed && !theirs_renamed) || (!ours_renamed && theirs_renamed) {
                            let renamed_in_ours = ours_renamed;
                            let (old_name, new_name) = if renamed_in_ours {
                                (base.name.clone(), ours.name.clone())
                            } else {
                                (base.name.clone(), theirs.name.clone())
                            };
                            stats.entities_conflicted += 1;
                            let conflict = EntityConflict {
                                entity_name: base.name.clone(),
                                entity_type: base.entity_type.clone(),
                                kind: ConflictKind::RenameModify {
                                    old_name,
                                    new_name,
                                    renamed_in_ours,
                                },
                                complexity: ConflictComplexity::SyntaxFunctional,
                                ours_content: Some(ours_rc),
                                theirs_content: Some(theirs_rc),
                                base_content: Some(base_rc),
                            };
                            return (ResolvedEntity::Conflict(conflict), ResolutionStrategy::ConflictRenameModify);
                        }

                        // Whitespace-aware shortcut: if one side only changed
                        // whitespace/formatting, take the other side's content changes.
                        // This handles the common case where one agent reformats while
                        // another makes semantic changes.
                        if is_whitespace_only_diff(&base_rc, &ours_rc) {
                            stats.entities_theirs_only += 1;
                            return (ResolvedEntity::Clean(entity_to_region_with_content(theirs, &theirs_rc)), ResolutionStrategy::TheirsOnly);
                        }
                        if is_whitespace_only_diff(&base_rc, &theirs_rc) {
                            stats.entities_ours_only += 1;
                            return (ResolvedEntity::Clean(entity_to_region_with_content(ours, &ours_rc)), ResolutionStrategy::OursOnly);
                        }

                        // Pick the renamed entity for output (prefer the side that did the rename)
                        let output_entity = if ours_renamed { ours } else if theirs_renamed { theirs } else { ours };

                        match diffy_merge(&merge_base_rc, &merge_ours_rc, &merge_theirs_rc) {
                            Some(merged) => {
                                stats.entities_both_changed_merged += 1;
                                stats.resolved_via_diffy += 1;
                                (ResolvedEntity::Clean(EntityRegion {
                                    entity_id: output_entity.id.clone(),
                                    entity_name: output_entity.name.clone(),
                                    entity_type: output_entity.entity_type.clone(),
                                    content: merged,
                                    start_line: output_entity.start_line,
                                    end_line: output_entity.end_line,
                                }), ResolutionStrategy::DiffyMerged)
                            }
                            None => {
                                // Strategy 1: decorator/annotation-aware merge
                                // Decorators are unordered annotations — merge them commutatively
                                if let Some(merged) = try_decorator_aware_merge(&base_rc, &ours_rc, &theirs_rc) {
                                    stats.entities_both_changed_merged += 1;
                                    stats.resolved_via_diffy += 1;
                                    return (ResolvedEntity::Clean(EntityRegion {
                                        entity_id: ours.id.clone(),
                                        entity_name: ours.name.clone(),
                                        entity_type: ours.entity_type.clone(),
                                        content: merged,
                                        start_line: ours.start_line,
                                        end_line: ours.end_line,
                                    }), ResolutionStrategy::DecoratorMerged);
                                }

                                // Strategy 2: inner entity merge for container types
                                // (LastMerge insight: class members are unordered children)
                                if is_container_entity_type(&ours.entity_type) {
                                    let base_children = in_base
                                        .map(|b| get_child_entities(b, base_all))
                                        .unwrap_or_default();
                                    let ours_children = get_child_entities(ours, ours_all);
                                    let theirs_children = in_theirs
                                        .map(|t| get_child_entities(t, theirs_all))
                                        .unwrap_or_default();
                                    let base_start = in_base.map(|b| b.start_line).unwrap_or(1);
                                    let ours_start = ours.start_line;
                                    let theirs_start = in_theirs.map(|t| t.start_line).unwrap_or(1);
                                    if let Some(inner) = try_inner_entity_merge(
                                        &base_rc, &ours_rc, &theirs_rc,
                                        &base_children, &ours_children, &theirs_children,
                                        base_start, ours_start, theirs_start,
                                        marker_format,
                                    ) {
                                        if inner.has_conflicts {
                                            // Inner merge produced per-member conflicts:
                                            // content has scoped markers for just the conflicted
                                            // members; clean members are merged normally.
                                            stats.entities_conflicted += 1;
                                            stats.resolved_via_inner_merge += 1;
                                            let complexity = classify_conflict(Some(&base_rc), Some(&ours_rc), Some(&theirs_rc));
                                            return (ResolvedEntity::ScopedConflict {
                                                content: inner.content,
                                                conflict: EntityConflict {
                                                    entity_name: ours.name.clone(),
                                                    entity_type: ours.entity_type.clone(),
                                                    kind: ConflictKind::BothModified,
                                                    complexity,
                                                    ours_content: Some(ours_rc),
                                                    theirs_content: Some(theirs_rc),
                                                    base_content: Some(base_rc),
                                                },
                                            }, ResolutionStrategy::InnerMerged);
                                        } else {
                                            stats.entities_both_changed_merged += 1;
                                            stats.resolved_via_inner_merge += 1;
                                            return (ResolvedEntity::Clean(EntityRegion {
                                                entity_id: ours.id.clone(),
                                                entity_name: ours.name.clone(),
                                                entity_type: ours.entity_type.clone(),
                                                content: inner.content,
                                                start_line: ours.start_line,
                                                end_line: ours.end_line,
                                            }), ResolutionStrategy::InnerMerged);
                                        }
                                    }
                                }
                                stats.entities_conflicted += 1;
                                let complexity = classify_conflict(Some(&base_rc), Some(&ours_rc), Some(&theirs_rc));
                                (ResolvedEntity::Conflict(EntityConflict {
                                    entity_name: ours.name.clone(),
                                    entity_type: ours.entity_type.clone(),
                                    kind: ConflictKind::BothModified,
                                    complexity,
                                    ours_content: Some(ours_rc),
                                    theirs_content: Some(theirs_rc),
                                    base_content: Some(base_rc),
                                }), ResolutionStrategy::ConflictBothModified)
                            }
                        }
                    }
                }
            }
        }

        // Entity in base and ours, but not theirs → theirs deleted it
        (Some(_base), Some(ours), None) => {
            let ours_modified = ours.content_hash != _base.content_hash;
            if ours_modified {
                // Modify/delete conflict
                stats.entities_conflicted += 1;
                let ours_rc = region_content(ours, ours_region_content);
                let base_rc = region_content(_base, base_region_content);
                let complexity = classify_conflict(Some(&base_rc), Some(&ours_rc), None);
                (ResolvedEntity::Conflict(EntityConflict {
                    entity_name: ours.name.clone(),
                    entity_type: ours.entity_type.clone(),
                    kind: ConflictKind::ModifyDelete {
                        modified_in_ours: true,
                    },
                    complexity,
                    ours_content: Some(ours_rc),
                    theirs_content: None,
                    base_content: Some(base_rc),
                }), ResolutionStrategy::ConflictModifyDelete)
            } else {
                // Theirs deleted, ours unchanged → accept deletion
                stats.entities_deleted += 1;
                (ResolvedEntity::Deleted, ResolutionStrategy::Deleted)
            }
        }

        // Entity in base and theirs, but not ours → ours deleted it
        (Some(_base), None, Some(theirs)) => {
            let theirs_modified = theirs.content_hash != _base.content_hash;
            if theirs_modified {
                // Modify/delete conflict
                stats.entities_conflicted += 1;
                let theirs_rc = region_content(theirs, theirs_region_content);
                let base_rc = region_content(_base, base_region_content);
                let complexity = classify_conflict(Some(&base_rc), None, Some(&theirs_rc));
                (ResolvedEntity::Conflict(EntityConflict {
                    entity_name: theirs.name.clone(),
                    entity_type: theirs.entity_type.clone(),
                    kind: ConflictKind::ModifyDelete {
                        modified_in_ours: false,
                    },
                    complexity,
                    ours_content: None,
                    theirs_content: Some(theirs_rc),
                    base_content: Some(base_rc),
                }), ResolutionStrategy::ConflictModifyDelete)
            } else {
                // Ours deleted, theirs unchanged → accept deletion
                stats.entities_deleted += 1;
                (ResolvedEntity::Deleted, ResolutionStrategy::Deleted)
            }
        }

        // Entity only in ours (added by ours)
        (None, Some(ours), None) => {
            stats.entities_added_ours += 1;
            (ResolvedEntity::Clean(entity_to_region_with_content(ours, &region_content(ours, ours_region_content))), ResolutionStrategy::AddedOurs)
        }

        // Entity only in theirs (added by theirs)
        (None, None, Some(theirs)) => {
            stats.entities_added_theirs += 1;
            (ResolvedEntity::Clean(entity_to_region_with_content(theirs, &region_content(theirs, theirs_region_content))), ResolutionStrategy::AddedTheirs)
        }

        // Entity in both ours and theirs but not base (both added)
        (None, Some(ours), Some(theirs)) => {
            if ours.content_hash == theirs.content_hash {
                // Same content added by both → take ours
                stats.entities_added_ours += 1;
                (ResolvedEntity::Clean(entity_to_region_with_content(ours, &region_content(ours, ours_region_content))), ResolutionStrategy::ContentEqual)
            } else {
                // Different content → conflict
                stats.entities_conflicted += 1;
                let ours_rc = region_content(ours, ours_region_content);
                let theirs_rc = region_content(theirs, theirs_region_content);
                let complexity = classify_conflict(None, Some(&ours_rc), Some(&theirs_rc));
                (ResolvedEntity::Conflict(EntityConflict {
                    entity_name: ours.name.clone(),
                    entity_type: ours.entity_type.clone(),
                    kind: ConflictKind::BothAdded,
                    complexity,
                    ours_content: Some(ours_rc),
                    theirs_content: Some(theirs_rc),
                    base_content: None,
                }), ResolutionStrategy::ConflictBothAdded)
            }
        }

        // Entity only in base (deleted by both)
        (Some(_), None, None) => {
            stats.entities_deleted += 1;
            (ResolvedEntity::Deleted, ResolutionStrategy::Deleted)
        }

        // Should not happen
        (None, None, None) => (ResolvedEntity::Deleted, ResolutionStrategy::Deleted),
    }
}

fn entity_to_region_with_content(entity: &SemanticEntity, content: &str) -> EntityRegion {
    EntityRegion {
        entity_id: entity.id.clone(),
        entity_name: entity.name.clone(),
        entity_type: entity.entity_type.clone(),
        content: content.to_string(),
        start_line: entity.start_line,
        end_line: entity.end_line,
    }
}

/// Build a map from entity_id to region content (from file lines).
/// This preserves surrounding syntax (like `export`) that sem-core's entity.content may strip.
/// Returns borrowed references since regions live for the merge duration.
fn build_region_content_map(regions: &[FileRegion]) -> HashMap<&str, &str> {
    regions
        .iter()
        .filter_map(|r| match r {
            FileRegion::Entity(e) => Some((e.entity_id.as_str(), e.content.as_str())),
            _ => None,
        })
        .collect()
}

/// Check if the only differences between two strings are whitespace changes.
/// This includes: indentation changes, trailing whitespace, blank line additions/removals.
fn is_whitespace_only_diff(a: &str, b: &str) -> bool {
    if a == b {
        return true; // identical, not really a "whitespace-only diff" but safe
    }
    let a_normalized: Vec<&str> = a.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();
    let b_normalized: Vec<&str> = b.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();
    a_normalized == b_normalized
}

/// Check if a line is a decorator or annotation.
/// Covers Python (@decorator), Java/TS (@Annotation), and comment-style annotations.
fn is_decorator_line(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with('@')
        && !trimmed.starts_with("@param")
        && !trimmed.starts_with("@return")
        && !trimmed.starts_with("@type")
        && !trimmed.starts_with("@see")
}

/// Split content into (decorators, body) where decorators are leading @-prefixed lines.
fn split_decorators(content: &str) -> (Vec<&str>, &str) {
    let mut decorator_end = 0;
    let mut byte_offset = 0;
    for line in content.lines() {
        if is_decorator_line(line) || line.trim().is_empty() {
            decorator_end += 1;
            byte_offset += line.len() + 1; // +1 for newline
        } else {
            break;
        }
    }
    // Trim trailing empty lines from decorator section
    let lines: Vec<&str> = content.lines().collect();
    while decorator_end > 0 && lines.get(decorator_end - 1).map_or(false, |l| l.trim().is_empty()) {
        byte_offset -= lines[decorator_end - 1].len() + 1;
        decorator_end -= 1;
    }
    let decorators: Vec<&str> = lines[..decorator_end]
        .iter()
        .filter(|l| is_decorator_line(l))
        .copied()
        .collect();
    let body = &content[byte_offset.min(content.len())..];
    (decorators, body)
}

/// Try decorator-aware merge: when both sides add different decorators/annotations,
/// merge them commutatively (like imports). Also try merging the bodies separately.
///
/// This handles the common pattern where one agent adds @cache and another adds @deprecated
/// to the same function — they should both be preserved.
fn try_decorator_aware_merge(base: &str, ours: &str, theirs: &str) -> Option<String> {
    let (base_decorators, base_body) = split_decorators(base);
    let (ours_decorators, ours_body) = split_decorators(ours);
    let (theirs_decorators, theirs_body) = split_decorators(theirs);

    // Only useful if at least one side has decorators
    if ours_decorators.is_empty() && theirs_decorators.is_empty() {
        return None;
    }

    // Merge bodies using diffy (or take unchanged side)
    let merged_body = if base_body == ours_body && base_body == theirs_body {
        base_body.to_string()
    } else if base_body == ours_body {
        theirs_body.to_string()
    } else if base_body == theirs_body {
        ours_body.to_string()
    } else {
        // Both changed body — try diffy on just the body
        diffy_merge(base_body, ours_body, theirs_body)?
    };

    // Merge decorators commutatively (set union)
    let base_set: HashSet<&str> = base_decorators.iter().copied().collect();
    let ours_set: HashSet<&str> = ours_decorators.iter().copied().collect();
    let theirs_set: HashSet<&str> = theirs_decorators.iter().copied().collect();

    // Deletions
    let ours_deleted: HashSet<&str> = base_set.difference(&ours_set).copied().collect();
    let theirs_deleted: HashSet<&str> = base_set.difference(&theirs_set).copied().collect();

    // Start with base decorators, remove deletions
    let mut merged_decorators: Vec<&str> = base_decorators
        .iter()
        .filter(|d| !ours_deleted.contains(**d) && !theirs_deleted.contains(**d))
        .copied()
        .collect();

    // Add new decorators from ours (not in base)
    for d in &ours_decorators {
        if !base_set.contains(d) && !merged_decorators.contains(d) {
            merged_decorators.push(d);
        }
    }
    // Add new decorators from theirs (not in base, not already added)
    for d in &theirs_decorators {
        if !base_set.contains(d) && !merged_decorators.contains(d) {
            merged_decorators.push(d);
        }
    }

    // Reconstruct
    let mut result = String::new();
    for d in &merged_decorators {
        result.push_str(d);
        result.push('\n');
    }
    result.push_str(&merged_body);

    Some(result)
}

/// Try 3-way merge on text using diffy. Returns None if there are conflicts.
fn diffy_merge(base: &str, ours: &str, theirs: &str) -> Option<String> {
    let result = diffy::merge(base, ours, theirs);
    match result {
        Ok(merged) => Some(merged),
        Err(_conflicted) => None,
    }
}

/// Try 3-way merge using git merge-file. Returns None on conflict or error.
/// This uses a different diff algorithm than diffy and can sometimes merge
/// cases that diffy cannot (and vice versa).
fn git_merge_string(base: &str, ours: &str, theirs: &str) -> Option<String> {
    let dir = tempfile::tempdir().ok()?;
    let base_path = dir.path().join("base");
    let ours_path = dir.path().join("ours");
    let theirs_path = dir.path().join("theirs");

    std::fs::write(&base_path, base).ok()?;
    std::fs::write(&ours_path, ours).ok()?;
    std::fs::write(&theirs_path, theirs).ok()?;

    let output = Command::new("git")
        .arg("merge-file")
        .arg("-p")
        .arg(&ours_path)
        .arg(&base_path)
        .arg(&theirs_path)
        .output()
        .ok()?;

    if output.status.success() {
        String::from_utf8(output.stdout).ok()
    } else {
        None
    }
}

/// Merge interstitial regions from all three versions.
/// Uses commutative (set-based) merge for import blocks — inspired by
/// LastMerge/Mergiraf's "unordered children" concept.
/// Falls back to line-level 3-way merge for non-import content.
fn merge_interstitials(
    base_regions: &[FileRegion],
    ours_regions: &[FileRegion],
    theirs_regions: &[FileRegion],
    marker_format: &MarkerFormat,
) -> (HashMap<String, String>, Vec<EntityConflict>) {
    let base_map: HashMap<&str, &str> = base_regions
        .iter()
        .filter_map(|r| match r {
            FileRegion::Interstitial(i) => Some((i.position_key.as_str(), i.content.as_str())),
            _ => None,
        })
        .collect();

    let ours_map: HashMap<&str, &str> = ours_regions
        .iter()
        .filter_map(|r| match r {
            FileRegion::Interstitial(i) => Some((i.position_key.as_str(), i.content.as_str())),
            _ => None,
        })
        .collect();

    let theirs_map: HashMap<&str, &str> = theirs_regions
        .iter()
        .filter_map(|r| match r {
            FileRegion::Interstitial(i) => Some((i.position_key.as_str(), i.content.as_str())),
            _ => None,
        })
        .collect();

    let mut all_keys: HashSet<&str> = HashSet::new();
    all_keys.extend(base_map.keys());
    all_keys.extend(ours_map.keys());
    all_keys.extend(theirs_map.keys());

    let mut merged: HashMap<String, String> = HashMap::new();
    let mut interstitial_conflicts: Vec<EntityConflict> = Vec::new();

    for key in all_keys {
        let base_content = base_map.get(key).copied().unwrap_or("");
        let ours_content = ours_map.get(key).copied().unwrap_or("");
        let theirs_content = theirs_map.get(key).copied().unwrap_or("");

        // If all same, no merge needed
        if ours_content == theirs_content {
            merged.insert(key.to_string(), ours_content.to_string());
        } else if base_content == ours_content {
            merged.insert(key.to_string(), theirs_content.to_string());
        } else if base_content == theirs_content {
            merged.insert(key.to_string(), ours_content.to_string());
        } else {
            // Both changed — check whitespace-only first
            if is_whitespace_only_diff(base_content, ours_content)
                && is_whitespace_only_diff(base_content, theirs_content)
            {
                // Both sides only changed whitespace, take theirs (arbitrary)
                merged.insert(key.to_string(), theirs_content.to_string());
            } else if is_whitespace_only_diff(base_content, ours_content) {
                // Ours is whitespace-only, theirs has real changes
                merged.insert(key.to_string(), theirs_content.to_string());
            } else if is_whitespace_only_diff(base_content, theirs_content) {
                // Theirs is whitespace-only, ours has real changes
                merged.insert(key.to_string(), ours_content.to_string());
            } else if is_import_region(base_content)
                || is_import_region(ours_content)
                || is_import_region(theirs_content)
            {
                // Commutative merge: treat import lines as a set
                let result = merge_imports_commutatively(base_content, ours_content, theirs_content);
                merged.insert(key.to_string(), result);
            } else {
                // Regular line-level merge
                match diffy::merge(base_content, ours_content, theirs_content) {
                    Ok(m) => {
                        merged.insert(key.to_string(), m);
                    }
                    Err(_conflicted) => {
                        // Create a proper conflict instead of silently embedding
                        // raw conflict markers into the output.
                        let complexity = classify_conflict(
                            Some(base_content),
                            Some(ours_content),
                            Some(theirs_content),
                        );
                        let conflict = EntityConflict {
                            entity_name: key.to_string(),
                            entity_type: "interstitial".to_string(),
                            kind: ConflictKind::BothModified,
                            complexity,
                            ours_content: Some(ours_content.to_string()),
                            theirs_content: Some(theirs_content.to_string()),
                            base_content: Some(base_content.to_string()),
                        };
                        merged.insert(key.to_string(), conflict.to_conflict_markers(marker_format));
                        interstitial_conflicts.push(conflict);
                    }
                }
            }
        }
    }

    (merged, interstitial_conflicts)
}

/// Check if a region is predominantly import/use statements.
/// Handles both single-line imports and multi-line import blocks
/// (e.g. `import { type a, type b } from "..."` spread across lines).
fn is_import_region(content: &str) -> bool {
    let lines: Vec<&str> = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .collect();
    if lines.is_empty() {
        return false;
    }
    let mut import_count = 0;
    let mut in_multiline_import = false;
    for line in &lines {
        if in_multiline_import {
            import_count += 1;
            let trimmed = line.trim();
            if trimmed.starts_with('}') || trimmed.ends_with(')') {
                in_multiline_import = false;
            }
        } else if is_import_line(line) {
            import_count += 1;
            let trimmed = line.trim();
            // Detect start of multi-line import: `import {` or `import (` without closing on same line
            if (trimmed.contains('{') && !trimmed.contains('}'))
                || (trimmed.starts_with("import (") && !trimmed.contains(')'))
                || (trimmed.starts_with("from ") && trimmed.contains("import (") && !trimmed.contains(')'))
            {
                in_multiline_import = true;
            }
        }
    }
    // If >50% of non-empty lines are imports, treat as import region
    import_count * 2 > lines.len()
}

/// Post-merge cleanup: remove consecutive duplicate lines and normalize blank lines.
///
/// Fixes two classes of merge artifacts:
/// 1. Duplicate lines/blocks that appear when both sides add the same content
///    (e.g. duplicate typedefs, forward declarations)
/// 2. Missing blank lines between entities or declarations, and excessive
///    blank lines (3+ consecutive) collapsed to 2
fn post_merge_cleanup(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut result: Vec<&str> = Vec::with_capacity(lines.len());

    // Pass 1: Remove consecutive duplicate lines that look like declarations or imports.
    // Only dedup lines that are plausibly merge artifacts (imports, exports, forward decls).
    // Preserve intentional duplicates like repeated assertions, assignments, or data lines.
    for line in &lines {
        if line.trim().is_empty() {
            result.push(line);
            continue;
        }
        if let Some(prev) = result.last() {
            if !prev.trim().is_empty() && *prev == *line && looks_like_declaration(line) {
                continue; // skip consecutive exact duplicate of declaration-like line
            }
        }
        result.push(line);
    }

    // Pass 2: Collapse 3+ consecutive blank lines to 2 (one separator blank line).
    let mut final_lines: Vec<&str> = Vec::with_capacity(result.len());
    let mut consecutive_blanks = 0;
    for line in &result {
        if line.trim().is_empty() {
            consecutive_blanks += 1;
            if consecutive_blanks <= 2 {
                final_lines.push(line);
            }
        } else {
            consecutive_blanks = 0;
            final_lines.push(line);
        }
    }

    let mut out = final_lines.join("\n");
    if content.ends_with('\n') && !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// Check if a line looks like a declaration/import that merge might duplicate.
/// Returns false for lines that could be intentionally repeated (assertions,
/// assignments, data initializers, struct fields, etc.).
fn looks_like_declaration(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with("import ")
        || trimmed.starts_with("from ")
        || trimmed.starts_with("use ")
        || trimmed.starts_with("export ")
        || trimmed.starts_with("require(")
        || trimmed.starts_with("#include")
        || trimmed.starts_with("typedef ")
        || trimmed.starts_with("using ")
        || (trimmed.starts_with("pub ") && trimmed.contains("mod "))
}

/// Check if a line is a top-level import/use/require statement.
///
/// Only matches unindented lines to avoid picking up conditional imports
/// inside `if TYPE_CHECKING:` blocks or similar constructs.
fn is_import_line(line: &str) -> bool {
    // Skip indented lines: these are inside conditional blocks (TYPE_CHECKING, etc.)
    if line.starts_with(' ') || line.starts_with('\t') {
        return false;
    }
    let trimmed = line.trim();
    trimmed.starts_with("import ")
        || trimmed.starts_with("from ")
        || trimmed.starts_with("use ")
        || trimmed.starts_with("require(")
        || trimmed.starts_with("const ") && trimmed.contains("require(")
        || trimmed.starts_with("package ")
        || trimmed.starts_with("#include ")
        || trimmed.starts_with("using ")
}

/// Like is_import_line but operates on already-trimmed strings.
/// Used in the line-level safety net where we compare trimmed lines.
fn is_import_line_trimmed(trimmed: &str) -> bool {
    trimmed.starts_with("import ")
        || trimmed.starts_with("from ")
        || trimmed.starts_with("use ")
        || trimmed.starts_with("require(")
        || trimmed.starts_with("const ") && trimmed.contains("require(")
        || trimmed.starts_with("package ")
        || trimmed.starts_with("#include ")
        || trimmed.starts_with("using ")
}

/// A complete import statement (possibly multi-line) as a single unit.
#[derive(Debug, Clone)]
struct ImportStatement {
    /// The full text of the import (may span multiple lines)
    lines: Vec<String>,
    /// The source module (e.g. "./foo", "react", "std::io")
    source: String,
    /// For multi-line imports: the individual specifiers (e.g. ["type a", "type b"])
    specifiers: Vec<String>,
    /// Whether this is a multi-line import block
    is_multiline: bool,
}

/// Extract specifiers from a single-line import statement.
/// e.g. "from X import A, B, C" → ["A", "B", "C"]
///      "import { A, B } from 'X'" → ["A", "B"]
///      "import X from 'Y'" → [] (default import, no named specifiers)
fn parse_single_line_specifiers(trimmed: &str) -> Vec<String> {
    // Python: "from X import A, B, C"
    if let Some(import_pos) = trimmed.find(" import ") {
        let after_import = &trimmed[import_pos + 8..];
        // Skip if it's "import *" or "import (..." (multi-line handled elsewhere)
        if after_import.starts_with('*') || after_import.starts_with('(') {
            return Vec::new();
        }
        return after_import
            .split(',')
            .map(|s| s.trim().trim_end_matches(';').to_string())
            .filter(|s| !s.is_empty())
            .collect();
    }
    // JS/TS: "import { A, B } from 'X'"
    if trimmed.starts_with("import ") {
        if let Some(brace_start) = trimmed.find('{') {
            if let Some(brace_end) = trimmed.find('}') {
                let inner = &trimmed[brace_start + 1..brace_end];
                return inner
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
            }
        }
    }
    Vec::new()
}

/// Parse content into import statements, handling multi-line imports as single units.
fn parse_import_statements(content: &str) -> (Vec<ImportStatement>, Vec<String>) {
    let mut imports: Vec<ImportStatement> = Vec::new();
    let mut non_import_lines: Vec<String> = Vec::new();
    let lines: Vec<&str> = content.lines().collect();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i];

        if line.trim().is_empty() {
            non_import_lines.push(line.to_string());
            i += 1;
            continue;
        }

        if is_import_line(line) {
            let trimmed = line.trim();
            // Check for multi-line import: `import {` without `}` on same line
            let starts_multiline = (trimmed.contains('{') && !trimmed.contains('}'))
                || (trimmed.starts_with("import (") && !trimmed.contains(')'))
                || (trimmed.starts_with("from ") && trimmed.contains("import (") && !trimmed.contains(')'));

            if starts_multiline {
                let mut block_lines = vec![line.to_string()];
                let mut specifiers = Vec::new();
                let close_char = if trimmed.contains('{') { '}' } else { ')' };
                i += 1;

                // Collect lines until closing brace/paren
                while i < lines.len() {
                    let inner = lines[i];
                    block_lines.push(inner.to_string());
                    let inner_trimmed = inner.trim();

                    if inner_trimmed.starts_with(close_char) {
                        // This is the closing line (e.g. `} from "./foo"`)
                        break;
                    } else if !inner_trimmed.is_empty() {
                        // This is a specifier line — strip trailing comma
                        let spec = inner_trimmed.trim_end_matches(',').trim().to_string();
                        if !spec.is_empty() {
                            specifiers.push(spec);
                        }
                    }
                    i += 1;
                }

                let full_text = block_lines.join("\n");
                let source = import_source_prefix(&full_text).to_string();
                imports.push(ImportStatement {
                    lines: block_lines,
                    source,
                    specifiers,
                    is_multiline: true,
                });
            } else {
                // Single-line import — also parse specifiers for set-based merging
                let source = import_source_prefix(line).to_string();
                let specifiers = parse_single_line_specifiers(trimmed);
                imports.push(ImportStatement {
                    lines: vec![line.to_string()],
                    source,
                    specifiers,
                    is_multiline: false,
                });
            }
        } else {
            non_import_lines.push(line.to_string());
        }
        i += 1;
    }

    (imports, non_import_lines)
}

/// Merge import blocks commutatively (as unordered sets), preserving grouping.
///
/// Handles both single-line imports and multi-line import blocks.
/// For multi-line imports from the same source, merges specifiers as a set.
/// Single-line imports are merged as before: set union with deletions.
fn merge_imports_commutatively(base: &str, ours: &str, theirs: &str) -> String {
    let (base_imports, _) = parse_import_statements(base);
    let (ours_imports, _) = parse_import_statements(ours);
    let (theirs_imports, _) = parse_import_statements(theirs);

    let has_multiline = base_imports.iter().any(|i| i.is_multiline)
        || ours_imports.iter().any(|i| i.is_multiline)
        || theirs_imports.iter().any(|i| i.is_multiline);

    if has_multiline {
        return merge_imports_with_multiline(base, ours, theirs,
            &base_imports, &ours_imports, &theirs_imports);
    }

    // Original single-line-only logic
    let base_lines: HashSet<&str> = base.lines().filter(|l| is_import_line(l)).collect();
    let ours_lines: HashSet<&str> = ours.lines().filter(|l| is_import_line(l)).collect();

    let theirs_deleted: HashSet<&str> = base_lines.difference(
        &theirs.lines().filter(|l| is_import_line(l)).collect::<HashSet<&str>>()
    ).copied().collect();

    let theirs_added: Vec<&str> = theirs
        .lines()
        .filter(|l| is_import_line(l) && !base_lines.contains(l) && !ours_lines.contains(l))
        .collect();

    // Build import groups from ours (import lines only)
    let mut groups: Vec<Vec<&str>> = Vec::new();
    let mut current_group: Vec<&str> = Vec::new();

    for line in ours.lines() {
        if line.trim().is_empty() {
            if !current_group.is_empty() {
                groups.push(current_group);
                current_group = Vec::new();
            }
        } else if is_import_line(line) {
            if theirs_deleted.contains(line) {
                continue;
            }
            current_group.push(line);
        }
    }
    if !current_group.is_empty() {
        groups.push(current_group);
    }

    for add in &theirs_added {
        let prefix = import_source_prefix(add);
        let mut best_group = if groups.is_empty() { 0 } else { groups.len() - 1 };
        for (i, group) in groups.iter().enumerate() {
            if group.iter().any(|l| {
                is_import_line(l) && import_source_prefix(l) == prefix
            }) {
                best_group = i;
                break;
            }
        }
        if best_group < groups.len() {
            groups[best_group].push(add);
        } else {
            groups.push(vec![add]);
        }
    }

    // Sort import lines within each group alphabetically
    for group in &mut groups {
        group.sort_unstable();
    }

    let mut import_lines: Vec<&str> = Vec::new();
    for (i, group) in groups.iter().enumerate() {
        if i > 0 {
            import_lines.push("");
        }
        import_lines.extend(group);
    }

    let mut result = import_lines.join("\n");

    // Non-import lines: use diffy 3-way merge so adds/deletes/edits on
    // either side are handled correctly (fixes #60).
    let extract_non_imports = |content: &str| -> String {
        content
            .lines()
            .filter(|l| !l.trim().is_empty() && !is_import_line(l))
            .collect::<Vec<_>>()
            .join("\n")
    };
    let base_ni = extract_non_imports(base);
    let ours_ni = extract_non_imports(ours);
    let theirs_ni = extract_non_imports(theirs);

    if !base_ni.is_empty() || !ours_ni.is_empty() || !theirs_ni.is_empty() {
        let merged_ni = match diffy::merge(&base_ni, &ours_ni, &theirs_ni) {
            Ok(m) => m,
            Err(conflicted) => conflicted,
        };
        if !merged_ni.trim().is_empty() {
            result.push('\n');
            result.push('\n');
            result.push_str(&merged_ni);
        }
    }
    let ours_trailing = ours.len() - ours.trim_end_matches('\n').len();
    let result_trailing = result.len() - result.trim_end_matches('\n').len();
    for _ in result_trailing..ours_trailing {
        result.push('\n');
    }
    result
}

/// Merge imports when multi-line import blocks are involved.
/// Matches imports by source module, merges specifiers as a set.
fn merge_imports_with_multiline(
    _base_raw: &str,
    ours_raw: &str,
    _theirs_raw: &str,
    base_imports: &[ImportStatement],
    ours_imports: &[ImportStatement],
    theirs_imports: &[ImportStatement],
) -> String {
    // Build source → specifier sets for base and theirs
    let base_specs: HashMap<&str, HashSet<&str>> = base_imports.iter().map(|imp| {
        let specs: HashSet<&str> = imp.specifiers.iter().map(|s| s.as_str()).collect();
        (imp.source.as_str(), specs)
    }).collect();

    let theirs_specs: HashMap<&str, HashSet<&str>> = theirs_imports.iter().map(|imp| {
        let specs: HashSet<&str> = imp.specifiers.iter().map(|s| s.as_str()).collect();
        (imp.source.as_str(), specs)
    }).collect();

    // Single-line import tracking: base lines and theirs-deleted
    let base_single: HashSet<String> = base_imports.iter()
        .filter(|i| !i.is_multiline)
        .map(|i| i.lines[0].clone())
        .collect();
    let theirs_single: HashSet<String> = theirs_imports.iter()
        .filter(|i| !i.is_multiline)
        .map(|i| i.lines[0].clone())
        .collect();
    let theirs_deleted_single: HashSet<&str> = base_single.iter()
        .filter(|l| !theirs_single.contains(l.as_str()))
        .map(|l| l.as_str())
        .collect();

    // Process ours imports, merging in theirs specifiers
    let mut result_parts: Vec<String> = Vec::new();
    let mut handled_theirs_sources: HashSet<&str> = HashSet::new();

    // Walk through ours_raw to preserve formatting (blank lines, comments)
    let lines: Vec<&str> = ours_raw.lines().collect();
    let mut i = 0;
    let mut ours_imp_idx = 0;

    while i < lines.len() {
        let line = lines[i];

        if line.trim().is_empty() {
            result_parts.push(line.to_string());
            i += 1;
            continue;
        }

        if is_import_line(line) {
            let trimmed = line.trim();
            let starts_multiline = (trimmed.contains('{') && !trimmed.contains('}'))
                || (trimmed.starts_with("import (") && !trimmed.contains(')'))
                || (trimmed.starts_with("from ") && trimmed.contains("import (") && !trimmed.contains(')'));

            if starts_multiline && ours_imp_idx < ours_imports.len() {
                let imp = &ours_imports[ours_imp_idx];
                // Find the matching import by source
                let source = imp.source.as_str();
                handled_theirs_sources.insert(source);

                // Merge specifiers: ours + theirs additions - theirs deletions
                let base_spec_set = base_specs.get(source).cloned().unwrap_or_default();
                let theirs_spec_set = theirs_specs.get(source).cloned().unwrap_or_default();
                // Added by theirs: in theirs but not in base
                let theirs_added: HashSet<&str> = theirs_spec_set.difference(&base_spec_set).copied().collect();
                // Deleted by theirs: in base but not in theirs
                let theirs_removed: HashSet<&str> = base_spec_set.difference(&theirs_spec_set).copied().collect();

                // Final set: ours (in original order) + theirs_added - theirs_removed
                let mut final_specs: Vec<&str> = imp.specifiers.iter()
                    .map(|s| s.as_str())
                    .filter(|s| !theirs_removed.contains(s))
                    .collect();
                for added in &theirs_added {
                    if !final_specs.contains(added) {
                        final_specs.push(added);
                    }
                }

                // Detect indentation from the original block
                let indent = if imp.lines.len() > 1 {
                    let second = &imp.lines[1];
                    &second[..second.len() - second.trim_start().len()]
                } else {
                    "     "
                };

                // Reconstruct multi-line import
                result_parts.push(imp.lines[0].clone()); // `import {`
                for spec in &final_specs {
                    result_parts.push(format!("{}{},", indent, spec));
                }
                // Closing line from ours
                if let Some(last) = imp.lines.last() {
                    result_parts.push(last.clone());
                }

                // Skip past the original multi-line block in ours_raw
                let close_char = if trimmed.contains('{') { '}' } else { ')' };
                i += 1;
                while i < lines.len() {
                    if lines[i].trim().starts_with(close_char) {
                        i += 1;
                        break;
                    }
                    i += 1;
                }
                ours_imp_idx += 1;
                continue;
            } else {
                // Single-line import
                if ours_imp_idx < ours_imports.len() {
                    let imp = &ours_imports[ours_imp_idx];
                    let source = imp.source.as_str();
                    handled_theirs_sources.insert(source);
                    ours_imp_idx += 1;

                    // Check if theirs has a multi-line version with more specifiers
                    if let Some(theirs_spec_set) = theirs_specs.get(source) {
                        let base_spec_set = base_specs.get(source).cloned().unwrap_or_default();
                        let theirs_added: HashSet<&str> = theirs_spec_set.difference(&base_spec_set).copied().collect();

                        if !theirs_added.is_empty() {
                            // Parse ours single-line specifier from the line text
                            let mut ours_specifiers: Vec<&str> = Vec::new();
                            let trimmed_line = line.trim();
                            // Python: "from X import Y, Z" → extract after "import "
                            if let Some(import_pos) = trimmed_line.find(" import ") {
                                let after_import = &trimmed_line[import_pos + 8..];
                                for spec in after_import.split(',') {
                                    let s = spec.trim().trim_end_matches(';');
                                    if !s.is_empty() {
                                        ours_specifiers.push(s);
                                    }
                                }
                            }
                            // JS/TS: "import X from 'Y'" → X is a default import, not a specifier
                            // Only merge if we found named specifiers
                            if !ours_specifiers.is_empty() {
                                let mut final_specs: Vec<&str> = ours_specifiers.clone();
                                for added in &theirs_added {
                                    if !final_specs.contains(added) {
                                        final_specs.push(added);
                                    }
                                }
                                // Find theirs import to get formatting
                                if let Some(theirs_imp) = theirs_imports.iter().find(|ti| ti.source == source) {
                                    if theirs_imp.is_multiline {
                                        // Use theirs's multi-line formatting
                                        let indent = if theirs_imp.lines.len() > 1 {
                                            let second = &theirs_imp.lines[1];
                                            &second[..second.len() - second.trim_start().len()]
                                        } else {
                                            "    "
                                        };
                                        // Reconstruct as multi-line using theirs's opening/closing style
                                        result_parts.push(theirs_imp.lines[0].clone());
                                        for spec in &final_specs {
                                            result_parts.push(format!("{}{},", indent, spec));
                                        }
                                        if let Some(last) = theirs_imp.lines.last() {
                                            result_parts.push(last.clone());
                                        }
                                        i += 1;
                                        continue;
                                    }
                                }
                                // Theirs not multi-line but has more specifiers: reconstruct single-line
                                // e.g. "from X import A, B, C"
                                let prefix = &trimmed_line[..trimmed_line.find(" import ").unwrap() + 8];
                                result_parts.push(format!("{}{}", prefix, final_specs.join(", ")));
                                i += 1;
                                continue;
                            }
                        }
                    }
                } else {
                    // No more ours imports to match
                }
                // Check if theirs deleted this single-line import
                if !theirs_deleted_single.contains(line) {
                    result_parts.push(line.to_string());
                }
            }
        } else {
            result_parts.push(line.to_string());
        }
        i += 1;
    }

    // Add any new imports from theirs that have new sources
    for imp in theirs_imports {
        if handled_theirs_sources.contains(imp.source.as_str()) {
            continue;
        }
        // Truly new import from theirs (source wasn't handled in the main loop)
        for line in &imp.lines {
            result_parts.push(line.clone());
        }
    }

    let mut result = result_parts.join("\n");

    // Non-import lines: use diffy 3-way merge so adds/deletes/edits on
    // either side are handled correctly (fixes #60).
    let extract_non_imports = |content: &str| -> String {
        content
            .lines()
            .filter(|l| !l.trim().is_empty() && !is_import_line(l))
            .filter(|l| {
                let t = l.trim();
                // Exclude multi-line import continuation lines (specifiers, closing parens/braces)
                !(t.ends_with(',') && !t.contains('='))
                    && t != ")"
                    && t != "}"
            })
            .collect::<Vec<_>>()
            .join("\n")
    };
    let base_ni = extract_non_imports(_base_raw);
    let ours_ni = extract_non_imports(ours_raw);
    let theirs_ni = extract_non_imports(_theirs_raw);

    if !base_ni.is_empty() || !ours_ni.is_empty() || !theirs_ni.is_empty() {
        let merged_ni = match diffy::merge(&base_ni, &ours_ni, &theirs_ni) {
            Ok(m) => m,
            Err(conflicted) => conflicted,
        };
        if !merged_ni.trim().is_empty() {
            result.push('\n');
            result.push('\n');
            result.push_str(&merged_ni);
        }
    }

    let ours_trailing = ours_raw.len() - ours_raw.trim_end_matches('\n').len();
    let result_trailing = result.len() - result.trim_end_matches('\n').len();
    for _ in result_trailing..ours_trailing {
        result.push('\n');
    }
    result
}

/// Extract the source/module prefix from an import line for group matching.
/// e.g. "from collections import OrderedDict" -> "collections"
///      "import React from 'react'" -> "react"
///      "use std::collections::HashMap;" -> "std::collections"
fn import_source_prefix(line: &str) -> &str {
    // For multi-line imports, search all lines for the source module
    // (e.g. `} from "./foo"` on the closing line)
    for l in line.lines() {
        let trimmed = l.trim();
        // Python: "from X import Y" -> X
        if let Some(rest) = trimmed.strip_prefix("from ") {
            return rest.split_whitespace().next().unwrap_or("");
        }
        // JS/TS closing line: `} from 'Y'` or `} from "Y"`
        if trimmed.starts_with('}') && trimmed.contains("from ") {
            if let Some(quote_start) = trimmed.find(|c: char| c == '\'' || c == '"') {
                let after = &trimmed[quote_start + 1..];
                if let Some(quote_end) = after.find(|c: char| c == '\'' || c == '"') {
                    return &after[..quote_end];
                }
            }
        }
        // JS/TS: "import X from 'Y'" -> Y (between quotes)
        if trimmed.starts_with("import ") {
            if let Some(quote_start) = trimmed.find(|c: char| c == '\'' || c == '"') {
                let after = &trimmed[quote_start + 1..];
                if let Some(quote_end) = after.find(|c: char| c == '\'' || c == '"') {
                    return &after[..quote_end];
                }
            }
        }
        // Rust: "use X::Y;" -> X
        if let Some(rest) = trimmed.strip_prefix("use ") {
            return rest.split("::").next().unwrap_or("").trim_end_matches(';');
        }
    }
    line.trim()
}

/// Fallback to line-level 3-way merge when entity extraction isn't possible.
///
/// Uses Sesame-inspired separator preprocessing (arXiv:2407.18888) to get
/// finer-grained alignment before line-level merge. Inserts newlines around
/// syntactic separators ({, }, ;) so that changes in different code blocks
/// align independently, reducing spurious conflicts.
///
/// Sesame expansion is skipped for data formats (JSON, YAML, TOML, lock files)
/// where `{`, `}`, `;` are structural content rather than code separators.
/// Expanding them destroys alignment and produces far more conflicts (confirmed
/// on GitButler: YAML went from 68 git markers to 192 weave markers with Sesame).
fn line_level_fallback(base: &str, ours: &str, theirs: &str, file_path: &str) -> MergeResult {
    let mut stats = MergeStats::default();
    stats.used_fallback = true;

    // Skip Sesame preprocessing for data formats where {/}/; are content, not separators
    let skip = skip_sesame(file_path);

    if skip {
        // Use git merge-file for data formats so we match git's output exactly.
        // diffy::merge uses a different diff algorithm that can produce more
        // conflict markers on structured data like lock files.
        return git_merge_file(base, ours, theirs, &mut stats);
    }

    // Try Sesame expansion + diffy first, then compare against git merge-file.
    // Use whichever produces fewer conflict markers so we're never worse than git.
    let base_expanded = expand_separators(base);
    let ours_expanded = expand_separators(ours);
    let theirs_expanded = expand_separators(theirs);

    let sesame_result = match diffy::merge(&base_expanded, &ours_expanded, &theirs_expanded) {
        Ok(merged) => {
            let content = collapse_separators(&merged, base);
            Some(MergeResult {
                content: post_merge_cleanup(&content),
                conflicts: vec![],
                warnings: vec![],
                stats: stats.clone(),
                audit: vec![],
            })
        }
        Err(_) => {
            // Sesame expansion conflicted, try plain diffy
            match diffy::merge(base, ours, theirs) {
                Ok(merged) => Some(MergeResult {
                    content: merged,
                    conflicts: vec![],
                    warnings: vec![],
                    stats: stats.clone(),
                    audit: vec![],
                }),
                Err(conflicted) => {
                    let _markers = conflicted.lines().filter(|l| l.starts_with("<<<<<<<")).count();
                    let mut s = stats.clone();
                    s.entities_conflicted = 1;
                    Some(MergeResult {
                        content: conflicted,
                        conflicts: vec![EntityConflict {
                            entity_name: "(file)".to_string(),
                            entity_type: "file".to_string(),
                            kind: ConflictKind::BothModified,
                            complexity: classify_conflict(Some(base), Some(ours), Some(theirs)),
                            ours_content: Some(ours.to_string()),
                            theirs_content: Some(theirs.to_string()),
                            base_content: Some(base.to_string()),
                        }],
                        warnings: vec![],
                        stats: s,
                        audit: vec![],
                    })
                }
            }
        }
    };

    // Get git merge-file result as our floor
    let git_result = git_merge_file(base, ours, theirs, &mut stats);

    // Compare: use sesame result only if it has fewer or equal markers
    match sesame_result {
        Some(sesame) if sesame.conflicts.is_empty() && !git_result.conflicts.is_empty() => {
            // Sesame resolved cleanly, git didn't: use sesame
            sesame
        }
        Some(sesame) if !sesame.conflicts.is_empty() && !git_result.conflicts.is_empty() => {
            // Both conflicted: use whichever has fewer markers
            let sesame_markers = sesame.content.lines().filter(|l| l.starts_with("<<<<<<<")).count();
            let git_markers = git_result.content.lines().filter(|l| l.starts_with("<<<<<<<")).count();
            if sesame_markers <= git_markers { sesame } else { git_result }
        }
        _ => git_result,
    }
}

/// Shell out to `git merge-file` for an exact match with git's line-level merge.
///
/// We use this instead of `diffy::merge` for data formats (lock files, JSON, YAML, TOML)
/// where weave can't improve on git. `diffy` uses a different diff algorithm that can
/// produce more conflict markers on structured data (e.g. 22 markers vs git's 19 on uv.lock).
fn git_merge_file(base: &str, ours: &str, theirs: &str, stats: &mut MergeStats) -> MergeResult {
    let dir = match tempfile::tempdir() {
        Ok(d) => d,
        Err(_) => return diffy_fallback(base, ours, theirs, stats),
    };

    let base_path = dir.path().join("base");
    let ours_path = dir.path().join("ours");
    let theirs_path = dir.path().join("theirs");

    let write_ok = (|| -> std::io::Result<()> {
        std::fs::File::create(&base_path)?.write_all(base.as_bytes())?;
        std::fs::File::create(&ours_path)?.write_all(ours.as_bytes())?;
        std::fs::File::create(&theirs_path)?.write_all(theirs.as_bytes())?;
        Ok(())
    })();

    if write_ok.is_err() {
        return diffy_fallback(base, ours, theirs, stats);
    }

    // git merge-file writes result to the first file (ours) in place
    let output = Command::new("git")
        .arg("merge-file")
        .arg("-p") // print to stdout instead of modifying ours in place
        .arg("--diff3") // include ||||||| base section for jj compatibility
        .arg("-L").arg("ours")
        .arg("-L").arg("base")
        .arg("-L").arg("theirs")
        .arg(&ours_path)
        .arg(&base_path)
        .arg(&theirs_path)
        .output();

    match output {
        Ok(result) => {
            let content = String::from_utf8_lossy(&result.stdout).into_owned();
            if result.status.success() {
                // Exit 0 = clean merge
                MergeResult {
                    content: post_merge_cleanup(&content),
                    conflicts: vec![],
                    warnings: vec![],
                    stats: stats.clone(),
                    audit: vec![],
                }
            } else {
                // Exit >0 = conflicts (exit code = number of conflicts)
                stats.entities_conflicted = 1;
                MergeResult {
                    content,
                    conflicts: vec![EntityConflict {
                        entity_name: "(file)".to_string(),
                        entity_type: "file".to_string(),
                        kind: ConflictKind::BothModified,
                        complexity: classify_conflict(Some(base), Some(ours), Some(theirs)),
                        ours_content: Some(ours.to_string()),
                        theirs_content: Some(theirs.to_string()),
                        base_content: Some(base.to_string()),
                    }],
                    warnings: vec![],
                    stats: stats.clone(),
                    audit: vec![],
                }
            }
        }
        // git not available, fall back to diffy
        Err(_) => diffy_fallback(base, ours, theirs, stats),
    }
}

/// Fallback to diffy::merge when git merge-file is unavailable.
fn diffy_fallback(base: &str, ours: &str, theirs: &str, stats: &mut MergeStats) -> MergeResult {
    match diffy::merge(base, ours, theirs) {
        Ok(merged) => {
            let content = post_merge_cleanup(&merged);
            MergeResult {
                content,
                conflicts: vec![],
                warnings: vec![],
                stats: stats.clone(),
                audit: vec![],
            }
        }
        Err(conflicted) => {
            stats.entities_conflicted = 1;
            MergeResult {
                content: conflicted,
                conflicts: vec![EntityConflict {
                    entity_name: "(file)".to_string(),
                    entity_type: "file".to_string(),
                    kind: ConflictKind::BothModified,
                    complexity: classify_conflict(Some(base), Some(ours), Some(theirs)),
                    ours_content: Some(ours.to_string()),
                    theirs_content: Some(theirs.to_string()),
                    base_content: Some(base.to_string()),
                }],
                warnings: vec![],
                stats: stats.clone(),
                audit: vec![],
            }
        }
    }
}

/// Filter out entities that are nested inside other entities.
///
/// When a class contains methods which contain local variables, sem-core may extract
/// all of them as entities. But for merge purposes, nested entities are part of their
/// parent — we handle them via inner entity merge. Keeping them causes false conflicts
/// (e.g. two methods both declaring `const user` would appear as BothAdded).
/// Check if entity list has too many duplicate names, which causes matching to hang.
fn has_excessive_duplicates(entities: &[SemanticEntity]) -> bool {
    let threshold = std::env::var("WEAVE_MAX_DUPLICATES")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(10);
    let mut counts: HashMap<&str, usize> = HashMap::new();
    for e in entities {
        *counts.entry(&e.name).or_default() += 1;
    }
    counts.values().any(|&c| c >= threshold)
}

/// Filter out entities that are nested inside other entities.
/// O(n log n) via sort + stack, replacing the previous O(n^2) approach.
fn filter_nested_entities(mut entities: Vec<SemanticEntity>) -> Vec<SemanticEntity> {
    if entities.len() <= 1 {
        return entities;
    }

    // Sort by start_line ASC, then by end_line DESC (widest span first).
    // A parent entity always appears before its children in this order.
    entities.sort_by(|a, b| {
        a.start_line.cmp(&b.start_line).then(b.end_line.cmp(&a.end_line))
    });

    // Stack-based filter: track the end_line of the current outermost entity.
    let mut result: Vec<SemanticEntity> = Vec::with_capacity(entities.len());
    let mut max_end: usize = 0;

    for entity in entities {
        if entity.start_line > max_end || max_end == 0 {
            // Not nested: new top-level entity
            max_end = entity.end_line;
            result.push(entity);
        } else if entity.start_line == result.last().map_or(0, |e| e.start_line)
            && entity.end_line == result.last().map_or(0, |e| e.end_line)
        {
            // Exact same span (e.g. decorated_definition wrapping function_definition)
            result.push(entity);
        }
        // else: strictly nested, skip
    }

    result
}

/// Get child entities of a parent, sorted by start line.
fn get_child_entities<'a>(
    parent: &SemanticEntity,
    all_entities: &'a [SemanticEntity],
) -> Vec<&'a SemanticEntity> {
    let mut children: Vec<&SemanticEntity> = all_entities
        .iter()
        .filter(|e| e.parent_id.as_deref() == Some(&parent.id))
        .collect();
    children.sort_by_key(|e| e.start_line);
    children
}

/// Compute a body hash for rename detection: the entity content with the entity
/// name replaced at word boundaries by a placeholder, so entities with identical
/// bodies but different names produce the same hash.
///
/// Compute Jaccard similarity on whitespace-split tokens of two strings.
/// Returns a value in [0.0, 1.0] where 1.0 means identical token sets.
fn token_jaccard(a: &str, b: &str) -> f64 {
    let tokens_a: HashSet<&str> = a.split_whitespace().collect();
    let tokens_b: HashSet<&str> = b.split_whitespace().collect();
    if tokens_a.is_empty() && tokens_b.is_empty() {
        return 1.0;
    }
    let intersection = tokens_a.intersection(&tokens_b).count();
    let union = tokens_a.union(&tokens_b).count();
    if union == 0 { 1.0 } else { intersection as f64 / union as f64 }
}

/// Uses word-boundary matching to avoid partial replacements (e.g. replacing
/// "get" inside "getAll"). Works across all languages since it operates on
/// the content string, not language-specific AST features.
fn body_hash(entity: &SemanticEntity) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let normalized = replace_at_word_boundaries(&entity.content, &entity.name, "__ENTITY__");
    let mut hasher = DefaultHasher::new();
    normalized.hash(&mut hasher);
    hasher.finish()
}

/// Replace `needle` with `replacement` only at word boundaries.
/// A word boundary means the character before/after the match is not
/// alphanumeric or underscore (i.e. not an identifier character).
fn replace_at_word_boundaries(content: &str, needle: &str, replacement: &str) -> String {
    if needle.is_empty() {
        return content.to_string();
    }
    let bytes = content.as_bytes();
    let mut result = String::with_capacity(content.len());
    let mut i = 0;
    while i < content.len() {
        if content.is_char_boundary(i) && content[i..].starts_with(needle) {
            let before_ok = i == 0 || {
                let prev_idx = content[..i]
                    .char_indices()
                    .next_back()
                    .map(|(idx, _)| idx)
                    .unwrap_or(0);
                !is_ident_char(bytes[prev_idx])
            };
            let after_idx = i + needle.len();
            let after_ok = after_idx >= content.len()
                || (content.is_char_boundary(after_idx)
                    && !is_ident_char(bytes[after_idx]));
            if before_ok && after_ok {
                result.push_str(replacement);
                i += needle.len();
                continue;
            }
        }
        if content.is_char_boundary(i) {
            let ch = content[i..].chars().next().unwrap();
            result.push(ch);
            i += ch.len_utf8();
        } else {
            i += 1;
        }
    }
    result
}

fn is_ident_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Build a rename map from new_id → base_id using confidence-scored matching.
///
/// Detects when an entity in the branch has the same body as an entity
/// in base but a different name/ID, indicating it was renamed.
/// Uses body_hash (name-stripped content hash) and structural_hash with
/// confidence scoring to resolve ambiguous matches correctly.
fn build_rename_map(
    base_entities: &[SemanticEntity],
    branch_entities: &[SemanticEntity],
) -> HashMap<String, String> {
    let mut rename_map: HashMap<String, String> = HashMap::new();

    let base_ids: HashSet<&str> = base_entities.iter().map(|e| e.id.as_str()).collect();

    // Build body_hash → base entities (multiple can have same hash)
    let mut base_by_body: HashMap<u64, Vec<&SemanticEntity>> = HashMap::new();
    for entity in base_entities {
        base_by_body.entry(body_hash(entity)).or_default().push(entity);
    }

    // Also keep structural_hash index as fallback
    let mut base_by_structural: HashMap<&str, Vec<&SemanticEntity>> = HashMap::new();
    for entity in base_entities {
        if let Some(ref sh) = entity.structural_hash {
            base_by_structural.entry(sh.as_str()).or_default().push(entity);
        }
    }

    // Collect all candidate (branch_entity, base_entity, confidence) triples
    struct RenameCandidate<'a> {
        branch: &'a SemanticEntity,
        base: &'a SemanticEntity,
        confidence: f64,
    }
    let mut candidates: Vec<RenameCandidate> = Vec::new();

    for branch_entity in branch_entities {
        if base_ids.contains(branch_entity.id.as_str()) {
            continue;
        }

        let bh = body_hash(branch_entity);

        // Body hash matches
        if let Some(base_entities_for_hash) = base_by_body.get(&bh) {
            for &base_entity in base_entities_for_hash {
                let same_type = base_entity.entity_type == branch_entity.entity_type;
                let same_parent = base_entity.parent_id == branch_entity.parent_id;
                let confidence = match (same_type, same_parent) {
                    (true, true) => 0.95,
                    (true, false) => 0.8,
                    (false, _) => 0.6,
                };
                candidates.push(RenameCandidate { branch: branch_entity, base: base_entity, confidence });
            }
        }

        // Structural hash fallback (lower confidence)
        if let Some(ref sh) = branch_entity.structural_hash {
            if let Some(base_entities_for_sh) = base_by_structural.get(sh.as_str()) {
                for &base_entity in base_entities_for_sh {
                    // Skip if already covered by body hash match
                    if candidates.iter().any(|c| c.branch.id == branch_entity.id && c.base.id == base_entity.id) {
                        continue;
                    }
                    candidates.push(RenameCandidate { branch: branch_entity, base: base_entity, confidence: 0.6 });
                }
            }
        }

        // Token similarity fallback: catches renames where internal references were also updated
        // (e.g. IDE "rename symbol" changes the name everywhere in the body).
        // Only check same-file, same-type entities not already matched above.
        let has_candidate = candidates.iter().any(|c| c.branch.id == branch_entity.id);
        if !has_candidate {
            for base_entity in base_entities {
                if base_entity.entity_type != branch_entity.entity_type {
                    continue;
                }
                if base_entity.file_path != branch_entity.file_path {
                    continue;
                }
                // Skip if base entity still exists in branch (not actually deleted/renamed)
                if branch_entities.iter().any(|e| e.id == base_entity.id) {
                    continue;
                }
                let similarity = token_jaccard(&base_entity.content, &branch_entity.content);
                if similarity >= 0.7 {
                    let same_parent = base_entity.parent_id == branch_entity.parent_id;
                    let confidence = if same_parent { 0.75 } else { 0.65 };
                    candidates.push(RenameCandidate { branch: branch_entity, base: base_entity, confidence });
                }
            }
        }
    }

    // Sort by confidence descending, assign greedily
    candidates.sort_by(|a, b| b.confidence.partial_cmp(&a.confidence).unwrap_or(std::cmp::Ordering::Equal));

    let mut used_base_ids: HashSet<String> = HashSet::new();
    let mut used_branch_ids: HashSet<String> = HashSet::new();

    for candidate in &candidates {
        if candidate.confidence < 0.6 {
            break;
        }
        if used_base_ids.contains(&candidate.base.id) || used_branch_ids.contains(&candidate.branch.id) {
            continue;
        }
        // Don't rename if the base entity's ID still exists in branch (it wasn't actually renamed)
        let base_id_in_branch = branch_entities.iter().any(|e| e.id == candidate.base.id);
        if base_id_in_branch {
            continue;
        }
        rename_map.insert(candidate.branch.id.clone(), candidate.base.id.clone());
        used_base_ids.insert(candidate.base.id.clone());
        used_branch_ids.insert(candidate.branch.id.clone());
    }

    rename_map
}

/// Check if an entity type is a container that may benefit from inner entity merge.
fn is_container_entity_type(entity_type: &str) -> bool {
    matches!(
        entity_type,
        "class" | "interface" | "enum" | "impl" | "trait" | "module" | "impl_item" | "trait_item"
            | "struct" | "union" | "namespace" | "struct_item" | "struct_specifier"
            | "variable" | "export"
    )
}

/// A named member chunk extracted from a class/container body.
#[derive(Debug, Clone)]
struct MemberChunk {
    /// The member name (method name, field name, etc.)
    name: String,
    /// Full content of the member including its body
    content: String,
}

/// Result of an inner entity merge attempt.
struct InnerMergeResult {
    /// Merged content (may contain per-member conflict markers)
    content: String,
    /// Whether any members had conflicts
    has_conflicts: bool,
}

/// Convert sem-core child entities to MemberChunks for inner merge.
///
/// Uses child entity line positions to extract content from the container text,
/// including any leading decorators/annotations that tree-sitter attaches as
/// sibling nodes rather than part of the method node.
fn children_to_chunks(
    children: &[&SemanticEntity],
    container_content: &str,
    container_start_line: usize,
) -> Vec<MemberChunk> {
    if children.is_empty() {
        return Vec::new();
    }

    let lines: Vec<&str> = container_content.lines().collect();
    let mut chunks = Vec::new();

    for (i, child) in children.iter().enumerate() {
        let child_start_idx = child.start_line.saturating_sub(container_start_line);
        // +1 because end_line is inclusive but we need an exclusive upper bound for slicing
        let child_end_idx = child.end_line.saturating_sub(container_start_line) + 1;

        if child_end_idx > lines.len() + 1 || child_start_idx >= lines.len() {
            // Position out of range, fall back to entity content
            chunks.push(MemberChunk {
                name: child.name.clone(),
                content: child.content.clone(),
            });
            continue;
        }
        let child_end_idx = child_end_idx.min(lines.len());

        // Determine the earliest line we can claim (after previous child's end, or body start)
        let floor = if i > 0 {
            children[i - 1].end_line.saturating_sub(container_start_line) + 1
        } else {
            // First child: start after the container header line (the `{` or `:` line)
            // For Python-style containers, find the declaration line ending with `:`
            // For brace-delimited, find the opening `{` on a declaration line
            let header_end = if is_python_style_container(&lines) {
                lines
                    .iter()
                    .position(|l| {
                        let t = l.trim();
                        (t.starts_with("class ") || t.starts_with("def ") || t.starts_with("async def "))
                            && t.ends_with(':')
                    })
                    .map(|p| p + 1)
                    .unwrap_or(0)
            } else {
                lines
                    .iter()
                    .position(|l| l.contains('{'))
                    .map(|p| p + 1)
                    .unwrap_or(0)
            };
            header_end
        };

        // Scan backwards from child_start_idx to include decorators/annotations/comments
        let mut content_start = child_start_idx;
        while content_start > floor {
            let prev = content_start - 1;
            let trimmed = lines[prev].trim();
            if trimmed.starts_with('@')
                || trimmed.starts_with("#[")
                || trimmed.starts_with("//")
                || trimmed.starts_with("///")
                || trimmed.starts_with("/**")
                || trimmed.starts_with("* ")
                || trimmed == "*/"
            {
                content_start = prev;
            } else if trimmed.is_empty() && content_start > floor + 1 {
                // Allow one blank line between decorator and method
                content_start = prev;
            } else {
                break;
            }
        }

        // Skip leading blank lines
        while content_start < child_start_idx && lines[content_start].trim().is_empty() {
            content_start += 1;
        }

        let chunk_content: String = lines[content_start..child_end_idx].join("\n");
        chunks.push(MemberChunk {
            name: child.name.clone(),
            content: chunk_content,
        });
    }

    chunks
}

/// Generate a scoped conflict marker for a single member within a container merge.
fn scoped_conflict_marker(
    name: &str,
    base: Option<&str>,
    ours: Option<&str>,
    theirs: Option<&str>,
    ours_deleted: bool,
    theirs_deleted: bool,
    fmt: &MarkerFormat,
) -> String {
    let open = "<".repeat(fmt.marker_length);
    let sep = "=".repeat(fmt.marker_length);
    let close = ">".repeat(fmt.marker_length);

    let o = ours.unwrap_or("");
    let t = theirs.unwrap_or("");

    // Narrow conflict markers to just the differing lines
    let ours_lines: Vec<&str> = o.lines().collect();
    let theirs_lines: Vec<&str> = t.lines().collect();
    let (prefix_len, suffix_len) = if ours.is_some() && theirs.is_some() {
        crate::conflict::narrow_conflict_lines(&ours_lines, &theirs_lines)
    } else {
        (0, 0)
    };
    let has_narrowing = prefix_len > 0 || suffix_len > 0;
    let ours_mid = &ours_lines[prefix_len..ours_lines.len() - suffix_len];
    let theirs_mid = &theirs_lines[prefix_len..theirs_lines.len() - suffix_len];

    let mut out = String::new();

    // Emit common prefix as clean text
    if has_narrowing {
        for line in &ours_lines[..prefix_len] {
            out.push_str(line);
            out.push('\n');
        }
    }

    // Opening marker
    if fmt.enhanced {
        if ours_deleted {
            out.push_str(&format!("{} ours ({} deleted)\n", open, name));
        } else {
            out.push_str(&format!("{} ours ({})\n", open, name));
        }
    } else {
        out.push_str(&format!("{} ours\n", open));
    }

    // Ours content (narrowed or full)
    if ours.is_some() {
        if has_narrowing {
            for line in ours_mid {
                out.push_str(line);
                out.push('\n');
            }
        } else {
            out.push_str(o);
            if !o.ends_with('\n') {
                out.push('\n');
            }
        }
    }

    // Base section for diff3 format (standard mode only)
    if !fmt.enhanced {
        let base_marker = "|".repeat(fmt.marker_length);
        out.push_str(&format!("{} base\n", base_marker));
        let b = base.unwrap_or("");
        if has_narrowing {
            let base_lines: Vec<&str> = b.lines().collect();
            let base_prefix = prefix_len.min(base_lines.len());
            let base_suffix = suffix_len.min(base_lines.len().saturating_sub(base_prefix));
            for line in &base_lines[base_prefix..base_lines.len() - base_suffix] {
                out.push_str(line);
                out.push('\n');
            }
        } else {
            out.push_str(b);
            if !b.is_empty() && !b.ends_with('\n') {
                out.push('\n');
            }
        }
    }

    // Separator
    out.push_str(&format!("{}\n", sep));

    // Theirs content (narrowed or full)
    if theirs.is_some() {
        if has_narrowing {
            for line in theirs_mid {
                out.push_str(line);
                out.push('\n');
            }
        } else {
            out.push_str(t);
            if !t.ends_with('\n') {
                out.push('\n');
            }
        }
    }

    // Closing marker
    if fmt.enhanced {
        if theirs_deleted {
            out.push_str(&format!("{} theirs ({} deleted)\n", close, name));
        } else {
            out.push_str(&format!("{} theirs ({})\n", close, name));
        }
    } else {
        out.push_str(&format!("{} theirs\n", close));
    }

    // Emit common suffix as clean text
    if has_narrowing {
        for line in &ours_lines[ours_lines.len() - suffix_len..] {
            out.push_str(line);
            out.push('\n');
        }
    }

    out
}

/// Try recursive inner entity merge for container types (classes, impls, etc.).
///
/// Inspired by LastMerge (arXiv:2507.19687): class members are "unordered children" —
/// reordering them is not a conflict. We chunk the class body into members, match by
/// name, and merge each member independently.
///
/// Returns Some(result) if chunking succeeded, None if we can't parse the container.
/// The result may contain per-member conflict markers (scoped conflicts).
fn try_inner_entity_merge(
    base: &str,
    ours: &str,
    theirs: &str,
    base_children: &[&SemanticEntity],
    ours_children: &[&SemanticEntity],
    theirs_children: &[&SemanticEntity],
    base_start_line: usize,
    ours_start_line: usize,
    theirs_start_line: usize,
    marker_format: &MarkerFormat,
) -> Option<InnerMergeResult> {
    // Try sem-core child entities first (tree-sitter-accurate boundaries),
    // fall back to indentation heuristic if children aren't available.
    // When children_to_chunks produces chunks, try indentation as a fallback
    // if the tree-sitter chunks lead to conflicts (the indentation heuristic
    // can include trailing context that helps diffy merge adjacent changes).
    let use_children = !ours_children.is_empty() || !theirs_children.is_empty();
    let (base_chunks, ours_chunks, theirs_chunks) = if use_children {
        (
            children_to_chunks(base_children, base, base_start_line),
            children_to_chunks(ours_children, ours, ours_start_line),
            children_to_chunks(theirs_children, theirs, theirs_start_line),
        )
    } else {
        (
            extract_member_chunks(base)?,
            extract_member_chunks(ours)?,
            extract_member_chunks(theirs)?,
        )
    };

    // Need at least 1 member to attempt inner merge
    // (Even single-member containers benefit from decorator-aware merge)
    if base_chunks.is_empty() && ours_chunks.is_empty() && theirs_chunks.is_empty() {
        return None;
    }

    // Build name → content maps
    let base_map: HashMap<&str, &str> = base_chunks
        .iter()
        .map(|c| (c.name.as_str(), c.content.as_str()))
        .collect();
    let ours_map: HashMap<&str, &str> = ours_chunks
        .iter()
        .map(|c| (c.name.as_str(), c.content.as_str()))
        .collect();
    let theirs_map: HashMap<&str, &str> = theirs_chunks
        .iter()
        .map(|c| (c.name.as_str(), c.content.as_str()))
        .collect();

    // Collect all member names
    let mut all_names: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    // Use ours ordering as skeleton
    for chunk in &ours_chunks {
        if seen.insert(chunk.name.clone()) {
            all_names.push(chunk.name.clone());
        }
    }
    // Add theirs-only members
    for chunk in &theirs_chunks {
        if seen.insert(chunk.name.clone()) {
            all_names.push(chunk.name.clone());
        }
    }

    // Extract header/footer (class declaration line and closing brace)
    let (ours_header, ours_footer) = extract_container_wrapper(ours)?;

    let mut merged_members: Vec<String> = Vec::new();
    let mut has_conflict = false;

    for name in &all_names {
        let in_base = base_map.get(name.as_str());
        let in_ours = ours_map.get(name.as_str());
        let in_theirs = theirs_map.get(name.as_str());

        match (in_base, in_ours, in_theirs) {
            // In all three
            (Some(b), Some(o), Some(t)) => {
                if o == t {
                    merged_members.push(o.to_string());
                } else if b == o {
                    merged_members.push(t.to_string());
                } else if b == t {
                    merged_members.push(o.to_string());
                } else {
                    // Both changed differently: try diffy, then git merge-file, then decorator merge
                    if let Some(merged) = diffy_merge(b, o, t) {
                        merged_members.push(merged);
                    } else if let Some(merged) = git_merge_string(b, o, t) {
                        merged_members.push(merged);
                    } else if let Some(merged) = try_decorator_aware_merge(b, o, t) {
                        merged_members.push(merged);
                    } else {
                        // Emit per-member conflict markers
                        has_conflict = true;
                        merged_members.push(scoped_conflict_marker(name, Some(b), Some(o), Some(t), false, false, marker_format));
                    }
                }
            }
            // Deleted by theirs, ours unchanged or not in base
            (Some(b), Some(o), None) => {
                if *b == *o {
                    // Ours unchanged, theirs deleted → accept deletion
                } else {
                    // Ours modified, theirs deleted → per-member conflict
                    has_conflict = true;
                    merged_members.push(scoped_conflict_marker(name, Some(b), Some(o), None, false, true, marker_format));
                }
            }
            // Deleted by ours, theirs unchanged or not in base
            (Some(b), None, Some(t)) => {
                if *b == *t {
                    // Theirs unchanged, ours deleted → accept deletion
                } else {
                    // Theirs modified, ours deleted → per-member conflict
                    has_conflict = true;
                    merged_members.push(scoped_conflict_marker(name, Some(b), None, Some(t), true, false, marker_format));
                }
            }
            // Added by ours only
            (None, Some(o), None) => {
                merged_members.push(o.to_string());
            }
            // Added by theirs only
            (None, None, Some(t)) => {
                merged_members.push(t.to_string());
            }
            // Added by both with different content
            (None, Some(o), Some(t)) => {
                if o == t {
                    merged_members.push(o.to_string());
                } else {
                    has_conflict = true;
                    merged_members.push(scoped_conflict_marker(name, None, Some(o), Some(t), false, false, marker_format));
                }
            }
            // Deleted by both
            (Some(_), None, None) => {}
            (None, None, None) => {}
        }
    }

    // Reconstruct: header + merged members + footer
    let mut result = String::new();
    result.push_str(ours_header);
    if !ours_header.ends_with('\n') {
        result.push('\n');
    }

    // Detect if members are single-line (fields, variants) vs multi-line (methods)
    let has_multiline_members = merged_members.iter().any(|m| m.contains('\n'));
    // Check if the original content had blank lines between members
    let original_has_blank_separators = {
        let body = ours_header.len()..ours.rfind(ours_footer).unwrap_or(ours.len());
        let body_content = &ours[body];
        body_content.contains("\n\n")
    };

    for (i, member) in merged_members.iter().enumerate() {
        result.push_str(member);
        if !member.ends_with('\n') {
            result.push('\n');
        }
        // Add blank line between multi-line members only if the original had them
        if i < merged_members.len() - 1 && has_multiline_members && original_has_blank_separators && !member.ends_with("\n\n") {
            result.push('\n');
        }
    }

    result.push_str(ours_footer);
    if !ours_footer.ends_with('\n') && ours.ends_with('\n') {
        result.push('\n');
    }

    // If children_to_chunks led to conflicts, retry with indentation heuristic.
    // The indentation approach includes trailing blank lines in chunks, giving
    // diffy more context to merge adjacent changes from different branches.
    if has_conflict && use_children {
        if let (Some(bc), Some(oc), Some(tc)) = (
            extract_member_chunks(base),
            extract_member_chunks(ours),
            extract_member_chunks(theirs),
        ) {
            if !bc.is_empty() || !oc.is_empty() || !tc.is_empty() {
                let fallback = try_inner_merge_with_chunks(
                    &bc, &oc, &tc, ours, ours_header, ours_footer,
                    has_multiline_members, marker_format,
                );
                if let Some(fb) = fallback {
                    if !fb.has_conflicts {
                        return Some(fb);
                    }
                }
            }
        }
    }

    Some(InnerMergeResult {
        content: result,
        has_conflicts: has_conflict,
    })
}

/// Inner merge helper using pre-extracted chunks. Used for indentation-heuristic fallback.
fn try_inner_merge_with_chunks(
    base_chunks: &[MemberChunk],
    ours_chunks: &[MemberChunk],
    theirs_chunks: &[MemberChunk],
    ours: &str,
    ours_header: &str,
    ours_footer: &str,
    has_multiline_hint: bool,
    marker_format: &MarkerFormat,
) -> Option<InnerMergeResult> {
    let base_map: HashMap<&str, &str> = base_chunks.iter().map(|c| (c.name.as_str(), c.content.as_str())).collect();
    let ours_map: HashMap<&str, &str> = ours_chunks.iter().map(|c| (c.name.as_str(), c.content.as_str())).collect();
    let theirs_map: HashMap<&str, &str> = theirs_chunks.iter().map(|c| (c.name.as_str(), c.content.as_str())).collect();

    let mut all_names: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    for chunk in ours_chunks {
        if seen.insert(chunk.name.clone()) {
            all_names.push(chunk.name.clone());
        }
    }
    for chunk in theirs_chunks {
        if seen.insert(chunk.name.clone()) {
            all_names.push(chunk.name.clone());
        }
    }

    let mut merged_members: Vec<String> = Vec::new();
    let mut has_conflict = false;

    for name in &all_names {
        let in_base = base_map.get(name.as_str());
        let in_ours = ours_map.get(name.as_str());
        let in_theirs = theirs_map.get(name.as_str());

        match (in_base, in_ours, in_theirs) {
            (Some(b), Some(o), Some(t)) => {
                if o == t {
                    merged_members.push(o.to_string());
                } else if b == o {
                    merged_members.push(t.to_string());
                } else if b == t {
                    merged_members.push(o.to_string());
                } else if let Some(merged) = diffy_merge(b, o, t) {
                    merged_members.push(merged);
                } else if let Some(merged) = git_merge_string(b, o, t) {
                    merged_members.push(merged);
                } else {
                    has_conflict = true;
                    merged_members.push(scoped_conflict_marker(name, Some(b), Some(o), Some(t), false, false, marker_format));
                }
            }
            (Some(b), Some(o), None) => {
                if *b != *o { merged_members.push(o.to_string()); }
            }
            (Some(b), None, Some(t)) => {
                if *b != *t { merged_members.push(t.to_string()); }
            }
            (None, Some(o), None) => merged_members.push(o.to_string()),
            (None, None, Some(t)) => merged_members.push(t.to_string()),
            (None, Some(o), Some(t)) => {
                if o == t {
                    merged_members.push(o.to_string());
                } else {
                    has_conflict = true;
                    merged_members.push(scoped_conflict_marker(name, None, Some(o), Some(t), false, false, marker_format));
                }
            }
            (Some(_), None, None) | (None, None, None) => {}
        }
    }

    let has_multiline_members = has_multiline_hint || merged_members.iter().any(|m| m.contains('\n'));
    let mut result = String::new();
    result.push_str(ours_header);
    if !ours_header.ends_with('\n') { result.push('\n'); }
    for (i, member) in merged_members.iter().enumerate() {
        result.push_str(member);
        if !member.ends_with('\n') { result.push('\n'); }
        if i < merged_members.len() - 1 && has_multiline_members && !member.ends_with("\n\n") {
            result.push('\n');
        }
    }
    result.push_str(ours_footer);
    if !ours_footer.ends_with('\n') && ours.ends_with('\n') { result.push('\n'); }

    Some(InnerMergeResult {
        content: result,
        has_conflicts: has_conflict,
    })
}

/// Extract the header (class declaration) and footer (closing brace) from a container.
/// Supports both brace-delimited (JS/TS/Java/Rust/C) and indentation-based (Python) containers.
/// Detect whether a container entity uses Python-style indentation (`:` terminated
/// declaration) or brace-delimited style (`{`). Only inspects the declaration
/// line(s), not the body, so dict literals / set comprehensions inside methods
/// don't cause a false negative.
fn is_python_style_container(lines: &[&str]) -> bool {
    // Find the first line that looks like a class/def/async def declaration
    let has_colon_decl = lines.iter().any(|l| {
        let trimmed = l.trim();
        (trimmed.starts_with("class ")
            || trimmed.starts_with("def ")
            || trimmed.starts_with("async def "))
            && trimmed.ends_with(':')
    });
    if !has_colon_decl {
        return false;
    }
    // Verify the container itself opens with `:`, not `{`.
    // Look at the declaration line (first line ending with `:` that is class/def).
    // If that line also contains `{` it's not Python style (edge case: shouldn't happen).
    if let Some(decl) = lines.iter().find(|l| {
        let t = l.trim();
        (t.starts_with("class ") || t.starts_with("def ") || t.starts_with("async def "))
            && t.ends_with(':')
    }) {
        !decl.contains('{')
    } else {
        false
    }
}

fn extract_container_wrapper(content: &str) -> Option<(&str, &str)> {
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() < 2 {
        return None;
    }

    // Check if this is a Python-style container (ends with `:` instead of `{`)
    let is_python_style = is_python_style_container(&lines);

    if is_python_style {
        // Python: header is the `class Foo:` line, no footer
        let header_end = lines.iter().position(|l| l.trim().ends_with(':'))?;
        let header_byte_end: usize = lines[..=header_end]
            .iter()
            .map(|l| l.len() + 1)
            .sum();
        let header = &content[..header_byte_end.min(content.len())];
        // No closing brace in Python — footer is empty
        let footer = &content[content.len()..];
        Some((header, footer))
    } else {
        // Brace-delimited: header up to `{`, footer from last `}`
        let header_end = lines.iter().position(|l| l.contains('{'))?;
        let header_byte_end = lines[..=header_end]
            .iter()
            .map(|l| l.len() + 1)
            .sum::<usize>();
        let header = &content[..header_byte_end.min(content.len())];

        let footer_start = lines.iter().rposition(|l| {
            let trimmed = l.trim();
            trimmed == "}" || trimmed == "};"
        })?;

        let footer_byte_start: usize = lines[..footer_start]
            .iter()
            .map(|l| l.len() + 1)
            .sum();
        let footer = &content[footer_byte_start.min(content.len())..];

        Some((header, footer))
    }
}

/// Extract named member chunks from a container body.
///
/// Identifies member boundaries by indentation: members start at the first
/// indentation level inside the container. Each member extends until the next
/// member starts or the container closes.
fn extract_member_chunks(content: &str) -> Option<Vec<MemberChunk>> {
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() < 2 {
        return None;
    }

    // Check if Python-style (indentation-based)
    let is_python_style = is_python_style_container(&lines);

    // Find the body range
    let body_start = if is_python_style {
        lines.iter().position(|l| l.trim().ends_with(':'))? + 1
    } else {
        lines.iter().position(|l| l.contains('{'))? + 1
    };
    let body_end = if is_python_style {
        // Python: body extends to end of content
        lines.len()
    } else {
        lines.iter().rposition(|l| {
            let trimmed = l.trim();
            trimmed == "}" || trimmed == "};"
        })?
    };

    if body_start >= body_end {
        return None;
    }

    // Determine member indentation level by looking at first non-empty body line
    let member_indent = lines[body_start..body_end]
        .iter()
        .find(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())?;

    let mut chunks: Vec<MemberChunk> = Vec::new();
    let mut current_chunk_lines: Vec<&str> = Vec::new();
    let mut current_name: Option<String> = None;

    for line in &lines[body_start..body_end] {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            // Blank lines: if we have a current chunk, include them
            if current_name.is_some() {
                // Only include if not trailing blanks
                current_chunk_lines.push(line);
            }
            continue;
        }

        let indent = line.len() - line.trim_start().len();

        // Is this a new member declaration at the member indent level?
        // Exclude closing braces, comments, and decorators/annotations
        if indent == member_indent
            && !trimmed.starts_with("//")
            && !trimmed.starts_with("/*")
            && !trimmed.starts_with("*")
            && !trimmed.starts_with("#")
            && !trimmed.starts_with("@")
            && !trimmed.starts_with("}")
            && trimmed != ","
        {
            // Save previous chunk
            if let Some(name) = current_name.take() {
                // Trim trailing blank lines
                while current_chunk_lines.last().map_or(false, |l| l.trim().is_empty()) {
                    current_chunk_lines.pop();
                }
                if !current_chunk_lines.is_empty() {
                    chunks.push(MemberChunk {
                        name,
                        content: current_chunk_lines.join("\n"),
                    });
                }
                current_chunk_lines.clear();
            }

            // Start new chunk — extract member name
            let name = extract_member_name(trimmed);
            current_name = Some(name);
            current_chunk_lines.push(line);
        } else if current_name.is_some() {
            // Continuation of current member (body lines, nested blocks)
            current_chunk_lines.push(line);
        } else {
            // Content before first member (decorators, comments for first member)
            // Attach to next member
            current_chunk_lines.push(line);
        }
    }

    // Save last chunk
    if let Some(name) = current_name {
        while current_chunk_lines.last().map_or(false, |l| l.trim().is_empty()) {
            current_chunk_lines.pop();
        }
        if !current_chunk_lines.is_empty() {
            chunks.push(MemberChunk {
                name,
                content: current_chunk_lines.join("\n"),
            });
        }
    }

    // Post-process: if any chunk has a brace-only name (anonymous struct literal
    // entries like Go's `{ Name: "x", ... }`), derive a name from the first
    // key-value field inside the chunk to avoid HashMap collisions.
    for chunk in &mut chunks {
        if chunk.name == "{" || chunk.name == "{}" {
            if let Some(better) = derive_name_from_struct_literal(&chunk.content) {
                chunk.name = better;
            }
        }
    }

    if chunks.is_empty() {
        None
    } else {
        Some(chunks)
    }
}

/// Extract a member name from a declaration line.
fn extract_member_name(line: &str) -> String {
    let trimmed = line.trim();

    // Go method receiver: `func (c *Calculator) Add(` -> skip receiver, find name before second `(`
    if trimmed.starts_with("func ") && trimmed.get(5..6) == Some("(") {
        // Skip past the receiver: find closing `)`, then extract name before next `(`
        if let Some(recv_close) = trimmed.find(')') {
            let after_recv = &trimmed[recv_close + 1..];
            if let Some(paren_pos) = after_recv.find('(') {
                let before = after_recv[..paren_pos].trim();
                let name: String = before
                    .chars()
                    .rev()
                    .take_while(|c| c.is_alphanumeric() || *c == '_')
                    .collect::<Vec<_>>()
                    .into_iter()
                    .rev()
                    .collect();
                if !name.is_empty() {
                    return name;
                }
            }
        }
    }

    // Strategy 1: For method/function declarations with parentheses,
    // the name is the identifier immediately before `(`.
    // This handles all languages: Java `public int add(`, Rust `pub fn add(`,
    // Python `def add(`, TS `async getUser(`, Go `func add(`, etc.
    if let Some(paren_pos) = trimmed.find('(') {
        let before = trimmed[..paren_pos].trim_end();
        let name: String = before
            .chars()
            .rev()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        if !name.is_empty() {
            return name;
        }
    }

    // Strategy 2: For fields/properties/variants without parens,
    // strip keywords and take the first identifier.
    let mut s = trimmed;
    for keyword in &[
        "export ", "public ", "private ", "protected ", "static ",
        "abstract ", "async ", "override ", "readonly ",
        "pub ", "pub(crate) ", "fn ", "def ", "get ", "set ",
    ] {
        if s.starts_with(keyword) {
            s = &s[keyword.len()..];
        }
    }
    if s.starts_with("fn ") {
        s = &s[3..];
    }

    let name: String = s
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();

    if name.is_empty() {
        trimmed.chars().take(20).collect()
    } else {
        name
    }
}

/// For anonymous struct literal entries (e.g., Go slice entries starting with `{`),
/// derive a name from the first key-value field inside the chunk.
/// E.g., `{ Name: "panelTitleSearch", ... }` → `panelTitleSearch`
fn derive_name_from_struct_literal(content: &str) -> Option<String> {
    for line in content.lines().skip(1) {
        let trimmed = line.trim().trim_end_matches(',');
        // Look for `Key: "value"` or `Key: value` pattern
        if let Some(colon_pos) = trimmed.find(':') {
            let value = trimmed[colon_pos + 1..].trim();
            // Strip quotes from string values
            let value = value.trim_matches('"').trim_matches('\'');
            if !value.is_empty() {
                return Some(value.to_string());
            }
        }
    }
    None
}

/// Returns true for data/config file formats where Sesame separator expansion
/// (`{`, `}`, `;`) is counterproductive because those chars are structural
/// content rather than code block separators.
///
/// Note: template files like .svelte/.vue are NOT included here because their
/// embedded `<script>` sections contain real code where Sesame helps.
/// Check if content looks binary (contains null bytes in first 8KB).
fn is_binary(content: &str) -> bool {
    content.as_bytes().iter().take(8192).any(|&b| b == 0)
}

/// Check if content already contains git conflict markers.
/// This happens with AU/AA conflicts where git stores markers in stage blobs.
fn has_conflict_markers(content: &str) -> bool {
    content.contains("<<<<<<<") && content.contains(">>>>>>>")
}

fn skip_sesame(file_path: &str) -> bool {
    let path_lower = file_path.to_lowercase();
    let extensions = [
        // Data/config formats
        ".json", ".yaml", ".yml", ".toml", ".lock", ".xml", ".csv", ".tsv",
        ".ini", ".cfg", ".conf", ".properties", ".env",
        // Markup/document formats
        ".md", ".markdown", ".txt", ".rst", ".svg", ".html", ".htm",
    ];
    extensions.iter().any(|ext| path_lower.ends_with(ext))
}

/// Expand syntactic separators into separate lines for finer merge alignment.
/// Inspired by Sesame (arXiv:2407.18888): isolating separators lets line-based
/// merge tools see block boundaries as independent change units.
/// Uses byte-level iteration since separators ({, }, ;) and string delimiters
/// (", ', `) are all ASCII.
fn expand_separators(content: &str) -> String {
    let bytes = content.as_bytes();
    let mut result = Vec::with_capacity(content.len() * 2);
    let mut in_string = false;
    let mut escape_next = false;
    let mut string_char = b'"';

    for &b in bytes {
        if escape_next {
            result.push(b);
            escape_next = false;
            continue;
        }
        if b == b'\\' && in_string {
            result.push(b);
            escape_next = true;
            continue;
        }
        if !in_string && (b == b'"' || b == b'\'' || b == b'`') {
            in_string = true;
            string_char = b;
            result.push(b);
            continue;
        }
        if in_string && b == string_char {
            in_string = false;
            result.push(b);
            continue;
        }

        if !in_string && (b == b'{' || b == b'}' || b == b';') {
            if result.last() != Some(&b'\n') && !result.is_empty() {
                result.push(b'\n');
            }
            result.push(b);
            result.push(b'\n');
        } else {
            result.push(b);
        }
    }

    // Safe: we only inserted ASCII bytes into valid UTF-8 content
    unsafe { String::from_utf8_unchecked(result) }
}

/// Collapse separator expansion back to original formatting.
/// Uses the base formatting as a guide where possible.
fn collapse_separators(merged: &str, _base: &str) -> String {
    // Simple approach: join lines that contain only a separator with adjacent lines
    let lines: Vec<&str> = merged.lines().collect();
    let mut result = String::new();
    let mut i = 0;

    while i < lines.len() {
        let trimmed = lines[i].trim();
        if (trimmed == "{" || trimmed == "}" || trimmed == ";") && trimmed.len() == 1 {
            // This is a separator-only line we may have created
            // Try to join with previous line if it doesn't end with a separator
            if !result.is_empty() && !result.ends_with('\n') {
                // Peek: if it's an opening brace, join with previous
                if trimmed == "{" {
                    result.push(' ');
                    result.push_str(trimmed);
                    result.push('\n');
                } else if trimmed == "}" {
                    result.push('\n');
                    result.push_str(trimmed);
                    result.push('\n');
                } else {
                    result.push_str(trimmed);
                    result.push('\n');
                }
            } else {
                result.push_str(lines[i]);
                result.push('\n');
            }
        } else {
            result.push_str(lines[i]);
            result.push('\n');
        }
        i += 1;
    }

    // Trim any trailing extra newlines to match original style
    while result.ends_with("\n\n") {
        result.pop();
    }

    result
}

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

    #[test]
    fn test_replace_at_word_boundaries() {
        // Should replace standalone occurrences
        assert_eq!(replace_at_word_boundaries("fn get() {}", "get", "__E__"), "fn __E__() {}");
        // Should NOT replace inside longer identifiers
        assert_eq!(replace_at_word_boundaries("fn getAll() {}", "get", "__E__"), "fn getAll() {}");
        assert_eq!(replace_at_word_boundaries("fn _get() {}", "get", "__E__"), "fn _get() {}");
        // Should replace multiple standalone occurrences
        assert_eq!(
            replace_at_word_boundaries("pub enum Source { Source }", "Source", "__E__"),
            "pub enum __E__ { __E__ }"
        );
        // Should not replace substring at start/end of identifiers
        assert_eq!(
            replace_at_word_boundaries("SourceManager isSource", "Source", "__E__"),
            "SourceManager isSource"
        );
        // Should handle multi-byte UTF-8 characters (emojis) without panicking
        assert_eq!(
            replace_at_word_boundaries("❌ get ✅", "get", "__E__"),
            "❌ __E__ ✅"
        );
        assert_eq!(
            replace_at_word_boundaries("fn 名前() { get }", "get", "__E__"),
            "fn 名前() { __E__ }"
        );
        // Emoji-only content with no needle match should pass through unchanged
        assert_eq!(
            replace_at_word_boundaries("🎉🚀✨", "get", "__E__"),
            "🎉🚀✨"
        );
    }

    #[test]
    fn test_fast_path_identical() {
        let content = "hello world";
        let result = entity_merge(content, content, content, "test.ts");
        assert!(result.is_clean());
        assert_eq!(result.content, content);
    }

    #[test]
    fn test_fast_path_only_ours_changed() {
        let base = "hello";
        let ours = "hello world";
        let result = entity_merge(base, ours, base, "test.ts");
        assert!(result.is_clean());
        assert_eq!(result.content, ours);
    }

    #[test]
    fn test_fast_path_only_theirs_changed() {
        let base = "hello";
        let theirs = "hello world";
        let result = entity_merge(base, base, theirs, "test.ts");
        assert!(result.is_clean());
        assert_eq!(result.content, theirs);
    }

    #[test]
    fn test_different_functions_no_conflict() {
        // Core value prop: two agents add different functions to the same file
        let base = r#"export function existing() {
    return 1;
}
"#;
        let ours = r#"export function existing() {
    return 1;
}

export function agentA() {
    return "added by agent A";
}
"#;
        let theirs = r#"export function existing() {
    return 1;
}

export function agentB() {
    return "added by agent B";
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            result.is_clean(),
            "Should auto-resolve: different functions added. Conflicts: {:?}",
            result.conflicts
        );
        assert!(
            result.content.contains("agentA"),
            "Should contain agentA function"
        );
        assert!(
            result.content.contains("agentB"),
            "Should contain agentB function"
        );
    }

    #[test]
    fn test_same_function_modified_by_both_conflict() {
        let base = r#"export function shared() {
    return "original";
}
"#;
        let ours = r#"export function shared() {
    return "modified by ours";
}
"#;
        let theirs = r#"export function shared() {
    return "modified by theirs";
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        // This should be a conflict since both modified the same function incompatibly
        assert!(
            !result.is_clean(),
            "Should conflict when both modify same function differently"
        );
        assert_eq!(result.conflicts.len(), 1);
        assert_eq!(result.conflicts[0].entity_name, "shared");
    }

    #[test]
    fn test_fallback_for_unknown_filetype() {
        // Non-adjacent changes should merge cleanly with line-level merge
        let base = "line 1\nline 2\nline 3\nline 4\nline 5\n";
        let ours = "line 1 modified\nline 2\nline 3\nline 4\nline 5\n";
        let theirs = "line 1\nline 2\nline 3\nline 4\nline 5 modified\n";
        let result = entity_merge(base, ours, theirs, "test.xyz");
        assert!(
            result.is_clean(),
            "Non-adjacent changes should merge cleanly. Conflicts: {:?}",
            result.conflicts,
        );
    }

    #[test]
    fn test_line_level_fallback() {
        // Non-adjacent changes merge cleanly in 3-way merge
        let base = "a\nb\nc\nd\ne\n";
        let ours = "A\nb\nc\nd\ne\n";
        let theirs = "a\nb\nc\nd\nE\n";
        let result = line_level_fallback(base, ours, theirs, "test.rs");
        assert!(result.is_clean());
        assert!(result.stats.used_fallback);
        assert_eq!(result.content, "A\nb\nc\nd\nE\n");
    }

    #[test]
    fn test_line_level_fallback_conflict() {
        // Same line changed differently → conflict
        let base = "a\nb\nc\n";
        let ours = "X\nb\nc\n";
        let theirs = "Y\nb\nc\n";
        let result = line_level_fallback(base, ours, theirs, "test.rs");
        assert!(!result.is_clean());
        assert!(result.stats.used_fallback);
    }

    #[test]
    fn test_expand_separators() {
        let code = "function foo() { return 1; }";
        let expanded = expand_separators(code);
        // Separators should be on their own lines
        assert!(expanded.contains("{\n"), "Opening brace should have newline after");
        assert!(expanded.contains(";\n"), "Semicolons should have newline after");
        assert!(expanded.contains("\n}"), "Closing brace should have newline before");
    }

    #[test]
    fn test_expand_separators_preserves_strings() {
        let code = r#"let x = "hello { world };";"#;
        let expanded = expand_separators(code);
        // Separators inside strings should NOT be expanded
        assert!(
            expanded.contains("\"hello { world };\""),
            "Separators in strings should be preserved: {}",
            expanded
        );
    }

    #[test]
    fn test_is_import_region() {
        assert!(is_import_region("import foo from 'foo';\nimport bar from 'bar';\n"));
        assert!(is_import_region("use std::io;\nuse std::fs;\n"));
        assert!(!is_import_region("let x = 1;\nlet y = 2;\n"));
        // Mixed: 1 import + 2 non-imports → not import region
        assert!(!is_import_region("import foo from 'foo';\nlet x = 1;\nlet y = 2;\n"));
        // Empty → not import region
        assert!(!is_import_region(""));
    }

    #[test]
    fn test_is_import_line() {
        // JS/TS
        assert!(is_import_line("import foo from 'foo';"));
        assert!(is_import_line("import { bar } from 'bar';"));
        assert!(is_import_line("from typing import List"));
        // Rust
        assert!(is_import_line("use std::io::Read;"));
        // C/C++
        assert!(is_import_line("#include <stdio.h>"));
        // Node require
        assert!(is_import_line("const fs = require('fs');"));
        // Not imports
        assert!(!is_import_line("let x = 1;"));
        assert!(!is_import_line("function foo() {}"));
    }

    #[test]
    fn test_commutative_import_merge_both_add_different() {
        // The key scenario: both branches add different imports
        let base = "import a from 'a';\nimport b from 'b';\n";
        let ours = "import a from 'a';\nimport b from 'b';\nimport c from 'c';\n";
        let theirs = "import a from 'a';\nimport b from 'b';\nimport d from 'd';\n";
        let result = merge_imports_commutatively(base, ours, theirs);
        assert!(result.contains("import a from 'a';"));
        assert!(result.contains("import b from 'b';"));
        assert!(result.contains("import c from 'c';"));
        assert!(result.contains("import d from 'd';"));
    }

    #[test]
    fn test_commutative_import_merge_one_removes() {
        // Ours removes an import, theirs keeps it → removed
        let base = "import a from 'a';\nimport b from 'b';\nimport c from 'c';\n";
        let ours = "import a from 'a';\nimport c from 'c';\n";
        let theirs = "import a from 'a';\nimport b from 'b';\nimport c from 'c';\n";
        let result = merge_imports_commutatively(base, ours, theirs);
        assert!(result.contains("import a from 'a';"));
        assert!(!result.contains("import b from 'b';"), "Removed import should stay removed");
        assert!(result.contains("import c from 'c';"));
    }

    #[test]
    fn test_commutative_import_merge_both_add_same() {
        // Both add the same import → should appear only once
        let base = "import a from 'a';\n";
        let ours = "import a from 'a';\nimport b from 'b';\n";
        let theirs = "import a from 'a';\nimport b from 'b';\n";
        let result = merge_imports_commutatively(base, ours, theirs);
        let count = result.matches("import b from 'b';").count();
        assert_eq!(count, 1, "Duplicate import should be deduplicated");
    }

    #[test]
    fn test_inner_entity_merge_different_methods() {
        // Two agents modify different methods in the same class
        // This would normally conflict with diffy because the changes are adjacent
        let base = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }

    subtract(a: number, b: number): number {
        return a - b;
    }
}
"#;
        let ours = r#"export class Calculator {
    add(a: number, b: number): number {
        // Added logging
        console.log("adding", a, b);
        return a + b;
    }

    subtract(a: number, b: number): number {
        return a - b;
    }
}
"#;
        let theirs = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }

    subtract(a: number, b: number): number {
        // Added validation
        if (b > a) throw new Error("negative");
        return a - b;
    }
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            result.is_clean(),
            "Different methods modified should auto-merge via inner entity merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("console.log"), "Should contain ours changes");
        assert!(result.content.contains("negative"), "Should contain theirs changes");
    }

    #[test]
    fn test_inner_entity_merge_both_add_different_methods() {
        // Both branches add different methods to the same class
        let base = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }
}
"#;
        let ours = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }

    multiply(a: number, b: number): number {
        return a * b;
    }
}
"#;
        let theirs = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }

    divide(a: number, b: number): number {
        return a / b;
    }
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            result.is_clean(),
            "Both adding different methods should auto-merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("multiply"), "Should contain ours's new method");
        assert!(result.content.contains("divide"), "Should contain theirs's new method");
    }

    #[test]
    fn test_inner_entity_merge_same_method_modified_still_conflicts() {
        // Both modify the same method differently → should still conflict
        let base = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b;
    }

    subtract(a: number, b: number): number {
        return a - b;
    }
}
"#;
        let ours = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b + 1;
    }

    subtract(a: number, b: number): number {
        return a - b;
    }
}
"#;
        let theirs = r#"export class Calculator {
    add(a: number, b: number): number {
        return a + b + 2;
    }

    subtract(a: number, b: number): number {
        return a - b;
    }
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            !result.is_clean(),
            "Both modifying same method differently should still conflict"
        );
    }

    #[test]
    fn test_extract_member_chunks() {
        let class_body = r#"export class Foo {
    bar() {
        return 1;
    }

    baz() {
        return 2;
    }
}
"#;
        let chunks = extract_member_chunks(class_body).unwrap();
        assert_eq!(chunks.len(), 2, "Should find 2 members, found {:?}", chunks.iter().map(|c| &c.name).collect::<Vec<_>>());
        assert_eq!(chunks[0].name, "bar");
        assert_eq!(chunks[1].name, "baz");
    }

    #[test]
    fn test_extract_member_name() {
        assert_eq!(extract_member_name("add(a, b) {"), "add");
        assert_eq!(extract_member_name("fn add(&self, a: i32) -> i32 {"), "add");
        assert_eq!(extract_member_name("def add(self, a, b):"), "add");
        assert_eq!(extract_member_name("public static getValue(): number {"), "getValue");
        assert_eq!(extract_member_name("async fetchData() {"), "fetchData");
    }

    #[test]
    fn test_commutative_import_merge_rust_use() {
        let base = "use std::io;\nuse std::fs;\n";
        let ours = "use std::io;\nuse std::fs;\nuse std::path::Path;\n";
        let theirs = "use std::io;\nuse std::fs;\nuse std::collections::HashMap;\n";
        let result = merge_imports_commutatively(base, ours, theirs);
        assert!(result.contains("use std::path::Path;"));
        assert!(result.contains("use std::collections::HashMap;"));
        assert!(result.contains("use std::io;"));
        assert!(result.contains("use std::fs;"));
    }

    #[test]
    fn test_is_whitespace_only_diff_true() {
        // Same content, different indentation
        assert!(is_whitespace_only_diff(
            "    return 1;\n    return 2;\n",
            "      return 1;\n      return 2;\n"
        ));
        // Same content, extra blank lines
        assert!(is_whitespace_only_diff(
            "return 1;\nreturn 2;\n",
            "return 1;\n\nreturn 2;\n"
        ));
    }

    #[test]
    fn test_is_whitespace_only_diff_false() {
        // Different content
        assert!(!is_whitespace_only_diff(
            "    return 1;\n",
            "    return 2;\n"
        ));
        // Added code
        assert!(!is_whitespace_only_diff(
            "return 1;\n",
            "return 1;\nconsole.log('x');\n"
        ));
    }

    #[test]
    fn test_ts_interface_both_add_different_fields() {
        let base = "interface Config {\n    name: string;\n}\n";
        let ours = "interface Config {\n    name: string;\n    age: number;\n}\n";
        let theirs = "interface Config {\n    name: string;\n    email: string;\n}\n";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS interface: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content: {:?}", result.content);
        assert!(
            result.is_clean(),
            "Both adding different fields to TS interface should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("age"));
        assert!(result.content.contains("email"));
    }

    #[test]
    fn test_rust_enum_both_add_different_variants() {
        let base = "enum Color {\n    Red,\n    Blue,\n}\n";
        let ours = "enum Color {\n    Red,\n    Blue,\n    Green,\n}\n";
        let theirs = "enum Color {\n    Red,\n    Blue,\n    Yellow,\n}\n";
        let result = entity_merge(base, ours, theirs, "test.rs");
        eprintln!("Rust enum: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content: {:?}", result.content);
        assert!(
            result.is_clean(),
            "Both adding different enum variants should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("Green"));
        assert!(result.content.contains("Yellow"));
    }

    #[test]
    fn test_python_both_add_different_decorators() {
        // Both add different decorators to the same function
        let base = "def foo():\n    return 1\n\ndef bar():\n    return 2\n";
        let ours = "@cache\ndef foo():\n    return 1\n\ndef bar():\n    return 2\n";
        let theirs = "@deprecated\ndef foo():\n    return 1\n\ndef bar():\n    return 2\n";
        let result = entity_merge(base, ours, theirs, "test.py");
        assert!(
            result.is_clean(),
            "Both adding different decorators should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("@cache"));
        assert!(result.content.contains("@deprecated"));
        assert!(result.content.contains("def foo()"));
    }

    #[test]
    fn test_decorator_plus_body_change() {
        // One adds decorator, other modifies body — should merge both
        let base = "def foo():\n    return 1\n";
        let ours = "@cache\ndef foo():\n    return 1\n";
        let theirs = "def foo():\n    return 42\n";
        let result = entity_merge(base, ours, theirs, "test.py");
        assert!(
            result.is_clean(),
            "Decorator + body change should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("@cache"));
        assert!(result.content.contains("return 42"));
    }

    #[test]
    fn test_ts_class_decorator_merge() {
        // TypeScript decorators on class methods — both add different decorators
        let base = "class Foo {\n    bar() {\n        return 1;\n    }\n}\n";
        let ours = "class Foo {\n    @Injectable()\n    bar() {\n        return 1;\n    }\n}\n";
        let theirs = "class Foo {\n    @Deprecated()\n    bar() {\n        return 1;\n    }\n}\n";
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            result.is_clean(),
            "Both adding different decorators to same method should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("@Injectable()"));
        assert!(result.content.contains("@Deprecated()"));
        assert!(result.content.contains("bar()"));
    }

    #[test]
    fn test_non_adjacent_intra_function_changes() {
        let base = r#"export function process(data: any) {
    const validated = validate(data);
    const transformed = transform(validated);
    const saved = save(transformed);
    return saved;
}
"#;
        let ours = r#"export function process(data: any) {
    const validated = validate(data);
    const transformed = transform(validated);
    const saved = save(transformed);
    console.log("saved", saved);
    return saved;
}
"#;
        let theirs = r#"export function process(data: any) {
    console.log("input", data);
    const validated = validate(data);
    const transformed = transform(validated);
    const saved = save(transformed);
    return saved;
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        assert!(
            result.is_clean(),
            "Non-adjacent changes within same function should merge via diffy. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("console.log(\"saved\""));
        assert!(result.content.contains("console.log(\"input\""));
    }

    #[test]
    fn test_method_reordering_with_modification() {
        // Agent A reorders methods in class, Agent B modifies one method
        // Inner entity merge matches by name, so reordering should be transparent
        let base = r#"class Service {
    getUser(id: string) {
        return db.find(id);
    }

    createUser(data: any) {
        return db.create(data);
    }

    deleteUser(id: string) {
        return db.delete(id);
    }
}
"#;
        // Ours: reorder methods (move deleteUser before createUser)
        let ours = r#"class Service {
    getUser(id: string) {
        return db.find(id);
    }

    deleteUser(id: string) {
        return db.delete(id);
    }

    createUser(data: any) {
        return db.create(data);
    }
}
"#;
        // Theirs: modify getUser
        let theirs = r#"class Service {
    getUser(id: string) {
        console.log("fetching", id);
        return db.find(id);
    }

    createUser(data: any) {
        return db.create(data);
    }

    deleteUser(id: string) {
        return db.delete(id);
    }
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("Method reorder: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(
            result.is_clean(),
            "Method reordering + modification should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("console.log(\"fetching\""), "Should contain theirs modification");
        assert!(result.content.contains("deleteUser"), "Should have deleteUser");
        assert!(result.content.contains("createUser"), "Should have createUser");
    }

    #[test]
    fn test_doc_comment_plus_body_change() {
        // One side adds JSDoc comment, other modifies function body
        // Doc comments are part of the entity region — they should merge with body changes
        let base = r#"export function calculate(a: number, b: number): number {
    return a + b;
}
"#;
        let ours = r#"/**
 * Calculate the sum of two numbers.
 * @param a - First number
 * @param b - Second number
 */
export function calculate(a: number, b: number): number {
    return a + b;
}
"#;
        let theirs = r#"export function calculate(a: number, b: number): number {
    const result = a + b;
    console.log("result:", result);
    return result;
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("Doc comment + body: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        // This tests whether weave can merge doc comment additions with body changes
    }

    #[test]
    fn test_both_add_different_guard_clauses() {
        // Both add different guard clauses at the start of a function
        let base = r#"export function processOrder(order: Order): Result {
    const total = calculateTotal(order);
    return { success: true, total };
}
"#;
        let ours = r#"export function processOrder(order: Order): Result {
    if (!order) throw new Error("Order required");
    const total = calculateTotal(order);
    return { success: true, total };
}
"#;
        let theirs = r#"export function processOrder(order: Order): Result {
    if (order.items.length === 0) throw new Error("Empty order");
    const total = calculateTotal(order);
    return { success: true, total };
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("Guard clauses: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        // Both add at same position — diffy may struggle since they're at the same insertion point
    }

    #[test]
    fn test_both_modify_different_enum_variants() {
        // One modifies a variant's value, other adds new variants
        let base = r#"enum Status {
    Active = "active",
    Inactive = "inactive",
    Pending = "pending",
}
"#;
        let ours = r#"enum Status {
    Active = "active",
    Inactive = "disabled",
    Pending = "pending",
}
"#;
        let theirs = r#"enum Status {
    Active = "active",
    Inactive = "inactive",
    Pending = "pending",
    Deleted = "deleted",
}
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("Enum modify+add: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(
            result.is_clean(),
            "Modify variant + add new variant should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("\"disabled\""), "Should have modified Inactive");
        assert!(result.content.contains("Deleted"), "Should have new Deleted variant");
    }

    #[test]
    fn test_config_object_field_additions() {
        // Both add different fields to a config object (exported const)
        let base = r#"export const config = {
    timeout: 5000,
    retries: 3,
};
"#;
        let ours = r#"export const config = {
    timeout: 5000,
    retries: 3,
    maxConnections: 10,
};
"#;
        let theirs = r#"export const config = {
    timeout: 5000,
    retries: 3,
    logLevel: "info",
};
"#;
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("Config fields: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        // This tests whether inner entity merge handles object literals
        // (it probably won't since object fields aren't extracted as members the same way)
    }

    #[test]
    fn test_rust_impl_block_both_add_methods() {
        // Both add different methods to a Rust impl block
        let base = r#"impl Calculator {
    fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}
"#;
        let ours = r#"impl Calculator {
    fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    fn multiply(&self, a: i32, b: i32) -> i32 {
        a * b
    }
}
"#;
        let theirs = r#"impl Calculator {
    fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    fn divide(&self, a: i32, b: i32) -> i32 {
        a / b
    }
}
"#;
        let result = entity_merge(base, ours, theirs, "test.rs");
        eprintln!("Rust impl: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(
            result.is_clean(),
            "Both adding methods to Rust impl should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("multiply"), "Should have multiply");
        assert!(result.content.contains("divide"), "Should have divide");
    }

    #[test]
    fn test_rust_impl_same_trait_different_types() {
        // Two impl blocks for the same trait but different types.
        // Each branch modifies a different impl. Both should be preserved.
        // Regression: sem-core <0.3.10 named both "Stream", causing collision.
        let base = r#"struct Foo;
struct Bar;

impl Stream for Foo {
    type Item = i32;
    fn poll_next(&self) -> Option<i32> {
        Some(1)
    }
}

impl Stream for Bar {
    type Item = String;
    fn poll_next(&self) -> Option<String> {
        Some("hello".into())
    }
}

fn other() {}
"#;
        let ours = r#"struct Foo;
struct Bar;

impl Stream for Foo {
    type Item = i32;
    fn poll_next(&self) -> Option<i32> {
        let x = compute();
        Some(x + 1)
    }
}

impl Stream for Bar {
    type Item = String;
    fn poll_next(&self) -> Option<String> {
        Some("hello".into())
    }
}

fn other() {}
"#;
        let theirs = r#"struct Foo;
struct Bar;

impl Stream for Foo {
    type Item = i32;
    fn poll_next(&self) -> Option<i32> {
        Some(1)
    }
}

impl Stream for Bar {
    type Item = String;
    fn poll_next(&self) -> Option<String> {
        let s = format!("hello {}", name);
        Some(s)
    }
}

fn other() {}
"#;
        let result = entity_merge(base, ours, theirs, "test.rs");
        assert!(
            result.is_clean(),
            "Same trait, different types should not conflict. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("impl Stream for Foo"), "Should have Foo impl");
        assert!(result.content.contains("impl Stream for Bar"), "Should have Bar impl");
        assert!(result.content.contains("compute()"), "Should have ours' Foo change");
        assert!(result.content.contains("format!"), "Should have theirs' Bar change");
    }

    #[test]
    fn test_rust_doc_comment_plus_body_change() {
        // One side adds Rust doc comment, other modifies body
        // Comment bundling ensures the doc comment is part of the entity
        let base = r#"fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn subtract(a: i32, b: i32) -> i32 {
    a - b
}
"#;
        let ours = r#"/// Adds two numbers together.
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn subtract(a: i32, b: i32) -> i32 {
    a - b
}
"#;
        let theirs = r#"fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn subtract(a: i32, b: i32) -> i32 {
    a - b - 1
}
"#;
        let result = entity_merge(base, ours, theirs, "test.rs");
        assert!(
            result.is_clean(),
            "Rust doc comment + body change should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("/// Adds two numbers"), "Should have ours doc comment");
        assert!(result.content.contains("a - b - 1"), "Should have theirs body change");
    }

    #[test]
    fn test_both_add_different_doc_comments() {
        // Both add doc comments to different functions — should merge cleanly
        let base = r#"fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn subtract(a: i32, b: i32) -> i32 {
    a - b
}
"#;
        let ours = r#"/// Adds two numbers.
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn subtract(a: i32, b: i32) -> i32 {
    a - b
}
"#;
        let theirs = r#"fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Subtracts b from a.
fn subtract(a: i32, b: i32) -> i32 {
    a - b
}
"#;
        let result = entity_merge(base, ours, theirs, "test.rs");
        assert!(
            result.is_clean(),
            "Both adding doc comments to different functions should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("/// Adds two numbers"), "Should have add's doc comment");
        assert!(result.content.contains("/// Subtracts b from a"), "Should have subtract's doc comment");
    }

    #[test]
    fn test_go_import_block_both_add_different() {
        // Go uses import (...) blocks — both add different imports
        let base = "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\"hello\")\n}\n";
        let ours = "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tfmt.Println(\"hello\")\n}\n";
        let theirs = "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"io\"\n)\n\nfunc main() {\n\tfmt.Println(\"hello\")\n}\n";
        let result = entity_merge(base, ours, theirs, "main.go");
        eprintln!("Go import block: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        // This tests whether Go import blocks (a single entity) get inner-merged
    }

    #[test]
    fn test_python_class_both_add_methods() {
        // Python class — both add different methods
        let base = "class Calculator:\n    def add(self, a, b):\n        return a + b\n";
        let ours = "class Calculator:\n    def add(self, a, b):\n        return a + b\n\n    def multiply(self, a, b):\n        return a * b\n";
        let theirs = "class Calculator:\n    def add(self, a, b):\n        return a + b\n\n    def divide(self, a, b):\n        return a / b\n";
        let result = entity_merge(base, ours, theirs, "test.py");
        eprintln!("Python class: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(
            result.is_clean(),
            "Both adding methods to Python class should merge. Conflicts: {:?}",
            result.conflicts,
        );
        assert!(result.content.contains("multiply"), "Should have multiply");
        assert!(result.content.contains("divide"), "Should have divide");
    }

    #[test]
    fn test_interstitial_conflict_not_silently_embedded() {
        // Regression test: when interstitial content between entities has a
        // both-modified conflict, merge_interstitials must report it as a real
        // conflict instead of silently embedding raw diffy markers and claiming
        // is_clean=true.
        //
        // Scenario: a barrel export file (index.ts) with comments between
        // export statements. Both sides modify the SAME interstitial comment
        // block differently. The exports are the entities; the comment between
        // them is interstitial content that goes through merge_interstitials
        // → diffy, which cannot auto-merge conflicting edits.
        let base = r#"export { alpha } from "./alpha";

// Section: data utilities
// TODO: add more exports here

export { beta } from "./beta";
"#;
        let ours = r#"export { alpha } from "./alpha";

// Section: data utilities (sorting)
// Sorting helpers for list views

export { beta } from "./beta";
"#;
        let theirs = r#"export { alpha } from "./alpha";

// Section: data utilities (filtering)
// Filtering helpers for search views

export { beta } from "./beta";
"#;
        let result = entity_merge(base, ours, theirs, "index.ts");

        // The key assertions:
        // 1. If the content has conflict markers, is_clean() MUST be false
        let has_markers = result.content.contains("<<<<<<<") || result.content.contains(">>>>>>>");
        if has_markers {
            assert!(
                !result.is_clean(),
                "BUG: is_clean()=true but merged content has conflict markers!\n\
                 stats: {}\nconflicts: {:?}\ncontent:\n{}",
                result.stats, result.conflicts, result.content
            );
            assert!(
                result.stats.entities_conflicted > 0,
                "entities_conflicted should be > 0 when markers are present"
            );
        }

        // 2. If it was resolved cleanly, no markers should exist
        if result.is_clean() {
            assert!(
                !has_markers,
                "Clean merge should not contain conflict markers!\ncontent:\n{}",
                result.content
            );
        }
    }

    #[test]
    fn test_pre_conflicted_input_not_treated_as_clean() {
        // Regression test for AU/AA conflicts: git can store conflict markers
        // directly into stage blobs. Weave must not return is_clean=true.
        let base = "";
        let theirs = "";
        let ours = r#"/**
 * MIT License
 */

<<<<<<<< HEAD:src/lib/exports/index.ts
export { renderDocToBuffer } from "./doc-exporter";
export type { ExportOptions, ExportMetadata, RenderContext } from "./types";
========
export * from "./editor";
export * from "./types";
>>>>>>>> feature:packages/core/src/editor/index.ts
"#;
        let result = entity_merge(base, ours, theirs, "index.ts");

        assert!(
            !result.is_clean(),
            "Pre-conflicted input must not be reported as clean!\n\
             stats: {}\nconflicts: {:?}",
            result.stats, result.conflicts,
        );
        assert!(result.stats.entities_conflicted > 0);
        assert!(!result.conflicts.is_empty());
    }

    #[test]
    fn test_multi_line_signature_classified_as_syntax() {
        // Multi-line parameter list: changing a param should be Syntax, not Functional
        let base = "function process(\n    a: number,\n    b: string\n) {\n    return a;\n}\n";
        let ours = "function process(\n    a: number,\n    b: string,\n    c: boolean\n) {\n    return a;\n}\n";
        let theirs = "function process(\n    a: number,\n    b: number\n) {\n    return a;\n}\n";
        let complexity = crate::conflict::classify_conflict(Some(base), Some(ours), Some(theirs));
        assert_eq!(
            complexity,
            crate::conflict::ConflictComplexity::Syntax,
            "Multi-line signature change should be classified as Syntax, got {:?}",
            complexity
        );
    }

    #[test]
    fn test_grouped_import_merge_preserves_groups() {
        let base = "import os\nimport sys\n\nfrom collections import OrderedDict\nfrom typing import List\n";
        let ours = "import os\nimport sys\nimport json\n\nfrom collections import OrderedDict\nfrom typing import List\n";
        let theirs = "import os\nimport sys\n\nfrom collections import OrderedDict\nfrom collections import defaultdict\nfrom typing import List\n";
        let result = merge_imports_commutatively(base, ours, theirs);
        // json should be in the first group (stdlib), defaultdict in the second (collections)
        let lines: Vec<&str> = result.lines().collect();
        let json_idx = lines.iter().position(|l| l.contains("json"));
        let blank_idx = lines.iter().position(|l| l.trim().is_empty());
        let defaultdict_idx = lines.iter().position(|l| l.contains("defaultdict"));
        assert!(json_idx.is_some(), "json import should be present");
        assert!(blank_idx.is_some(), "blank line separator should be present");
        assert!(defaultdict_idx.is_some(), "defaultdict import should be present");
        // json should come before the blank line, defaultdict after
        assert!(json_idx.unwrap() < blank_idx.unwrap(), "json should be in first group");
        assert!(defaultdict_idx.unwrap() > blank_idx.unwrap(), "defaultdict should be in second group");
    }

    #[test]
    fn test_configurable_duplicate_threshold() {
        // Create entities with 15 same-name entities
        let entities: Vec<SemanticEntity> = (0..15).map(|i| SemanticEntity {
            id: format!("test::function::test_{}", i),
            file_path: "test.ts".to_string(),
            entity_type: "function".to_string(),
            name: "test".to_string(),
            parent_id: None,
            content: format!("function test() {{ return {}; }}", i),
            content_hash: format!("hash_{}", i),
            structural_hash: None,
            start_line: i * 3 + 1,
            end_line: i * 3 + 3,
            metadata: None,
        }).collect();
        // Default threshold (10): should trigger
        assert!(has_excessive_duplicates(&entities));
        // Set threshold to 20: should not trigger
        std::env::set_var("WEAVE_MAX_DUPLICATES", "20");
        assert!(!has_excessive_duplicates(&entities));
        std::env::remove_var("WEAVE_MAX_DUPLICATES");
    }

    #[test]
    fn test_ts_multiline_import_consolidation() {
        // Issue #24: when incoming consolidates two imports into one multi-line import,
        // the `import {` opening line can get dropped.
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let ours = base;
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import consolidation: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        // Theirs is the only change, result should match theirs exactly
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type Foo,"), "type Foo must be present");
        assert!(result.content.contains("} from \"./foo\""), "closing must be present");
        assert!(!result.content.contains("import type { Foo }"), "old separate import should be removed");
    }

    #[test]
    fn test_ts_multiline_import_both_modify() {
        // Issue #24 variant: both sides modify the import block
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        // Ours: consolidates imports + adds type d
        let ours = "\
import {
     type Foo,
     type a,
     type b,
     type c,
     type d,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        // Theirs: consolidates imports + adds type e
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
     type e,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import both modify: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type Foo,"), "type Foo must be present");
        assert!(result.content.contains("type d,"), "ours addition must be present");
        assert!(result.content.contains("type e,"), "theirs addition must be present");
        assert!(result.content.contains("} from \"./foo\""), "closing must be present");
    }

    #[test]
    fn test_ts_multiline_import_no_entities() {
        // Issue #24: file with only imports, no other entities
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"
";
        let ours = base;
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import no entities: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type Foo,"), "type Foo must be present");
    }

    #[test]
    fn test_ts_multiline_import_export_variable() {
        // Issue #24: import block near an export variable entity
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"

export const X = 1;

export function bar() {
    return 1;
}
";
        let ours = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
     type d,
} from \"./foo\"

export const X = 1;

export function bar() {
    return 1;
}
";
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"

export const X = 2;

export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import + export var: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
    }

    #[test]
    fn test_ts_multiline_import_adjacent_to_entity() {
        // Issue #24: import block directly adjacent to entity (no blank line)
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"
export function bar() {
    return 1;
}
";
        let ours = base;
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"
export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import adjacent: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type Foo,"), "type Foo must be present");
    }

    #[test]
    fn test_ts_multiline_import_both_consolidate_differently() {
        // Issue #24: both sides consolidate imports but add different specifiers
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let ours = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type d,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS both consolidate: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type Foo,"), "type Foo must be present");
        assert!(result.content.contains("} from \"./foo\""), "closing must be present");
    }

    #[test]
    fn test_ts_multiline_import_ours_adds_theirs_consolidates() {
        // Issue #24 variant: ours adds new import, theirs consolidates
        let base = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        // Ours: adds a new specifier to the multiline import
        let ours = "\
import type { Foo } from \"./foo\"
import {
     type a,
     type b,
     type c,
     type d,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        // Theirs: consolidates into one import
        let theirs = "\
import {
     type Foo,
     type a,
     type b,
     type c,
} from \"./foo\"

export function bar() {
    return 1;
}
";
        let result = entity_merge(base, ours, theirs, "test.ts");
        eprintln!("TS import ours-adds theirs-consolidates: clean={}, conflicts={:?}", result.is_clean(), result.conflicts);
        eprintln!("Content:\n{}", result.content);
        assert!(result.content.contains("import {"), "import {{ must not be dropped");
        assert!(result.content.contains("type d,"), "ours addition must be present");
        assert!(result.content.contains("} from \"./foo\""), "closing must be present");
    }

    #[test]
    fn test_rename_plus_modify_auto_resolves() {
        // Issue #53: ours renames a variable (IDE rename symbol), theirs modifies it.
        // Should detect the rename via token similarity and merge cleanly.
        let base = r#"export const cubeQueryExecutorTool = tool({
    name: "cubeQueryExecutorTool",
    description: "Execute a cube query",
    schema: z.object({ query: z.string() }),
    execute: async (input) => {
        return await runQuery(input.query);
    },
});
"#;
        // Ours: renamed cubeQueryExecutorTool → cubeQueryTool (all refs updated)
        let ours = r#"export const cubeQueryTool = tool({
    name: "cubeQueryTool",
    description: "Execute a cube query",
    schema: z.object({ query: z.string() }),
    execute: async (input) => {
        return await runQuery(input.query);
    },
});
"#;
        // Theirs: modified the body (added unit inference logic)
        let theirs = r#"export const cubeQueryExecutorTool = tool({
    name: "cubeQueryExecutorTool",
    description: "Execute a cube query with unit inference",
    schema: z.object({ query: z.string(), unit: z.string().optional() }),
    execute: async (input) => {
        const unit = input.unit || inferUnit(input.query);
        return await runQuery(input.query, unit);
    },
});
"#;
        let result = entity_merge(base, ours, theirs, "cubeQueryTool.ts");
        // Rename + modify should conflict (developer who modified didn't know about rename)
        assert_eq!(result.conflicts.len(), 1, "Should have exactly one conflict");
        assert!(
            matches!(result.conflicts[0].kind, ConflictKind::RenameModify { renamed_in_ours: true, .. }),
            "Should be a RenameModify conflict, got: {:?}",
            result.conflicts[0].kind
        );
        // Both versions should be present in the conflict
        assert!(result.content.contains("cubeQueryTool"), "Ours (renamed) should be in conflict markers");
        assert!(result.content.contains("unit inference"), "Theirs (modified) should be in conflict markers");
    }
}