agentty 0.9.2

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Merge, rebase, and cleanup workflows for session branches.

use std::collections::hash_map::DefaultHasher;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use askama::Template;
use tokio::sync::mpsc;
use tracing::warn;

use super::{SessionTaskService, session_branch};
use crate::app::assist::{
    AssistContext, AssistPolicy, FailureTracker, append_assist_header, format_detail_lines,
    run_agent_assist,
};
use crate::app::service::SessionUpdateVersionMap;
use crate::app::session::{Clock, SessionError};
use crate::app::{AppEvent, AppServices, ProjectManager, SessionManager};
use crate::domain::agent::{AgentModel, ReasoningLevel};
use crate::domain::session::{PublishedBranchSyncStatus, SessionId, Status};
use crate::domain::transcript_notice::TranscriptNotice;
use crate::infra::agent;
use crate::infra::agent::protocol::AgentResponseSummary;
use crate::infra::db::AppRepositories;
use crate::infra::fs::{self as fs, FsClient};
use crate::infra::git::{self as git, GitClient};

const REBASE_ASSIST_POLICY: AssistPolicy = AssistPolicy {
    max_attempts: 3,
    // Allow up to 3 consecutive identical-content observations before
    // giving up, so the agent gets a genuine second chance when partial
    // progress is made inside a file without fully clearing all markers.
    max_identical_failure_streak: 3,
};

/// Coordinates merge/rebase session workflows behind a dedicated service
/// boundary.
pub(crate) struct SessionMergeService;

/// Askama view model for rendering rebase conflict-assistance prompts.
#[derive(Template)]
#[template(path = "rebase_assist_prompt.md", escape = "none")]
struct RebaseAssistPromptTemplate<'a> {
    base_branch: &'a str,
    conflicted_files: &'a str,
}

/// Boxed async result used by sync conflict assistance boundary methods.
type SyncAssistFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Shared context needed to restore a failed merge-start attempt back to
/// `Review`.
struct MergeStartRestoreContext<'a> {
    app_event_tx: &'a mpsc::UnboundedSender<AppEvent>,
    clock: &'a dyn Clock,
    db: &'a AppRepositories,
    session_id: &'a str,
    session_update_versions: &'a SessionUpdateVersionMap,
    status: &'a Arc<Mutex<Status>>,
}

struct MergeTaskInput {
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    base_branch: String,
    child_pid: Arc<Mutex<Option<u32>>>,
    clock: Arc<dyn Clock>,
    db: AppRepositories,
    folder: PathBuf,
    fs_client: Arc<dyn FsClient>,
    git_client: Arc<dyn GitClient>,
    id: SessionId,
    output: Arc<Mutex<String>>,
    repo_root: PathBuf,
    session_model: AgentModel,
    session_update_versions: SessionUpdateVersionMap,
    source_branch: String,
    status: Arc<Mutex<Status>>,
}

#[derive(Clone)]
struct RebaseAssistInput {
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    child_pid: Arc<Mutex<Option<u32>>>,
    db: AppRepositories,
    folder: PathBuf,
    fs_client: Arc<dyn FsClient>,
    git_client: Arc<dyn GitClient>,
    id: SessionId,
    output: Arc<Mutex<String>>,
    rebase_target: String,
    session_model: AgentModel,
    session_update_versions: SessionUpdateVersionMap,
}

struct RebaseTaskInput {
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    base_branch: String,
    child_pid: Arc<Mutex<Option<u32>>>,
    clock: Arc<dyn Clock>,
    db: AppRepositories,
    folder: PathBuf,
    fs_client: Arc<dyn FsClient>,
    git_client: Arc<dyn GitClient>,
    id: SessionId,
    output: Arc<Mutex<String>>,
    session_model: AgentModel,
    session_update_versions: SessionUpdateVersionMap,
    status: Arc<Mutex<Status>>,
}

/// Bundled context for finalizing one rebase task.
struct FinalizeRebaseInput<'a> {
    app_event_tx: &'a mpsc::UnboundedSender<AppEvent>,
    clock: &'a dyn Clock,
    db: &'a AppRepositories,
    folder: &'a Path,
    git_client: &'a Arc<dyn GitClient>,
    id: &'a str,
    output: &'a Arc<Mutex<String>>,
    rebase_result: Result<String, SessionError>,
    session_update_versions: &'a SessionUpdateVersionMap,
    status: &'a Arc<Mutex<Status>>,
}

/// Bundled context for finalizing one merge task.
struct FinalizeMergeInput<'a> {
    clock: &'a dyn Clock,
    db: &'a AppRepositories,
    app_event_tx: &'a mpsc::UnboundedSender<AppEvent>,
    id: &'a str,
    output: &'a Arc<Mutex<String>>,
    result: Result<String, SessionError>,
    session_update_versions: &'a SessionUpdateVersionMap,
    status: &'a Arc<Mutex<Status>>,
}

/// Input context for assisted conflict resolution during `sync main`.
struct SyncRebaseAssistInput {
    base_branch: String,
    folder: PathBuf,
    fs_client: Arc<dyn FsClient>,
    git_client: Arc<dyn GitClient>,
    session_model: AgentModel,
    sync_assist_client: Arc<dyn SyncAssistClient>,
}

/// Polymorphic input for shared assisted rebase loop orchestration.
enum RebaseAssistLoopInput {
    Session(RebaseAssistInput),
    Project(SyncRebaseAssistInput),
}

impl RebaseAssistLoopInput {
    /// Returns worktree path used for conflict fingerprinting.
    fn folder(&self) -> &Path {
        match self {
            Self::Session(input) => &input.folder,
            Self::Project(input) => &input.folder,
        }
    }

    /// Returns the filesystem boundary used by assist fingerprinting.
    fn fs_client(&self) -> &dyn FsClient {
        match self {
            Self::Session(input) => input.fs_client.as_ref(),
            Self::Project(input) => input.fs_client.as_ref(),
        }
    }

    /// Builds conflict-state no-progress error text for the active workflow.
    fn repeated_conflict_state_error(&self, detail: &str) -> String {
        match self {
            Self::Session(_) => format!(
                "Rebase assistance made no progress: repeated identical conflict state. Last \
                 detail: {detail}"
            ),
            Self::Project(_) => format!(
                "Sync rebase assistance made no progress: repeated identical conflict state. Last \
                 detail: {detail}"
            ),
        }
    }

    /// Builds unchanged-conflict-files no-progress error text for the active
    /// workflow.
    fn unchanged_conflict_files_error(&self) -> String {
        match self {
            Self::Session(_) => {
                "Rebase assistance made no progress: conflicted files did not change".to_string()
            }
            Self::Project(_) => "Sync rebase assistance made no progress: conflicted files did \
                                 not change"
                .to_string(),
        }
    }

    /// Builds unresolved-conflict-after-assistance error text for the active
    /// workflow.
    fn still_conflicted_error(&self, detail: &str) -> String {
        match self {
            Self::Session(_) => format!("Rebase still has conflicts after assistance: {detail}"),
            Self::Project(_) => {
                format!("Sync rebase still has conflicts after assistance: {detail}")
            }
        }
    }

    /// Returns final exhausted-attempts error text for the active workflow.
    fn exhausted_error(&self) -> String {
        match self {
            Self::Session(_) => "Failed to complete assisted rebase".to_string(),
            Self::Project(_) => "Failed to complete assisted sync rebase".to_string(),
        }
    }

    /// Loads conflicted files for the active workflow.
    ///
    /// # Errors
    /// Returns an error if conflicted-file inspection fails.
    async fn load_conflicted_files(
        &self,
        previous_conflict_files: &[String],
    ) -> Result<Vec<String>, SessionError> {
        match self {
            Self::Session(input) => {
                SessionManager::load_conflicted_files(input, previous_conflict_files).await
            }
            Self::Project(input) => {
                SessionManager::load_sync_conflicted_files(input, previous_conflict_files).await
            }
        }
    }

    /// Executes one assistance attempt for the active workflow.
    ///
    /// # Errors
    /// Returns an error when assistance command execution fails.
    async fn run_assist_attempt(
        &self,
        assist_attempt: usize,
        conflicted_files: &[String],
    ) -> Result<(), SessionError> {
        match self {
            Self::Session(input) => {
                SessionManager::append_rebase_assist_header(
                    input,
                    assist_attempt,
                    conflicted_files,
                )
                .await;
                SessionManager::run_rebase_assist_agent(input, conflicted_files).await
            }
            Self::Project(input) => {
                SessionManager::run_sync_rebase_assist_agent(input, conflicted_files).await
            }
        }
    }

    /// Stages edits and checks whether conflicts remain for the active
    /// workflow.
    ///
    /// # Errors
    /// Returns an error when staging or conflict checks fail.
    async fn stage_and_check_for_conflicts(
        &self,
        conflict_files: &[String],
    ) -> Result<bool, SessionError> {
        match self {
            Self::Session(input) => {
                SessionManager::stage_and_check_for_conflicts(input, conflict_files).await
            }
            Self::Project(input) => {
                SessionManager::stage_and_check_for_sync_conflicts(input, conflict_files).await
            }
        }
    }

    /// Continues in-progress rebase for the active workflow.
    ///
    /// # Errors
    /// Returns an error when `git rebase --continue` fails with non-conflict
    /// errors.
    async fn run_rebase_continue(&self) -> Result<git::RebaseStepResult, SessionError> {
        match self {
            Self::Session(input) => SessionManager::run_rebase_continue(input).await,
            Self::Project(input) => SessionManager::run_sync_rebase_continue(input).await,
        }
    }

    /// Aborts rebase for the active workflow after assistance failure.
    async fn abort_rebase_after_assist_failure(&self) {
        match self {
            Self::Session(input) => {
                SessionManager::abort_rebase_after_assist_failure(input).await;
            }
            Self::Project(input) => {
                SessionManager::abort_sync_rebase_after_assist_failure(input).await;
            }
        }
    }
}

/// Async boundary for one sync rebase assistance attempt.
#[cfg_attr(test, mockall::automock)]
trait SyncAssistClient: Send + Sync {
    /// Executes one agent-assisted edit attempt for the provided rebase prompt.
    fn resolve_rebase_conflicts(
        &self,
        folder: PathBuf,
        prompt: String,
        session_model: AgentModel,
    ) -> SyncAssistFuture<Result<(), SessionError>>;
}

/// Production sync-assistance executor backed by real agent commands.
struct RealSyncAssistClient;

impl RealSyncAssistClient {
    /// Runs one sync conflict assistance command through the shared one-shot
    /// agent submission path.
    ///
    /// # Errors
    /// Returns an error when the one-shot agent command fails.
    async fn run_assist_command(
        folder: PathBuf,
        prompt: String,
        session_model: AgentModel,
    ) -> Result<(), SessionError> {
        // Success payload unused; run for side effects only.
        let _ = agent::submit_one_shot(agent::OneShotRequest {
            child_pid: None,
            folder: &folder,
            model: session_model,
            prompt: &prompt,
            request_kind: crate::infra::channel::AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
        })
        .await
        .map_err(SessionError::Workflow)?;

        Ok(())
    }
}

impl SyncAssistClient for RealSyncAssistClient {
    fn resolve_rebase_conflicts(
        &self,
        folder: PathBuf,
        prompt: String,
        session_model: AgentModel,
    ) -> SyncAssistFuture<Result<(), SessionError>> {
        Box::pin(async move { Self::run_assist_command(folder, prompt, session_model).await })
    }
}

/// User-facing reasons why repository branch sync cannot be started.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum SyncSessionStartError {
    /// Sync cannot run while the selected project branch has local
    /// modifications.
    MainHasUncommittedChanges { default_branch: String },
    /// Generic start failure outside sync-specific policy constraints.
    Other(String),
}

/// Summary of one completed main-branch sync run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SyncMainOutcome {
    /// Commit titles discovered upstream and pulled during sync.
    pub(crate) pulled_commit_titles: Vec<String>,
    /// Number of commits rebased from upstream into the local branch.
    pub(crate) pulled_commits: Option<u32>,
    /// Commit titles discovered locally and pushed during sync.
    pub(crate) pushed_commit_titles: Vec<String>,
    /// Number of local commits pushed to upstream during sync.
    pub(crate) pushed_commits: Option<u32>,
    /// Paths that were conflicted and resolved during assisted sync rebase.
    pub(crate) resolved_conflict_files: Vec<String>,
}

/// Successful assisted rebase completion details.
#[derive(Debug)]
struct RebaseAssistOutcome {
    resolved_conflict_files: Vec<String>,
}

impl RebaseAssistOutcome {
    /// Creates an empty assisted-rebase completion payload.
    fn empty() -> Self {
        Self {
            resolved_conflict_files: Vec::new(),
        }
    }

    /// Adds conflicted file names and keeps the list unique and sorted.
    fn extend_resolved_conflict_files(&mut self, conflict_files: &[String]) {
        for conflict_file in conflict_files {
            if !self.resolved_conflict_files.contains(conflict_file) {
                self.resolved_conflict_files.push(conflict_file.clone());
            }
        }

        self.resolved_conflict_files.sort_unstable();
    }
}

impl SyncSessionStartError {
    /// Returns user-facing detail for non-popup sync start errors.
    pub(crate) fn detail_message(&self) -> String {
        match self {
            Self::MainHasUncommittedChanges { default_branch } => format!(
                "Sync cannot run while `{default_branch}` has uncommitted changes.\nCommit or \
                 stash changes in `{default_branch}`, then try again."
            ),
            Self::Other(detail) => detail.clone(),
        }
    }
}

impl SessionMergeService {
    /// Starts a squash merge for a review-ready or queued session branch in
    /// the background.
    ///
    /// # Errors
    /// Returns an error if the session is invalid for merge, required git
    /// metadata is missing, or the status transition to `Merging` fails.
    async fn merge_session(
        &self,
        manager: &SessionManager,
        session_id: &str,
        projects: &ProjectManager,
        services: &AppServices,
    ) -> Result<(), SessionError> {
        let session = manager
            .session_or_err(session_id)
            .map_err(|_| SessionError::NotFound)?;
        if !(session.status.allows_review_actions() || session.status == Status::Queued) {
            return Err(SessionError::Workflow(
                "Session must be in review or queued status".to_string(),
            ));
        }

        let (db, folder, id, session_model) = (
            services.db().clone(),
            session.folder.clone(),
            session.id.clone(),
            session.model,
        );
        let (app_event_tx, clock, fs_client, git_client, session_update_versions) = (
            services.event_sender(),
            services.clock(),
            services.fs_client(),
            manager.git_client(),
            services.session_update_versions(),
        );

        let handles = manager
            .session_handles_or_err(session_id)
            .map_err(|_| SessionError::HandlesNotFound)?;
        let (child_pid, output, status) = (
            Arc::clone(&handles.child_pid),
            Arc::clone(&handles.output),
            Arc::clone(&handles.status),
        );
        let restore_context = MergeStartRestoreContext {
            app_event_tx: &app_event_tx,
            clock: clock.as_ref(),
            db: &db,
            session_id: &id,
            session_update_versions: &session_update_versions,
            status: &status,
        };
        if !SessionTaskService::update_status(
            &status,
            clock.as_ref(),
            &db,
            &app_event_tx,
            &session_update_versions,
            &id,
            Status::Merging,
        )
        .await
        {
            return Err(SessionError::Workflow(
                "Invalid status transition to Merging".to_string(),
            ));
        }

        let base_branch = Self::load_merge_base_branch(&restore_context).await?;
        let repo_root = Self::find_merge_repo_root(
            git_client.as_ref(),
            projects.working_dir().to_path_buf(),
            &restore_context,
        )
        .await?;
        Self::ensure_merge_target_clean(
            git_client.as_ref(),
            repo_root.clone(),
            &base_branch,
            &restore_context,
        )
        .await?;

        let merge_task_input = MergeTaskInput {
            app_event_tx,
            base_branch,
            child_pid,
            clock,
            db,
            folder,
            fs_client,
            git_client,
            id: id.clone(),
            output,
            repo_root,
            session_model,
            session_update_versions,
            source_branch: session_branch(&id),
            status,
        };
        tokio::spawn(async move {
            SessionManager::run_merge_task(merge_task_input).await;
        });

        Ok(())
    }

    /// Restores a failed merge-start attempt to `Review` status without
    /// masking the original error.
    async fn restore_review_status(context: &MergeStartRestoreContext<'_>) {
        if !SessionTaskService::update_status(
            context.status,
            context.clock,
            context.db,
            context.app_event_tx,
            context.session_update_versions,
            context.session_id,
            Status::Review,
        )
        .await
        {
            warn!(
                session_id = context.session_id,
                "skipped restoring review status because the in-memory status was already current"
            );
        }
    }

    /// Loads the persisted base branch for a mergeable session or restores the
    /// session to `Review` when required metadata is missing.
    ///
    /// # Errors
    /// Returns an error when the session lacks a worktree-backed base branch
    /// or when reading the metadata from persistence fails.
    async fn load_merge_base_branch(
        context: &MergeStartRestoreContext<'_>,
    ) -> Result<String, SessionError> {
        match context
            .db
            .sessions()
            .get_session_base_branch(context.session_id)
            .await
        {
            Ok(Some(base_branch)) => Ok(base_branch),
            Ok(None) => {
                Self::restore_review_status(context).await;

                Err(SessionError::Workflow(
                    "No git worktree for this session".to_string(),
                ))
            }
            Err(error) => {
                Self::restore_review_status(context).await;

                Err(SessionError::Db(error))
            }
        }
    }

    /// Resolves the main repository root for a mergeable session or restores
    /// the session to `Review` when the repository cannot be found.
    ///
    /// # Errors
    /// Returns an error when the repository root cannot be discovered.
    async fn find_merge_repo_root(
        git_client: &dyn GitClient,
        working_dir: PathBuf,
        context: &MergeStartRestoreContext<'_>,
    ) -> Result<PathBuf, SessionError> {
        if let Some(repo_root) = git_client.find_git_repo_root(working_dir).await {
            return Ok(repo_root);
        }

        Self::restore_review_status(context).await;

        Err(SessionError::Workflow(
            "Failed to find git repository root".to_string(),
        ))
    }

    /// Verifies the merge target checkout is clean before starting a squash
    /// merge task, restoring the session to `Review` when merge cannot start.
    ///
    /// # Errors
    /// Returns an error when git status cannot be inspected or when the target
    /// checkout has local changes that would make the merge unsafe.
    async fn ensure_merge_target_clean(
        git_client: &dyn GitClient,
        repo_root: PathBuf,
        base_branch: &str,
        context: &MergeStartRestoreContext<'_>,
    ) -> Result<(), SessionError> {
        let is_clean = match git_client.is_worktree_clean(repo_root).await {
            Ok(is_clean) => is_clean,
            Err(error) => {
                Self::restore_review_status(context).await;

                return Err(SessionError::Workflow(format!(
                    "Failed to inspect `{base_branch}` before merge: {error}"
                )));
            }
        };
        if is_clean {
            return Ok(());
        }

        Self::restore_review_status(context).await;

        Err(SessionError::Workflow(format!(
            "Merge cannot run while `{base_branch}` has uncommitted changes.\nCommit or stash \
             changes in `{base_branch}`, then try again."
        )))
    }

    /// Rebases a reviewed session branch onto its base branch.
    ///
    /// # Errors
    /// Returns an error if the session is invalid for rebase, required git
    /// metadata is missing, or starting the rebase task fails.
    async fn rebase_session(
        &self,
        manager: &SessionManager,
        services: &AppServices,
        session_id: &str,
    ) -> Result<(), SessionError> {
        let session = manager
            .session_or_err(session_id)
            .map_err(|_| SessionError::NotFound)?;
        if !session.status.allows_review_actions() {
            return Err(SessionError::Workflow(
                "Session must be in review status".to_string(),
            ));
        }

        let base_branch = services
            .db()
            .sessions()
            .get_session_base_branch(&session.id)
            .await?
            .ok_or_else(|| {
                SessionError::Workflow("No git worktree for this session".to_string())
            })?;

        let handles = manager
            .session_handles_or_err(session_id)
            .map_err(|_| SessionError::HandlesNotFound)?;
        let child_pid = Arc::clone(&handles.child_pid);
        let output = Arc::clone(&handles.output);

        let status = Arc::clone(&handles.status);
        let db = services.db().clone();
        let app_event_tx = services.event_sender();
        let clock = services.clock();
        let fs_client = services.fs_client();
        let git_client = manager.git_client();
        let session_update_versions = services.session_update_versions();

        if !SessionTaskService::update_status(
            &status,
            clock.as_ref(),
            &db,
            &app_event_tx,
            &session_update_versions,
            &session.id,
            Status::Rebasing,
        )
        .await
        {
            return Err(SessionError::Workflow(
                "Invalid status transition to Rebasing".to_string(),
            ));
        }

        let id = session.id.clone();
        let session_model = session.model;

        let rebase_task_input = RebaseTaskInput {
            app_event_tx,
            base_branch,
            child_pid,
            clock,
            db,
            folder: session.folder.clone(),
            fs_client,
            git_client,
            id,
            output,
            session_model,
            session_update_versions,
            status,
        };
        tokio::spawn(async move {
            SessionManager::run_rebase_task(rebase_task_input).await;
        });

        Ok(())
    }
}

impl SessionManager {
    /// Starts a squash merge for a review-ready or queued session branch in
    /// the background.
    ///
    /// # Errors
    /// Returns an error if the session is invalid for merge, required git
    /// metadata is missing, or the status transition to `Merging` fails.
    pub async fn merge_session(
        &self,
        session_id: &str,
        projects: &ProjectManager,
        services: &AppServices,
    ) -> Result<(), SessionError> {
        self.merge_service()
            .merge_session(self, session_id, projects, services)
            .await
    }

    async fn run_merge_task(input: MergeTaskInput) {
        let output = Arc::clone(&input.output);
        let clock = Arc::clone(&input.clock);
        let db = input.db.clone();
        let app_event_tx = input.app_event_tx.clone();
        let id = input.id.clone();
        let status = Arc::clone(&input.status);
        let session_update_versions = input.session_update_versions.clone();

        let merge_result = Self::execute_merge_workflow(input).await;
        Self::finalize_merge_task(FinalizeMergeInput {
            clock: clock.as_ref(),
            db: &db,
            app_event_tx: &app_event_tx,
            id: &id,
            output: &output,
            result: merge_result,
            session_update_versions: &session_update_versions,
            status: &status,
        })
        .await;
    }

    /// Executes the merge workflow for one session branch.
    ///
    /// # Errors
    /// Returns an error when the rebase step fails, the canonical session
    /// commit message cannot be loaded, squash-merge git commands fail, status
    /// transitions are invalid, or worktree cleanup fails.
    async fn execute_merge_workflow(input: MergeTaskInput) -> Result<String, SessionError> {
        let rebase_input = Self::merge_rebase_input(&input);
        let MergeTaskInput {
            app_event_tx,
            base_branch,
            clock,
            db,
            folder,
            fs_client,
            git_client,
            id,
            output: _,
            repo_root,
            source_branch,
            session_update_versions,
            status,
            ..
        } = input;

        // Rebase onto the base branch first to ensure the merge is clean and
        // includes all recent changes. This also handles auto-commit and
        // conflict resolution via the agent.
        if let Err(error) = Self::execute_rebase_workflow(rebase_input).await {
            return Err(SessionError::Workflow(format!(
                "Merge failed during rebase step: {error}"
            )));
        }

        let squash_diff = Self::load_squash_diff(
            git_client.as_ref(),
            repo_root.clone(),
            source_branch.clone(),
            base_branch.clone(),
        )
        .await?;
        let authoritative_commit_message = if squash_diff.trim().is_empty() {
            None
        } else {
            Some(
                Self::load_authoritative_session_commit_message(
                    git_client.as_ref(),
                    folder.clone(),
                )
                .await?,
            )
        };
        let merge_outcome = if let Some(commit_message) = authoritative_commit_message.as_ref() {
            let repo_root = repo_root.clone();
            let source_branch = source_branch.clone();
            let base_branch = base_branch.clone();
            let commit_message = commit_message.clone();

            git_client
                .squash_merge(repo_root, source_branch, base_branch, commit_message)
                .await?
        } else {
            git::SquashMergeOutcome::AlreadyPresentInTarget
        };
        let merged_commit_hash =
            Self::load_merged_commit_hash(git_client.as_ref(), repo_root.clone(), merge_outcome)
                .await?;

        Self::cleanup_merged_session_worktree(
            folder.clone(),
            Arc::clone(&fs_client),
            Arc::clone(&git_client),
            source_branch.clone(),
            Some(repo_root),
        )
        .await
        .map_err(|error| {
            SessionError::Workflow(format!(
                "Merged successfully but failed to remove worktree: {error}"
            ))
        })?;

        Self::persist_merged_session_metadata(
            &db,
            &id,
            authoritative_commit_message.as_deref(),
            merged_commit_hash.as_deref(),
            &app_event_tx,
        )
        .await?;

        if !SessionTaskService::update_status(
            &status,
            clock.as_ref(),
            &db,
            &app_event_tx,
            &session_update_versions,
            &id,
            Status::Done,
        )
        .await
        {
            return Err(SessionError::Workflow(
                "Invalid status transition to Done".to_string(),
            ));
        }

        Ok(Self::merge_success_message(
            &source_branch,
            &base_branch,
            merge_outcome,
        ))
    }

    /// Persists post-merge metadata derived from the authoritative session
    /// commit message and merged base-branch commit hash.
    ///
    /// # Errors
    /// Returns an error when the merged commit hash cannot be saved.
    async fn persist_merged_session_metadata(
        db: &AppRepositories,
        session_id: &str,
        authoritative_commit_message: Option<&str>,
        merged_commit_hash: Option<&str>,
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
    ) -> Result<(), SessionError> {
        if let Some(commit_message) = authoritative_commit_message {
            Self::update_session_title_from_commit_message(
                db,
                session_id,
                commit_message,
                app_event_tx,
            )
            .await;
            Self::update_done_session_summary_from_commit_message(db, session_id, commit_message)
                .await;
        }
        if let Some(merged_commit_hash) = merged_commit_hash {
            db.sessions()
                .update_session_merged_commit_hash(session_id, Some(merged_commit_hash.to_string()))
                .await?;
        }

        Ok(())
    }

    /// Loads the target-branch `HEAD` hash created by one completed squash
    /// merge, when the merge produced a new commit.
    ///
    /// # Errors
    /// Returns an error when the merged commit hash cannot be inspected after
    /// a successful squash commit.
    async fn load_merged_commit_hash(
        git_client: &dyn GitClient,
        repo_root: PathBuf,
        merge_outcome: git::SquashMergeOutcome,
    ) -> Result<Option<String>, SessionError> {
        if merge_outcome != git::SquashMergeOutcome::Committed {
            return Ok(None);
        }

        let merged_commit_hash = git_client.head_hash(repo_root).await?;

        Ok(Some(merged_commit_hash))
    }

    /// Builds rebase input used by merge workflows.
    fn merge_rebase_input(input: &MergeTaskInput) -> RebaseAssistInput {
        RebaseAssistInput {
            app_event_tx: input.app_event_tx.clone(),
            child_pid: Arc::clone(&input.child_pid),
            db: input.db.clone(),
            folder: input.folder.clone(),
            fs_client: Arc::clone(&input.fs_client),
            git_client: Arc::clone(&input.git_client),
            id: input.id.clone(),
            output: Arc::clone(&input.output),
            rebase_target: input.base_branch.clone(),
            session_model: input.session_model,
            session_update_versions: input.session_update_versions.clone(),
        }
    }

    /// Loads the squash-diff preview for one merge candidate.
    ///
    /// # Errors
    /// Returns an error when the diff cannot be generated.
    async fn load_squash_diff(
        git_client: &dyn GitClient,
        repo_root: PathBuf,
        source_branch: String,
        base_branch: String,
    ) -> Result<String, SessionError> {
        git_client
            .squash_merge_diff(repo_root, source_branch, base_branch)
            .await
            .map_err(|error| {
                SessionError::Workflow(format!("Failed to inspect merge diff: {error}"))
            })
    }

    /// Loads the canonical session commit message from the worktree `HEAD` for
    /// reuse during squash merge.
    ///
    /// # Errors
    /// Returns an error when `HEAD` cannot be inspected or does not contain a
    /// non-blank commit message.
    async fn load_authoritative_session_commit_message(
        git_client: &dyn GitClient,
        folder: PathBuf,
    ) -> Result<String, SessionError> {
        let commit_message = git_client.head_commit_message(folder).await?;
        let Some(commit_message) = commit_message else {
            return Err(SessionError::Workflow(
                "Session branch has no commit message to reuse for merge".to_string(),
            ));
        };
        let trimmed_commit_message = commit_message.trim();
        if trimmed_commit_message.is_empty() {
            return Err(SessionError::Workflow(
                "Session branch has a blank commit message to reuse for merge".to_string(),
            ));
        }

        Ok(trimmed_commit_message.to_string())
    }

    /// Finalizes one merge task by reporting the outcome and restoring review
    /// state only when the merge failed.
    ///
    /// Successful merges request an immediate git-status refresh so footer
    /// branch stats reflect the new refs without waiting for the periodic
    /// poller. The success notice is transient so the completed transcript does
    /// not persist merge bookkeeping as standalone chat content. The `Done`
    /// status transition also emits a full session refresh, which refreshes
    /// active-project roadmap task data.
    async fn finalize_merge_task(input: FinalizeMergeInput<'_>) {
        let FinalizeMergeInput {
            clock,
            db,
            app_event_tx,
            id,
            output,
            result,
            session_update_versions,
            status,
        } = input;

        match result {
            Ok(message) => {
                let merge_message = TranscriptNotice::Merge.format_line(message);
                SessionTaskService::emit_session_workflow_notice(app_event_tx, id, merge_message);
                SessionTaskService::request_git_status_refresh(app_event_tx);
            }
            Err(error) => {
                let merge_error = TranscriptNotice::MergeError.format(error);
                SessionTaskService::append_session_output(
                    output,
                    db,
                    app_event_tx,
                    session_update_versions,
                    id,
                    &merge_error,
                )
                .await;
                if !SessionTaskService::update_status(
                    status,
                    clock,
                    db,
                    app_event_tx,
                    session_update_versions,
                    id,
                    Status::Review,
                )
                .await
                {
                    warn!(
                        session_id = id,
                        "skipped restoring review status after merge error because the in-memory \
                         status was already current"
                    );
                }
            }
        }
    }

    /// Builds merge success output text for commit and no-op outcomes.
    fn merge_success_message(
        source_branch: &str,
        base_branch: &str,
        merge_outcome: git::SquashMergeOutcome,
    ) -> String {
        match merge_outcome {
            git::SquashMergeOutcome::Committed => {
                format!("Successfully merged {source_branch} into {base_branch}")
            }
            git::SquashMergeOutcome::AlreadyPresentInTarget => {
                format!("Session changes from {source_branch} are already present in {base_branch}")
            }
        }
    }

    /// Rebases a reviewed session branch onto its base branch.
    ///
    /// # Errors
    /// Returns an error if the session is invalid for rebase, required git
    /// metadata is missing, or starting the rebase task fails.
    pub async fn rebase_session(
        &self,
        services: &AppServices,
        session_id: &str,
    ) -> Result<(), SessionError> {
        self.merge_service()
            .rebase_session(self, services, session_id)
            .await
    }

    /// Synchronizes a project branch with upstream using only project context.
    ///
    /// This helper is reused by background-triggered sync workflows and tests.
    /// On success returns a [`SyncMainOutcome`] for popup status messaging.
    ///
    /// # Errors
    /// Returns a [`SyncSessionStartError`] when project context is invalid or
    /// updating the default branch fails (`git pull --rebase`, assisted
    /// conflict resolution, or `git push`).
    pub(crate) async fn sync_main_for_project(
        default_branch: Option<String>,
        working_dir: PathBuf,
        git_client: Arc<dyn GitClient>,
        session_model: AgentModel,
    ) -> Result<SyncMainOutcome, SyncSessionStartError> {
        let fs_client: Arc<dyn FsClient> = Arc::new(fs::RealFsClient);
        let sync_assist_client: Arc<dyn SyncAssistClient> = Arc::new(RealSyncAssistClient);

        Self::sync_main_for_project_with_assist_client(
            default_branch,
            working_dir,
            fs_client,
            git_client,
            session_model,
            sync_assist_client,
        )
        .await
    }

    /// Synchronizes the selected project branch with optional mocked assistance
    /// support for tests.
    ///
    /// # Errors
    /// Returns a [`SyncSessionStartError`] when project context is invalid,
    /// git operations fail, or rebase conflicts remain unresolved after
    /// assisted attempts.
    async fn sync_main_for_project_with_assist_client(
        default_branch: Option<String>,
        working_dir: PathBuf,
        fs_client: Arc<dyn FsClient>,
        git_client: Arc<dyn GitClient>,
        session_model: AgentModel,
        sync_assist_client: Arc<dyn SyncAssistClient>,
    ) -> Result<SyncMainOutcome, SyncSessionStartError> {
        let default_branch = default_branch.ok_or_else(|| {
            SyncSessionStartError::Other("Active project has no git branch".to_string())
        })?;

        let _repo_root = git_client
            .find_git_repo_root(working_dir.clone())
            .await
            .ok_or_else(|| {
                SyncSessionStartError::Other("Failed to find git repository root".to_string())
            })?;

        let is_default_branch_clean = git_client
            .is_worktree_clean(working_dir.clone())
            .await
            .map_err(|error| SyncSessionStartError::Other(error.to_string()))?;
        if !is_default_branch_clean {
            return Err(SyncSessionStartError::MainHasUncommittedChanges {
                default_branch: default_branch.clone(),
            });
        }

        let ahead_behind_before_pull = git_client.get_ahead_behind(working_dir.clone()).await.ok();
        let pulled_commit_titles = git_client
            .list_upstream_commit_titles(working_dir.clone())
            .await
            .unwrap_or_default();

        let pull_result = git_client
            .pull_rebase(working_dir.clone())
            .await
            .map_err(|error| SyncSessionStartError::Other(error.to_string()))?;
        let mut resolved_conflict_files = Vec::new();
        if let git::PullRebaseResult::Conflict { detail } = pull_result {
            let sync_rebase_input = SyncRebaseAssistInput {
                base_branch: default_branch.clone(),
                folder: working_dir.clone(),
                fs_client: Arc::clone(&fs_client),
                git_client: Arc::clone(&git_client),
                session_model,
                sync_assist_client,
            };
            resolved_conflict_files =
                match Self::run_sync_rebase_assist_loop(sync_rebase_input, detail.clone()).await {
                    Ok(resolved_conflict_files) => resolved_conflict_files,
                    Err(error) => {
                        return Err(SyncSessionStartError::Other(format!(
                            "Sync stopped on rebase conflicts while updating `{default_branch}`: \
                             {detail}. Assisted resolution failed: {error}"
                        )));
                    }
                };
        }
        let ahead_behind_after_pull = git_client.get_ahead_behind(working_dir.clone()).await.ok();
        let pushed_commit_titles = git_client
            .list_local_commit_titles(working_dir.clone())
            .await
            .unwrap_or_default();

        git_client
            .push_current_branch(working_dir)
            .await
            .map_err(|error| SyncSessionStartError::Other(error.to_string()))?;

        let (pulled_commits, pushed_commits) = Self::summarize_sync_ahead_behind_counts(
            ahead_behind_before_pull,
            ahead_behind_after_pull,
        );

        Ok(SyncMainOutcome {
            pulled_commit_titles,
            pulled_commits,
            pushed_commit_titles,
            pushed_commits,
            resolved_conflict_files,
        })
    }

    /// Runs assisted conflict resolution for a main-project rebase in progress.
    ///
    /// # Errors
    /// Returns an error when conflicts remain unresolved after all attempts or
    /// when git/agent operations fail. On success returns resolved conflict
    /// file paths observed during assistance.
    async fn run_sync_rebase_assist_loop(
        input: SyncRebaseAssistInput,
        initial_conflict_detail: String,
    ) -> Result<Vec<String>, SessionError> {
        Self::run_rebase_assist_loop_core(
            RebaseAssistLoopInput::Project(input),
            Some(initial_conflict_detail),
        )
        .await
        .map(|outcome| outcome.resolved_conflict_files)
    }

    /// Returns pull/push counts inferred around one completed sync run.
    fn summarize_sync_ahead_behind_counts(
        ahead_behind_before_pull: Option<(u32, u32)>,
        ahead_behind_after_pull: Option<(u32, u32)>,
    ) -> (Option<u32>, Option<u32>) {
        let pulled_commits = ahead_behind_before_pull.map(|(_ahead, behind)| behind);
        let pushed_commits = ahead_behind_after_pull
            .map(|(ahead, _behind)| ahead)
            .or_else(|| ahead_behind_before_pull.map(|(ahead, _behind)| ahead));

        (pulled_commits, pushed_commits)
    }

    /// Loads current conflicted files for sync assistance.
    ///
    /// # Errors
    /// Returns an error if conflicted-file inspection fails.
    async fn load_sync_conflicted_files(
        input: &SyncRebaseAssistInput,
        previous_conflict_files: &[String],
    ) -> Result<Vec<String>, SessionError> {
        let folder = input.folder.clone();
        let mut conflicted = input
            .git_client
            .list_conflicted_files(folder.clone())
            .await?;

        let staged_with_markers = input
            .git_client
            .list_staged_conflict_marker_files(folder, previous_conflict_files.to_vec())
            .await?;
        for file in staged_with_markers {
            if !conflicted.contains(&file) {
                conflicted.push(file);
            }
        }
        conflicted.sort_unstable();

        Ok(conflicted)
    }

    /// Executes one agent-assisted sync rebase conflict resolution attempt.
    ///
    /// # Errors
    /// Returns an error when the assistance command fails.
    async fn run_sync_rebase_assist_agent(
        input: &SyncRebaseAssistInput,
        conflicted_files: &[String],
    ) -> Result<(), SessionError> {
        let prompt = Self::rebase_assist_prompt(&input.base_branch, conflicted_files)?;
        input
            .sync_assist_client
            .resolve_rebase_conflicts(input.folder.clone(), prompt, input.session_model)
            .await
            .map_err(|error| error.with_context("Sync rebase assistance failed"))
    }

    /// Stages sync edits and checks whether rebase conflicts remain.
    ///
    /// # Errors
    /// Returns an error when staging or conflict checks fail.
    async fn stage_and_check_for_sync_conflicts(
        input: &SyncRebaseAssistInput,
        conflict_files: &[String],
    ) -> Result<bool, SessionError> {
        let folder = input.folder.clone();
        input.git_client.stage_all(folder).await?;

        let folder = input.folder.clone();
        if input.git_client.has_unmerged_paths(folder).await? {
            return Ok(true);
        }

        let folder = input.folder.clone();
        let staged_with_markers = input
            .git_client
            .list_staged_conflict_marker_files(folder, conflict_files.to_vec())
            .await?;

        Ok(!staged_with_markers.is_empty())
    }

    /// Continues the in-progress sync rebase.
    ///
    /// # Errors
    /// Returns an error when `git rebase --continue` fails with non-conflict
    /// errors.
    async fn run_sync_rebase_continue(
        input: &SyncRebaseAssistInput,
    ) -> Result<git::RebaseStepResult, SessionError> {
        let folder = input.folder.clone();
        let result = input.git_client.rebase_continue(folder).await?;

        Ok(result)
    }

    /// Aborts an in-progress sync rebase after assistance failure.
    async fn abort_sync_rebase_after_assist_failure(input: &SyncRebaseAssistInput) {
        let folder = input.folder.clone();
        if let Err(error) = input.git_client.abort_rebase(folder).await {
            warn!(
                base_branch = input.base_branch,
                error = %error,
                "failed to abort sync rebase after assistance failure"
            );
        }
    }

    async fn run_rebase_task(input: RebaseTaskInput) {
        let RebaseTaskInput {
            app_event_tx,
            base_branch,
            child_pid,
            clock,
            db,
            folder,
            fs_client,
            git_client,
            id,
            output,
            session_model,
            session_update_versions,
            status,
        } = input;

        let rebase_result: Result<String, SessionError> = async {
            let rebase_target = Self::resolve_session_rebase_target(
                &db,
                git_client.as_ref(),
                &folder,
                &id,
                &base_branch,
            )
            .await?;
            let rebase_input = RebaseAssistInput {
                app_event_tx: app_event_tx.clone(),
                child_pid: Arc::clone(&child_pid),
                db: db.clone(),
                folder: folder.clone(),
                fs_client: Arc::clone(&fs_client),
                git_client: Arc::clone(&git_client),
                id: id.clone(),
                output: Arc::clone(&output),
                rebase_target,
                session_model,
                session_update_versions: session_update_versions.clone(),
            };

            Self::execute_rebase_workflow(rebase_input).await
        }
        .await;

        Self::finalize_rebase_task(FinalizeRebaseInput {
            app_event_tx: &app_event_tx,
            clock: clock.as_ref(),
            db: &db,
            folder: &folder,
            git_client: &git_client,
            id: &id,
            output: &output,
            rebase_result,
            session_update_versions: &session_update_versions,
            status: &status,
        })
        .await;
    }

    /// Resolves the git ref used for rebasing one session branch.
    ///
    /// Unpublished sessions rebase against the stored local base branch. Once
    /// a session branch is published, the rebase first fetches and targets the
    /// remote base ref from the same remote as the published upstream so the
    /// pull request comparison is updated against the forge-visible base.
    ///
    /// # Errors
    /// Returns an error when the published-session fetch fails.
    async fn resolve_session_rebase_target(
        db: &AppRepositories,
        git_client: &dyn GitClient,
        folder: &Path,
        session_id: &str,
        base_branch: &str,
    ) -> Result<String, SessionError> {
        let Some(published_upstream_ref) = db
            .sessions()
            .load_session_published_upstream_ref(session_id)
            .await
            .map_err(SessionError::Db)?
        else {
            return Ok(base_branch.to_string());
        };

        let Some((remote_name, _branch_name)) = published_upstream_ref.split_once('/') else {
            return Ok(base_branch.to_string());
        };

        git_client
            .fetch_remote(folder.to_path_buf())
            .await
            .map_err(|error| {
                SessionError::Workflow(format!(
                    "Failed to fetch `{remote_name}` before rebasing published session branch: \
                     {error}"
                ))
            })?;

        Ok(format!("{remote_name}/{base_branch}"))
    }

    /// Executes one assisted rebase workflow for a session worktree.
    ///
    /// Aborts any in-progress rebase when the assist loop fails so stale
    /// rebase metadata does not leak into later merge/rebase operations.
    ///
    /// # Errors
    /// Returns an error when pre-rebase auto-commit fails or assisted rebase
    /// cannot be completed.
    ///
    /// Emits user-visible commit output before rebase starts so users can see
    /// whether pending changes were committed or there was nothing to commit.
    /// The pre-rebase auto-commit reuses the active project's fast-model
    /// default when generating or repairing the session commit message, and a
    /// successful commit requests an immediate git-status refresh.
    async fn execute_rebase_workflow(input: RebaseAssistInput) -> Result<String, SessionError> {
        // Auto-commit any pending changes before rebasing to avoid
        // "cannot rebase: You have unstaged changes".
        let include_coauthored_by_agentty =
            SessionTaskService::load_include_coauthored_by_agentty_setting(&input.db, &input.id)
                .await;
        let auto_commit_model = SessionTaskService::load_auto_commit_model_setting(
            &input.db,
            &input.id,
            input.session_model,
        )
        .await;
        match SessionTaskService::commit_session_changes(
            input.git_client.as_ref(),
            &input.folder,
            &input.rebase_target,
            auto_commit_model,
            true,
            include_coauthored_by_agentty,
        )
        .await
        {
            Ok(outcome) => {
                Self::update_session_title_from_commit_message(
                    &input.db,
                    &input.id,
                    &outcome.commit_message,
                    &input.app_event_tx,
                )
                .await;

                let commit_message = TranscriptNotice::Commit
                    .format_line(format!("committed with hash `{}`", outcome.commit_hash));
                SessionTaskService::emit_session_workflow_notice(
                    &input.app_event_tx,
                    &input.id,
                    commit_message,
                );
                SessionTaskService::request_git_status_refresh(&input.app_event_tx);
            }
            Err(error) if error.to_string().contains("Nothing to commit") => {
                let commit_message = TranscriptNotice::Commit.format_line("No changes to commit.");
                SessionTaskService::emit_session_workflow_notice(
                    &input.app_event_tx,
                    &input.id,
                    commit_message,
                );
            }
            Err(error) => {
                return Err(SessionError::Workflow(format!(
                    "Failed to commit pending changes before rebase: {error}"
                )));
            }
        }

        if let Err(error) = Self::run_rebase_assist_loop(input.clone()).await {
            Self::abort_rebase_after_assist_failure(&input).await;

            return Err(SessionError::Workflow(format!("Failed to rebase: {error}")));
        }

        let source_branch = session_branch(&input.id);
        let rebase_target = &input.rebase_target;

        Ok(format!(
            "Successfully rebased {source_branch} onto {rebase_target}"
        ))
    }

    /// Finalizes one rebase task by appending the outcome and restoring the
    /// session lifecycle state.
    ///
    /// Successful rebases request an immediate git-status refresh so footer
    /// branch stats do not wait for the periodic poller, and trigger an
    /// auto-push when the session has a previously published upstream branch.
    async fn finalize_rebase_task(input: FinalizeRebaseInput<'_>) {
        let FinalizeRebaseInput {
            app_event_tx,
            clock,
            db,
            folder,
            git_client,
            id,
            output,
            rebase_result,
            session_update_versions,
            status,
        } = input;

        match rebase_result {
            Ok(message) => {
                let rebase_message = TranscriptNotice::Rebase.format(message);
                SessionTaskService::append_session_output(
                    output,
                    db,
                    app_event_tx,
                    session_update_versions,
                    id,
                    &rebase_message,
                )
                .await;
                SessionTaskService::request_git_status_refresh(app_event_tx);

                Self::start_auto_push_after_rebase(
                    db,
                    app_event_tx,
                    folder,
                    git_client,
                    output,
                    id,
                    session_update_versions,
                )
                .await;
            }
            Err(error) => {
                let rebase_error = TranscriptNotice::RebaseError.format(error);
                SessionTaskService::append_session_output(
                    output,
                    db,
                    app_event_tx,
                    session_update_versions,
                    id,
                    &rebase_error,
                )
                .await;
            }
        }

        if !SessionTaskService::update_status(
            status,
            clock,
            db,
            app_event_tx,
            session_update_versions,
            id,
            Status::Review,
        )
        .await
        {
            warn!(
                session_id = id,
                "skipped restoring review status after rebase because the in-memory status was \
                 already current"
            );
        }
    }

    /// Starts a detached auto-push task when the rebased session has a
    /// previously published upstream branch.
    async fn start_auto_push_after_rebase(
        db: &AppRepositories,
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
        folder: &Path,
        git_client: &Arc<dyn GitClient>,
        output: &Arc<Mutex<String>>,
        session_id: &str,
        session_update_versions: &SessionUpdateVersionMap,
    ) {
        let published_upstream_ref = db
            .sessions()
            .load_session_published_upstream_ref(session_id)
            .await
            .ok()
            .flatten();

        let Some(published_upstream_ref) = published_upstream_ref else {
            return;
        };

        let sync_operation_id = uuid::Uuid::new_v4().to_string();

        if app_event_tx
            .send(AppEvent::PublishedBranchSyncUpdated {
                session_id: SessionId::from(session_id),
                sync_operation_id: sync_operation_id.clone(),
                sync_status: PublishedBranchSyncStatus::InProgress,
            })
            .is_err()
        {
            warn!(
                session_id = session_id,
                sync_operation_id = sync_operation_id,
                "failed to publish branch sync start because the app event receiver is closed"
            );
        }

        let app_event_tx = app_event_tx.clone();
        let db = db.clone();
        let folder = folder.to_path_buf();
        let git_client = Arc::clone(git_client);
        let output = Arc::clone(output);
        let session_id = SessionId::from(session_id);
        let auto_push_input = super::worker::PublishedBranchAutoPushInput {
            app_event_tx,
            db,
            folder,
            git_client,
            output,
            published_upstream_ref,
            session_id,
            session_update_versions: session_update_versions.clone(),
            sync_operation_id,
        };

        tokio::spawn(async move {
            super::worker::run_published_branch_auto_push(auto_push_input).await;
        });
    }

    /// Updates the persisted session title from the canonical commit message.
    pub(crate) async fn update_session_title_from_commit_message(
        db: &AppRepositories,
        session_id: &str,
        commit_message: &str,
        app_event_tx: &mpsc::UnboundedSender<AppEvent>,
    ) {
        let title = Self::session_title_from_commit_message(commit_message);

        if let Err(error) = db.sessions().update_session_title(session_id, &title).await {
            warn!(
                session_id = session_id,
                error = %error,
                "failed to persist session title from commit message"
            );
        }

        if app_event_tx.send(AppEvent::RefreshSessions).is_err() {
            warn!(
                session_id = session_id,
                "failed to refresh sessions after commit-title update because the app event \
                 receiver is closed"
            );
        }
    }

    /// Updates the persisted done-session summary by formatting the latest
    /// persisted agent session-summary text, extracting `summary.session`
    /// from raw JSON payloads when needed, and canonical commit message into
    /// markdown sections.
    async fn update_done_session_summary_from_commit_message(
        db: &AppRepositories,
        session_id: &str,
        commit_message: &str,
    ) {
        let summary = Self::session_summary_with_commit_message(
            Self::persisted_session_summary(db, session_id)
                .await
                .as_deref(),
            commit_message,
        );

        if let Err(error) = db
            .sessions()
            .update_session_summary(session_id, &summary)
            .await
        {
            warn!(
                session_id = session_id,
                error = %error,
                "failed to persist done-session summary from commit message"
            );
        }
    }

    /// Loads the currently persisted session summary text for one session.
    async fn persisted_session_summary(db: &AppRepositories, session_id: &str) -> Option<String> {
        db.sessions()
            .load_session_summary(session_id)
            .await
            .ok()
            .flatten()
    }

    /// Extracts the first non-empty line from one session commit message for
    /// use as the session title.
    fn session_title_from_commit_message(commit_message: &str) -> String {
        let trimmed_message = commit_message.trim();
        if trimmed_message.is_empty() {
            return "Apply session updates".to_string();
        }

        trimmed_message
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty())
            .unwrap_or("Apply session updates")
            .to_string()
    }

    /// Builds the persisted done-session summary with markdown sections.
    ///
    /// Includes `# Summary` from the final agent session-summary text,
    /// extracting `summary.session` from persisted JSON payloads when needed,
    /// and `# Commit` from the canonical session commit message.
    fn session_summary_with_commit_message(
        session_summary: Option<&str>,
        commit_message: &str,
    ) -> String {
        let trimmed_summary = session_summary.map(str::trim).unwrap_or_default();
        let summary_text = serde_json::from_str::<AgentResponseSummary>(trimmed_summary)
            .map_or_else(
                |_| trimmed_summary.to_string(),
                |summary_payload| summary_payload.session,
            );
        let trimmed_commit_message = commit_message.trim();

        format!("# Summary\n\n{summary_text}\n\n# Commit\n\n{trimmed_commit_message}")
    }

    /// Runs a bounded rebase-assistance loop until conflicts are resolved.
    ///
    /// # Errors
    /// Returns an error when conflict resolution fails after all attempts or
    /// when git/agent operations fail.
    async fn run_rebase_assist_loop(input: RebaseAssistInput) -> Result<(), SessionError> {
        let rebase_in_progress = Self::is_rebase_in_progress(&input).await?;
        if !rebase_in_progress {
            let initial_step = Self::run_rebase_start(&input).await?;
            if initial_step == git::RebaseStepResult::Completed {
                return Ok(());
            }
        }

        Self::run_rebase_assist_loop_core(RebaseAssistLoopInput::Session(input), None)
            .await
            .map(|_| ())
    }

    /// Executes shared bounded assistance loop for both session rebases and
    /// main-project sync rebases.
    ///
    /// # Errors
    /// Returns an error when assistance fails to make progress, rebase remains
    /// conflicted after all attempts, or git operations fail. On every error
    /// path (including early `?` failures), the in-progress rebase is aborted
    /// before returning.
    async fn run_rebase_assist_loop_core(
        assist_input: RebaseAssistLoopInput,
        initial_conflict_detail: Option<String>,
    ) -> Result<RebaseAssistOutcome, SessionError> {
        let assist_result: Result<RebaseAssistOutcome, SessionError> = async {
            let mut failure_tracker =
                FailureTracker::new(REBASE_ASSIST_POLICY.max_identical_failure_streak);
            let mut assist_outcome = RebaseAssistOutcome::empty();
            if let Some(initial_conflict_detail) = initial_conflict_detail {
                // Seed the tracker with the initial conflict fingerprint.
                let _ = failure_tracker.observe(&initial_conflict_detail);
            }

            let mut previous_conflict_files: Vec<String> = vec![];

            for assist_attempt in 1..=REBASE_ASSIST_POLICY.max_attempts {
                let conflicted_files = assist_input
                    .load_conflicted_files(&previous_conflict_files)
                    .await?;
                if conflicted_files.is_empty() {
                    let continue_step = assist_input.run_rebase_continue().await?;
                    match continue_step {
                        git::RebaseStepResult::Completed => {
                            return Ok(assist_outcome);
                        }
                        git::RebaseStepResult::Conflict { detail } => {
                            if failure_tracker.observe(&detail) {
                                return Err(SessionError::Workflow(
                                    assist_input.repeated_conflict_state_error(&detail),
                                ));
                            }

                            if assist_attempt == REBASE_ASSIST_POLICY.max_attempts {
                                return Err(SessionError::Workflow(
                                    assist_input.still_conflicted_error(&detail),
                                ));
                            }
                        }
                    }

                    continue;
                }

                let conflict_fingerprint = Self::conflicted_file_fingerprint(
                    assist_input.fs_client(),
                    assist_input.folder(),
                    &conflicted_files,
                )
                .await;
                if failure_tracker.observe(&conflict_fingerprint) {
                    return Err(SessionError::Workflow(
                        assist_input.unchanged_conflict_files_error(),
                    ));
                }
                assist_outcome.extend_resolved_conflict_files(&conflicted_files);

                assist_input
                    .run_assist_attempt(assist_attempt, &conflicted_files)
                    .await?;

                let still_has_conflicts = assist_input
                    .stage_and_check_for_conflicts(&conflicted_files)
                    .await?;
                previous_conflict_files = conflicted_files;
                if still_has_conflicts {
                    if assist_attempt == REBASE_ASSIST_POLICY.max_attempts {
                        return Err(SessionError::Workflow(
                            "Conflicts remain unresolved after maximum assistance attempts"
                                .to_string(),
                        ));
                    }

                    continue;
                }

                let continue_step = assist_input.run_rebase_continue().await?;
                match continue_step {
                    git::RebaseStepResult::Completed => {
                        return Ok(assist_outcome);
                    }
                    git::RebaseStepResult::Conflict { detail } => {
                        if failure_tracker.observe(&detail) {
                            return Err(SessionError::Workflow(
                                assist_input.repeated_conflict_state_error(&detail),
                            ));
                        }

                        if assist_attempt == REBASE_ASSIST_POLICY.max_attempts {
                            return Err(SessionError::Workflow(
                                assist_input.still_conflicted_error(&detail),
                            ));
                        }
                    }
                }
            }

            Err(SessionError::Workflow(assist_input.exhausted_error()))
        }
        .await;

        match assist_result {
            Ok(assist_outcome) => Ok(assist_outcome),
            Err(error) => {
                assist_input.abort_rebase_after_assist_failure().await;

                Err(error)
            }
        }
    }

    /// Returns whether the session worktree has an in-progress rebase.
    ///
    /// # Errors
    /// Returns an error if git state cannot be queried.
    async fn is_rebase_in_progress(input: &RebaseAssistInput) -> Result<bool, SessionError> {
        let folder = input.folder.clone();
        let is_rebase_in_progress = input.git_client.is_rebase_in_progress(folder).await?;

        Ok(is_rebase_in_progress)
    }

    /// Starts the rebase step for an assisted rebase flow.
    ///
    /// When git reports stale rebase metadata (`rebase-merge`/`rebase-apply`)
    /// this helper attempts one cleanup pass via `git rebase --abort` and then
    /// retries the start command once.
    ///
    /// # Errors
    /// Returns an error if spawning the git process fails or git returns a
    /// non-conflict failure that cannot be recovered.
    async fn run_rebase_start(
        input: &RebaseAssistInput,
    ) -> Result<git::RebaseStepResult, SessionError> {
        let folder = input.folder.clone();
        let rebase_target = input.rebase_target.clone();
        match input
            .git_client
            .rebase_start(folder.clone(), rebase_target.clone())
            .await
        {
            Ok(result) => Ok(result),
            Err(error) => {
                let error_string = error.to_string();
                if !Self::is_stale_rebase_state_error(&error_string) {
                    return Err(SessionError::Workflow(error_string));
                }

                Self::recover_from_stale_rebase_start_error(input, &error_string).await?;

                input
                    .git_client
                    .rebase_start(folder, rebase_target)
                    .await
                    .map_err(SessionError::Git)
            }
        }
    }

    /// Returns whether a rebase start error indicates stale rebase metadata.
    fn is_stale_rebase_state_error(error: &str) -> bool {
        let normalized_error = error.to_ascii_lowercase();

        normalized_error.contains("already a rebase-merge directory")
            || normalized_error.contains("already a rebase-apply directory")
            || normalized_error.contains("middle of another rebase")
    }

    /// Tries to clean stale rebase metadata before retrying rebase start.
    ///
    /// # Errors
    /// Returns an error when `git rebase --abort` cannot clean up stale state.
    async fn recover_from_stale_rebase_start_error(
        input: &RebaseAssistInput,
        start_error: &str,
    ) -> Result<(), SessionError> {
        let folder = input.folder.clone();
        input
            .git_client
            .abort_rebase(folder)
            .await
            .map_err(|abort_error| {
                SessionError::Workflow(format!(
                    "Detected stale rebase metadata after failed rebase start: {start_error}. \
                     Cleanup with `git rebase --abort` failed: {abort_error}"
                ))
            })?;

        Ok(())
    }

    /// Loads all conflicted files from the worktree.
    ///
    /// Returns the union of two sets:
    /// - Files with *unmerged* index entries (classic rebase conflict state).
    /// - Files that were staged (`git add`) while still containing `<<<<<<<`
    ///   conflict markers, scoped to the provided `previous_conflict_files`.
    ///   This catches the case where an agent partially resolves a conflict and
    ///   stages the file without removing all markers, which would otherwise
    ///   make the file appear resolved.
    ///
    /// On the first call (no known prior conflicts), pass an empty slice for
    /// `previous_conflict_files`; only unmerged entries will be returned.
    ///
    /// # Errors
    /// Returns an error if either git query fails.
    async fn load_conflicted_files(
        input: &RebaseAssistInput,
        previous_conflict_files: &[String],
    ) -> Result<Vec<String>, SessionError> {
        let folder = input.folder.clone();
        let mut conflicted = input
            .git_client
            .list_conflicted_files(folder.clone())
            .await?;

        let staged_with_markers = input
            .git_client
            .list_staged_conflict_marker_files(folder, previous_conflict_files.to_vec())
            .await?;
        for file in staged_with_markers {
            if !conflicted.contains(&file) {
                conflicted.push(file);
            }
        }
        conflicted.sort_unstable();

        Ok(conflicted)
    }

    /// Appends an informational header for one rebase assistance attempt.
    async fn append_rebase_assist_header(
        input: &RebaseAssistInput,
        assist_attempt: usize,
        conflicted_files: &[String],
    ) {
        let conflict_summary = Self::format_conflicted_file_list(conflicted_files);
        append_assist_header(
            &Self::assist_context(input),
            TranscriptNotice::RebaseAssist,
            assist_attempt,
            REBASE_ASSIST_POLICY.max_attempts,
            "Resolving conflicts in:",
            &conflict_summary,
        )
        .await;
    }

    /// Runs an agent task to resolve the provided conflicted files.
    ///
    /// # Errors
    /// Returns an error if the agent process fails.
    async fn run_rebase_assist_agent(
        input: &RebaseAssistInput,
        conflicted_files: &[String],
    ) -> Result<(), SessionError> {
        let prompt = Self::rebase_assist_prompt(&input.rebase_target, conflicted_files)?;
        let assist_context = Self::assist_context(input);

        run_agent_assist(&assist_context, &prompt)
            .await
            .map_err(|error| error.with_context("Rebase assistance failed"))
    }

    /// Stages all worktree edits and checks whether any conflicts remain.
    ///
    /// Performs two checks after staging:
    /// 1. Unmerged index entries — files that were never resolved (`git add`d).
    /// 2. Staged content with `<<<<<<<` markers in `conflict_files` — files
    ///    that were staged while still containing residual conflict markers.
    ///
    /// Both checks are required because `git add` transitions a file from
    /// "Unmerged" to "Modified-in-index", making it invisible to the unmerged
    /// check even when conflict markers remain in its content.
    ///
    /// # Errors
    /// Returns an error when staging or either conflict check fails.
    async fn stage_and_check_for_conflicts(
        input: &RebaseAssistInput,
        conflict_files: &[String],
    ) -> Result<bool, SessionError> {
        let folder = input.folder.clone();
        input.git_client.stage_all(folder).await?;

        let folder = input.folder.clone();
        if input.git_client.has_unmerged_paths(folder).await? {
            return Ok(true);
        }

        let folder = input.folder.clone();
        let staged_with_markers = input
            .git_client
            .list_staged_conflict_marker_files(folder, conflict_files.to_vec())
            .await?;

        Ok(!staged_with_markers.is_empty())
    }

    /// Continues an in-progress rebase after conflict edits are applied.
    ///
    /// # Errors
    /// Returns an error if git reports a non-conflict failure.
    async fn run_rebase_continue(
        input: &RebaseAssistInput,
    ) -> Result<git::RebaseStepResult, SessionError> {
        let folder = input.folder.clone();
        let result = input.git_client.rebase_continue(folder).await?;

        Ok(result)
    }

    /// Renders the rebase-assist prompt from the markdown template.
    ///
    /// # Errors
    /// Returns an error if Askama template rendering fails.
    fn rebase_assist_prompt(
        base_branch: &str,
        conflicted_files: &[String],
    ) -> Result<String, SessionError> {
        let conflicted_files = Self::format_conflicted_file_list(conflicted_files);
        let template = RebaseAssistPromptTemplate {
            base_branch,
            conflicted_files: &conflicted_files,
        };

        template.render().map_err(|error| {
            SessionError::Workflow(format!(
                "Failed to render `rebase_assist_prompt.md`: {error}"
            ))
        })
    }

    /// Formats conflicted file paths as a bullet list for prompt rendering.
    fn format_conflicted_file_list(conflicted_files: &[String]) -> String {
        format_detail_lines(&conflicted_files.join("\n"))
    }

    /// Computes a content-based fingerprint for the current set of conflicted
    /// files.
    ///
    /// Reads each file from disk and hashes both its path and content so that
    /// partial progress made by the rebase-assist agent (e.g. removing some
    /// but not all conflict markers) changes the fingerprint and prevents the
    /// [`FailureTracker`] from firing prematurely. The fingerprint is
    /// order-independent because paths are sorted before hashing.
    async fn conflicted_file_fingerprint(
        fs_client: &dyn FsClient,
        folder: &Path,
        conflicted_files: &[String],
    ) -> String {
        let mut sorted_files = conflicted_files.to_vec();
        sorted_files.sort_unstable();

        let mut hasher = DefaultHasher::new();
        for file in &sorted_files {
            file.hash(&mut hasher);
            let file_path = folder.join(file);
            if let Ok(content) = fs_client.read_file(file_path).await {
                content.hash(&mut hasher);
            }
        }

        format!("{:016x}", hasher.finish())
    }

    /// Builds shared assistance context from rebase input state.
    fn assist_context(input: &RebaseAssistInput) -> AssistContext {
        AssistContext {
            app_event_tx: input.app_event_tx.clone(),
            child_pid: Arc::clone(&input.child_pid),
            db: input.db.clone(),
            folder: input.folder.clone(),
            git_client: Arc::clone(&input.git_client),
            id: input.id.to_string(),
            output: Arc::clone(&input.output),
            session_model: input.session_model,
            session_update_versions: input.session_update_versions.clone(),
        }
    }

    /// Aborts rebase after assistance fails to keep worktree state clean.
    async fn abort_rebase_after_assist_failure(input: &RebaseAssistInput) {
        let folder = input.folder.clone();
        if let Err(error) = input.git_client.abort_rebase(folder).await {
            warn!(
                session_id = %input.id,
                error = %error,
                "failed to abort rebase after assistance failure"
            );
        }
    }

    /// Removes a merged session worktree and deletes its source branch.
    ///
    /// When `repo_root` is not provided, this resolves the shared repository
    /// root through `git rev-parse` via `GitClient`.
    ///
    /// # Errors
    /// Returns an error if worktree or branch cleanup fails.
    pub(crate) async fn cleanup_merged_session_worktree(
        folder: PathBuf,
        fs_client: Arc<dyn FsClient>,
        git_client: Arc<dyn GitClient>,
        source_branch: String,
        repo_root: Option<PathBuf>,
    ) -> Result<(), SessionError> {
        let repo_root = match repo_root {
            Some(repo_root) => Some(repo_root),
            None => git_client.main_repo_root(folder.clone()).await.ok(),
        };

        git_client.remove_worktree(folder.clone()).await?;

        if let Some(repo_root) = repo_root {
            git_client.delete_branch(repo_root, source_branch).await?;
        }

        if let Err(error) = fs_client.remove_dir_all(folder).await {
            warn!(
                error = %error,
                "failed to remove merged session worktree directory"
            );
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use mockall::Sequence;
    use tempfile::{TempDir, tempdir};

    use super::*;
    use crate::infra::git::GitError;

    /// Builds a filesystem mock that delegates operations to local disk.
    fn create_passthrough_mock_fs_client() -> fs::MockFsClient {
        let mut mock_fs_client = fs::MockFsClient::new();
        mock_fs_client
            .expect_create_dir_all()
            .times(0..)
            .returning(|path| {
                Box::pin(async move {
                    tokio::fs::create_dir_all(path)
                        .await
                        .map_err(fs::FsError::from)
                })
            });
        mock_fs_client
            .expect_remove_dir_all()
            .times(0..)
            .returning(|path| {
                Box::pin(async move {
                    tokio::fs::remove_dir_all(path)
                        .await
                        .map_err(fs::FsError::from)
                })
            });
        mock_fs_client
            .expect_read_file()
            .times(0..)
            .returning(|path| {
                Box::pin(async move { tokio::fs::read(path).await.map_err(fs::FsError::from) })
            });
        mock_fs_client
            .expect_remove_file()
            .times(0..)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_fs_client
            .expect_is_dir()
            .times(0..)
            .returning(|path| path.is_dir());

        mock_fs_client
    }

    /// Returns a fresh mocked filesystem client trait object for tests.
    fn test_fs_client() -> Arc<dyn FsClient> {
        Arc::new(create_passthrough_mock_fs_client())
    }

    /// Builds rebase assistance input with the provided git client for unit
    /// tests.
    async fn build_rebase_assist_input_for_test(
        git_client: Arc<dyn GitClient>,
    ) -> (TempDir, RebaseAssistInput) {
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let folder = temp_dir.path().to_path_buf();

        (
            temp_dir,
            RebaseAssistInput {
                app_event_tx,
                child_pid: Arc::new(Mutex::new(None)),
                db,
                folder,
                fs_client: test_fs_client(),
                git_client,
                id: "session-123".into(),
                output: Arc::new(Mutex::new(String::new())),
                rebase_target: "main".to_string(),
                session_model: AgentModel::Gemini3FlashPreview,
                session_update_versions: Arc::default(),
            },
        )
    }

    /// Builds merge-task input with injected git client for deterministic
    /// workflow tests.
    async fn build_merge_task_input_for_test(
        git_client: Arc<dyn GitClient>,
    ) -> (TempDir, MergeTaskInput) {
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let folder = temp_dir.path().join("session-worktree");
        let repo_root = temp_dir.path().join("repo-root");

        (
            temp_dir,
            MergeTaskInput {
                app_event_tx,
                base_branch: "main".to_string(),
                child_pid: Arc::new(Mutex::new(None)),
                clock: Arc::new(crate::app::session::RealClock),
                db,
                folder,
                fs_client: test_fs_client(),
                git_client,
                id: "session-123".into(),
                output: Arc::new(Mutex::new(String::new())),
                repo_root,
                session_update_versions: Arc::default(),
                session_model: AgentModel::Gemini3FlashPreview,
                source_branch: "wt/session-123".to_string(),
                status: Arc::new(Mutex::new(Status::Merging)),
            },
        )
    }

    /// Builds sync rebase assistance input with injected git and assistance
    /// clients for project-level conflict tests.
    fn build_sync_rebase_input_for_test(
        folder: PathBuf,
        git_client: Arc<dyn GitClient>,
        sync_assist_client: Arc<dyn SyncAssistClient>,
    ) -> SyncRebaseAssistInput {
        SyncRebaseAssistInput {
            base_branch: "main".to_string(),
            folder,
            fs_client: test_fs_client(),
            git_client,
            session_model: AgentModel::Gemini3FlashPreview,
            sync_assist_client,
        }
    }

    #[tokio::test]
    /// Ensures [`SessionError`] from the sync assist client propagates through
    /// `run_sync_rebase_assist_agent` with an operation-specific context
    /// prefix.
    async fn test_sync_rebase_assist_agent_adds_context_to_workflow_error() {
        // Arrange
        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(1)
            .returning(|_, _, _| {
                Box::pin(async {
                    Err(SessionError::Workflow(
                        "agent backend unavailable".to_string(),
                    ))
                })
            });
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let input = build_sync_rebase_input_for_test(
            temp_dir.path().to_path_buf(),
            Arc::new(git::MockGitClient::new()),
            Arc::new(mock_sync_assist_client),
        );

        // Act
        let result =
            SessionManager::run_sync_rebase_assist_agent(&input, &["src/lib.rs".to_string()]).await;

        // Assert
        let error = result.expect_err("assist failure should propagate");
        assert!(
            matches!(error, SessionError::Workflow(_)),
            "expected SessionError::Workflow, got: {error:?}"
        );
        assert_eq!(
            error.to_string(),
            "Sync rebase assistance failed: agent backend unavailable"
        );
    }

    #[test]
    fn test_rebase_assist_prompt_includes_branch_and_files() {
        // Arrange
        let base_branch = "main";
        let conflicted_files = vec!["src/lib.rs".to_string(), "README.md".to_string()];

        // Act
        let prompt = SessionManager::rebase_assist_prompt(base_branch, &conflicted_files)
            .expect("rebase assist prompt should render");

        // Assert
        assert!(prompt.contains("rebasing onto `main`"));
        assert!(prompt.contains("- src/lib.rs"));
        assert!(prompt.contains("- README.md"));
        assert!(prompt.contains("repository-defined quality checks"));
        assert!(prompt.contains("affected dependencies or dependents"));
    }

    #[test]
    fn test_format_conflicted_file_list_returns_bulleted_lines() {
        // Arrange
        let conflicted_files = vec!["src/main.rs".to_string(), "src/lib.rs".to_string()];

        // Act
        let summary = SessionManager::format_conflicted_file_list(&conflicted_files);

        // Assert
        assert_eq!(summary, "- src/main.rs\n- src/lib.rs");
    }

    #[test]
    fn test_session_title_from_commit_message() {
        // Arrange
        let commit_message = "Refine merge flow\n\n- Update title handling";

        // Act
        let title = SessionManager::session_title_from_commit_message(commit_message);

        // Assert
        assert_eq!(title, "Refine merge flow");
    }

    #[test]
    fn test_session_title_from_commit_message_skips_blank_prefix() {
        // Arrange
        let commit_message = "\n\nRefine merge flow\n\n- Update title handling";

        // Act
        let title = SessionManager::session_title_from_commit_message(commit_message);

        // Assert
        assert_eq!(title, "Refine merge flow");
    }

    #[test]
    fn test_session_title_from_commit_message_empty_uses_fallback() {
        // Arrange
        let commit_message = "  \n";

        // Act
        let title = SessionManager::session_title_from_commit_message(commit_message);

        // Assert
        assert_eq!(title, "Apply session updates");
    }

    #[test]
    fn test_session_summary_with_commit_message_builds_markdown_sections() {
        // Arrange
        let session_summary = Some("- Session branch now handles refresh races.");
        let commit_message = "Refine session summary\n\n- Append commit context";

        // Act
        let summary =
            SessionManager::session_summary_with_commit_message(session_summary, commit_message);

        // Assert
        assert_eq!(
            summary,
            "# Summary\n\n- Session branch now handles refresh races.\n\n# Commit\n\nRefine \
             session summary\n\n- Append commit context"
        );
    }

    #[test]
    fn test_session_summary_with_commit_message_formats_empty_summary_section() {
        // Arrange
        let session_summary = Some("   ");
        let commit_message = "Refine session summary";

        // Act
        let summary =
            SessionManager::session_summary_with_commit_message(session_summary, commit_message);

        // Assert
        assert_eq!(
            summary,
            "# Summary\n\n\n\n# Commit\n\nRefine session summary"
        );
    }

    #[test]
    fn test_session_summary_with_commit_message_extracts_session_text_from_json_payload() {
        // Arrange
        let session_summary = Some(
            r#"{"turn":"Updated the greeting flow.","session":"Session now greets users on startup."}"#,
        );
        let commit_message = "Refine session summary";

        // Act
        let summary =
            SessionManager::session_summary_with_commit_message(session_summary, commit_message);

        // Assert
        assert_eq!(
            summary,
            "# Summary\n\nSession now greets users on startup.\n\n# Commit\n\nRefine session \
             summary"
        );
    }

    #[tokio::test]
    async fn test_update_session_title_from_commit_message_preserves_existing_summary() {
        // Arrange
        let database = AppRepositories::in_memory().await;
        let project_id = database
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        database
            .sessions()
            .insert_session(
                "session-id",
                AgentModel::ClaudeSonnet46.as_str(),
                "main",
                "Review",
                project_id,
            )
            .await
            .expect("failed to insert session");
        let existing_summary = "- Session branch updates README.";
        database
            .sessions()
            .update_session_summary("session-id", existing_summary)
            .await
            .expect("failed to persist existing summary");
        let (app_event_tx, mut app_event_rx) = mpsc::unbounded_channel();
        let commit_message = "Refine session commit message\n\n- Keep title in sync";

        // Act
        SessionManager::update_session_title_from_commit_message(
            &database,
            "session-id",
            commit_message,
            &app_event_tx,
        )
        .await;
        let sessions = database
            .sessions()
            .load_sessions()
            .await
            .expect("failed to load sessions");

        // Assert
        assert_eq!(
            sessions[0].title.as_deref(),
            Some("Refine session commit message")
        );
        assert_eq!(sessions[0].summary.as_deref(), Some(existing_summary));
        assert_eq!(
            app_event_rx.try_recv().ok(),
            Some(AppEvent::RefreshSessions)
        );
    }

    #[tokio::test]
    async fn test_update_done_session_summary_from_commit_message_appends_commit_message() {
        // Arrange
        let database = AppRepositories::in_memory().await;
        let project_id = database
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        database
            .sessions()
            .insert_session(
                "session-id",
                AgentModel::ClaudeSonnet46.as_str(),
                "main",
                "Review",
                project_id,
            )
            .await
            .expect("failed to insert session");
        let existing_summary = "- Session branch updates README.";
        let commit_message = "Refine session commit message\n\n- Keep title in sync";
        database
            .sessions()
            .update_session_summary("session-id", existing_summary)
            .await
            .expect("failed to persist existing summary");

        // Act
        SessionManager::update_done_session_summary_from_commit_message(
            &database,
            "session-id",
            commit_message,
        )
        .await;
        let sessions = database
            .sessions()
            .load_sessions()
            .await
            .expect("failed to load sessions");

        // Assert
        assert_eq!(
            sessions[0].summary.as_deref(),
            Some(
                "# Summary\n\n- Session branch updates README.\n\n# Commit\n\nRefine session \
                 commit message\n\n- Keep title in sync"
            )
        );
    }

    #[tokio::test]
    async fn test_execute_merge_workflow_reuses_session_head_commit_message() {
        // Arrange
        let expected_merged_commit_hash = "704de31d0f4b5a1234567890abcdef1234567890";
        let canonical_commit_message = "Refine merge flow\n\n- Reuse the session commit body";
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_is_rebase_in_progress()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(false) }));
        mock_git_client
            .expect_rebase_start()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(git::RebaseStepResult::Completed) }));
        mock_git_client
            .expect_squash_merge_diff()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _, _| Box::pin(async { Ok("diff --git a/file b/file".to_string()) }));
        mock_git_client
            .expect_head_commit_message()
            .times(1)
            .in_sequence(&mut sequence)
            .returning({
                let canonical_commit_message = canonical_commit_message.to_string();

                move |_| {
                    let canonical_commit_message = canonical_commit_message.clone();

                    Box::pin(async move { Ok(Some(canonical_commit_message)) })
                }
            });
        mock_git_client
            .expect_squash_merge()
            .times(1)
            .in_sequence(&mut sequence)
            .returning({
                let canonical_commit_message = canonical_commit_message.to_string();

                move |_, _, _, commit_message| {
                    let canonical_commit_message = canonical_commit_message.clone();

                    Box::pin(async move {
                        assert_eq!(commit_message, canonical_commit_message);

                        Ok(git::SquashMergeOutcome::Committed)
                    })
                }
            });
        mock_git_client
            .expect_head_hash()
            .times(1)
            .in_sequence(&mut sequence)
            .returning({
                let expected_merged_commit_hash = expected_merged_commit_hash.to_string();

                move |_| {
                    let expected_merged_commit_hash = expected_merged_commit_hash.clone();

                    Box::pin(async move { Ok(expected_merged_commit_hash) })
                }
            });
        mock_git_client
            .expect_remove_worktree()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_delete_branch()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(()) }));
        let (_temp_dir, input) = build_merge_task_input_for_test(Arc::new(mock_git_client)).await;
        let project_id = input
            .db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to insert project");
        input
            .db
            .sessions()
            .insert_session("session-123", "gpt-5.4", "main", "Merging", project_id)
            .await
            .expect("failed to insert merge session row");
        let db = input.db.clone();

        // Act
        let result = SessionManager::execute_merge_workflow(input).await;

        // Assert
        let message = result.expect("merge workflow should succeed");
        assert_eq!(message, "Successfully merged wt/session-123 into main");
        let merged_commit_hash = db
            .sessions()
            .load_session_merged_commit_hash("session-123")
            .await
            .expect("failed to load merged commit hash");
        assert_eq!(
            merged_commit_hash.as_deref(),
            Some(expected_merged_commit_hash)
        );
    }

    #[tokio::test]
    async fn test_execute_merge_workflow_skips_commit_creation_for_empty_squash_diff() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_is_rebase_in_progress()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(false) }));
        mock_git_client
            .expect_rebase_start()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(git::RebaseStepResult::Completed) }));
        mock_git_client
            .expect_squash_merge_diff()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _, _| Box::pin(async { Ok("   ".to_string()) }));
        mock_git_client.expect_head_commit_message().times(0);
        mock_git_client.expect_squash_merge().times(0);
        mock_git_client
            .expect_remove_worktree()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_delete_branch()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(()) }));
        let (_temp_dir, input) = build_merge_task_input_for_test(Arc::new(mock_git_client)).await;
        let project_id = input
            .db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to insert project");
        input
            .db
            .sessions()
            .insert_session("session-123", "gpt-5.4", "main", "Merging", project_id)
            .await
            .expect("failed to insert merge session row");
        let db = input.db.clone();

        // Act
        let result = SessionManager::execute_merge_workflow(input).await;

        // Assert
        let message = result.expect("merge workflow should succeed for empty diff");
        assert_eq!(
            message,
            "Session changes from wt/session-123 are already present in main"
        );
        let merged_commit_hash = db
            .sessions()
            .load_session_merged_commit_hash("session-123")
            .await
            .expect("failed to load merged commit hash");
        assert_eq!(merged_commit_hash, None);
    }

    #[tokio::test]
    async fn test_rebase_assist_input_clone() {
        // Arrange
        let (tx, _rx) = mpsc::unbounded_channel();
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let input = RebaseAssistInput {
            app_event_tx: tx,
            child_pid: Arc::new(Mutex::new(None)),
            db,
            folder: temp_dir.path().to_path_buf(),
            fs_client: test_fs_client(),
            git_client: Arc::new(git::RealGitClient),
            id: "session-123".into(),
            output: Arc::new(Mutex::new(String::new())),
            rebase_target: "origin/main".to_string(),
            session_model: AgentModel::Gemini3FlashPreview,
            session_update_versions: Arc::default(),
        };

        // Act
        let cloned_input = input.clone();

        // Assert
        assert_eq!(input.id, cloned_input.id);
        assert_eq!(input.folder, cloned_input.folder);
        assert_eq!(input.rebase_target, cloned_input.rebase_target);
        assert_eq!(input.session_model, cloned_input.session_model);
    }

    #[tokio::test]
    async fn test_resolve_session_rebase_target_keeps_local_base_for_unpublished_session() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let project_path = temp_dir.path().to_string_lossy().to_string();
        let project_id = db
            .projects()
            .upsert_project(&project_path, Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        db.sessions()
            .insert_session("sess-local", "gpt-5.4", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client.expect_fetch_remote().times(0);
        let folder = temp_dir.path().join("sess-local");

        // Act
        let rebase_target = SessionManager::resolve_session_rebase_target(
            &db,
            &mock_git_client,
            &folder,
            "sess-local",
            "main",
        )
        .await
        .expect("failed to resolve local rebase target");

        // Assert
        assert_eq!(rebase_target, "main");
    }

    #[tokio::test]
    async fn test_resolve_session_rebase_target_fetches_remote_base_for_published_session() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let project_path = temp_dir.path().to_string_lossy().to_string();
        let project_id = db
            .projects()
            .upsert_project(&project_path, Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        db.sessions()
            .insert_session("sess-remote", "gpt-5.4", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        db.sessions()
            .update_session_published_upstream_ref(
                "sess-remote",
                Some("origin/wt/sess-remote".to_string()),
            )
            .await
            .expect("failed to set published upstream");
        let folder = temp_dir.path().join("sess-remote");
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_fetch_remote()
            .once()
            .withf(|repo_path| repo_path.ends_with("sess-remote"))
            .returning(|_| Box::pin(async { Ok(()) }));

        // Act
        let rebase_target = SessionManager::resolve_session_rebase_target(
            &db,
            &mock_git_client,
            &folder,
            "sess-remote",
            "main",
        )
        .await
        .expect("failed to resolve remote rebase target");

        // Assert
        assert_eq!(rebase_target, "origin/main");
    }

    #[tokio::test]
    async fn test_resolve_session_rebase_target_reports_published_fetch_failure() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let project_path = temp_dir.path().to_string_lossy().to_string();
        let project_id = db
            .projects()
            .upsert_project(&project_path, Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        db.sessions()
            .insert_session("sess-fetch", "gpt-5.4", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        db.sessions()
            .update_session_published_upstream_ref(
                "sess-fetch",
                Some("origin/wt/sess-fetch".to_string()),
            )
            .await
            .expect("failed to set published upstream");
        let folder = temp_dir.path().join("sess-fetch");
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_fetch_remote()
            .once()
            .returning(|_| Box::pin(async { Err(GitError::OutputParse("fetch failed".into())) }));

        // Act
        let result = SessionManager::resolve_session_rebase_target(
            &db,
            &mock_git_client,
            &folder,
            "sess-fetch",
            "main",
        )
        .await;

        // Assert
        let error = result.expect_err("fetch failure should stop published rebase");
        assert!(
            error
                .to_string()
                .contains("Failed to fetch `origin` before rebasing published session branch"),
            "error should name the published upstream remote"
        );
    }

    #[tokio::test]
    async fn test_execute_rebase_workflow_aborts_when_assist_loop_fails() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(false) }));
        mock_git_client
            .expect_has_commits_since()
            .times(1)
            .in_sequence(&mut sequence)
            .withf(|_, base_branch| base_branch == "origin/main")
            .returning(|_, _| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_head_commit_message()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(Some("Existing session commit".to_string())) }));
        mock_git_client
            .expect_commit_all_preserving_single_commit()
            .times(1)
            .in_sequence(&mut sequence)
            .withf(|_, base_branch, _, _, _| base_branch == "origin/main")
            .returning(|_, _, _, _, _| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_head_short_hash()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok("abc1234".to_string()) }));
        mock_git_client
            .expect_is_rebase_in_progress()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| {
                Box::pin(async { Err(GitError::OutputParse("state query failed".to_string())) })
            });
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        let (_temp_dir, mut input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;
        input.rebase_target = "origin/main".to_string();

        // Act
        let result = SessionManager::execute_rebase_workflow(input).await;

        // Assert
        let error = result.expect_err("rebase workflow should fail");
        assert!(
            error
                .to_string()
                .contains("Failed to rebase: state query failed"),
            "workflow error should include assist-loop failure reason"
        );
    }

    #[tokio::test]
    async fn test_run_rebase_assist_loop_core_aborts_on_early_error() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_list_conflicted_files()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| {
                Box::pin(async {
                    Err(GitError::OutputParse(
                        "failed to list conflicts".to_string(),
                    ))
                })
            });
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        let (_temp_dir, input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;

        // Act
        let result = SessionManager::run_rebase_assist_loop_core(
            RebaseAssistLoopInput::Session(input),
            None,
        )
        .await;

        // Assert
        let error = result.expect_err("assist loop should fail");
        assert_eq!(error.to_string(), "failed to list conflicts");
    }

    /// Verifies session rebase assistance stops when the same conflict detail
    /// repeats after the initial conflict state.
    #[tokio::test]
    async fn test_run_rebase_assist_loop_core_stops_on_repeated_conflict_detail() {
        // Arrange
        let repeated_detail = "CONFLICT (content): Merge conflict in src/lib.rs".to_string();
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_list_conflicted_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_| Box::pin(async { Ok(Vec::new()) }));
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_, _| Box::pin(async { Ok(Vec::new()) }));
        mock_git_client
            .expect_rebase_continue()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning({
                let repeated_detail = repeated_detail.clone();

                move |_| {
                    let repeated_detail = repeated_detail.clone();

                    Box::pin(async move {
                        Ok(git::RebaseStepResult::Conflict {
                            detail: repeated_detail,
                        })
                    })
                }
            });
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));
        let (_temp_dir, input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;

        // Act
        let result = SessionManager::run_rebase_assist_loop_core(
            RebaseAssistLoopInput::Session(input),
            Some(repeated_detail.clone()),
        )
        .await;

        // Assert
        let error = result.expect_err("assist loop should stop on repeated conflict detail");
        assert_eq!(
            error.to_string(),
            format!(
                "Rebase assistance made no progress: repeated identical conflict state. Last \
                 detail: {repeated_detail}"
            )
        );
    }

    /// Verifies session rebase assistance surfaces the final conflict detail
    /// when every retry hits a distinct conflict state until the retry budget
    /// is exhausted.
    #[tokio::test]
    async fn test_run_rebase_assist_loop_core_reports_retry_exhaustion_detail() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        for detail in [
            "CONFLICT (content): Merge conflict in src/lib.rs",
            "CONFLICT (content): Merge conflict in src/main.rs",
            "CONFLICT (content): Merge conflict in README.md",
        ] {
            mock_git_client
                .expect_list_conflicted_files()
                .times(1)
                .in_sequence(&mut sequence)
                .returning(|_| Box::pin(async { Ok(Vec::new()) }));
            mock_git_client
                .expect_list_staged_conflict_marker_files()
                .times(1)
                .in_sequence(&mut sequence)
                .returning(|_, _| Box::pin(async { Ok(Vec::new()) }));
            mock_git_client
                .expect_rebase_continue()
                .times(1)
                .in_sequence(&mut sequence)
                .returning({
                    let detail = detail.to_string();

                    move |_| {
                        let detail = detail.clone();

                        Box::pin(async move { Ok(git::RebaseStepResult::Conflict { detail }) })
                    }
                });
        }
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));
        let (_temp_dir, input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;

        // Act
        let result = SessionManager::run_rebase_assist_loop_core(
            RebaseAssistLoopInput::Session(input),
            None,
        )
        .await;

        // Assert
        let error = result.expect_err("assist loop should report the final retry conflict");
        assert_eq!(
            error.to_string(),
            "Rebase still has conflicts after assistance: CONFLICT (content): Merge conflict in \
             README.md"
        );
    }

    #[tokio::test]
    async fn test_run_rebase_start_recovers_stale_rebase_state_and_retries() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_rebase_start()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| {
                Box::pin(async {
                    Err(GitError::OutputParse(
                        "fatal: It seems that there is already a rebase-merge directory"
                            .to_string(),
                    ))
                })
            });
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_rebase_start()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(git::RebaseStepResult::Completed) }));
        let (_temp_dir, input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;

        // Act
        let result = SessionManager::run_rebase_start(&input).await;

        // Assert
        let step_result = result.expect("rebase start should succeed");
        assert_eq!(step_result, git::RebaseStepResult::Completed);
    }

    #[tokio::test]
    async fn test_run_rebase_start_uses_resolved_rebase_target() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_rebase_start()
            .once()
            .withf(|_, rebase_target| rebase_target == "origin/main")
            .returning(|_, _| Box::pin(async { Ok(git::RebaseStepResult::Completed) }));
        let (_temp_dir, mut input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;
        input.rebase_target = "origin/main".to_string();

        // Act
        let result = SessionManager::run_rebase_start(&input).await;

        // Assert
        let step_result = result.expect("rebase start should succeed");
        assert_eq!(step_result, git::RebaseStepResult::Completed);
    }

    #[tokio::test]
    async fn test_run_rebase_start_reports_cleanup_failure_for_stale_rebase_state() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_rebase_start()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| {
                Box::pin(async {
                    Err(GitError::OutputParse(
                        "fatal: It seems that there is already a rebase-merge directory"
                            .to_string(),
                    ))
                })
            });
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| {
                Box::pin(async { Err(GitError::OutputParse("abort failed".to_string())) })
            });
        let (_temp_dir, input) =
            build_rebase_assist_input_for_test(Arc::new(mock_git_client)).await;

        // Act
        let result = SessionManager::run_rebase_start(&input).await;

        // Assert
        let error = result.expect_err("cleanup failure should stop retry flow");
        assert!(
            error
                .to_string()
                .contains("Cleanup with `git rebase --abort` failed: abort failed"),
            "error should include abort failure detail"
        );
    }

    /// Verifies merged-session cleanup surfaces branch deletion failures after
    /// the worktree itself has already been removed.
    #[tokio::test]
    async fn test_cleanup_merged_session_worktree_reports_delete_branch_failure() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let folder = temp_dir.path().join("session-worktree");
        let repo_root = temp_dir.path().join("repo-root");
        let source_branch = "wt/session-123".to_string();
        let mut mock_git_client = git::MockGitClient::new();
        let mut mock_fs_client = fs::MockFsClient::new();
        mock_git_client
            .expect_remove_worktree()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_delete_branch()
            .times(1)
            .returning(|_, _| {
                Box::pin(async { Err(GitError::OutputParse("delete failed".to_string())) })
            });
        mock_fs_client.expect_remove_dir_all().times(0);

        // Act
        let result = SessionManager::cleanup_merged_session_worktree(
            folder,
            Arc::new(mock_fs_client),
            Arc::new(mock_git_client),
            source_branch,
            Some(repo_root),
        )
        .await;

        // Assert
        let error = result.expect_err("cleanup should fail on branch deletion error");
        assert_eq!(error.to_string(), "delete failed");
    }

    #[test]
    fn test_detail_message_for_uncommitted_changes_uses_sentence_lines() {
        // Arrange
        let sync_error = SyncSessionStartError::MainHasUncommittedChanges {
            default_branch: "main".to_string(),
        };

        // Act
        let detail_message = sync_error.detail_message();

        // Assert
        assert_eq!(
            detail_message,
            "Sync cannot run while `main` has uncommitted changes.\nCommit or stash changes in \
             `main`, then try again."
        );
    }

    #[tokio::test]
    async fn test_ensure_merge_target_clean_blocks_dirty_main_checkout() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let project_id = db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to insert project");
        db.sessions()
            .insert_session("session-123", "gpt-5.4", "main", "Merging", project_id)
            .await
            .expect("failed to insert merge session row");
        let status = Arc::new(Mutex::new(Status::Merging));
        let session_update_versions = Arc::default();
        let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| Box::pin(async { Ok(false) }));
        let restore_context = MergeStartRestoreContext {
            app_event_tx: &app_event_tx,
            clock: &crate::app::session::RealClock,
            db: &db,
            session_id: "session-123",
            session_update_versions: &session_update_versions,
            status: &status,
        };

        // Act
        let result = SessionMergeService::ensure_merge_target_clean(
            &mock_git_client,
            PathBuf::from("/tmp/project"),
            "main",
            &restore_context,
        )
        .await;

        // Assert
        let error = result.expect_err("dirty merge target should block merge");
        assert_eq!(
            error.to_string(),
            "Merge cannot run while `main` has uncommitted changes.\nCommit or stash changes in \
             `main`, then try again."
        );
        assert_eq!(
            *status.lock().expect("status lock poisoned"),
            Status::Review
        );
    }

    #[tokio::test]
    async fn test_sync_main_for_project_resolves_conflicts_with_assistance() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let working_dir = temp_dir.path().to_path_buf();
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_find_git_repo_root()
            .times(1)
            .returning(|folder| Box::pin(async move { Some(folder) }));
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_get_ahead_behind()
            .times(1)
            .return_once(|_| Box::pin(async { Ok((1, 2)) }));
        mock_git_client
            .expect_list_upstream_commit_titles()
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(vec![
                        "Update changelog format".to_string(),
                        "Fix sync popup copy".to_string(),
                    ])
                })
            });
        mock_git_client
            .expect_get_ahead_behind()
            .times(1)
            .return_once(|_| Box::pin(async { Ok((1, 0)) }));
        mock_git_client
            .expect_list_local_commit_titles()
            .times(1)
            .returning(|_| {
                Box::pin(async { Ok(vec!["Refine sync conflict messaging".to_string()]) })
            });
        mock_git_client
            .expect_pull_rebase()
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(git::PullRebaseResult::Conflict {
                        detail: "CONFLICT (content): Merge conflict in src/lib.rs".to_string(),
                    })
                })
            });
        mock_git_client
            .expect_list_conflicted_files()
            .times(1)
            .returning(|_| Box::pin(async { Ok(vec!["src/lib.rs".to_string()]) }));
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(2)
            .returning(|_, _| Box::pin(async { Ok(vec![]) }));
        mock_git_client
            .expect_stage_all()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_has_unmerged_paths()
            .times(1)
            .returning(|_| Box::pin(async { Ok(false) }));
        mock_git_client
            .expect_rebase_continue()
            .times(1)
            .returning(|_| Box::pin(async { Ok(git::RebaseStepResult::Completed) }));
        mock_git_client
            .expect_push_current_branch()
            .times(1)
            .returning(|_| Box::pin(async { Ok("origin/main".to_string()) }));
        mock_git_client.expect_abort_rebase().times(0);

        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(1)
            .returning(|_, _, _| Box::pin(async { Ok(()) }));

        // Act
        let result = SessionManager::sync_main_for_project_with_assist_client(
            Some("main".to_string()),
            working_dir,
            test_fs_client(),
            Arc::new(mock_git_client),
            AgentModel::Gemini3FlashPreview,
            Arc::new(mock_sync_assist_client),
        )
        .await;

        // Assert
        assert_eq!(
            result,
            Ok(SyncMainOutcome {
                pulled_commit_titles: vec![
                    "Update changelog format".to_string(),
                    "Fix sync popup copy".to_string(),
                ],
                pulled_commits: Some(2),
                pushed_commit_titles: vec!["Refine sync conflict messaging".to_string()],
                pushed_commits: Some(1),
                resolved_conflict_files: vec!["src/lib.rs".to_string()],
            }),
            "sync should succeed after assistance with summary details"
        );
    }

    #[tokio::test]
    async fn test_sync_main_for_project_fails_after_max_assistance_attempts() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let working_dir = temp_dir.path().to_path_buf();
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_find_git_repo_root()
            .times(1)
            .returning(|folder| Box::pin(async move { Some(folder) }));
        mock_git_client
            .expect_is_worktree_clean()
            .times(1)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_get_ahead_behind()
            .times(1)
            .returning(|_| Box::pin(async { Ok((0, 1)) }));
        mock_git_client
            .expect_list_upstream_commit_titles()
            .times(1)
            .returning(|_| Box::pin(async { Ok(vec!["Upstream patch".to_string()]) }));
        mock_git_client
            .expect_pull_rebase()
            .times(1)
            .returning(|_| {
                Box::pin(async {
                    Ok(git::PullRebaseResult::Conflict {
                        detail: "CONFLICT (content): Merge conflict in src/lib.rs".to_string(),
                    })
                })
            });
        mock_git_client
            .expect_list_conflicted_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_| Box::pin(async { Ok(vec!["src/lib.rs".to_string()]) }));
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_, _| Box::pin(async { Ok(vec![]) }));
        mock_git_client
            .expect_stage_all()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_has_unmerged_paths()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client.expect_rebase_continue().times(0);
        mock_git_client.expect_push_current_branch().times(0);
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));

        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_, _, _| Box::pin(async { Ok(()) }));

        // Act
        let result = SessionManager::sync_main_for_project_with_assist_client(
            Some("main".to_string()),
            working_dir,
            test_fs_client(),
            Arc::new(mock_git_client),
            AgentModel::Gemini3FlashPreview,
            Arc::new(mock_sync_assist_client),
        )
        .await;

        // Assert
        let error = result.expect_err("sync should fail when conflicts remain unresolved");
        assert!(matches!(error, SyncSessionStartError::Other(_)));
        assert!(
            error
                .detail_message()
                .contains("Conflicts remain unresolved after maximum assistance attempts"),
            "error detail should mention unresolved conflicts"
        );
    }

    /// Verifies sync assistance merges tracked conflicts with staged conflict
    /// marker files and returns a sorted unique list.
    #[tokio::test]
    async fn test_load_sync_conflicted_files_merges_and_sorts_results() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_list_conflicted_files()
            .times(1)
            .returning(|_| {
                Box::pin(async { Ok(vec!["src/b.rs".to_string(), "src/c.rs".to_string()]) })
            });
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(1)
            .returning(|_, _| {
                Box::pin(async { Ok(vec!["src/a.rs".to_string(), "src/c.rs".to_string()]) })
            });

        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(0);
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let input = build_sync_rebase_input_for_test(
            temp_dir.path().to_path_buf(),
            Arc::new(mock_git_client),
            Arc::new(mock_sync_assist_client),
        );

        // Act
        let conflicted_files = SessionManager::load_sync_conflicted_files(&input, &[]).await;

        // Assert
        let files = conflicted_files.expect("load_sync_conflicted_files should succeed");
        assert_eq!(
            files,
            vec![
                "src/a.rs".to_string(),
                "src/b.rs".to_string(),
                "src/c.rs".to_string(),
            ]
        );
    }

    /// Verifies sync conflict checks keep the loop in assistance mode when
    /// staged files still contain conflict markers.
    #[tokio::test]
    async fn test_stage_and_check_for_sync_conflicts_detects_remaining_markers() {
        // Arrange
        let mut mock_git_client = git::MockGitClient::new();
        let mut sequence = Sequence::new();
        mock_git_client
            .expect_stage_all()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_has_unmerged_paths()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_| Box::pin(async { Ok(false) }));
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(1)
            .in_sequence(&mut sequence)
            .returning(|_, _| Box::pin(async { Ok(vec!["src/lib.rs".to_string()]) }));

        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(0);
        let temp_dir = tempdir().expect("failed to create temporary test directory");
        let input = build_sync_rebase_input_for_test(
            temp_dir.path().to_path_buf(),
            Arc::new(mock_git_client),
            Arc::new(mock_sync_assist_client),
        );

        // Act
        let still_has_conflicts =
            SessionManager::stage_and_check_for_sync_conflicts(&input, &["src/lib.rs".to_string()])
                .await;

        // Assert
        let has_conflicts = still_has_conflicts.expect("stage_and_check should succeed");
        assert!(has_conflicts);
    }

    /// Verifies sync assistance aborts when the conflicted file fingerprint
    /// repeats across attempts without any file changes.
    #[tokio::test]
    async fn test_run_sync_rebase_assist_loop_aborts_for_unchanged_conflict_files() {
        // Arrange
        let temp_dir = tempdir().expect("create temp dir");
        let conflict_file = temp_dir.path().join("src/lib.rs");
        std::fs::create_dir_all(
            conflict_file
                .parent()
                .expect("conflict file should have a parent directory"),
        )
        .expect("create conflict directory");
        std::fs::write(&conflict_file, "<<<<<<< HEAD\none\n=======\ntwo\n>>>>>>>")
            .expect("write conflict file");

        let fingerprint_fs_client = create_passthrough_mock_fs_client();
        let fingerprint = SessionManager::conflicted_file_fingerprint(
            &fingerprint_fs_client,
            temp_dir.path(),
            &["src/lib.rs".to_string()],
        )
        .await;

        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_list_conflicted_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_| Box::pin(async { Ok(vec!["src/lib.rs".to_string()]) }));
        mock_git_client
            .expect_list_staged_conflict_marker_files()
            .times(REBASE_ASSIST_POLICY.max_attempts)
            .returning(|_, _| Box::pin(async { Ok(vec![]) }));
        mock_git_client
            .expect_stage_all()
            .times(REBASE_ASSIST_POLICY.max_attempts - 1)
            .returning(|_| Box::pin(async { Ok(()) }));
        mock_git_client
            .expect_has_unmerged_paths()
            .times(REBASE_ASSIST_POLICY.max_attempts - 1)
            .returning(|_| Box::pin(async { Ok(true) }));
        mock_git_client
            .expect_abort_rebase()
            .times(1)
            .returning(|_| Box::pin(async { Ok(()) }));

        let mut mock_sync_assist_client = MockSyncAssistClient::new();
        mock_sync_assist_client
            .expect_resolve_rebase_conflicts()
            .times(REBASE_ASSIST_POLICY.max_attempts - 1)
            .returning(|_, _, _| Box::pin(async { Ok(()) }));

        let input = build_sync_rebase_input_for_test(
            temp_dir.path().to_path_buf(),
            Arc::new(mock_git_client),
            Arc::new(mock_sync_assist_client),
        );

        // Act
        let result = SessionManager::run_sync_rebase_assist_loop(input, fingerprint).await;

        // Assert
        assert_eq!(
            result.map_err(|error| error.to_string()),
            Err(
                "Sync rebase assistance made no progress: conflicted files did not change"
                    .to_string()
            )
        );
    }

    #[tokio::test]
    async fn test_conflicted_file_fingerprint_changes_with_file_content() {
        // Arrange
        let fs_client = create_passthrough_mock_fs_client();
        let temp_dir = std::env::temp_dir().join(format!(
            "agentty_fp_content_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_dir).expect("create temp dir");
        let file_path = temp_dir.join("conflict.rs");
        let files = vec!["conflict.rs".to_string()];

        // Act
        std::fs::write(&file_path, "<<<<<<< HEAD\nfoo\n=======\nbar\n>>>>>>>")
            .expect("write initial content");
        let fingerprint_before =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;
        std::fs::write(
            &file_path,
            "<<<<<<< HEAD\nfoo_patched\n=======\nbar\n>>>>>>>",
        )
        .expect("write patched content");
        let fingerprint_after =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;

        // Assert — partial progress changes the fingerprint
        assert_ne!(fingerprint_before, fingerprint_after);

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    async fn test_conflicted_file_fingerprint_stable_for_unchanged_content() {
        // Arrange
        let fs_client = create_passthrough_mock_fs_client();
        let temp_dir = std::env::temp_dir().join(format!(
            "agentty_fp_stable_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_dir).expect("create temp dir");
        std::fs::write(temp_dir.join("conflict.rs"), "same content").expect("write file");
        let files = vec!["conflict.rs".to_string()];

        // Act
        let fingerprint_a =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;
        let fingerprint_b =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;

        // Assert — identical content produces identical fingerprint
        assert_eq!(fingerprint_a, fingerprint_b);

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    async fn test_conflicted_file_fingerprint_order_independent() {
        // Arrange
        let fs_client = create_passthrough_mock_fs_client();
        let temp_dir = std::env::temp_dir().join(format!(
            "agentty_fp_order_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_dir).expect("create temp dir");
        std::fs::write(temp_dir.join("a.rs"), "content a").expect("write a.rs");
        std::fs::write(temp_dir.join("b.rs"), "content b").expect("write b.rs");

        // Act
        let fingerprint_ab = SessionManager::conflicted_file_fingerprint(
            &fs_client,
            &temp_dir,
            &["a.rs".to_string(), "b.rs".to_string()],
        )
        .await;
        let fingerprint_ba = SessionManager::conflicted_file_fingerprint(
            &fs_client,
            &temp_dir,
            &["b.rs".to_string(), "a.rs".to_string()],
        )
        .await;

        // Assert — order of file list does not affect the fingerprint
        assert_eq!(fingerprint_ab, fingerprint_ba);

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    async fn test_conflicted_file_fingerprint_missing_file_is_stable() {
        // Arrange — reference a file that does not exist on disk
        let fs_client = create_passthrough_mock_fs_client();
        let temp_dir = std::env::temp_dir().join(format!(
            "agentty_fp_missing_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&temp_dir).expect("create temp dir");
        let files = vec!["nonexistent.rs".to_string()];

        // Act — should not panic; missing files are silently skipped
        let fingerprint_a =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;
        let fingerprint_b =
            SessionManager::conflicted_file_fingerprint(&fs_client, &temp_dir, &files).await;

        // Assert — deterministic even when file is absent
        assert_eq!(fingerprint_a, fingerprint_b);

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[tokio::test]
    /// Verifies that a successful rebase triggers an auto-push and reports the
    /// successful sync state when the session has a previously published
    /// upstream branch.
    async fn test_finalize_rebase_task_triggers_auto_push_for_published_branch() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let project_id = db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        db.sessions()
            .insert_session(
                "sess-rebase",
                "gemini-3-flash-preview",
                "main",
                "Rebasing",
                project_id,
            )
            .await
            .expect("failed to insert session");
        db.sessions()
            .update_session_published_upstream_ref(
                "sess-rebase",
                Some("origin/wt/sess-rebase".to_string()),
            )
            .await
            .expect("failed to set published upstream ref");

        let (app_event_tx, mut app_event_rx) = mpsc::unbounded_channel();
        let temp_dir = tempdir().expect("failed to create temp dir");
        let folder = temp_dir.path().join("sess-rebase");
        let output = Arc::new(Mutex::new(String::new()));
        let status = Arc::new(Mutex::new(Status::Rebasing));

        let mut mock_git_client = git::MockGitClient::new();
        mock_git_client
            .expect_push_current_branch_to_remote_branch()
            .once()
            .withf(|session_folder, remote_branch_name| {
                session_folder.ends_with("sess-rebase") && remote_branch_name == "wt/sess-rebase"
            })
            .returning(|_, _| Box::pin(async { Ok("origin/wt/sess-rebase".to_string()) }));
        let git_client: Arc<dyn GitClient> = Arc::new(mock_git_client);

        // Act
        SessionManager::finalize_rebase_task(FinalizeRebaseInput {
            app_event_tx: &app_event_tx,
            clock: &crate::app::session::RealClock,
            db: &db,
            folder: &folder,
            git_client: &git_client,
            id: "sess-rebase",
            output: &output,
            rebase_result: Ok("Successfully rebased wt/sess-rebase onto main".to_string()),
            session_update_versions: &Arc::default(),
            status: &status,
        })
        .await;

        // Assert — collect sync events emitted by the auto-push task.
        let sync_events = tokio::time::timeout(std::time::Duration::from_secs(2), async {
            let mut sync_events = Vec::new();
            while sync_events.len() < 2 {
                let event = app_event_rx.recv().await.expect("missing app event");
                if let AppEvent::PublishedBranchSyncUpdated {
                    session_id,
                    sync_operation_id,
                    sync_status,
                } = event
                {
                    sync_events.push((session_id, sync_operation_id, sync_status));
                }
            }

            sync_events
        })
        .await
        .expect("timed out waiting for sync events");

        assert_eq!(sync_events[0].0, "sess-rebase");
        assert_eq!(sync_events[0].2, PublishedBranchSyncStatus::InProgress);
        assert_eq!(sync_events[1].0, "sess-rebase");
        assert_eq!(sync_events[1].2, PublishedBranchSyncStatus::Succeeded);
        assert_eq!(sync_events[0].1, sync_events[1].1);

        let output_text = output.lock().expect("output lock poisoned").clone();
        assert!(output_text.contains("[Rebase] Successfully rebased"));
    }

    #[tokio::test]
    /// Verifies that a successful rebase does not trigger auto-push when the
    /// session has no published upstream branch.
    async fn test_finalize_rebase_task_skips_auto_push_without_published_branch() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        let project_id = db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to upsert project");
        db.sessions()
            .insert_session(
                "sess-no-push",
                "gemini-3-flash-preview",
                "main",
                "Rebasing",
                project_id,
            )
            .await
            .expect("failed to insert session");

        let (app_event_tx, mut app_event_rx) = mpsc::unbounded_channel();
        let temp_dir = tempdir().expect("failed to create temp dir");
        let folder = temp_dir.path().join("sess-no-push");
        let output = Arc::new(Mutex::new(String::new()));
        let status = Arc::new(Mutex::new(Status::Rebasing));
        let git_client: Arc<dyn GitClient> = Arc::new(git::MockGitClient::new());

        // Act
        SessionManager::finalize_rebase_task(FinalizeRebaseInput {
            app_event_tx: &app_event_tx,
            clock: &crate::app::session::RealClock,
            db: &db,
            folder: &folder,
            git_client: &git_client,
            id: "sess-no-push",
            output: &output,
            rebase_result: Ok("Successfully rebased wt/sess-no-push onto main".to_string()),
            session_update_versions: &Arc::default(),
            status: &status,
        })
        .await;

        // Assert — no PublishedBranchSyncUpdated events should be emitted.
        // Drain remaining events and check that none are sync events.
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let mut sync_event_count = 0;
        while let Ok(event) = app_event_rx.try_recv() {
            if matches!(event, AppEvent::PublishedBranchSyncUpdated { .. }) {
                sync_event_count += 1;
            }
        }
        assert_eq!(
            sync_event_count, 0,
            "should not emit sync events without published branch"
        );

        let output_text = output.lock().expect("output lock poisoned").clone();
        assert!(output_text.contains("[Rebase] Successfully rebased"));
    }
}