rpi-cli 0.18.0

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

mod backend;

use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex, OnceLock};

use rpi_ai::Provider;
use rpi_harness::agent_harness::AgentHarness;
use rpi_harness::context_files::{format_project_context, load_project_context_files};
use rpi_harness::session::memory::{InMemorySessionStorage, SystemClock};
use rpi_harness::session::session::DefaultIdGenerator;
use rpi_harness::session::types::SessionMetadata;
use rpi_harness::session::Session;
use rpi_harness::system_prompt::compose_system_prompt;
use rpi_harness::types::{
    AgentHarnessOptions, AgentHarnessResources, AgentHarnessStreamOptions, DrivingMode,
    HarnessTool, HarnessToolExecution, ToolReplay,
};
#[cfg(windows)]
use rpi_tools::create_powershell_tool;
use rpi_tools::{
    create_bash_tool, create_edit_tool, create_read_tool, create_write_tool, ExecutionToolContext,
    MutationQueueRegistry, OsExecutionEnv,
};

use crate::args::Args;
use crate::docs_tool::create_docs_tool;
use crate::provider::ResolvedModel;
use crate::resource_dirs::{
    discover_append_system_prompt_file, discover_system_prompt_file, extension_dirs,
    global_extension_dirs, global_prompt_template_dirs, global_skill_dirs,
    load_prompt_templates_with_precedence, load_skills_with_precedence, project_extension_dirs,
    project_prompt_template_dirs, project_skill_dirs, prompt_template_dirs, skill_dirs,
};
use crate::startup_diagnostics::{Phase, StartupSpan};
use rpi_extensions::{
    emit_resources_discover, ExtensionEmitter, ExtensionSession, NullDiagnostics,
    PluginDiagnostics, PluginToolAdapter, TeeEmitter, ToolPromptMetadata,
};

// Preserve the existing public modes::rpc signature. This CLI-only attachment
// table holds no session/router alive and keys by storage allocation identity,
// NOT by a durable ID (two independent restored hosts must never share routing).
// The session/tools/ReloadContext own the actual router. RPC owns its client.
// Reload MUST reuse ReloadContext::file_io, including a disconnected selected
// client backend; rebuilding a default router would silently restore host file
// authority. Missing attachments reject configuration (never infer a router or
// install host-backed replacements). This compatibility bridge can be replaced
// by an explicit neutral harness attachment when its public API is revised.
type FileIOAttachment = (
    std::sync::Weak<dyn rpi_harness::session::types::SessionStorage>,
    std::sync::Weak<rpi_tools::file_io::FileIORouter>,
);
fn file_io_attachments() -> &'static Mutex<Vec<FileIOAttachment>> {
    static ATTACHMENTS: std::sync::OnceLock<Mutex<Vec<FileIOAttachment>>> =
        std::sync::OnceLock::new();
    ATTACHMENTS.get_or_init(|| Mutex::new(Vec::new()))
}
pub(crate) fn register_file_io_router(
    harness: &AgentHarness,
    router: &Arc<rpi_tools::file_io::FileIORouter>,
) {
    let storage = harness.session().storage();
    let mut attachments = file_io_attachments()
        .lock()
        .expect("file I/O attachments poisoned");
    attachments.retain(|(s, r)| {
        s.strong_count() > 0
            && r.strong_count() > 0
            && !s
                .upgrade()
                .is_some_and(|known| Arc::ptr_eq(&known, &storage))
    });
    attachments.push((Arc::downgrade(&storage), Arc::downgrade(router)));
}
pub(crate) fn file_io_router(
    harness: &AgentHarness,
) -> Option<Arc<rpi_tools::file_io::FileIORouter>> {
    let storage = harness.session().storage();
    let mut attachments = file_io_attachments()
        .lock()
        .expect("file I/O attachments poisoned");
    attachments.retain(|(s, r)| s.strong_count() > 0 && r.strong_count() > 0);
    attachments.iter().find_map(|(s, r)| {
        s.upgrade()
            .filter(|known| Arc::ptr_eq(known, &storage))
            .and_then(|_| r.upgrade())
    })
}

/// The coding tools registered by the CLI by default.
pub const BUILTIN_TOOL_NAMES: &[&str] = &["read", "bash", "edit", "write", "docs"];

/// The default coding system prompt for the CLI's built-in tools.
///
/// This retains the two-argument API for library callers. Session startup and
/// reload use [`default_system_prompt_with_tool_prompts`] with the actual active
/// tools and their winning extension metadata.
pub fn default_system_prompt(cwd: &str, prior_reasoning_replayed: bool) -> String {
    let tools = BUILTIN_TOOL_NAMES
        .iter()
        .map(|name| (*name).to_owned())
        .collect::<Vec<_>>();
    default_system_prompt_with_tools(cwd, prior_reasoning_replayed, &tools)
}

/// A coding system prompt for the selected tools. A condensed port of the TS
/// `packages/coding-agent/src/core/system-prompt.ts` base prompt.
///
/// `tools` is the active tool set after `--tools`/`--exclude-tools` and
/// extension merging. Like pi, the text list includes only tools with an
/// explicit prompt snippet; other active tools remain available through their
/// provider-facing schemas. Tool-specific guidelines still follow the full
/// active set, so restricted runs get no guidance for unavailable tools.
pub fn default_system_prompt_with_tools(
    cwd: &str,
    prior_reasoning_replayed: bool,
    tools: &[String],
) -> String {
    default_system_prompt_with_tool_prompts(cwd, prior_reasoning_replayed, tools, &BTreeMap::new())
}

/// Render pi-style explicit prompt contributions for the active tool set.
/// Entries override built-in metadata, including an empty entry for an
/// extension that replaces a built-in without contributing a prompt snippet.
/// Inactive metadata is ignored. Schemas and callable tools are not modified.
pub fn default_system_prompt_with_tool_prompts(
    cwd: &str,
    prior_reasoning_replayed: bool,
    tools: &[String],
    overrides: &BTreeMap<String, ToolPromptMetadata>,
) -> String {
    let metadata: BTreeMap<_, _> = tools
        .iter()
        .map(|name| {
            let prompt = overrides
                .get(name)
                .cloned()
                .unwrap_or_else(|| ToolPromptMetadata {
                    prompt_snippet: builtin_tool_snippet(name).map(str::to_owned),
                    prompt_guidelines: Vec::new(),
                })
                .normalized();
            (name.as_str(), prompt)
        })
        .collect();
    // The working-state rule must match what actually comes back on the next
    // request. With `compat.requiresThinkingAsText` (or the native thinking
    // channels of anthropic/responses) the model *does* see its own reasoning
    // again, and claiming otherwise makes it re-derive and restate the plan
    // every turn — the re-plan symptom in `docs/llm-repetition-forensics.md`.
    let working_state_rule = if prior_reasoning_replayed {
        "- Your reasoning is carried back to you on the next turn: do not re-derive it or restate
  the plan. Continue from the last unfinished step, and when a step lands, say which one.
  Re-stating the same plan without acting on it is a bug, not progress."
    } else {
        "- Your reasoning is not carried into your next turn; only your visible replies and tool
  output come back. Before each batch of tool calls, write one short line naming the step you
  are on and what remains, and say which step is done when it lands.
  Re-stating the same plan without acting on it is a bug, not progress."
    };

    // The text list is a selective summary, not the tool registry. In
    // particular, do not repeat extension tool names without a prompt snippet.
    let tool_lines = tools
        .iter()
        .filter_map(|name| {
            metadata
                .get(name.as_str())?
                .prompt_snippet
                .as_ref()
                .map(|snippet| format!("- {name:<5} — {snippet}"))
        })
        .collect::<Vec<_>>()
        .join("\n");
    let tool_lines = if tool_lines.is_empty() {
        "(none)".to_string()
    } else {
        tool_lines
    };

    // Tool-specific rules (Bash on Windows, docs before guessing) live in the
    // tool's own line or description, not here a second time.
    let guidelines = [
        "- Reply in the same language as the user's latest message (the conversation's language when
  that message is too short to tell), unless the user asks for another.",
        "- Be concise in your responses",
        "- Show file paths clearly when working with files",
        "- Prefer the smallest change that solves the problem",
        working_state_rule,
        "- Read only what you need. If a file or search result was already shown earlier in this
  conversation, use it instead of fetching it again.",
    ];
    // Tools contribute rules even without snippets. Like pi, trim and dedupe
    // across the full active set and the core rules, preserving first occurrence.
    let mut seen = HashSet::new();
    let tool_rules = tools
        .iter()
        .flat_map(|name| &metadata[name.as_str()].prompt_guidelines)
        .map(String::as_str);
    let core_rules = guidelines
        .iter()
        .map(|rule| rule.strip_prefix("- ").unwrap_or(rule));
    let guidelines = tool_rules
        .chain(core_rules)
        .map(str::trim)
        .filter(|rule| !rule.is_empty() && seen.insert(*rule))
        .map(|rule| format!("- {rule}"))
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        "You are an expert coding assistant operating inside rpi, a coding agent harness. \
You help users by reading files, executing commands, editing code, and writing new files.

Available tools:
{tool_lines}

In addition to the tools above, you may have access to other custom tools depending on the project.

Guidelines:
{guidelines}

Current working directory: {cwd}"
    )
}

/// Take metadata from the same winning extension definitions used for tool
/// merging, including empty metadata for overrides. Called on startup/reload.
fn extension_tool_prompt_metadata(
    session: &ExtensionSession,
) -> BTreeMap<String, ToolPromptMetadata> {
    session
        .snapshot()
        .map(|snapshot| {
            snapshot
                .tools()
                .iter()
                .map(|tool| (tool.tool.name.clone(), tool.prompt.clone()))
                .collect()
        })
        .unwrap_or_default()
}

/// One-line prompt descriptions of the tools rpi itself registers.
fn builtin_tool_snippet(name: &str) -> Option<&'static str> {
    Some(match name {
        "read" => "Read file contents",
        "bash" => "Execute Bash commands (Bash/POSIX syntax, also on Windows)",
        "edit" => "Find/replace edits to existing files",
        "write" => "Create or overwrite files",
        "docs" => "Look up rpi commands, extensions, Pi package compatibility and .rpi configuration instead of guessing",
        "grep" => "Search file contents for a pattern",
        "find" => "Find files by glob pattern",
        "ls" => "List directory contents",
        "powershell" => "Execute PowerShell commands on Windows",
        _ => return None,
    })
}

/// How the user asked to select a session. v1 honors `NoSession` (ephemeral
/// `InMemorySessionStorage`), `New` (a fresh JSONL file), and — new this pass —
/// `Latest` / `ById`, which **restore** an existing JSONL session on launch
/// (`--continue`/`-c`, `--resume`/`-r`, `--session <id|path>`). The restored
/// transcript renders into the TUI on startup and the run continues appending
/// to the same file.
#[derive(Debug, Clone)]
pub enum SessionSelection {
    /// `--no-session`: ephemeral, in-memory, nothing persisted.
    Ephemeral,
    /// Fresh durable JSONL session under `--session-dir` (or the default dir).
    New { dir: PathBuf, name: Option<String> },
    /// Explicit fresh print-only experimental backend; never a restore selection.
    ExperimentalNative { dir: PathBuf },
    /// `-c` / `-r`: restore the most recent session in the default dir.
    Latest { dir: PathBuf },
    /// `--session <id|path>`: restore the session whose id matches, or whose
    /// file name contains the id.
    ById { id: String, dir: PathBuf },
    /// `--session-id <id>`: use the EXACT session id, creating it if missing.
    ByExactId { id: String, dir: PathBuf },
    /// `--fork <path|id>`: fork the given session into a new one and start in
    /// the fork.
    Fork { source: String, dir: PathBuf },
}

/// Decide the session selection from parsed args + the resolved cwd.
pub fn select_session(args: &Args, cwd: &Path) -> SessionSelection {
    select_session_in_dir(args, configured_session_dir(args, cwd))
}

/// Resolve the root once at startup; runtime actions retain this selection.
pub(crate) fn configured_session_dir(args: &Args, cwd: &Path) -> PathBuf {
    if let Some(root) = &args.experimental_native_store {
        return if root.is_absolute() {
            root.clone()
        } else {
            cwd.join(root)
        };
    }
    let dir = args
        .session_dir
        .clone()
        .or_else(|| {
            crate::settings::load_settings()
                .ok()
                .and_then(|settings| settings.session_dir)
        })
        .unwrap_or_else(|| default_session_dir(cwd));
    // Relative roots belong to the launch project, even if an extension later
    // changes the process working directory.
    if dir.is_relative() && !dir.has_root() {
        cwd.join(dir)
    } else {
        dir
    }
}

pub(crate) fn select_session_in_dir(args: &Args, dir: PathBuf) -> SessionSelection {
    if args.experimental_native_store.is_some() {
        return SessionSelection::ExperimentalNative { dir };
    }
    if args.no_session {
        return SessionSelection::Ephemeral;
    }
    // `--session-dir` wins; then the saved `sessionDir` (upstream's key, same
    // format as the flag); then the built-in default. Keep this directory on
    // restore selections too, not only on fresh sessions.
    if args.continue_session || args.resume {
        return SessionSelection::Latest { dir };
    }
    if let Some(s) = &args.fork {
        return SessionSelection::Fork {
            source: s.clone(),
            dir,
        };
    }
    if let Some(s) = &args.session_id {
        return SessionSelection::ByExactId { id: s.clone(), dir };
    }
    if let Some(s) = &args.session {
        return SessionSelection::ById { id: s.clone(), dir };
    }
    SessionSelection::New {
        dir,
        name: args.name.clone(),
    }
}

/// The default session directory is `<cwd>/.rpi/sessions`, unless
/// `RPI_CODING_AGENT_SESSION_DIR` is set (in which case its value is used).
pub fn default_session_dir(cwd: &Path) -> PathBuf {
    std::env::var("RPI_CODING_AGENT_SESSION_DIR")
        .ok()
        .map(PathBuf::from)
        .unwrap_or_else(|| cwd.join(".rpi").join("sessions"))
}

/// Extensions are loaded exactly once before model resolution. Their action
/// host remains unbound until the harness and authenticated catalog exist.
pub struct PreparedExtensions {
    resource_leases: Arc<Vec<crate::resource_management::Lease>>,
    resource_selection: Option<crate::resource_selection::ResolvedSelection>,
    session_selection: SessionSelection,
    transition_session: Option<Session>,
    pub extension_session: ExtensionSession,
    native_store: Option<PathBuf>,
    session_dir: PathBuf,
    runtime: tokio::runtime::Handle,
    tool_context: rpi_extensions::ToolCallContext,
    action_host: Arc<crate::extensions_actions::HarnessActionHost>,
    harness_cell: Arc<std::sync::OnceLock<rpi_harness::agent_harness::WeakAgentHarness>>,
    reload_mailbox: rpi_extensions::ReloadMailbox,
    ui_dialog_mailbox: rpi_extensions::UiDialogMailbox,
    ext_status_mailbox: rpi_extensions::ExtensionStatusMailbox,
    editor_text_mailbox: rpi_extensions::EditorTextMailbox,
    action_bridge: Arc<rpi_extensions::ActionBridge>,
}

/// Validate native durable resource ownership BEFORE loading any executable code.
/// The synchronous public prepare_extensions API is retained: a scoped reader
/// thread uses its own runtime so this also works inside current-thread Tokio.
/// It does no registration, provider callbacks, session creation, or lock claiming.
pub(crate) fn preflight_extension_startup(
    args: &Args,
    cwd: &Path,
    trusted: bool,
) -> Result<
    (
        Option<crate::resource_selection::ResolvedSelection>,
        SessionSelection,
    ),
    BuildError,
> {
    let mut resources = crate::resource_selection::ResolvedSelection::load(args, cwd, trusted)
        .map_err(BuildError::HarnessCreate)?;
    let selection = select_session(args, cwd);
    let pinned = std::thread::scope(|scope| {
        scope
            .spawn(|| {
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| BuildError::SessionOpen(e.to_string()))?
                    .block_on(async {
                        if let Some(selected) = &mut resources {
                            let env: Arc<dyn rpi_tools::ExecutionEnv> =
                                Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
                            selected
                                .validate_skills(&env)
                                .await
                                .map_err(BuildError::HarnessCreate)?;
                        }
                        let cwd_str = cwd.to_string_lossy();
                        let target = match &selection {
                            SessionSelection::Fork { source, dir } => {
                                match session_metadata_at(Path::new(source)) {
                                    Some(meta) => Some(meta),
                                    None => find_session_metadata(source, &cwd_str, dir).await?,
                                }
                            }
                            _ => resolve_restore_target(&selection, &cwd_str).await?,
                        };
                        let Some(meta) = target else {
                            if resources.as_ref().is_some_and(|r| r.transition.is_some()) {
                                return Err(BuildError::SessionOpen("resource transition requires an existing native session".into()));
                            }
                            return Ok(selection.clone());
                        };
                        if resources.as_ref().is_some_and(|r| r.transition.is_some()) && matches!(selection, SessionSelection::Fork { .. }) {
                            return Err(BuildError::SessionOpen("resource transition cannot fork".into()));
                        }
                        use rpi_harness::session::jsonl::{
                            JsonlSessionRepo, JsonlSessionRepoOptions,
                        };
                        let dir = selection_dir(&selection);
                        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
                            fs: Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
                            sessions_root: dir.to_string_lossy().into_owned(),
                            clock: Arc::new(SystemClock),
                            ids: Arc::new(DefaultIdGenerator::new()),
                        });
                        let binding_facts = StartupSpan::start(Phase::BindingFacts);
                        let facts = if resources.as_ref().is_some_and(|r| r.transition.is_some()) {
                            rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
                                Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &meta.path,
                                Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
                            ).await
                        } else { repo.read_facts_by_jsonl_metadata(&meta).await }
                            .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
                        crate::resource_selection::validate_session_binding(
                            &facts.values,
                            resources.as_ref(),
                        )
                        .map_err(BuildError::SessionOpen)?;
                        binding_facts.finish();
                        Ok(match selection {
                            SessionSelection::Fork { .. } => SessionSelection::Fork {
                                source: meta.path,
                                dir,
                            },
                            _ => SessionSelection::ByExactId { id: meta.id, dir },
                        })
                    })
            })
            .join()
            .map_err(|_| BuildError::SessionOpen("resource preflight reader panicked".into()))?
    })?;
    Ok((resources, pinned))
}

pub fn prepare_extensions(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
) -> Result<PreparedExtensions, BuildError> {
    let native_store =
        crate::native_store::root(args, cwd).map_err(BuildError::NativeStorePolicy)?;
    let resource_leases =
        crate::resource_management::host_leases(cwd).map_err(BuildError::HarnessCreate)?;
    let (resource_selection, session_selection) =
        preflight_extension_startup(args, cwd, project_trusted)?;
    // Transition hosts own the writer before any DLL registration. The strict
    // loader cannot repair history/progress or migrate metadata on rejection.
    let transition_session = if resource_selection
        .as_ref()
        .is_some_and(|r| r.transition.is_some())
    {
        Some(std::thread::scope(|scope| {
            scope.spawn(|| {
            tokio::runtime::Builder::new_current_thread().enable_all().build()
                .map_err(|e| BuildError::SessionOpen(e.to_string()))?.block_on(async {
                    let meta = resolve_restore_target(&session_selection, &cwd.to_string_lossy()).await?
                        .ok_or_else(|| BuildError::SessionOpen("transition session disappeared".into()))?;
                    let path = std::fs::canonicalize(&meta.path).map_err(|e| BuildError::SessionOpen(e.to_string()))?;
                    claim_session_lock_inner(&path.to_string_lossy(), false).map_err(BuildError::SessionOpen)?;
                    let storage = rpi_harness::session::jsonl::JsonlSessionStorage::load_for_resource_transition(
                        Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())), &path.to_string_lossy(),
                        Arc::new(SystemClock), Arc::new(DefaultIdGenerator::new()),
                    ).await.map_err(|e| BuildError::SessionOpen(e.to_string()))?;
                    let session = Session::new(Arc::new(storage), None);
                    crate::resource_selection::bind_session(&session, resource_selection.as_ref()).await.map_err(BuildError::SessionOpen)?;
                    Ok::<_, BuildError>(session)
                })
        }).join().map_err(|_| BuildError::SessionOpen("transition writer preparation panicked".into()))?
        })?)
    } else {
        None
    };
    let session_dir = if matches!(session_selection, SessionSelection::Ephemeral) {
        configured_session_dir(args, cwd)
    } else {
        selection_dir(&session_selection)
    };
    let cwd_str = cwd.to_string_lossy().to_string();
    let tool_context = rpi_extensions::ToolCallContext::new(cwd_str.clone());
    if !project_trusted && args.verbose {
        eprintln!(
            "warning: current-project settings, resources, and discovered extensions are explicitly disabled (use --approve or /trust yes to re-enable)"
        );
    }
    // Pi packages are explicitly opt-in because discovery can start Node and
    // execute package code. An explicit project opt-out limits discovery to
    // global settings.

    // ---- B5a: build the action bridge BEFORE extension load ----
    // Extensions load before `AgentHarness::create` (extensions provide tools the
    // harness is built with), but a plugin stores the `ActionBridge`'s raw
    // `user_data` pointer during `register` and it must remain valid + the host
    // must be ready for the whole session. So:
    //  1. Capture the current tokio `Handle` (the async main-thread runtime) —
    //     the bridge spawns dispatch from any thread via `Handle::spawn`.
    //  2. Build an *empty* `HarnessActionHost` (its harness cell is unset; no
    //     plugin can call a runtime action before the harness runs).
    //  3. Wrap it as `Arc<dyn RuntimeActionHost>` + `ActionBridge`, thread
    //     `Some(bridge)` into `load_extensions` so every plugin's `user_data`
    //     points at this bridge.
    //  4. After `AgentHarness::create` succeeds, call `set_harness(&cell, …)` to
    //     fill the host cell the bridge recovers on the first action call.
    let runtime = tokio::runtime::Handle::try_current().map_err(|e| {
        BuildError::HarnessCreate(format!("no tokio runtime for action bridge: {e}"))
    })?;
    let catalog = Vec::new();
    let (action_host, harness_cell) = crate::extensions_actions::HarnessActionHost::new_empty(
        catalog.clone(),
        cwd.to_path_buf(),
        runtime.clone(),
        args.unknown_flags.clone(),
        tool_context.clone(),
    );
    let action_host = Arc::new(
        action_host
            .with_session_dir(session_dir.clone())
            .with_fresh_session_only(native_store.is_some()),
    );
    let host_arc: Arc<dyn rpi_extensions::RuntimeActionHost> = action_host.clone();
    // `runtime` is reused below (B5c: `PluggableProvider` needs a captured
    // `Handle` to `spawn_blocking` the sync `ProviderRequestFn`), so clone here.
    //
    // B5d: build the initial bridge WITH a reload callback backed by a session-
    // long `ReloadMailbox` (cloned into `ReloadContext` + handed to the TUI). A
    // plugin's `runtime_action(Reload)` then signals the TUI's main loop instead
    // of hitting the "not configured" fallback. The same mailbox is reused on
    // `/reload` (the fresh bridge carries `ctx.mailbox`), so the bridge always
    // points at the one TUI-installed sender across reloads.
    let reload_mailbox = rpi_extensions::ReloadMailbox::new();
    // Session-scoped UI-dialog mailbox (runtime action 17 / `ask_user`). The
    // initial bridge carries it and the TUI attaches itself once it starts
    // polling; a headless run leaves it detached so `ask_user` fails loudly
    // instead of fabricating a user answer. The SAME mailbox is reused across
    // `/reload` so in-flight prompts + TUI attachment survive a plugin swap.
    let ui_dialog_mailbox = rpi_extensions::UiDialogMailbox::new();
    // Session-scoped extension status registry (runtime action 18 / `SetStatus`).
    // The bridge lets plugins write; the TUI polls the revision and repaints its
    // footer. Reused across `/reload` so a plugin's status survives the swap.
    let ext_status_mailbox = rpi_extensions::ExtensionStatusMailbox::new();
    // Session-scoped editor-text queue (runtime action 19 / `SetEditorText`).
    // The bridge lets a plugin drop a draft into the prompt editor; the TUI
    // drains it each tick. Reused across `/reload` so a pending transcription
    // survives a plugin swap.
    let editor_text_mailbox = rpi_extensions::EditorTextMailbox::new();
    let action_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
        runtime.clone(),
        host_arc,
        rpi_extensions::reload_callback_from_mailbox(reload_mailbox.clone()),
        ui_dialog_mailbox.clone(),
        ext_status_mailbox.clone(),
        editor_text_mailbox.clone(),
    );

    let extension_register = StartupSpan::start(Phase::ExtensionRegister);
    let extension_session = if let Some(selected) = &resource_selection {
        let session = rpi_extensions::load_session_mixed_guarded(
            &[],
            &selected.extensions,
            Arc::new(NullDiagnostics),
            Some(Arc::clone(&action_bridge)),
            Some(resource_leases.clone()),
        );
        if session.loaded_paths() != selected.extensions.as_slice() {
            return Err(BuildError::HarnessCreate(
                "selected native extension failed to load/register".into(),
            ));
        }
        if session.owns_stdio() {
            return Err(BuildError::HarnessCreate(
                "stdio-owning extensions are unsupported with --resource-config".into(),
            ));
        }
        session
    } else if args.no_extensions {
        ExtensionSession::none()
    } else {
        load_extensions(args, cwd, project_trusted, Some(Arc::clone(&action_bridge)))
    };
    extension_register.finish();
    if args.verbose {
        if let Some(s) = extension_session.summary() {
            eprintln!("extensions: {s}");
        }
        report_deferred_renderers(&extension_session);
    }
    crate::native_store::validate_stdio(native_store.is_some(), extension_session.owns_stdio())
        .map_err(BuildError::NativeStorePolicy)?;
    // Publish the extension registry so `ListCommands` can enumerate slash
    // commands. Done here rather than at host construction because the registry
    // only exists after extensions load; `/reload` republishes the new snapshot
    // via `RuntimeActionHost::publish_registry`.
    action_host.publish_registry_impl(extension_session.snapshot_arc());
    Ok(PreparedExtensions {
        resource_leases,
        resource_selection,
        session_selection,
        transition_session,
        native_store,
        session_dir,
        runtime,
        tool_context,
        action_host,
        harness_cell,
        reload_mailbox,
        ui_dialog_mailbox,
        ext_status_mailbox,
        editor_text_mailbox,
        action_bridge,
        extension_session,
    })
}

/// Build the `AgentHarness` from the resolved model + parsed args + cwd.
///
/// This is the v1 equivalent of TS `createAgentSession`. It:
/// 1. Builds the `OsExecutionEnv` rooted at `cwd`.
/// 2. Constructs the built-in tools (optionally filtered by `--tools`/
///    `--exclude-tools`/`--no-tools`/`--no-builtin-tools`).
/// 3. Resolves the session storage (ephemeral vs fresh JSONL vs restore-error).
/// 4. Assembles `AgentHarnessOptions` and calls `AgentHarness::create`.
///
/// Returns the harness plus a `broadcast::Receiver<AgentEvent>` carrying the
/// live `AgentEvent` stream from every run (backed by a `BroadcastEmitter`
/// installed on the harness). Interactive mode drains this to render streaming
/// responses; the non-interactive modes simply drop it.
/// Returns the harness, the live `AgentEvent` broadcast receiver, and a
/// [`ReloadContext`] the interactive TUI holds to drive `/reload` (and a
/// plugin's `runtime_action(Reload)` via the mailbox). Non-interactive modes
/// drop the context (no `/reload` surface in print/json mode).
pub async fn build(
    resolved: &ResolvedModel,
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
) -> Result<
    (
        AgentHarness,
        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
        ReloadContext,
    ),
    BuildError,
> {
    let prepared = prepare_extensions(args, cwd, project_trusted)?;
    build_prepared(resolved, args, cwd, project_trusted, prepared).await
}

pub async fn build_prepared(
    resolved: &ResolvedModel,
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
    prepared: PreparedExtensions,
) -> Result<
    (
        AgentHarness,
        tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>,
        ReloadContext,
    ),
    BuildError,
> {
    let native_store =
        crate::native_store::root(args, cwd).map_err(BuildError::NativeStorePolicy)?;
    if native_store != prepared.native_store {
        return Err(BuildError::NativeStorePolicy(
            "experimental session selection changed after extension preparation".into(),
        ));
    }
    crate::native_store::validate_stdio(
        native_store.is_some(),
        prepared.extension_session.owns_stdio(),
    )
    .map_err(BuildError::NativeStorePolicy)?;
    let fresh_session_only = native_store.is_some();
    let cwd_str = cwd.to_string_lossy().to_string();
    // Plugin tools get the session's identity injected into every call's
    // arguments (see `rpi_extensions::ToolCallContext`). It is created here,
    // before the tools are built, and completed with the session id below once
    // the session exists — the tool set has to exist before the harness does.
    let PreparedExtensions {
        resource_leases,
        resource_selection,
        session_selection: selection,
        transition_session,
        native_store: _,
        session_dir,
        runtime,
        tool_context,
        action_host,
        harness_cell,
        reload_mailbox,
        ui_dialog_mailbox,
        ext_status_mailbox,
        editor_text_mailbox,
        action_bridge,
        extension_session,
    } = prepared;
    let catalog = crate::provider::authenticated_catalog(resolved);
    action_host.set_catalog(catalog.clone());

    // ---- Execution env + tools ----
    let env = Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf()));
    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
    let _registry = Arc::new(MutationQueueRegistry::new());
    // `env_dyn` is shared between the tool context (moved in) and the resource
    // loaders below (borrowed); clone one branch so both hold a reference.
    let file_io = Arc::new(rpi_tools::file_io::FileIORouter::new());
    let ctx =
        ExecutionToolContext::new(env_dyn.clone(), Some(mut_env)).with_file_io(file_io.clone());

    let mut tools = build_tools(&ctx, args);

    // ---- Extensions (Part B2) ----
    // Load cdylib plugins from the resolved extension dirs, merge their tools
    // into the built-in set (extension overrides same-named built-in; first-
    // extension-wins across plugins; explicit `--tools`/`--exclude-tools` still
    // apply to the merged set), and keep the loaded `Library` handles alive for
    // the harness lifetime via the returned session guard. `--no-extensions`
    // skips discovery entirely (no dirs scanned, no plugins loaded).
    merge_extension_tools(&mut tools, &extension_session, args, &tool_context);
    let active = if let Some(selected) = &resource_selection {
        selected
            .active_tools(
                &tools
                    .iter()
                    .map(|t| t.tool.schema().name.clone())
                    .collect::<Vec<_>>(),
            )
            .map_err(BuildError::HarnessCreate)?
    } else {
        filter_active_tool_names(active_tool_names(&tools, args), args)
    };

    // ---- Session storage ----
    // The root is the one `prepare_extensions` froze at startup, never a fresh
    // `configured_session_dir(args, cwd)`: settings and `RPI_CODING_AGENT_SESSION_DIR`
    // can change while extensions load, and an adopted session cwd would point
    // at another project's tree. Both the cwd peek and this build must read the
    // same root, so the caller pins it into `args` before either runs.
    let session = match transition_session {
        Some(session) => session,
        None => build_session(&selection, &cwd_str, resource_selection.as_ref()).await?,
    };
    crate::resource_selection::bind_session(&session, resource_selection.as_ref())
        .await
        .map_err(BuildError::SessionOpen)?;
    // Plugin tools now know which session they serve: `todo` and friends key
    // their per-session state off it. A session without an id (ephemeral) leaves
    // the field unset and a plugin is expected to fall back to project scope.
    if let Ok(metadata) = session.get_metadata().await {
        publish_session_identity(&tool_context, &metadata.id);
    }
    // `--name`/`-n` sets the session display name durably (a `name` fact in the
    // log). It applies to whichever session this launch works in — a fresh one
    // or a restored one — and an empty value clears a previous name. This is the
    // only place the flag is applied: `SessionSelection::New` carries it, but
    // builds that do not create a session (restore/fork) must still honor it.
    if let Some(requested) = args.name.as_deref() {
        let name = requested.trim();
        let name = if name.is_empty() { None } else { Some(name) };
        if let Err(error) = session.set_name(name).await {
            if fresh_session_only {
                return Err(BuildError::SessionOpen(format!(
                    "native session name persistence failed: {error}"
                )));
            }
            if args.verbose {
                eprintln!("warning: could not set session name: {error}");
            }
        }
    }
    // ---- System prompt base (precedence: --system-prompt > SYSTEM.md > default) ----
    // Mirrors pi `discoverSystemPromptFile` (`resource-loader.ts:1022-1034`):
    // an explicit `--system-prompt` flag wins; otherwise a discovered
    // `<cwd>/.rpi/SYSTEM.md` wins, then
    // `<agent_dir>/SYSTEM.md`.
    // (global); otherwise the built-in default. **Project-wins** — the same
    // direction as skills/prompts precedence.
    // Whether this model sees its own prior reasoning again decides how the
    // working-state rule is worded (see `default_system_prompt`).
    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&resolved.model);
    let prompt_tools = active.clone();
    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
    let default_prompt = || {
        default_system_prompt_with_tool_prompts(
            &cwd_str,
            prior_reasoning_replayed,
            &prompt_tools,
            &prompt_metadata,
        )
    };
    let mut context_paths = Vec::new();
    let base_prompt = match args.system_prompt.as_deref() {
        Some(explicit) => explicit.to_string(),
        None if project_trusted && resource_selection.is_none() => {
            match discover_system_prompt_file(cwd) {
                Some(path) => {
                    read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
                }
                None => default_prompt(),
            }
        }
        None => default_prompt(),
    };

    // ---- Append-text sources (precedence: --append-system-prompt > APPEND_SYSTEM.md) ----
    // Mirrors pi `appendSystemPrompt` (`resource-loader.ts:525-542`). Explicit
    // `--append-system-prompt` flags are joined together; when none are given, a
    // discovered `APPEND_SYSTEM.md` (project-wins over global) provides the
    // append text. `--append-system-prompt` takes a value that may be a literal
    // string OR a readable file path (mirrors TS `resolvePromptInput`).
    let mut append_texts: Vec<String> = Vec::new();
    for extra in &args.append_system_prompt {
        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
        append_texts.push(text);
    }
    if let Some(selected) = &resource_selection {
        append_texts.extend(
            selected
                .instructions
                .iter()
                .map(|(_, _, text)| text.clone()),
        );
    }
    if args.append_system_prompt.is_empty() && resource_selection.is_none() {
        if let Some(path) = project_trusted
            .then(|| discover_append_system_prompt_file(cwd))
            .flatten()
        {
            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
                append_texts.push(text);
            }
        }
    }
    let append_join = if append_texts.is_empty() {
        None
    } else {
        Some(append_texts.join("\n\n"))
    };

    // ---- Resource discovery (skills + prompt-templates + context-files) ----
    // The env is OS-backed, rooted at cwd. Each `--no-*` flag suppresses its
    // channel independently (pi parity). Skills/prompts load project→global,
    // explicit/plugin paths, then static packages; dedupe first-wins-by-name
    // keeps project and user resources ahead of packages. Context files walk
    // global→ancestor(cwd→root), deepest-last (pi parity).
    //
    // **Trust gate (v1 divergence):** pi gates project config discovery on
    // `isProjectTrusted()` (global resources are unconditional). rpi v1 has no
    // trust prompt — project resources are discovered unconditionally (a copied
    // `.rpi/` dir drops in and works). Full trust gating is deferred.
    let agent_dir = crate::config::agent_dir().ok();

    // ---- B5b: extension resources_discover ----
    // If any plugin registered a `resources_discover` handler, fan the event out
    // (reason "startup") and collect skill/prompt/theme paths. These plugin-
    // contributed paths merge WITH the static Part-A dirs (project
    // `.rpi/skills` +
    // `agent_dir/skills`, etc.) and the loaders re-run over the union — the
    // coherence point: a plugin's discovered skills land through the SAME loaders
    // as static skills. Static dirs load FIRST so project skills keep winning name
    // collisions (a plugin must not shadow a project skill of the same name —
    // mirrors pi `extendResources` running AFTER the default load's first-wins
    // map). `load_skills` now accepts both dirs and individual `.md` files, so a
    // plugin returning bare `SKILL.md` paths loads them (the gap this closes).
    // Theme paths are available to the TUI through the package resource list;
    // skill/prompt loaders are the only resources needed by the harness here.
    // A `--no-*` flag suppresses its channel for BOTH static and discovered paths.
    let discovered = extension_session
        .snapshot_arc()
        .filter(|_| resource_selection.is_none())
        .map(|snap| emit_resources_discover(&cwd_str, "startup", &snap))
        .unwrap_or_default();

    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
    if let Some(selected) = &resource_selection {
        // Consume the preflight's parsed resources, never rediscover or reread
        // selected Skills after executable registration / writer opening.
        skills = selected
            .validated_skills()
            .map_err(BuildError::HarnessCreate)?
            .skills
            .clone();
    } else if !args.no_skills {
        let mut dirs = if args.dev_local_only || args.project_only {
            project_skill_dirs(cwd)
        } else if project_trusted {
            skill_dirs(cwd)
        } else {
            global_skill_dirs()
        };
        dirs.extend(args.skill.iter().cloned());
        dirs.extend(discovered.skill_paths.iter().map(PathBuf::from));
        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
        skills = result.skills;
        skill_diags = result.diagnostics;
        resource_diags.extend(result.resource_diagnostics);
    }

    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
    if !args.no_prompt_templates && resource_selection.is_none() {
        let mut dirs = if args.dev_local_only || args.project_only {
            project_prompt_template_dirs(cwd)
        } else if project_trusted {
            prompt_template_dirs(cwd)
        } else {
            global_prompt_template_dirs()
        };
        dirs.extend(args.prompt_template.iter().cloned());
        dirs.extend(discovered.prompt_paths.iter().map(PathBuf::from));
        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
        prompt_templates = result.prompt_templates;
        prompt_diags = result.diagnostics;
        resource_diags.extend(result.resource_diagnostics);
    }

    let context_block = if args.no_context_files || !project_trusted || resource_selection.is_some()
    {
        String::new()
    } else {
        // `load_project_context_files` walks the global agentDir first then
        // ancestor-walks cwd→root (deepest last). It needs a real agent_dir; if
        // none is resolvable, pass the cwd dir so only the ancestor-walk runs
        // (the global step returns None anyway).
        let agent_dir_path = agent_dir.clone().unwrap_or_else(|| cwd.to_path_buf());
        let files = load_project_context_files(&env_dyn, cwd, &agent_dir_path).await;
        context_paths.extend(
            files
                .iter()
                .map(|file| file.path.to_string_lossy().into_owned()),
        );
        format_project_context(&files)
    };

    // Surface resource-discovery diagnostics as startup warnings (verbose-only).
    if args.verbose {
        for d in &skill_diags {
            eprintln!(
                "warning: skill {} ({}): {}",
                d.path,
                d.code.as_str(),
                d.message
            );
        }
        for d in &prompt_diags {
            eprintln!(
                "warning: prompt template {} ({}): {}",
                d.path,
                d.code.as_str(),
                d.message
            );
        }
        // Structured collisions: make the winner/loser explicit.
        for d in &resource_diags {
            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
                eprintln!(
                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
                    c.resource_type.as_str(),
                    c.name,
                    c.winner_path,
                    c.loser_path
                );
            }
        }
    }

    // ---- Compose the full system prompt ----
    // Order mirrors pi `buildSystemPrompt` (`system-prompt.ts:28-72`):
    // base → append → context → skills. The skills listing is the harness's own
    // section: `AgentHarness::compose_prompt` appends `<available_skills>` (gated
    // on the `read` tool + `disable_model_invocation`, applied inside
    // `format_skills_for_system_prompt`). So we pass None for skills here (the
    // harness adds the listing itself) and fold only base+append+context into
    // the prompt we hand the harness.
    let system_prompt = compose_system_prompt(
        Some(&base_prompt),
        &[], // skills: harness appends the listing itself
        if context_block.is_empty() {
            None
        } else {
            Some(&context_block)
        },
        append_join.as_deref(),
    );

    // ---- Debug: dump the resolved system-prompt sections (verification) ----
    // A verification affordance for Part-A resource discovery: prints the
    // composed sections + resource counts to stderr so a smoke can confirm
    // `<available_skills>` + `<project_context>` + appended text reached the
    // prompt without parsing a provider round-trip. The harness composes the
    // final prompt (base → append → context → skills); here we print the
    // pre-harness sections (the harness adds the skills listing itself, gated
    // on `read` + `disable_model_invocation`).
    if args.debug_system_prompt {
        eprintln!("=== --debug-system-prompt ===");
        let base_src = if args.system_prompt.is_some() {
            "--system-prompt"
        } else if discover_system_prompt_file(cwd).is_some() {
            "SYSTEM.md"
        } else {
            "default"
        };
        eprintln!("[base source: {base_src}]");
        eprintln!("--- base ---\n{base_prompt}");
        if let Some(append) = append_join.as_deref() {
            eprintln!("--- append ---\n{append}");
        } else {
            eprintln!("--- append: (none) ---");
        }
        if context_block.is_empty() {
            eprintln!("--- context: (none) ---");
        } else {
            eprintln!("--- context ---{context_block}");
        }
        let visible_skills = skills
            .iter()
            .filter(|s| s.disable_model_invocation != Some(true))
            .count();
        eprintln!(
            "--- skills: {} loaded ({} model-visible, {} hidden) ---",
            skills.len(),
            visible_skills,
            skills.len() - visible_skills
        );
        for s in &skills {
            let hidden = if s.disable_model_invocation == Some(true) {
                " [hidden]"
            } else {
                ""
            };
            eprintln!("    {}{hidden} — {}", s.name, s.description);
        }
        eprintln!("--- prompt templates: {} ---", prompt_templates.len());
        for t in &prompt_templates {
            eprintln!("    /{}", t.name);
        }
        // B5b: surface plugin-contributed discovery paths so a smoke can confirm
        // the resources_discover round-trip fed the loaders; package themes are
        // selected by the TUI rather than injected into the harness prompt.
        eprintln!(
            "--- discovered via resources_discover: {} skill(s), {} prompt(s), {} theme(s) ---",
            discovered.skill_paths.len(),
            discovered.prompt_paths.len(),
            discovered.theme_paths.len(),
        );
        for p in &discovered.skill_paths {
            eprintln!("    skill: {p}");
        }
        for p in &discovered.prompt_paths {
            eprintln!("    prompt: {p}");
        }
        eprintln!(
            "--- final composed base+append+context (skills listing added by harness) ---\n{system_prompt}"
        );
        eprintln!("=== end --debug-system-prompt ===");
    }

    // ---- Options ----
    // Install a BroadcastEmitter so the caller (the interactive TUI) can drain
    // AgentEvents live as a run unfolds. The corresponding broadcast::Receiver
    // is returned alongside the harness; non-interactive modes simply drop it.
    let (broadcast, event_rx) = rpi_agent::events::BroadcastEmitter::new(256);
    let broadcast_emitter: Arc<dyn rpi_agent::AgentEmitter> = Arc::new(broadcast);
    // The broadcast half stays live for the whole session (the TUI's drain task
    // holds the receiver); reload re-wraps it in a fresh `TeeEmitter`, so keep
    // a clone for the `ReloadContext` before the tee match consumes the original.
    let broadcast_for_context: Arc<dyn rpi_agent::AgentEmitter> = Arc::clone(&broadcast_emitter);

    // ---- Extensions emitter (Part B3a) ----
    // If extensions loaded + registered any `on()` handlers, wrap the
    // broadcast emitter in a `TeeEmitter` so every `AgentEvent` flows to BOTH
    // the TUI (via the broadcast receiver above) AND the plugin handlers (via
    // the `ExtensionEmitter`, which translates each `AgentEvent` →
    // `StablePluginEvent` and fans out to the handlers registered for its tag).
    // With no extensions the tee degrades to the bare broadcast emitter (a
    // one-child passthrough), so the TUI path is unchanged.
    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
        Some(snapshot) => {
            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
            Arc::new(TeeEmitter::new(vec![broadcast_emitter, Arc::new(ext)]))
        }
        None => broadcast_emitter,
    };

    // Saved user defaults. Best-effort: a missing or malformed file must not stop
    // a session from starting, and every accessor falls back to the harness
    // default when its key is absent.
    let saved_settings = crate::settings::load_settings().unwrap_or_default();

    // `httpProxy` applies to rpi's own HTTP clients. Setting the environment is how
    // they are configured (`pi-ai/src/http.rs`), and upstream does the same thing
    // with this key — an explicit environment variable still wins, so a shell-level
    // proxy override is not silently replaced by the setting.
    if let Some(proxy) = &saved_settings.http_proxy {
        for key in ["HTTP_PROXY", "HTTPS_PROXY"] {
            if std::env::var_os(key).is_none() {
                std::env::set_var(key, proxy);
            }
        }
    }

    // Share the live session cell with both /reload and the approval hook.
    // The hook is installed only when the current snapshot has a tool-call
    // handler; a later reload rebuilds the hook state together with the
    // extension session.
    let extension_session_cell = Arc::new(Mutex::new(extension_session.clone()));
    // Only install the approval hook when a plugin actually registered a
    // tool-call handler. An extension session may contain flags/resources but
    // no handler; dispatching through that empty session needlessly crosses
    // the plugin bridge and can leave a headless RPC tool call waiting.
    let before_tool_call = extension_session
        .snapshot()
        .filter(|snapshot| {
            !snapshot
                .handlers_for(rpi_plugin_sdk::EventTag::ToolCall)
                .is_empty()
        })
        .map(|_| {
            extension_tool_call_hook(
                Arc::clone(&extension_session_cell),
                ui_dialog_mailbox.clone(),
            )
        });

    let options = AgentHarnessOptions {
        model: resolved.model.clone(),
        thinking_level: resolved.thinking_level,
        active_tool_names: active.clone(),
        tools,
        system_prompt: Some(system_prompt),
        resources: AgentHarnessResources {
            context_files: context_paths,
            skills: if skills.is_empty() {
                None
            } else {
                Some(skills)
            },
            prompt_templates: if prompt_templates.is_empty() {
                None
            } else {
                Some(prompt_templates)
            },
        },
        // A restored session (--continue/--resume/--session) already has
        // records — let the harness load it and keep appending.
        allow_existing_session: matches!(
            selection,
            SessionSelection::Latest { .. }
                | SessionSelection::ById { .. }
                | SessionSelection::ByExactId { .. }
                | SessionSelection::Fork { .. }
        ),
        stream_options: AgentHarnessStreamOptions {
            timeout: args.timeout,
            stream_idle_timeout: args.stream_idle_timeout.or_else(|| {
                saved_settings
                    .stream_idle_timeout
                    .map(std::time::Duration::from_secs)
            }),
            thinking_budgets: saved_settings.thinking_budgets,
            ..Default::default()
        },
        // Settings-backed harness options: upstream lets users tune retry,
        // compaction and queue drain modes from settings.json. Global only,
        // matching how `defaultTools` and the other settings-backed options in
        // this file are read.
        retry: saved_settings.retry_policy(),
        compaction: saved_settings.compaction_settings(),
        steering_mode: saved_settings.steering_mode(),
        follow_up_mode: saved_settings.follow_up_mode(),
        tool_execution: HarnessToolExecution::default(),
        drive: DrivingMode::default(),
        session,
        // B5c: inject the resolved gateway provider PLUS one `Arc<dyn Provider>`
        // per registered extension provider (`PluggableProvider` wraps a plugin's
        // sync `ProviderRequestFn`). The harness's `build_stream_fn` resolves a
        // provider lazily per call by `models.iter().find(|p| p.id() == model.provider)`,
        // so a catalog model whose `provider` matches an extension provider's id
        // routes to it. Extension providers land AFTER the gateway so the gateway
        // stays first-match for its own ids (first-wins on a `.find`).
        models: build_models_with_extensions(resolved, &extension_session, runtime.clone()),
        to_provider_messages: None,
        entry_projectors: Default::default(),
        agent_emitter: Some(emitter),
        // B3b loop hooks. `before_tool_call` dispatches the pi `on("tool_call")`
        // extension event and honors a veto (a permission gate can block a tool
        // before it runs). `after_tool_call`/`transform_context` remain `None`
        // (their host-side adapters are not wired yet).
        before_tool_call,
        after_tool_call: None,
        transform_context: None,
        entry_transforms: Vec::new(),
        // Extension provider hooks (B4): plugins subscribing to the
        // BeforeProviderRequest / BeforeProviderHeaders / AfterProviderResponse
        // events observe every provider call (observer semantics — the handler
        // ABI has no patch channel in v1). A session without provider-hook
        // subscribers runs hook-free.
        provider_hooks: rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
            .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
    };

    let harness = AgentHarness::create(options)
        .await
        .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
    // Manual skill commands read current bodies through the same environment
    // that discovered these host-owned resources, including after /reload.
    harness.set_skill_execution_env(env_dyn.clone());

    // Retain read leases even for resource-only/--no-extensions hosts.
    let harness_leases = resource_leases.clone();
    harness
        .events()
        .on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |_| {
            let _ = &harness_leases;
        });
    install_extension_settlement_bridge(harness.events(), extension_session_cell.clone());
    if let Some(selected) = &resource_selection {
        harness
            .seal_resources(active)
            .map_err(|e| BuildError::HarnessCreate(e.to_string()))?;
        crate::resource_selection::attach(
            &harness,
            serde_json::json!({
                "version": 1,
                "hostId": uuid::Uuid::new_v4().to_string(),
                "host": {"name": crate::APP_NAME, "version": crate::VERSION, "pid": std::process::id()},
                "selection": selected.selection,
                "package": selected.package,
                "selectedSkills": selected.skills,
                "skillDiagnostics": [],
                "loadedExtensions": extension_session.loaded_paths().iter().map(|p| serde_json::json!({"identity": p.file_stem().and_then(|s| s.to_str()), "path": p})).collect::<Vec<_>>(),
                "instructions": selected.provenance(),
                "baseSystemPrompt": "native-default",
                "projectContext": "disabled",
                "resourceDiscovery": "disabled",
                "changes": "restart-required"
            }),
        );
        let resource_observation = StartupSpan::start(Phase::ResourceObservation);
        crate::resource_selection::get_resource_state(&harness)
            .await
            .map_err(BuildError::HarnessCreate)?;
        resource_observation.finish();
        if selected.transition.is_some() {
            // Re-read persisted facts at commit, not merely the startup mirror.
            // The canonical OS writer claim acquired before registration is
            // retained by the host for the entire session lifetime.
            let meta = resolve_restore_target(&selection, &cwd_str)
                .await?
                .ok_or_else(|| {
                    BuildError::SessionOpen("transition session disappeared before commit".into())
                })?;
            let path = std::fs::canonicalize(&meta.path)
                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
            let lock_path = PathBuf::from(format!("{}.lock", path.display()));
            if !SESSION_LOCK_PATHS
                .get_or_init(|| Mutex::new(HashSet::new()))
                .lock()
                .unwrap()
                .contains(&lock_path)
            {
                return Err(BuildError::SessionOpen(
                    "resource transition lost canonical writer ownership".into(),
                ));
            }
            let facts =
                rpi_harness::session::jsonl::JsonlSessionStorage::read_resource_transition_facts(
                    Arc::new(OsExecutionEnv::with_cwd(cwd.to_path_buf())),
                    &path.to_string_lossy(),
                    Arc::new(SystemClock),
                    Arc::new(DefaultIdGenerator::new()),
                )
                .await
                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
            crate::resource_selection::validate_session_binding(&facts.values, Some(selected))
                .map_err(BuildError::SessionOpen)?;
            let mirror = rpi_harness::session::SessionValues::load(harness.session())
                .await
                .map_err(|e| BuildError::SessionOpen(e.to_string()))?;
            if crate::resource_selection::binding_state(&mirror)
                != crate::resource_selection::binding_state(&facts.values)
            {
                return Err(BuildError::SessionOpen(
                    "resource binding changed before commit".into(),
                ));
            }
        }
        let inventory_bind = StartupSpan::start(Phase::InventoryBind);
        crate::resource_selection::bind_inventory(&harness, selected)
            .await
            .map_err(BuildError::SessionOpen)?;
        inventory_bind.finish();
    }
    // Publish only after exact resources have been sealed and validated.
    crate::extensions_actions::HarnessActionHost::set_harness(
        &harness_cell,
        Arc::new(harness.clone()),
    );
    register_file_io_router(&harness, &file_io);

    // ---- Durable operation recovery (runtime layer) ----
    // A previous process can die between `operation_started` and
    // `operation_finished`, leaving the lane with an orphaned operation. Sweep
    // every lane, surface what was found, and emit `run_start`/`run_end`
    // (aborted) pairs so a TUI that already attached sees the settle. This is
    // read-only: nothing is mutated here, so a failed sweep cannot corrupt the
    // log. A clean session (the common case) reports no findings.
    {
        let runtime = rpi_harness::runtime::SessionRuntime::new(harness.session().clone());
        match rpi_harness::runtime::recover_all_lanes(&runtime).await {
            Ok(reports) => {
                for (lane, report) in reports {
                    if report.is_clean() {
                        continue;
                    }
                    if report.is_corrupt() {
                        eprintln!(
                            "warning: session lane '{lane}' is corrupt ({} open operations); \
                             refusing to auto-repair — inspect the session file",
                            report.open_operations.len()
                        );
                        continue;
                    }
                    for decision in runtime.reconcile(&report) {
                        if let rpi_harness::runtime::RecoveryDecision::Abort { run_id } = decision {
                            if args.verbose {
                                eprintln!(
                                    "recovered interrupted run {run_id} on lane '{lane}' (aborted)"
                                );
                            }
                        }
                    }
                    runtime.emit_recovery_events(harness.events(), &report);
                }
            }
            Err(e) => {
                if args.verbose {
                    eprintln!("warning: session recovery sweep failed: {e}");
                }
            }
        }
    }

    // ---- B5d: assemble the ReloadContext the TUI holds ----
    // Every field is cheap to clone (Arc / Vec / args Clone). The cells own the
    // live session + bridge so `/reload` can swap them; the harness itself is
    // NOT held here (the TUI already owns a `&AgentHarness` / clone at the call
    // site — passing it into `reload_extension_resources` keeps this structfree
    // of a harness back-reference so it can be `Clone` into the reload callback).
    // Retain the resolved root in the existing args snapshot so reload never
    // reselects it from mutable settings or environment variables.
    let mut reload_args = args.clone();
    reload_args.session_dir = Some(session_dir);
    let reload_context = ReloadContext {
        resource_leases,
        fresh_session_only,
        extension_session: extension_session_cell,
        action_bridge: Arc::new(Mutex::new(Some(Arc::clone(&action_bridge)))),
        tool_context,
        file_io,
        catalog: Arc::new(std::sync::RwLock::new(catalog)),
        providers: Arc::new(std::sync::RwLock::new(resolved.providers.clone())),
        runtime: runtime.clone(),
        cwd: cwd.to_path_buf(),
        project_trusted,
        discovered_theme_paths: Arc::new(std::sync::Mutex::new(discovered.theme_paths.clone())),
        args: reload_args,
        resolved_model: resolved.model.clone(),
        broadcast: broadcast_for_context,
        mailbox: reload_mailbox,
        ui_dialog: ui_dialog_mailbox,
        ext_status: ext_status_mailbox,
        editor_text: editor_text_mailbox,
        dev_extension: None,
        startup_notices: Vec::new(),
    };

    Ok((harness, event_rx, reload_context))
}

/// Project authoritative harness termination, not per-attempt AgentEnd, to
/// plugins. The bus owns this listener; its session cell follows reloads and
/// retains callback libraries, while the action host binds the harness weakly.
fn install_extension_settlement_bridge(
    events: &rpi_harness::events::HarnessEventBus,
    sessions: ExtensionSessionCell,
) {
    events.on_lifetime::<rpi_harness::events::RunEndEvent, _>(move |event| {
        if event.lane != "main" {
            return;
        }
        let session = sessions.lock().unwrap().clone();
        if let Some(snapshot) = session.snapshot_arc() {
            rpi_extensions::dispatch_empty_event(&snapshot, rpi_plugin_sdk::EventTag::AgentSettled);
        }
    });
}

/// Resolve the current plugin session for each call rather than keeping a
/// startup snapshot. A clone retains its libraries while approval is pending.
fn extension_tool_call_hook(
    sessions: ExtensionSessionCell,
    ui_dialog: rpi_extensions::UiDialogMailbox,
) -> rpi_agent::BeforeToolCall {
    Arc::new(move |ctx: rpi_agent::BeforeToolCallContext<'_>, signal| {
        let session = sessions
            .lock()
            .map(|session| session.clone())
            .map_err(|_| ());
        let ui_dialog = ui_dialog.clone();
        let tool_call_id = ctx.tool_call.id.clone();
        let tool_name = ctx.tool_call.name.clone();
        let params = ctx.args.clone();
        Box::pin(async move {
            let reason = match session {
                Ok(session) => {
                    rpi_extensions::dispatch_tool_call_event(
                        &session,
                        &tool_call_id,
                        &tool_name,
                        &params,
                        &signal,
                        &ui_dialog,
                    )
                    .await
                }
                Err(_) => Some("extension approval session is unavailable".to_string()),
            };
            reason.map(|reason| rpi_agent::BeforeToolCallResult {
                block: true,
                reason: Some(reason),
                terminate: false,
                args: None,
            })
        })
    })
}

// ===========================================================================
// B5d — `/reload`: re-run extension + resource discovery into a LIVE harness
// ===========================================================================
//
// `/reload` (interactive TUI command, or a plugin's `runtime_action(Reload)`)
// re-runs everything `build` did around resources/extensions WITHOUT rebuilding
// the `AgentHarness` itself (rebuilding would tear down the session/lane/event
// wiring + the broadcast drain task the TUI owns). Instead it:
//
//  1. Builds a fresh `ExtensionSession` (re-load the cdylibs) over the same
//     dir set, with a FRESH `ActionBridge` (the old one is `invalidate`d so
//     in-flight plugin→host calls on the old bridge fail fast).
//  2. Fans `resources_discover(_, "reload")` over the fresh snapshot.
//  3. Re-runs the Part-A loaders (skills/prompts/context/SYSTEM.md/
//     APPEND_SYSTEM.md) with the discovered paths merged in — same precedence
//     + `--no-*` gates as startup.
//  4. Rebuilds the harness's live state via the B5d setters
//     (`set_system_prompt`/`set_resources`/`set_agent_emitter`/`set_models`/
//     `set_provider_hooks`/`set_tools`) so the NEXT run observes the reloaded
//     config (in-flight runs finish on the old `ConfigSnapshot`).
//  5. Swaps the cells (`ExtensionSession`, `ActionBridge`, harness action
//     host's harness cell stays — the harness is the same object) and drops
//     the old session + bridge (their keepalives unmap the old cdylibs; the
//     new session's keepalive holds the fresh mappings).
//
// The reload is a `rpi-cli` concern (NOT a harness op): `rpi-extensions`
// carries only the `ActionBridge` staleness flag + a `ReloadMailbox` `()` signal
// (no pi-cli `TuiMessage` type — leaf DAG preserved). The TUI owns the mailbox
// receiver + the actual reload routine; a plugin's
// `runtime_action(Reload)` signals the mailbox and returns `Ok(null)`
// immediately so the calling plugin's cdylib is NOT unmapped while its
// `runtime_action` frame is still on the stack (the self-unmapping race a
// synchronous plugin-initiated reload would have).
//
// `reload_extension_resources` is the shared routine both `/reload` (TUI) and
// a plugin's `runtime_action(Reload)` (via the mailbox) drive. It is `pub` so
// the TUI's main-loop handler + the mailbox-driven path call the same code.

/// The cell that holds the live `ExtensionSession` across a `/reload`. Cloned
/// into every site that needs the current session (the TUI, the reload
/// callback). On reload the old session is `replace`d out (its `active` flag
/// flipped) and the fresh one stored atomically. In-flight callbacks retain
/// the old keepalive until they return; callers never observe an empty
/// placeholder during the swap.
pub type ExtensionSessionCell = Arc<Mutex<ExtensionSession>>;

/// The cell that holds the live `ActionBridge` across a `/reload`. A plugin
/// stores the bridge's raw `user_data` pointer during `register`; on reload the
/// old bridge is `invalidate`d (in-flight calls fail fast) and the fresh one
/// `store`d. The fresh session's plugins are handed the fresh bridge pointer.
pub type ActionBridgeCell = Arc<Mutex<Option<Arc<rpi_extensions::ActionBridge>>>>;

/// Everything `/reload` needs to rebuild extension + resource state into a live
/// harness. Built once in [`build`] (alongside the harness) and held by the TUI
/// (cloned into the reload callback the bridge carries + the `/reload` command
/// handler). The harness itself is NOT held here — the TUI already owns a
/// `&AgentHarness` / a clone; passing it at the call site keeps this struct
/// free of a harness back-reference (so it can be `Clone` and moved into the
/// reload callback without borrowing the harness).
#[derive(Clone)]
pub struct ReloadContext {
    resource_leases: Arc<Vec<crate::resource_management::Lease>>,
    /// Startup routing capability, retained independently of mutable args/settings.
    fresh_session_only: bool,
    /// One neutral router for all built-ins, including those reconstructed on reload.
    pub file_io: Arc<rpi_tools::file_io::FileIORouter>,
    /// The live extension-session cell (swapped on reload).
    pub extension_session: ExtensionSessionCell,
    /// The session's plugin-tool context (`cwd` + session id), reused — not
    /// rebuilt — on reload so the rebuilt adapters keep serving the SAME
    /// session. A reload that made a fresh context would leave every plugin
    /// tool without a session id until the next launch.
    pub tool_context: rpi_extensions::ToolCallContext,
    /// The live action-bridge cell (swapped + old invalidated on reload).
    pub action_bridge: ActionBridgeCell,
    /// The extension status registry the TUI renders in its footer (`SetStatus`).
    /// Lives in the context (not the cell) so it survives a bridge swap.
    pub ext_status: rpi_extensions::ExtensionStatusMailbox,
    /// The extension editor-text queue the TUI drains into the prompt editor
    /// (`SetEditorText`, runtime action 19). Lives in the context (not the cell)
    /// so it survives a bridge swap — exactly like `ext_status`. A voice plugin
    /// writes a transcription here as a *draft*; the TUI applies it, starts the
    /// optional auto-send countdown, and submits through the normal path so the
    /// user bubble renders as usual.
    pub editor_text: rpi_extensions::EditorTextMailbox,
    /// Shared authenticated model catalog for runtime actions and the TUI.
    /// Provider-package reloads replace it together with the runtime bindings.
    pub catalog: Arc<std::sync::RwLock<Vec<rpi_ai::Model>>>,
    /// Current configured provider runtimes. Replaced after package reload so
    /// subsequent reloads cannot recover stale plugin snapshots.
    pub providers: Arc<std::sync::RwLock<Vec<Arc<dyn Provider>>>>,
    /// The ambient runtime handle (captured in `build`) — `PluggableProvider`
    /// + the fresh `ActionBridge` need a captured `Handle` to spawn from any
    /// thread.
    pub runtime: tokio::runtime::Handle,
    /// The cwd (for static resource-dir resolution + context-file walk).
    pub cwd: PathBuf,
    /// The project-trust decision captured before provider and session setup.
    /// Startup consumers reuse this value so extension code cannot change the
    /// effective policy by mutating the process cwd while it is loading.
    pub project_trusted: bool,
    /// Theme file paths contributed by extensions via `resources_discover`,
    /// shared so the TUI theme registry can merge them. Filled at startup,
    /// replaced on every `/reload` (paths are unattributed — the v1 divergence
    /// documented in `rpi-extensions::resources`).
    pub discovered_theme_paths: Arc<std::sync::Mutex<Vec<String>>>,
    /// The parsed args (cloned) — `--no-*`/`--tools`/`--exclude-tools`/
    /// `--extensions-dir`/`--no-extensions`/`--system-prompt`/etc all apply on
    /// reload exactly as at startup (a reload re-reads the same flags; it does
    /// not pick up argv changes mid-session, which is the right contract — pi's
    /// `/reload` re-runs discovery with the same config). `session_dir` holds
    /// the resolved startup root, including saved settings/environment defaults.
    pub args: Args,
    /// The resolved model + thinking level (the harness's active model stays
    /// unless `set_model` changed it; reload does not touch the model).
    pub resolved_model: rpi_ai::Model,
    /// The broadcast emitter the harness was built with. Reload rebuilds the
    /// `TeeEmitter` over the fresh `ExtensionEmitter` (the old tee's extension
    /// child is dropped, unsubscribing from the old registry). The broadcast
    /// half stays live the whole session (the TUI's drain task holds the
    /// receiver), so we keep a handle to re-wrap.
    pub broadcast: Arc<dyn rpi_agent::AgentEmitter>,
    /// The session-long reload mailbox (B5d). Build creates one, installs it on
    /// the initial `ActionBridge` via [`reload_callback_from_mailbox`], and hands
    /// a clone to the TUI. The TUI installs its `TuiMessage` sender so a plugin's
    /// `runtime_action(Reload)` signals the main loop — the reload routine reuses
    /// THIS mailbox (not a fresh default) when building the fresh bridge, so the
    /// bridge always carries the mailbox the TUI installed across reloads.
    pub mailbox: rpi_extensions::ReloadMailbox,
    /// Session-long UI-dialog mailbox (runtime action 17). The initial bridge
    /// carries it; the TUI attaches itself and polls `take_pending` from its key
    /// loop, and `/reload` reuses THIS mailbox when it builds the fresh bridge.
    /// A detached mailbox makes `ask_user` fail with "requires an interactive
    /// UI" (headless contract).
    pub ui_dialog: rpi_extensions::UiDialogMailbox,
    /// Active `rpi dev` extension builder. `/reload` rebuilds it before
    /// swapping plugin sessions; its watcher signals `mailbox` after a
    /// successful background build.
    pub dev_extension: Option<Arc<crate::dev_extension::DevExtension>>,
    /// One-line notices the host should show at startup (a session directory
    /// that fell back, an untrusted adopted directory). Filled by the CLI after
    /// the build and rendered as transcript notes in the TUI; headless modes
    /// print them to stderr. Kept as data — never `eprintln!`d from here, which
    /// would corrupt the alternate screen (issue #115).
    pub startup_notices: Vec<String>,
}

impl ReloadContext {
    pub(crate) fn session_dir(&self) -> PathBuf {
        // The fallback also supports contexts constructed by embedding hosts.
        self.args
            .session_dir
            .clone()
            .unwrap_or_else(|| configured_session_dir(&self.args, &self.cwd))
    }
}

/// Dispatch a no-payload lifecycle event (e.g. `SessionStart`, `SessionShutdown`,
/// the rpi-specific `BeforeTuiStart`) to every extension handler subscribed to
/// that tag, with **veto** + **timeout** semantics (P1).
///
/// Resolves the **current** extension session from the reload cell so a
/// `/reload`-swapped session is honored. Each handler runs on a blocking thread
/// with a per-event timeout ([`rpi_extensions::lifecycle_timeout_for`]); a
/// handler returning [`rpi_plugin_sdk::EVENT_HANDLER_ABORT`] vetoes the phase
/// and this returns `Some(reason)`. No-op (`None`) when no plugins loaded, no
/// handler subscribes, or the registry is stale.
///
/// The caller decides what a veto means: a `BeforeTuiStart` veto aborts startup
/// (never enter the TUI); `SessionStart`/`SessionShutdown` vetoes are advisory
/// (the session is already up or already closing).
pub async fn dispatch_session_event_async(
    reload_context: &ReloadContext,
    tag: rpi_plugin_sdk::EventTag,
) -> Option<String> {
    // Take the snapshot Arc + keepalive, drop the session lock, then dispatch —
    // we must not hold the session cell's mutex across the await (a handler
    // could re-enter a reload path that locks it). Holding the keepalive across
    // the await keeps the cdylibs (owning the handler fn pointers) mapped even
    // if a concurrent `/reload` swaps the session cell out.
    let (snapshot, keepalive) = {
        let session = reload_context.extension_session.lock().unwrap();
        (session.snapshot_arc(), session.keepalive())
    };
    match snapshot {
        Some(snapshot) => rpi_extensions::dispatch_lifecycle_event(&snapshot, tag, keepalive).await,
        None => None,
    }
}

/// Join plugin teardown before unloading modules. A detached timed-out handler
/// could still execute code in the old DLL, so it cannot safely permit a swap.
async fn shutdown_extensions_for_reload(
    snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
    keepalive: Arc<rpi_extensions::PluginKeepalive>,
) -> Result<(), String> {
    if let Some(snapshot) = snapshot {
        tokio::task::spawn_blocking(move || {
            let _keepalive = keepalive;
            rpi_extensions::dispatch_empty_event(
                &snapshot,
                rpi_plugin_sdk::EventTag::SessionShutdown,
            );
        })
        .await
        .map_err(|error| error.to_string())?;
    }
    Ok(())
}

/// The outcome of a reload: a human-readable status line for the transcript
/// (counts of what reloaded), and whether any load diagnostics appeared.
pub struct ReloadOutcome {
    /// One-line summary for the transcript note (e.g. "Reloaded 2 plugin(s),
    /// 5 skill(s), 1 prompt(s).").
    pub summary: String,
    /// True iff at least one extension load warning fired (ABI mismatch / skip).
    pub had_warnings: bool,
    /// Formatted diagnostic lines (package / skill / prompt-template warnings)
    /// that the caller should surface in its UI. Kept out of `eprintln!`
    /// because the TUI owns the terminal: direct stderr writes during a run
    /// would corrupt the alternate-screen input row.
    pub details: Vec<String>,
    /// True iff the reload itself failed hard (e.g. the extension build or
    /// settings reload errored) and the previous resources were kept. Soft
    /// diagnostics (skill shadowing, name validation) do not set this.
    pub had_errors: bool,
    /// The project-trust policy this reload actually resolved and applied.
    /// `None` when the reload failed hard and kept the previous resources, so
    /// consumers (e.g. theme discovery) should stay on the snapshot they
    /// already match instead of re-reading a stale startup bool.
    pub project_trusted: Option<bool>,
}

struct PreparedReloadInputs {
    extension_dirs: Vec<PathBuf>,
    skill_base_dirs: Vec<PathBuf>,
    prompt_base_dirs: Vec<PathBuf>,
}

/// Append the resource sources that are specific to a reload after the
/// conventional project/global directories. Keep this order aligned with the
/// initial build: explicit CLI paths must remain available after `/reload`,
/// while discovered and package resources retain their lower precedence.
fn append_reload_resource_paths(
    mut paths: Vec<PathBuf>,
    explicit: &[PathBuf],
    discovered: &[String],
    js_paths: &[PathBuf],
    package_paths: &[PathBuf],
) -> Vec<PathBuf> {
    paths.extend(explicit.iter().cloned());
    paths.extend(discovered.iter().map(PathBuf::from));
    paths.extend(js_paths.iter().cloned());
    paths.extend(package_paths.iter().cloned());
    paths
}

/// Re-run extension + resource discovery and push the rebuilt state into the
/// live `harness` via the B5d setters. The old `ExtensionSession` +
/// `ActionBridge` are invalidated + swapped in [`ReloadContext`]'s cells. This
/// is the single routine both `/reload` (TUI) and a plugin's
/// `runtime_action(Reload)` drive (the latter via the mailbox signal).
///
/// Returns a [`ReloadOutcome`] for the transcript. Best-effort: a failure in
/// one channel (e.g. a plugin that fails to reload) does not abort the others —
/// the reload completes with whatever loaded, mirroring pi's per-plugin
/// skip-on-error. A hard failure (e.g. the harness is closed) surfaces as an
/// error summary.
pub async fn reload_extension_resources(
    harness: &AgentHarness,
    ctx: &ReloadContext,
) -> ReloadOutcome {
    reload_extension_resources_inner(harness, ctx, || {}).await
}

async fn reload_extension_resources_inner<F>(
    harness: &AgentHarness,
    ctx: &ReloadContext,
    after_prepare: F,
) -> ReloadOutcome
where
    F: FnOnce() + Send,
{
    if harness.has_exact_resources()
        || ctx.args.resource_config.is_some()
        || ctx.args.resource_transition.is_some()
    {
        return ReloadOutcome {
            summary:
                "Exact resource selection is restart-required; reload/dev hot apply unsupported"
                    .into(),
            had_warnings: true,
            details: Vec::new(),
            had_errors: true,
            project_trusted: None,
        };
    }
    // Resolve the arguments once for this reload. `rpi dev` may append its
    // freshly staged extension directory; every subsequent loader and policy
    // decision must observe that same effective set rather than falling back
    // to the pre-dev snapshot held in `ctx.args`.
    let mut effective_args = ctx.args.clone();
    if let Some(dev) = &ctx.dev_extension {
        if let Err(error) = dev
            .rebuild()
            .and_then(|_| dev.apply_to_args(&mut effective_args))
        {
            return ReloadOutcome {
                summary: format!(
                    "Extension build failed for {}: {error}. Keeping the currently loaded version.",
                    dev.package_name()
                ),
                had_warnings: true,
                details: Vec::new(),
                had_errors: true,
                project_trusted: None,
            };
        }
    }
    let cwd_str = ctx.cwd.to_string_lossy().to_string();
    let project_trusted = resolve_project_trust(&effective_args, &ctx.cwd);
    let prepared = match prepare_reload_inputs(&effective_args, &ctx.cwd, project_trusted) {
        Ok(prepared) => prepared,
        Err(error) => {
            return ReloadOutcome {
                summary: format!(
                    "Settings reload failed: {error}. Keeping the currently loaded resources."
                ),
                had_warnings: true,
                details: Vec::new(),
                had_errors: true,
                project_trusted: None,
            };
        }
    };
    after_prepare();
    let PreparedReloadInputs {
        extension_dirs,
        skill_base_dirs,
        prompt_base_dirs,
    } = prepared;
    let mut warnings = false;

    // Shutdown callbacks must finish before a replacement can unload old DLLs.
    // Ordinary lifecycle dispatch can time out or stop on a veto; unload cleanup
    // instead joins every handler while keeping its module mapped.
    let (shutdown_snapshot, shutdown_keepalive) = {
        let session = ctx.extension_session.lock().unwrap();
        (session.snapshot_arc(), session.keepalive())
    };
    if let Err(reason) = shutdown_extensions_for_reload(shutdown_snapshot, shutdown_keepalive).await
    {
        return ReloadOutcome {
            summary: "Reload failed during extension shutdown".into(),
            had_warnings: true,
            details: vec![reason],
            had_errors: true,
            project_trusted: None,
        };
    }

    // ---- 1. Build a fresh ActionBridge + ExtensionSession ----
    // The fresh bridge carries the SAME `HarnessActionHost` (the host's harness
    // cell already points at this harness; the host impl is reusable across
    // reloads — only the bridge's staleness flag + reload callback differ). We
    // re-use the host by reading it off the OLD bridge (it's the same
    // `Arc<dyn RuntimeActionHost>`).
    let old_bridge = ctx.action_bridge.lock().unwrap().clone();
    let host: Arc<dyn rpi_extensions::RuntimeActionHost> = match &old_bridge {
        Some(b) => b.clone_host(),
        None => {
            // No prior bridge (no extensions ever loaded). Build a fresh host so
            // a reload that newly discovers plugins can still drive actions.
            let (action_host, _cell) = crate::extensions_actions::HarnessActionHost::new_empty(
                ctx.catalog
                    .read()
                    .unwrap_or_else(|error| error.into_inner())
                    .clone(),
                ctx.cwd.clone(),
                ctx.runtime.clone(),
                ctx.args.unknown_flags.clone(),
                ctx.tool_context.clone(),
            );
            crate::extensions_actions::HarnessActionHost::set_harness(
                &_cell,
                Arc::new(harness.clone()),
            );
            Arc::new(
                action_host
                    .with_session_dir(ctx.session_dir())
                    .with_fresh_session_only(ctx.fresh_session_only),
            )
        }
    };

    let reload_cb = rpi_extensions::reload_callback_from_mailbox(ctx.mailbox.clone());
    let publish_host = Arc::clone(&host);
    let fresh_bridge = rpi_extensions::ActionBridge::with_reload_and_ui(
        ctx.runtime.clone(),
        host,
        reload_cb,
        ctx.ui_dialog.clone(),
        ctx.ext_status.clone(),
        ctx.editor_text.clone(),
    );

    let extension_session = if effective_args.no_extensions {
        rpi_extensions::ExtensionSession::none()
    } else {
        load_extensions_from_dirs(
            &effective_args,
            &extension_dirs,
            Some(Arc::clone(&fresh_bridge)),
            Some(ctx.resource_leases.clone()),
        )
    };
    if let Err(error) =
        crate::native_store::validate_stdio(ctx.fresh_session_only, extension_session.owns_stdio())
    {
        return ReloadOutcome {
            summary: "Reload refused by experimental native session policy".into(),
            had_warnings: true,
            details: vec![error],
            had_errors: true,
            project_trusted: None,
        };
    }
    if extension_session.is_empty() && !effective_args.no_extensions {
        // The fresh session may be empty if no cdylibs are present — not a
        // warning per se, but note it.
    }
    if effective_args.verbose {
        if let Some(s) = extension_session.summary() {
            eprintln!("reload: {s}");
        }
        report_deferred_renderers(&extension_session);
    }

    let has_package_providers = |session: &ExtensionSession| {
        session.snapshot().is_some_and(|snapshot| {
            snapshot
                .providers()
                .iter()
                .any(|provider| snapshot.provider_manifest(&provider.provider_id).is_some())
        })
    };
    let packaged = has_package_providers(&extension_session)
        || has_package_providers(&ctx.extension_session.lock().unwrap());
    let refreshed = if packaged {
        let mut args = effective_args.clone();
        if let Ok(current) = harness.lane("main").get_model().await {
            let was_package = ctx
                .extension_session
                .lock()
                .unwrap()
                .snapshot()
                .is_some_and(|snapshot| snapshot.provider_manifest(&current.provider).is_some());
            let has_replacement = extension_session.snapshot().is_some_and(|snapshot| {
                snapshot
                    .providers()
                    .iter()
                    .any(|provider| provider.provider_id == current.provider)
            });
            if was_package && !has_replacement {
                return ReloadOutcome {
                    summary: "Reload failed while resolving provider packages".into(),
                    had_warnings: true,
                    details: vec![format!(
                        "active provider package '{}' is no longer loaded",
                        current.provider
                    )],
                    had_errors: true,
                    project_trusted: None,
                };
            }
            args.provider = Some(current.provider.clone());
            args.model = Some(current.id);
            if current.provider != ctx.resolved_model.provider {
                args.api_key = None;
                args.base_url = None;
            }
        }
        match crate::provider::resolve_with_extensions(
            &args,
            &ctx.cwd,
            ctx.project_trusted,
            &extension_session,
        ) {
            Ok(resolved) => Some(resolved),
            Err(error) => {
                return ReloadOutcome {
                    summary: "Reload failed while resolving provider packages".into(),
                    had_warnings: true,
                    details: vec![error.to_string()],
                    had_errors: true,
                    project_trusted: None,
                }
            }
        }
    } else {
        None
    };

    // ---- 2. Invalidate the old session + bridge BEFORE the swap ----
    // The old registry's `active` flag flips false so any in-flight
    // `emit_resources_discover`/event dispatch on the old snapshot no-ops; the
    // old bridge's flag flips false so in-flight `runtime_action` calls parked
    // on the old `user_data` hit the staleness guard. Invalidate under the
    // session lock before exposing the replacement to approval callbacks.
    //
    // Swap directly to the fresh session under the same lock that approvals
    // use. A temporary empty session would let a concurrent call bypass its gate.
    // In-flight approvals retain their old session until their callback exits;
    // its staleness flag prevents them from authorizing after this swap.
    let old_session = {
        let mut session_guard = ctx.extension_session.lock().unwrap();
        let old_session = std::mem::replace(&mut *session_guard, extension_session.clone());
        if let Some(old_snap) = old_session.snapshot_arc() {
            // `invalidate` is on the registry, but the snapshot shares the flag —
            // flipping the snapshot's flag invalidates the registry too (same Arc).
            // `RegistrySnapshot` exposes `active_flag()` for this.
            old_snap.active_flag().store(false, Ordering::SeqCst);
        }
        old_session
    };
    if let Some(old_b) = old_bridge {
        old_b.invalidate();
    }
    // Shutdown callbacks see stale host actions and run outside session locks.
    old_session.begin_shutdown();

    // The session was swapped atomically above; expose its matching bridge.
    *ctx.action_bridge.lock().unwrap() = Some(Arc::clone(&fresh_bridge));
    // Republish the registry so `ListCommands` reflects the commands the reload
    // just discovered — without this a remote UI keeps serving the startup set
    // until the host process restarts. Via the trait method because all we hold
    // here is `Arc<dyn RuntimeActionHost>`.
    // Publish even when the reload found nothing: a nonempty -> empty reload
    // returns `ExtensionSession::none()`, and skipping it would leave the old
    // snapshot advertised.
    publish_host.publish_registry_opt(extension_session.snapshot_arc());

    // ---- 3. resources_discover ("reload") over the fresh snapshot ----
    let discovered = extension_session
        .snapshot_arc()
        .map(|snap| rpi_extensions::emit_resources_discover(&cwd_str, "reload", &snap))
        .unwrap_or_default();
    // Publish the fresh theme paths so the TUI registry rebuild sees the same
    // set the skill/prompt loaders just consumed.
    if let Ok(mut guard) = ctx.discovered_theme_paths.lock() {
        *guard = discovered.theme_paths.clone();
    }

    // ---- 4. Re-run the Part-A loaders (same precedence + --no-* gates) ----
    let env = Arc::new(rpi_tools::OsExecutionEnv::with_cwd(ctx.cwd.clone()));
    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();

    let mut skills: Vec<rpi_harness::types::Skill> = Vec::new();
    let mut skill_diags: Vec<rpi_harness::skills::SkillDiagnostic> = Vec::new();
    let mut resource_diags: Vec<rpi_harness::diagnostics::ResourceDiagnostic> = Vec::new();
    if !effective_args.no_skills {
        // JS discovery is backed by the session-long lazy Node host. Until
        // that host is swapped as part of a future full JS reload, preserve
        // the paths it contributed at startup across `/reload`.
        let js_paths: &[PathBuf] = &[];
        let package_paths: &[PathBuf] = &[];
        let dirs = append_reload_resource_paths(
            skill_base_dirs,
            &effective_args.skill,
            &discovered.skill_paths,
            js_paths,
            package_paths,
        );
        let result = load_skills_with_precedence(&env_dyn, &dirs).await;
        skills = result.skills;
        skill_diags = result.diagnostics;
        resource_diags.extend(result.resource_diagnostics);
    }

    let mut prompt_templates: Vec<rpi_harness::types::PromptTemplate> = Vec::new();
    let mut prompt_diags: Vec<rpi_harness::prompt_templates::PromptTemplateDiagnostic> = Vec::new();
    if !effective_args.no_prompt_templates {
        let js_paths: &[PathBuf] = &[];
        let package_paths: &[PathBuf] = &[];
        let dirs = append_reload_resource_paths(
            prompt_base_dirs,
            &effective_args.prompt_template,
            &discovered.prompt_paths,
            js_paths,
            package_paths,
        );
        let result = load_prompt_templates_with_precedence(&env_dyn, &dirs).await;
        prompt_templates = result.prompt_templates;
        prompt_diags = result.diagnostics;
        resource_diags.extend(result.resource_diagnostics);
    }

    let context_files = if effective_args.no_context_files || !project_trusted {
        Vec::new()
    } else {
        let agent_dir = crate::config::agent_dir().ok();
        let agent_dir_path = agent_dir.unwrap_or_else(|| ctx.cwd.clone());
        load_project_context_files(&env_dyn, &ctx.cwd, &agent_dir_path).await
    };
    let context_block = format_project_context(&context_files);

    let mut details: Vec<String> = Vec::new();
    if let Some(resolved) = &refreshed {
        warnings |= !resolved.compat_warnings.is_empty();
        details.extend(
            resolved
                .compat_warnings
                .iter()
                .map(|warning| format!("warning: models.json: {warning}")),
        );
    }
    if !skill_diags.is_empty() || !prompt_diags.is_empty() || !resource_diags.is_empty() {
        warnings = true;
        // Collect formatted diagnostics for the caller to surface in its UI
        // instead of writing to stderr directly: the TUI owns the terminal,
        // and a raw `eprintln!` during a run would scribble over the
        // alternate-screen input row.
        for d in &skill_diags {
            details.push(format!(
                "warning: skill {} ({}): {}",
                d.path,
                d.code.as_str(),
                d.message
            ));
        }
        for d in &prompt_diags {
            details.push(format!(
                "warning: prompt template {} ({}): {}",
                d.path,
                d.code.as_str(),
                d.message
            ));
        }
        // Structured collisions: winner (kept) · loser (shadowed).
        for d in &resource_diags {
            if let rpi_harness::diagnostics::ResourceDiagnostic::Collision(c) = d {
                details.push(format!(
                    "warning: {} name \"{}\" collision: keeping {} (shadowed {})",
                    c.resource_type.as_str(),
                    c.name,
                    c.winner_path,
                    c.loser_path
                ));
            }
        }
    }

    // ---- Re-compose the system prompt (same precedence as build) ----
    // Same working-state wording rule as `build`; a mid-session `/model` switch
    // re-composes the prompt on the next reload, which is the same staleness the
    // rest of this path already has (provider resolution is a startup concern).
    // Re-merge extension tools (a reloaded plugin may have added/removed a
    // tool). The built-in set is rebuilt from scratch + extension tools merged
    // on top, mirroring `build`. Built before the
    // prompt so the prompt lists exactly the active tools.
    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
    let tool_ctx = rpi_tools::ExecutionToolContext::new(env_dyn.clone(), Some(mut_env))
        .with_file_io(ctx.file_io.clone());
    let mut tools = build_tools(&tool_ctx, &effective_args);
    merge_extension_tools(
        &mut tools,
        &extension_session,
        &effective_args,
        &ctx.tool_context,
    );
    let mut active = active_tool_names(&tools, &effective_args);
    active = filter_active_tool_names(active, &effective_args);
    let prompt_tools = active.clone();
    let prompt_metadata = extension_tool_prompt_metadata(&extension_session);
    let prior_reasoning_replayed = rpi_ai::model::prior_reasoning_is_replayed(&ctx.resolved_model);
    let default_prompt = || {
        default_system_prompt_with_tool_prompts(
            &cwd_str,
            prior_reasoning_replayed,
            &prompt_tools,
            &prompt_metadata,
        )
    };
    let mut context_paths = Vec::new();
    let base_prompt = match effective_args.system_prompt.as_deref() {
        Some(explicit) => explicit.to_string(),
        None if project_trusted => match discover_system_prompt_file(&ctx.cwd) {
            Some(path) => {
                read_prompt_source(&path, &mut context_paths).unwrap_or_else(default_prompt)
            }
            None => default_prompt(),
        },
        None => default_prompt(),
    };
    let mut append_texts: Vec<String> = Vec::new();
    for extra in &effective_args.append_system_prompt {
        let text = read_append_target(extra, &mut context_paths).unwrap_or_else(|| extra.clone());
        append_texts.push(text);
    }
    if effective_args.append_system_prompt.is_empty() {
        if let Some(path) = project_trusted
            .then(|| discover_append_system_prompt_file(&ctx.cwd))
            .flatten()
        {
            if let Some(text) = read_prompt_source(&path, &mut context_paths) {
                append_texts.push(text);
            }
        }
    }
    context_paths.extend(
        context_files
            .iter()
            .map(|file| file.path.to_string_lossy().into_owned()),
    );
    let append_join = if append_texts.is_empty() {
        None
    } else {
        Some(append_texts.join("\n\n"))
    };
    let system_prompt = compose_system_prompt(
        Some(&base_prompt),
        &[],
        if context_block.is_empty() {
            None
        } else {
            Some(&context_block)
        },
        append_join.as_deref(),
    );

    // ---- Rebuild the emitter (TeeEmitter over fresh ExtensionEmitter) ----
    let emitter: Arc<dyn rpi_agent::AgentEmitter> = match extension_session.snapshot_arc() {
        Some(snapshot) => {
            let ext = ExtensionEmitter::new(snapshot, extension_session.keepalive());
            Arc::new(TeeEmitter::new(vec![ctx.broadcast.clone(), Arc::new(ext)]))
        }
        None => ctx.broadcast.clone(),
    };

    // ---- 5. Push the rebuilt state into the live harness via the B5d setters ----
    let resources = AgentHarnessResources {
        context_files: context_paths,
        skills: if skills.is_empty() {
            None
        } else {
            Some(skills.clone())
        },
        prompt_templates: if prompt_templates.is_empty() {
            None
        } else {
            Some(prompt_templates.clone())
        },
    };
    let _ = harness.set_system_prompt(Some(system_prompt)).await;
    let _ = harness.set_resources(resources).await;
    let _ = harness.set_agent_emitter(Some(emitter)).await;
    let _ = harness
        .set_models(build_models_with_extensions_for_reload(
            &refreshed
                .as_ref()
                .map(|resolved| resolved.providers.clone())
                .unwrap_or_else(|| {
                    ctx.providers
                        .read()
                        .unwrap_or_else(|error| error.into_inner())
                        .clone()
                }),
            &extension_session,
            ctx.runtime.clone(),
        ))
        .await;
    let _ = harness
        .set_provider_hooks(
            rpi_extensions::ExtensionProviderHooks::from_session(&extension_session)
                .map(|h| Arc::new(h) as Arc<dyn rpi_ai::ProviderHooks>),
        )
        .await;

    if let Some(resolved) = &refreshed {
        *ctx.providers
            .write()
            .unwrap_or_else(|error| error.into_inner()) = resolved.providers.clone();
        let catalog = crate::provider::authenticated_catalog(resolved);
        fresh_bridge
            .clone_host()
            .replace_model_catalog(catalog.clone());
        *ctx.catalog
            .write()
            .unwrap_or_else(|error| error.into_inner()) = catalog;
        // Refresh the public descriptor. Credentials remain in the newly bound
        // provider instances installed above and never enter the lane model.
        let _ = harness.lane("main").set_model(resolved.model.clone()).await;
    }

    let _ = harness.set_tools(tools, Some(active)).await;

    let summary = format!(
        "Reloaded {} plugin(s), {} skill(s), {} prompt(s).",
        extension_session.loaded_paths().len(),
        skills.len(),
        prompt_templates.len(),
    );
    ReloadOutcome {
        summary,
        had_warnings: warnings,
        details,
        // Reload completed; any diagnostics here are soft (shadowing / name
        // validation / skipped optional resources), not hard failures.
        had_errors: false,
        project_trusted: Some(project_trusted),
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ReloadSettingsFields {
    skill_dirs: Option<Vec<String>>,
    prompt_dirs: Option<Vec<String>>,
    extension_dirs: Option<Vec<String>>,
}

impl From<crate::settings::Settings> for ReloadSettingsFields {
    fn from(settings: crate::settings::Settings) -> Self {
        Self {
            skill_dirs: settings.skill_dirs,
            prompt_dirs: settings.prompt_dirs,
            extension_dirs: settings.extension_dirs,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ReloadSettingsSnapshot {
    global: ReloadSettingsFields,
    project: Option<ReloadSettingsFields>,
}

fn reload_reads_settings(args: &Args) -> bool {
    !args.dev_local_only && (!args.no_extensions || !args.no_skills || !args.no_prompt_templates)
}

/// Strictly read the settings fields consumed while preparing a reload. The
/// snapshot intentionally excludes UI/model fields that `/reload` does not
/// use, so an unrelated settings save does not invalidate the operation.
fn load_reload_settings_snapshot(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
) -> Result<Option<ReloadSettingsSnapshot>, String> {
    if !reload_reads_settings(args) {
        return Ok(None);
    }
    let global = crate::settings::load_settings()
        .map_err(|error| format!("could not load global settings: {error}"))?
        .into();
    let project = if project_trusted {
        crate::settings::load_active_project_settings(cwd)
            .map_err(|error| format!("could not load project settings: {error}"))?
            .map(|(_, settings)| settings.into())
    } else {
        None
    };
    Ok(Some(ReloadSettingsSnapshot { global, project }))
}

/// Validate every settings document that this reload will consume before
/// replacing any live extension, bridge, or harness resource.
#[cfg(test)]
fn validate_settings_for_reload(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
) -> Result<(), String> {
    load_reload_settings_snapshot(args, cwd, project_trusted).map(|_| ())
}

fn prepare_reload_inputs(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
) -> Result<PreparedReloadInputs, String> {
    prepare_reload_inputs_inner(args, cwd, project_trusted, || {})
}

fn prepare_reload_inputs_inner<F>(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
    before_verify: F,
) -> Result<PreparedReloadInputs, String>
where
    F: FnOnce(),
{
    let settings_before = load_reload_settings_snapshot(args, cwd, project_trusted)?;

    let mut extension_dirs = if args.no_extensions || args.dev_local_only {
        Vec::new()
    } else if args.project_only {
        project_extension_dirs(cwd)
    } else if project_trusted {
        extension_dirs(cwd)
    } else {
        global_extension_dirs()
    };
    if !args.no_extensions {
        extension_dirs.extend(args.extensions_dir.iter().cloned());
    }

    let skill_base_dirs = if args.no_skills {
        Vec::new()
    } else if args.dev_local_only || args.project_only {
        project_skill_dirs(cwd)
    } else if project_trusted {
        skill_dirs(cwd)
    } else {
        global_skill_dirs()
    };

    let prompt_base_dirs = if args.no_prompt_templates {
        Vec::new()
    } else if args.dev_local_only || args.project_only {
        project_prompt_template_dirs(cwd)
    } else if project_trusted {
        prompt_template_dirs(cwd)
    } else {
        global_prompt_template_dirs()
    };

    before_verify();
    let settings_after = load_reload_settings_snapshot(args, cwd, project_trusted)?;
    if settings_before != settings_after {
        return Err(
            "settings changed while reload inputs were being prepared; retry /reload".to_string(),
        );
    }

    Ok(PreparedReloadInputs {
        extension_dirs,
        skill_base_dirs,
        prompt_base_dirs,
    })
}

/// `build_models_with_extensions` for the reload path: the resolved provider
/// runtimes (NOT `resolved` — the reload context carries the `Arc<dyn Provider>`
/// list directly, since provider/auth did not change) first, then one
/// `PluggableProvider` per registered extension provider in the fresh session.
fn build_models_with_extensions_for_reload(
    providers: &[Arc<dyn Provider>],
    extension_session: &ExtensionSession,
    runtime: tokio::runtime::Handle,
) -> Vec<Arc<dyn Provider>> {
    let mut models: Vec<Arc<dyn Provider>> = providers.to_vec();
    let pluggable = rpi_extensions::PluggableProvider::from_session(extension_session, runtime);
    for provider in pluggable {
        // Declared packages must enter through credential-bound factories.
        // Falling back to a raw adapter would reintroduce packages rejected by
        // auth filtering and would discard their configured model snapshot.
        if extension_session
            .snapshot()
            .is_some_and(|snapshot| snapshot.provider_manifest(provider.id()).is_some())
        {
            continue;
        }
        if !models.iter().any(|known| known.id() == provider.id()) {
            models.push(provider);
        }
    }
    models
}

/// Diagnostic for registered TUI renderers. All three renderer kinds are
/// consumed by the interactive TUI's JSON component adapter; this line remains
/// useful under `--verbose` for extension authors.
fn report_deferred_renderers(session: &ExtensionSession) {
    let Some(snap) = session.snapshot_arc() else {
        return;
    };
    let all = snap.renderers();
    let markdown = all
        .iter()
        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Markdown)
        .count();
    let message = all
        .iter()
        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Message)
        .count();
    let entry = all
        .iter()
        .filter(|r| r.kind == rpi_extensions::RegisteredRendererKind::Entry)
        .count();
    if markdown + message + entry == 0 {
        return;
    }
    eprintln!(
        "renderers: {} markdown-transform, {} message-render, {} entry-render (active)",
        markdown, message, entry
    );
}

/// A harness-build error.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    #[error("Experimental native session policy: {0}")]
    NativeStorePolicy(String),
    #[error("Could not create the session directory: {0}")]
    SessionDir(String),
    #[error("Could not open the saved session: {0}")]
    SessionOpen(String),
    #[error("No session found for {requested} in {dir}. Start a fresh session instead (drop --continue/--resume/--session).")]
    SessionNotFound { requested: String, dir: String },
    #[error("Could not build the harness: {0}")]
    HarnessCreate(String),
}

/// Keep configured factories (including package-specific auth and catalogs)
/// first, then append legacy plugin registrations that have no runtime yet.
fn build_models_with_extensions(
    resolved: &ResolvedModel,
    extension_session: &ExtensionSession,
    runtime: tokio::runtime::Handle,
) -> Vec<Arc<dyn Provider>> {
    build_models_with_extensions_for_reload(&resolved.providers, extension_session, runtime)
}

/// Resolve project resource loading without prompting. Explicit CLI overrides
/// win, then a stored decision; projects with no decision load by default.
pub(crate) fn resolve_project_trust(args: &Args, cwd: &Path) -> bool {
    if let Some(override_value) = args.trust_override {
        return override_value;
    }
    crate::config::project_trust_decision(cwd)
        .ok()
        .flatten()
        .unwrap_or(true)
}

/// Resolve the extension dirs to scan and load the cdylib plugins, returning
/// the loaded session guard (keeps the `Library` handles alive for the harness
/// lifetime). Scan order: configured project paths, project `.rpi/extensions`,
/// configured/global conventional paths, then any
/// `--extensions-dir` flags (scanned after the defaults — `args.rs`).
/// Diagnostics are a no-op sink for now; load skips/ABI mismatches surface via
/// the `--verbose` summary.
pub(crate) fn load_extensions(
    args: &Args,
    cwd: &Path,
    project_trusted: bool,
    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
) -> ExtensionSession {
    if args.no_extensions {
        return ExtensionSession::none();
    }
    let mut dirs = if args.dev_local_only {
        Vec::new()
    } else if args.project_only {
        project_extension_dirs(cwd)
    } else if project_trusted {
        extension_dirs(cwd)
    } else {
        global_extension_dirs()
    };
    dirs.extend(args.extensions_dir.iter().cloned());
    let leases = match crate::resource_management::host_leases(cwd) {
        Ok(leases) => leases,
        Err(error) => {
            eprintln!("warning: refusing extension loading: {error}");
            return ExtensionSession::none();
        }
    };
    load_extensions_from_dirs(args, &dirs, action_bridge, Some(leases))
}

fn load_extensions_from_dirs(
    args: &Args,
    dirs: &[PathBuf],
    action_bridge: Option<Arc<rpi_extensions::ActionBridge>>,
    host_guard: Option<Arc<dyn Send + Sync>>,
) -> ExtensionSession {
    let diagnostics: Arc<dyn PluginDiagnostics> = Arc::new(NullDiagnostics);
    // B5a: the action bridge is cloned into every loaded plugin's vtable
    // `user_data` so post-register `runtime_action` calls recover the harness
    // host from any thread. The call site already gates `load_extensions` behind
    // `!no_extensions` and threads `Some(bridge)`; `None` is only passed by the
    // `--no-extensions` branch (which calls `ExtensionSession::none()` directly)
    // and tests. Explicit `--extension`/`-e` files load after the dirs.
    rpi_extensions::load_session_mixed_guarded(
        dirs,
        &args.extension,
        diagnostics,
        action_bridge,
        host_guard,
    )
}

/// Merge the loaded extension tools into the built-in set. An extension tool
/// overrides a same-named built-in; first-extension-wins across plugins is
/// already guaranteed by the registry (`register_tool` keeps the prior). The
/// explicit `--tools` allowlist / `--exclude-tools` denylist apply to the
/// merged set (the built-ins were already filtered in [`build_tools`]).
fn merge_extension_tools(
    tools: &mut Vec<HarnessTool>,
    session: &ExtensionSession,
    args: &Args,
    tool_context: &rpi_extensions::ToolCallContext,
) {
    let Some(snapshot) = session.snapshot() else {
        return;
    };
    for et in snapshot.tools() {
        let name = &et.tool.name;
        if !tool_name_allowed(name, args) {
            continue;
        }
        let adapter = PluginToolAdapter::new(et.tool.clone(), et.handle(), session.keepalive())
            .with_context(tool_context.clone());
        let harness_tool = HarnessTool::new(Arc::new(adapter));
        match tools.iter_mut().find(|t| t.tool.schema().name == *name) {
            Some(slot) => *slot = harness_tool,
            None => tools.push(harness_tool),
        }
    }
}

/// Build the tool list per `--tools`/`--exclude-tools`/`--no-tools`/
/// `--no-builtin-tools`. Mirrors the TS `tools`/`excludeTools`/`noTools`
/// resolution in `createAgentSession`.
/// Default bash timeout: 120s when the model doesn't pass one (prevents a
/// forgotten `timeout` from hanging the run forever — the "卡住" report).
/// `RPI_BASH_TIMEOUT` overrides; a model-supplied timeout always wins.
pub fn bash_options() -> rpi_tools::tools::bash::BashToolOptions {
    use rpi_tools::tools::bash::BashToolOptions;
    let default = std::env::var("RPI_BASH_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<f64>().ok())
        .unwrap_or(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS);
    // Saved user defaults, matching how `defaultTools` is read in `build_tools`.
    // `shellCommandPrefix` is prepended to every command (upstream's key for
    // alias/`shopt` setup). Native's `shellPath` is *not* wired: neither
    // `BashToolOptions` nor `ShellCaptureOptions` carries a shell binary today, so
    // honouring it means plumbing one through pi-tools first.
    let settings = crate::settings::load_settings().unwrap_or_default();
    BashToolOptions {
        command_prefix: settings.shell_command_prefix.clone(),
        default_timeout: Some(default),
        prepare: None,
    }
}

fn build_tools(ctx: &ExecutionToolContext, args: &Args) -> Vec<HarnessTool> {
    if args.no_tools {
        return Vec::new();
    }
    // Keep the coding tools aligned with Pi and expose rpi's read-only docs
    // lookup as a default assistant capability.
    //
    // Replay policy (native `ToolDeclaration.replay`): only tools that are
    // genuinely free of side effects may be re-run when a crash leaves their
    // outcome unknown — everything else must stay `Never`, because replaying
    // `bash`/`write`/`edit` would duplicate a side effect. `HarnessTool::new`
    // already defaults to `Never`, so this is opt-in per read-only tool.
    let mut all: Vec<(&'static str, HarnessTool)> = vec![
        (
            "read",
            HarnessTool::new(create_read_tool(
                ctx,
                Some(rpi_tools::tools::read::ReadToolOptions {
                    image_processor: Some(Arc::new(
                        rpi_tools::image_processing::InlineImageProcessor,
                    )),
                    ..Default::default()
                }),
            ))
            .with_replay(ToolReplay::Safe),
        ),
        (
            "bash",
            HarnessTool::new(create_bash_tool(ctx, Some(bash_options()))),
        ),
        ("edit", HarnessTool::new(create_edit_tool(ctx))),
        ("write", HarnessTool::new(create_write_tool(ctx))),
        (
            "docs",
            HarnessTool::new(create_docs_tool()).with_replay(ToolReplay::Safe),
        ),
    ];

    // Add PowerShell tool on Windows
    #[cfg(target_os = "windows")]
    all.push(("powershell", HarnessTool::new(create_powershell_tool(ctx))));

    // Apply default_tools from settings (if no CLI override)
    if args.tools.is_none() && args.resource_config.is_none() && args.resource_transition.is_none()
    {
        if let Ok(settings) = crate::settings::load_settings() {
            if let Some(default_tools) = &settings.default_tools {
                all.retain(|(name, _)| default_tools.iter().any(|t| t == name));
            }
        }
    }

    // `--no-builtin-tools` disables the built-in set but would keep
    // extension/custom tools — v1 has none, so it's equivalent to `--no-tools`
    // here. We honor it by clearing the built-ins.
    if args.no_builtin_tools {
        all.clear();
    }

    // Allowlist (`--tools`): keep only named built-ins.
    if let Some(allow) = &args.tools {
        all.retain(|(name, _)| allow.iter().any(|a| a == name));
    }
    // Denylist (`--exclude-tools`): drop named tools.
    if let Some(deny) = &args.exclude_tools {
        all.retain(|(name, _)| !deny.iter().any(|d| d == name));
    }

    all.into_iter().map(|(_, t)| t).collect()
}

/// Resolve the active tool names from the constructed tools when no explicit
/// `--tools` allowlist was given. Mirrors the TS default: all registered tools
/// active.
fn active_tool_names(tools: &[HarnessTool], args: &Args) -> Vec<String> {
    filter_active_tool_names(
        tools.iter().map(|tool| tool.tool.schema().name.clone()),
        args,
    )
}

/// Whether a tool name survives the command-line tool policy. Keep this check
/// centralized so extension-provided tools honor the same policy as built-ins.
pub(crate) fn tool_name_allowed(name: &str, args: &Args) -> bool {
    if args.no_tools {
        return false;
    }
    if args
        .tools
        .as_ref()
        .is_some_and(|allow| !allow.iter().any(|value| value == name))
    {
        return false;
    }
    if args
        .exclude_tools
        .as_ref()
        .is_some_and(|deny| deny.iter().any(|value| value == name))
    {
        return false;
    }
    true
}

pub(crate) fn filter_active_tool_names<I>(names: I, args: &Args) -> Vec<String>
where
    I: IntoIterator<Item = String>,
{
    names
        .into_iter()
        .filter(|name| tool_name_allowed(name, args))
        .collect()
}

/// Build the `Session` facade for the chosen selection.
async fn build_session(
    selection: &SessionSelection,
    cwd: &str,
    selected: Option<&crate::resource_selection::ResolvedSelection>,
) -> Result<Session, BuildError> {
    match selection {
        SessionSelection::Ephemeral => Ok(ephemeral_session()),
        SessionSelection::ExperimentalNative { dir } => Ok(Session::new(
            backend::fresh_experimental_native(dir).await?,
            None,
        )),
        SessionSelection::New { dir, .. } => {
            // Ensure the sessions directory exists, then create a fresh JSONL
            // session file inside it.
            std::fs::create_dir_all(dir)
                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
            let session = create_jsonl_session(dir, cwd)
                .await
                .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
            Ok(session)
        }
        SessionSelection::Latest { .. }
        | SessionSelection::ById { .. }
        | SessionSelection::ByExactId { .. } => restore_session(selection, cwd).await,
        SessionSelection::Fork { source, dir } => {
            fork_session_at_launch(source, dir, cwd, selected).await
        }
    }
}

/// Open an existing JSONL session for `Latest` / `ById`. Mirrors the TS
/// `SessionManager.resume`/`open` flow: list the session dir (newest-first),
/// match the request, then open the matched file and wrap it in a `Session`
/// facade. The restored transcript renders into the TUI at startup and the
/// harness continues appending to the same file.
async fn restore_session(selection: &SessionSelection, cwd: &str) -> Result<Session, BuildError> {
    // `resolve_restore_target` is newest-first; `Latest` takes the head, `ById`
    // matches the id exactly or by file-name containment (so `--session 01a02…`
    // or a partial id works, mirroring the TS id/path matching).
    let Some(meta) = resolve_restore_target(selection, cwd).await? else {
        return match selection {
            // Exact id match only (pi `--session-id`): a missing session is
            // created fresh under the selected dir instead of an error.
            SessionSelection::ByExactId { id, dir } => {
                std::fs::create_dir_all(dir)
                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
                create_jsonl_session_with_id(dir, cwd, Some(id.clone()))
                    .await
                    .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))
            }
            SessionSelection::Latest { dir } => Err(BuildError::SessionNotFound {
                requested: "the most recent session".to_string(),
                dir: dir.display().to_string(),
            }),
            SessionSelection::ById { id, dir } => Err(BuildError::SessionNotFound {
                requested: format!("session {id}"),
                dir: dir.display().to_string(),
            }),
            _ => unreachable!("resolve_restore_target only returns None for restore selections"),
        };
    };
    let sessions_root = selection_dir(selection);
    let writer_restore = StartupSpan::start(Phase::WriterRestore);
    let result = open_session(&meta, cwd, &sessions_root)
        .await
        .map(|restored| restored.session);
    if result.is_ok() {
        writer_restore.finish();
    }
    result
}

/// The sessions root a selection was resolved against.
fn selection_dir(selection: &SessionSelection) -> PathBuf {
    match selection {
        SessionSelection::Ephemeral => PathBuf::new(),
        SessionSelection::New { dir, .. }
        | SessionSelection::ExperimentalNative { dir }
        | SessionSelection::Latest { dir }
        | SessionSelection::ById { dir, .. }
        | SessionSelection::ByExactId { dir, .. }
        | SessionSelection::Fork { dir, .. } => dir.clone(),
    }
}

/// Resolve the metadata a restore selection names, without opening the file.
///
/// Shared by the startup build ([`restore_session`]) and the cwd peek
/// ([`peek_restored_session_cwd`]) so the two can never disagree about which
/// session a launch restores. Pure listing + matching: no session lock is
/// claimed and nothing is created.
async fn resolve_restore_target(
    selection: &SessionSelection,
    cwd: &str,
) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
    match selection {
        SessionSelection::Latest { dir } => {
            let metas = list_session_metadata_in_dir(cwd, dir).await?;
            Ok(first_resumable_session(&metas).cloned())
        }
        SessionSelection::ById { id, dir } => find_session_metadata(id, cwd, dir).await,
        SessionSelection::ByExactId { id, dir } => {
            let metas = list_session_metadata_in_dir(cwd, dir).await?;
            Ok(metas.into_iter().find(|m| m.id == *id))
        }
        SessionSelection::Fork { .. }
        | SessionSelection::ExperimentalNative { .. }
        | SessionSelection::New { .. }
        | SessionSelection::Ephemeral => Ok(None),
    }
}

/// The metadata of the session whose id matches exactly or by file-name
/// containment (so `--session 01a02…` / a partial id / a full file name all
/// work), or `None` when nothing matches.
async fn find_session_metadata(
    id: &str,
    cwd: &str,
    dir: &Path,
) -> Result<Option<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
    let metas = list_session_metadata_in_dir(cwd, dir).await?;
    Ok(metas
        .into_iter()
        .find(|m| m.id == id || m.path.contains(id) || id.contains(&m.id)))
}

/// What a launch that would restore a session says about the working directory.
pub(crate) struct RestoredSessionCwd {
    /// The id of the session this launch will restore. The host pins it into
    /// `args` so the later build opens exactly this session — a directory
    /// listing taken twice can disagree (another `rpi` may write a newer
    /// session in between), and adopting one session's directory while opening
    /// another is the very bug this restores.
    pub id: String,
    /// The directory recorded in the session header.
    pub recorded: PathBuf,
    /// `Some` when the recorded directory still exists and the run adopts it;
    /// `None` when the caller must fall back to the launch cwd and say so.
    pub adopted: Option<PathBuf>,
}

/// The working directory the launch's restored session was created in, resolved
/// WITHOUT opening, locking, or creating anything.
///
/// Read-only by design: this runs before trust resolution and extension
/// preparation, where a failure must not take the run down — the real open
/// happens later and surfaces its own errors. Returns `None` when the selection
/// is not a restore (fresh/ephemeral/fork) or cannot be resolved.
pub(crate) async fn peek_restored_session_cwd(
    selection: &SessionSelection,
    launch_cwd: &Path,
) -> Option<RestoredSessionCwd> {
    let cwd_str = launch_cwd.to_string_lossy().into_owned();
    let meta = resolve_restore_target(selection, &cwd_str).await.ok()??;
    let recorded = PathBuf::from(&meta.cwd);
    if recorded.as_os_str().is_empty() {
        return None;
    }
    Some(RestoredSessionCwd {
        id: meta.id,
        adopted: crate::session_cwd::resolve_session_cwd(&recorded),
        recorded,
    })
}

/// Pin a peeked restore target into `args` so the later build opens exactly the
/// session the peek inspected.
///
/// `Latest` (`-c`) re-lists the session directory when the build runs, and
/// another `rpi` may have written a newer session in between. Adopting one
/// session's working directory while opening a different conversation would put
/// the tools in a directory that conversation never used — the exact failure
/// this adoption exists to prevent. Pinning the resolved id turns the second
/// listing into an exact match instead of a fresh "newest" choice.
pub(crate) fn pin_restored_selection(args: &mut Args, restored: &RestoredSessionCwd) {
    args.continue_session = false;
    args.resume = false;
    args.session = Some(restored.id.clone());
}

/// `--fork <path|id>`: open the source session, fork it into a new JSONL
/// session (records the parent id), and start in the fork.
async fn fork_session_at_launch(
    source: &str,
    dir: &Path,
    cwd: &str,
    selected: Option<&crate::resource_selection::ResolvedSelection>,
) -> Result<Session, BuildError> {
    use rpi_harness::session::jsonl::{
        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
    };
    use rpi_harness::session::types::{ForkOptions, SessionStorage};
    use rpi_tools::FileSystem;

    let dir = dir.to_path_buf();
    std::fs::create_dir_all(&dir)
        .map_err(|e| BuildError::SessionDir(format!("{}: {e}", dir.display())))?;
    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let fs: Arc<dyn FileSystem> = env.clone();
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs: fs.clone(),
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });
    // A session file given by path forks from wherever it lives (pi parity:
    // `pi --fork <file>` takes any session file); an id or a name fragment is
    // looked up in the session directory.
    let source_meta = match session_metadata_at(Path::new(source)) {
        Some(meta) => meta,
        None => {
            let metas = repo
                .list_typed(&rpi_harness::session::jsonl::JsonlSessionListOptions::default())
                .await
                .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")))?;
            metas
                .into_iter()
                .find(|m| m.id == *source || m.path.contains(source) || source.contains(&m.id))
                .ok_or_else(|| BuildError::SessionNotFound {
                    requested: format!("--fork {source}"),
                    dir: dir.display().to_string(),
                })?
        }
    };
    let fork_storage = repo
        .fork_typed_with_value_initializer(
            &source_meta,
            &JsonlSessionCreateOptions {
                id: None,
                parent_session_id: Some(source_meta.id.clone()),
                cwd: cwd.to_string(),
                metadata: None,
            },
            &ForkOptions::default(),
            |values| crate::resource_selection::fork_initial_values_for_selection(values, selected),
        )
        .await
        .map_err(|e| BuildError::SessionDir(format!("fork {}: {e}", source_meta.path)))?;
    claim_session_lock(&fork_storage.jsonl_metadata().path).map_err(BuildError::SessionOpen)?;
    let storage_arc: Arc<dyn SessionStorage> = Arc::new(fork_storage);
    Ok(Session::new(storage_arc, None))
}

/// The metadata of the JSONL session file at `path`, or `None` when `path` is
/// not a readable session file.
fn session_metadata_at(path: &Path) -> Option<rpi_harness::session::jsonl::JsonlSessionMetadata> {
    use rpi_harness::session::jsonl::codec::{metadata_from_header, parse_header};
    use std::io::BufRead;

    let file = std::fs::File::open(path).ok()?;
    let modified_at = file
        .metadata()
        .ok()?
        .modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_millis() as i64;
    let mut first_line = String::new();
    std::io::BufReader::new(file)
        .read_line(&mut first_line)
        .ok()?;
    let header = parse_header(first_line.trim_end()).ok()?;
    let path = std::fs::canonicalize(path).ok()?;
    Some(metadata_from_header(
        &header,
        &path.to_string_lossy(),
        modified_at,
    ))
}

/// Errors from [`open_session_by_id`], split so the CLI can map them to
/// [`BuildError`] while the TUI can surface a friendlier note.
pub enum OpenError {
    /// No session matched the request.
    NotFound { requested: String },
    /// The match existed but could not be opened/parsed.
    Other(String),
}

impl std::fmt::Display for OpenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OpenError::NotFound { requested } => write!(f, "no session matches {requested}"),
            // `Other` carries the bare reason (see `open_session_by_id`); the
            // prefix lives here so the TUI and the CLI's
            // `BuildError::SessionOpen` wrapper each render it exactly once
            // (wrapping the already-prefixed `BuildError` string doubled it).
            OpenError::Other(msg) => write!(f, "Could not open the saved session: {msg}"),
        }
    }
}

/// List the JSONL session metadata under the default session dir, newest
/// first. Shared by startup restore and the TUI `/session` hot-switch.
pub async fn list_session_metadata(
    cwd: &str,
) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
    let dir = default_session_dir(Path::new(cwd));
    list_session_metadata_in_dir(cwd, &dir).await
}

pub(crate) async fn list_session_metadata_in_dir(
    cwd: &str,
    dir: &Path,
) -> Result<Vec<rpi_harness::session::jsonl::JsonlSessionMetadata>, BuildError> {
    use rpi_harness::session::jsonl::{
        JsonlSessionListOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
    };
    use rpi_tools::FileSystem;

    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let fs: Arc<dyn FileSystem> = env.clone();
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs: fs.clone(),
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });
    let metadata_lookup = StartupSpan::start(Phase::MetadataLookup);
    let result = repo
        .list_typed(&JsonlSessionListOptions::default())
        .await
        .map_err(|e| BuildError::SessionDir(format!("list sessions: {e}")));
    if result.is_ok() {
        metadata_lookup.finish();
    }
    result
}

/// A cheap, display-oriented summary of one JSONL session file.
///
/// The session pickers (`-r` and `/session`) need enough context to tell saved
/// sessions apart. The header-only [`JsonlSessionMetadata`] carries no name and
/// no transcript, so a list built from it renders as a wall of identical
/// `2026-09-25T15-05-15-847Z_…` file names — including the many header-only
/// sessions an abandoned launch leaves behind. This reads just the head (and a
/// small tail, for a late `--name`/`/name` fact) of the file to recover:
///
/// - the session display name, when one was recorded;
/// - the first user prompt, single-lined and truncated, for a readable label;
/// - whether the file is header-only (nothing to resume).
///
/// It intentionally does **not** parse the whole log: sessions can be tens of
/// megabytes, and the picker runs over every session at startup.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SessionSummary {
    /// The session display name (`--name` / `/name`), if one was recorded.
    pub name: Option<String>,
    /// The first user prompt, single-lined and trimmed to a label-sized length.
    pub preview: Option<String>,
    /// True when the file holds only its header (a session with no content).
    pub empty: bool,
    /// On-disk size in bytes (a rough content-volume hint for the picker).
    pub bytes: u64,
}

/// Bytes read from the head of a session file to recover a name + first prompt.
const SUMMARY_HEAD_BYTES: u64 = 256 * 1024;
/// Bytes read from the tail of a session file to recover a late name fact.
const SUMMARY_TAIL_BYTES: u64 = 8 * 1024;
/// Longest preview retained (characters, not bytes).
const SUMMARY_PREVIEW_CHARS: usize = 80;

/// Summarize one session file for the pickers. Best-effort: an unreadable or
/// malformed file yields a summary with `empty: false` and no label, so it is
/// still selectable rather than silently dropped.
pub fn summarize_session_file(path: &Path) -> SessionSummary {
    use std::io::{Read, Seek, SeekFrom};

    let Ok(mut file) = std::fs::File::open(path) else {
        return SessionSummary::default();
    };
    let Ok(size) = file.metadata().map(|m| m.len()) else {
        return SessionSummary::default();
    };
    if size == 0 {
        return SessionSummary {
            name: None,
            preview: None,
            empty: true,
            bytes: 0,
        };
    }

    // Head: the header line (for the empty check) + a name fact + the first user
    // prompt. The whole window is scanned; it is already in memory.
    let mut head = vec![0u8; SUMMARY_HEAD_BYTES.min(size) as usize];
    let head_len = file.read(&mut head).unwrap_or(0);
    head.truncate(head_len);
    let head = String::from_utf8_lossy(&head);
    let mut lines: Vec<&str> = head.lines().collect();
    let header_len = lines.first().map(|line| line.len()).unwrap_or(0);
    // A header-only file is exactly the header plus an optional trailing `\n`.
    let empty = (size as usize) <= header_len + 1;
    // When the window stopped short of the file end, its final line is partial:
    // drop it so a half-read message can never be mistaken for a complete one.
    if (head_len as u64) < size && !lines.is_empty() {
        lines.pop();
    }

    let mut summary = SessionSummary {
        name: None,
        preview: None,
        empty,
        bytes: size,
    };
    for line in lines {
        apply_summary_line(line, &mut summary);
    }

    // Tail: a name set late in the session lives after the head window. Read the
    // last window and scan only complete lines so a torn/partial first line is
    // ignored. Only do this when the file is larger than the head window.
    if size > SUMMARY_HEAD_BYTES
        && file
            .seek(SeekFrom::End(-(SUMMARY_TAIL_BYTES as i64)))
            .is_ok()
    {
        let mut tail = Vec::new();
        if file.read_to_end(&mut tail).is_ok() {
            let tail = String::from_utf8_lossy(&tail);
            let mut tail_lines = tail.lines();
            // Drop the possibly-partial first line of the window.
            tail_lines.next();
            for line in tail_lines {
                if let Some(name) = name_from_line(line) {
                    summary.name = name;
                }
            }
        }
    }
    summary
}

/// Extract the name from a `{"kind":"fact","fact":"name","name":…}` line.
/// Returns `Some(None)` for an explicit `name: null` (the fact was cleared).
fn name_from_line(line: &str) -> Option<Option<String>> {
    let value: serde_json::Value = serde_json::from_str(line).ok()?;
    if value.get("kind").and_then(|v| v.as_str()) != Some("fact") {
        return None;
    }
    if value.get("fact").and_then(|v| v.as_str()) != Some("name") {
        return None;
    }
    Some(match value.get("name") {
        Some(serde_json::Value::String(name)) => Some(name.clone()),
        _ => None,
    })
}

/// Fold one JSONL line into `summary`: record a name fact, or capture the first
/// user prompt as the preview.
fn apply_summary_line(line: &str, summary: &mut SessionSummary) {
    if let Some(name) = name_from_line(line) {
        summary.name = name;
        return;
    }
    if summary.preview.is_some() {
        return;
    }
    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
        return;
    };
    if value.get("kind").and_then(|v| v.as_str()) != Some("entry") {
        return;
    }
    if value.get("type").and_then(|v| v.as_str()) != Some("message") {
        return;
    }
    let Some(message) = value.get("message") else {
        return;
    };
    if message.get("role").and_then(|v| v.as_str()) != Some("user") {
        return;
    }
    let text = match message.get("content") {
        Some(serde_json::Value::String(text)) => Some(text.as_str()),
        Some(serde_json::Value::Array(blocks)) => blocks.iter().find_map(|block| {
            (block.get("type").and_then(|v| v.as_str()) == Some("text"))
                .then(|| block.get("text").and_then(|v| v.as_str()))
                .flatten()
        }),
        _ => None,
    };
    let Some(text) = text else { return };
    let collapsed = text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    if collapsed.is_empty() {
        return;
    }
    summary.preview = Some(collapsed.chars().take(SUMMARY_PREVIEW_CHARS).collect());
}

/// The human label for a session row: its recorded name, else the first user
/// prompt, else a marker that says the file has no transcript to show. Shared
/// by the startup picker and the in-TUI `/session` selector.
pub fn session_display_label(summary: &SessionSummary) -> String {
    if let Some(name) = summary.name.as_deref().map(str::trim) {
        if !name.is_empty() {
            return name.to_string();
        }
    }
    match summary.preview.as_deref().map(str::trim) {
        Some(preview) if !preview.is_empty() => preview.to_string(),
        _ => "(no messages)".to_string(),
    }
}

/// Compact byte count (1.2MB / 34KB / 512B), shared by the startup picker and
/// the in-TUI `/session` selector.
pub fn format_session_bytes(bytes: u64) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{}KB", bytes / 1024)
    } else {
        format!("{bytes}B")
    }
}

/// The first 8 characters of a session id, enough to disambiguate two rows that
/// share a timestamp without shouting the whole UUID.
pub fn short_session_id(id: &str) -> &str {
    &id[..id.len().min(8)]
}

/// Synchronously list every JSONL session file under `dir`, newest-first by
/// modification time.
///
/// The repo's [`list_session_metadata`] is async and scans one cwd-encoded
/// subdirectory level; the in-TUI `/session` selector runs on the blocking key
/// thread and cannot await it, so this walks the same layout directly. Both
/// `.jsonl` files directly under `dir` and one level of subdirectories are
/// accepted.
pub fn list_session_files_sync(dir: &Path) -> Vec<PathBuf> {
    let mut files: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
    let mut visit = |path: PathBuf| {
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl")
            || path.to_string_lossy().ends_with(".progress.jsonl")
        {
            return;
        }
        let modified = std::fs::metadata(&path)
            .and_then(|m| m.modified())
            .unwrap_or(std::time::UNIX_EPOCH);
        files.push((path, modified));
    };
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                if let Ok(inner) = std::fs::read_dir(&path) {
                    for child in inner.flatten() {
                        visit(child.path());
                    }
                }
            } else {
                visit(path);
            }
        }
    }
    files.sort_by(|a, b| b.1.cmp(&a.1));
    files.into_iter().map(|(path, _)| path).collect()
}

/// Pick the session `--continue`/`-c` should open: the newest session that has
/// content (a header-only session resumes to an empty transcript). Falls back to
/// the newest overall when every session is empty, and `None` only when the
/// list is empty.
fn first_resumable_session(
    metas: &[rpi_harness::session::jsonl::JsonlSessionMetadata],
) -> Option<&rpi_harness::session::jsonl::JsonlSessionMetadata> {
    metas
        .iter()
        .find(|meta| !summarize_session_file(Path::new(&meta.path)).empty)
        .or_else(|| metas.first())
}

/// Open a session whose id matches exactly or by file-name containment
/// (so `--session 01a02…` / a partial id / a full file name all work). The
/// TUI `/session` hot-switch calls this with the selector's item value.
pub async fn open_session_by_id(id: &str, cwd: &str) -> Result<Session, OpenError> {
    let dir = default_session_dir(Path::new(cwd));
    open_session_by_id_in_dir(id, cwd, &dir)
        .await
        .map(|restored| restored.session)
}

pub(crate) async fn open_session_by_id_in_dir(
    id: &str,
    cwd: &str,
    dir: &Path,
) -> Result<RestoredSession, OpenError> {
    let meta = find_session_metadata(id, cwd, dir)
        .await
        .map_err(|e| OpenError::Other(e.to_string()))?;
    let Some(meta) = meta else {
        return Err(OpenError::NotFound {
            requested: format!("session {id}"),
        });
    };
    open_session(&meta, cwd, dir).await.map_err(|e| {
        OpenError::Other(match e {
            // `open_session` renders as "Could not open the saved session:
            // <reason>" via `BuildError`. Carry the bare reason so it is not
            // prefixed twice (once here, once by the CLI/TUI).
            BuildError::SessionOpen(reason) => reason,
            other => other.to_string(),
        })
    })
}

/// Publish the active session's id to plugins, on both channels that carry it.
///
/// Called on **every** activation of a session — the startup build AND every
/// in-process swap (`switch_to_session`, `fork_session`, and the plugin
/// `NewSession`/`Fork`/`SwitchSession` runtime actions all route through
/// [`set_active_session`]). Two things must stay in step:
///
/// - `ToolCallContext` — read per plugin **tool** call, which is why a stale
///   value there made a plugin's `todo`-style state follow the wrong session.
/// - `RPI_SESSION_ID` — read per **turn** by the provider hooks, which is the
///   only channel an observer gets for a pure-chat run. Process-global, which is
///   exactly the scope of "the session this process is serving".
///
/// The write overwrites unconditionally, deliberately. An inherited value is not
/// an override: `rpi` spawning `rpi` would otherwise hand the child the parent's
/// session id, and the child — which is *serving its own* session — would report
/// it forever. (Children no longer inherit the variable at all; see
/// `rpi_tools::HOST_PRIVATE_ENV`. This overwrite is the second line of defence,
/// for any other way a value can arrive pre-set.)
///
/// An embedder that genuinely wants to pin the id can revert to the old
/// behaviour by setting the variable *after* this runs; there is no supported
/// way to pin it before, because a session that does not match its own id is
/// never what the caller wants.
fn publish_session_identity(tool_context: &rpi_extensions::ToolCallContext, id: &str) {
    std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, id);
    tool_context.set_session_id(id);
}

/// Swap the session the harness serves, republishing the identity to plugins.
///
/// The single funnel for an in-process session change. Prefer this over calling
/// `AgentHarness::set_session` directly: the harness holds no reference to the
/// plugin channels, so a bare `set_session` would leave every plugin reporting
/// the session it had before the swap.
///
/// `tool_context` is optional because not every caller has one (the harness's own
/// tests, a headless embedder); the env channel is always published, since the
/// provider hooks depend on it.
pub(crate) async fn set_active_session(
    harness: &AgentHarness,
    session: Session,
    tool_context: Option<&rpi_extensions::ToolCallContext>,
) -> Result<(), String> {
    let metadata = session.get_metadata().await.ok();
    harness
        .set_session(session)
        .await
        .map_err(|e| e.to_string())?;
    if let Some(metadata) = metadata {
        std::env::set_var(rpi_plugin_sdk::SESSION_ID_ENV, &metadata.id);
        if let Some(context) = tool_context {
            context.set_session_id(metadata.id);
        }
    }
    Ok(())
}

/// Fork the harness's current session into a new JSONL session (new id, parent
/// set to the source) and wrap it in a `Session`. Mirrors the TUI's
/// `fork_session` flow (`interactive_tui.rs`) — hoisted here so both the TUI
/// and the plugin `runtime_action(Fork)` host share one implementation.
/// Returns the new `Session` (NOT yet swapped onto the harness — the caller
/// does `harness.set_session(...)`).
pub(crate) async fn fork_session_storage(
    harness: &AgentHarness,
    cwd: &str,
    dir: &Path,
) -> Result<Session, String> {
    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
    use rpi_tools::FileSystem;

    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let fs: Arc<dyn FileSystem> = env.clone();
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs,
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });
    // The fork needs the rich JSONL metadata (with the on-disk path); resolve
    // it from the session list by the current session's id.
    let id = harness.session().storage().metadata().id.clone();
    let metas = list_session_metadata_in_dir(cwd, dir)
        .await
        .map_err(|e| e.to_string())?;
    let Some(source) = metas.iter().find(|m| m.id == id) else {
        return Err(format!("current session {id} not found on disk"));
    };
    let fork_storage = repo
        .fork_typed_with_value_initializer(
            source,
            &rpi_harness::session::jsonl::JsonlSessionCreateOptions {
                id: None,
                parent_session_id: Some(source.id.clone()),
                cwd: cwd.to_string(),
                metadata: None,
            },
            &rpi_harness::session::types::ForkOptions::default(),
            crate::resource_selection::fork_initial_values,
        )
        .await
        .map_err(|e| e.to_string())?;
    claim_session_lock(&fork_storage.jsonl_metadata().path)?;
    Ok(Session::new(Arc::new(fork_storage), None))
}

/// Validate a private copy before publishing it in the repo's normal cwd
/// directory. Keep the imported identity/history and never overwrite a saved
/// session (including when the source is already inside this repository).
pub(crate) async fn import_session_file(
    source: &Path,
    cwd: &str,
    dir: &Path,
) -> Result<Session, String> {
    use rpi_harness::session::jsonl::{
        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions, JsonlSessionStorage,
    };
    use rpi_harness::session::types::SessionStorage;
    use rpi_tools::FileSystem;

    let dir = if dir.is_absolute() {
        dir.to_path_buf()
    } else {
        Path::new(cwd).join(dir)
    };
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    // External writers must be closed. This process deliberately retains locks
    // for previously opened sessions, so its own copies additionally verify a
    // stable history around the sidecar snapshot (bind/entry before retirement).
    let source_progress = PathBuf::from(format!("{}.progress.jsonl", source.display()));
    let source_lock_path = PathBuf::from(format!("{}.lock", source.display()));
    let canonical_lock = std::fs::canonicalize(&source_lock_path).ok();
    let owned_here = SESSION_LOCK_PATHS.get().is_some_and(|paths| {
        paths.lock().unwrap().iter().any(|path| {
            path == &source_lock_path
                || canonical_lock.as_ref().is_some_and(|canonical| {
                    std::fs::canonicalize(path).ok().as_ref() == Some(canonical)
                })
        })
    });
    let _source_lock = if !owned_here && source_progress.try_exists().map_err(|e| e.to_string())? {
        let lock = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(format!("{}.lock", source.display()))
            .map_err(|e| format!("lock import source: {e}"))?;
        fs2::FileExt::try_lock_exclusive(&lock).map_err(|_| {
            "close the source session before importing its recovery pair".to_owned()
        })?;
        Some(lock)
    } else {
        None
    };
    let staging = tempfile::tempdir_in(&dir).map_err(|e| e.to_string())?;
    let staged = staging.path().join("history.stage");
    let staged_progress = PathBuf::from(format!("{}.progress.jsonl", staged.display()));
    let mut attempts = 0;
    let has_progress = loop {
        std::fs::copy(source, &staged).map_err(|e| format!("copy import: {e}"))?;
        let copied_history = std::fs::read(&staged).map_err(|e| e.to_string())?;
        let has_progress = match std::fs::copy(&source_progress, &staged_progress) {
            Ok(_) => true,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                let _ = std::fs::remove_file(&staged_progress);
                false
            }
            Err(error) => return Err(format!("copy progress import: {error}")),
        };
        if copied_history == std::fs::read(source).map_err(|e| e.to_string())? {
            break has_progress;
        }
        attempts += 1;
        if attempts >= 4 {
            return Err(
                "source history changed during import; retry when the session is idle".into(),
            );
        }
        tokio::task::yield_now().await;
    };
    let fs: Arc<dyn FileSystem> = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let validated = JsonlSessionStorage::load(
        fs.clone(),
        &staged.to_string_lossy(),
        Arc::new(SystemClock),
        Arc::new(DefaultIdGenerator::new()),
    )
    .await
    .map_err(|e| format!("invalid session import: {e}"))?;
    validated
        .read_progress("")
        .await
        .map_err(|e| format!("invalid recovery import: {e}"))?;
    let mut metadata = validated.jsonl_metadata().clone();
    drop(validated);
    let text = std::fs::read_to_string(&staged).map_err(|e| e.to_string())?;
    let (first, rest) = text
        .split_once('\n')
        .ok_or_else(|| "import has no complete header".to_owned())?;
    let mut header =
        rpi_harness::session::jsonl::codec::parse_header(first).map_err(|e| e.to_string())?;
    if has_progress && header.progress_format.is_none() {
        return Err("history-only artifact has an undeclared recovery companion".into());
    }
    // An imported history-only artifact receives the destination's empty store.
    // Imports of live-format sessions retain their validated companion instead.
    header.progress_format = Some("assistant-progress-v1".into());
    std::fs::write(
        &staged,
        format!(
            "{}{}",
            rpi_harness::session::jsonl::codec::encode_header(&header),
            rest
        ),
    )
    .map_err(|e| e.to_string())?;
    if list_session_metadata_in_dir(cwd, &dir)
        .await
        .map_err(|e| e.to_string())?
        .iter()
        .any(|saved| saved.id == metadata.id)
    {
        return Err(format!(
            "session {} already exists in {}",
            metadata.id,
            dir.display()
        ));
    }
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs,
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });
    // Let the repository validate the id and choose its canonical destination.
    let destination = repo
        .create_typed(&JsonlSessionCreateOptions {
            id: Some(metadata.id.clone()),
            parent_session_id: metadata.parent_session_id.clone(),
            cwd: cwd.to_string(),
            metadata: metadata.metadata.clone(),
        })
        .await
        .map_err(|e| e.to_string())?;
    let path = destination.jsonl_metadata().path.clone();
    drop(destination);
    if let Err(error) = claim_session_lock(&path) {
        // Another process owns this destination; leave its file intact.
        return Err(error);
    }
    let destination_progress = format!("{path}.progress.jsonl");
    let publish = (|| -> std::io::Result<()> {
        if has_progress {
            std::fs::rename(&staged_progress, &destination_progress)?;
        }
        std::fs::rename(&staged, &path)
    })();
    if let Err(error) = publish {
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(&destination_progress);
        return Err(format!("publish import: {error}"));
    }
    metadata.path = path;
    let storage = repo
        .open_by_jsonl_metadata(&metadata)
        .await
        .map_err(|e| e.to_string())?;
    Ok(Session::new(Arc::new(storage), None))
}

/// Session logs this process has claimed, so re-claiming is a no-op.
static SESSION_LOCK_PATHS: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();
/// The held lock handles. Kept alive for the process lifetime — dropping the
/// `File` would release the OS lock, so the guard is parked here.
static SESSION_LOCKS: OnceLock<Mutex<Vec<std::fs::File>>> = OnceLock::new();

/// Claim the exclusive lock for a session log.
///
/// Two rpi processes appending to one JSONL diverge their `sequence` counters
/// (duplicate / gapped seqs) and corrupt it. The lock is an OS advisory lock on
/// `<path>.lock`: the second process gets a clear "already open" error instead
/// of corrupting the log, and the OS releases it automatically when the holder
/// exits (no stale-lock cleanup). Re-claiming a path this process already holds
/// is a no-op, so the TUI's session hot-switch can re-open freely.
fn claim_session_lock(session_path: &str) -> Result<(), String> {
    claim_session_lock_inner(session_path, true)
}
fn claim_session_lock_inner(session_path: &str, allow_reentry: bool) -> Result<(), String> {
    let canonical =
        std::fs::canonicalize(session_path).unwrap_or_else(|_| PathBuf::from(session_path));
    let lock_path = PathBuf::from(format!("{}.lock", canonical.display()));
    let mut paths = SESSION_LOCK_PATHS
        .get_or_init(|| Mutex::new(HashSet::new()))
        .lock()
        .unwrap();
    if paths.contains(&lock_path) {
        return if allow_reentry {
            Ok(())
        } else {
            Err("transition session already has a writer in this process".into())
        };
    }
    let file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .open(&lock_path)
        .map_err(|e| format!("open session lock {}: {e}", lock_path.display()))?;
    if fs2::FileExt::try_lock_exclusive(&file).is_err() {
        return Err(format!(
            "session {session_path} is already open in another rpi process"
        ));
    }
    SESSION_LOCKS
        .get_or_init(|| Mutex::new(Vec::new()))
        .lock()
        .unwrap()
        .push(file);
    paths.insert(lock_path);
    Ok(())
}

/// A restored session together with the working directory it was created in.
///
/// The recorded cwd is data for the host's notices, never a silent adoption:
/// the launch path adopts the directory in [`app`](crate::app) before any
/// resource loads (tools, extensions, system prompt, and trust all key off it),
/// and the `/session` hot-switch does not move the running tools at all. Either
/// way the user hears about the directory instead of the process quietly
/// working somewhere unexpected.
pub(crate) struct RestoredSession {
    pub session: Session,
    /// The directory recorded in the session header, when it still exists.
    /// `None` when the record is empty or the path is gone (or is a file).
    pub recorded_cwd: Option<PathBuf>,
}

/// Wrap an opened [`JsonlSessionStorage`] in the `Session` facade (shared by
/// startup restore + TUI hot-switch).
///
/// `sessions_root` is passed in rather than re-derived from `cwd`: after a
/// restore adopts the session's directory, `default_session_dir(cwd)` would
/// name the ADOPTED project's tree, which is not where this session was found.
async fn open_session(
    meta: &rpi_harness::session::jsonl::JsonlSessionMetadata,
    cwd: &str,
    sessions_root: &Path,
) -> Result<RestoredSession, BuildError> {
    use rpi_harness::session::jsonl::{JsonlSessionRepo, JsonlSessionRepoOptions};
    use rpi_harness::session::types::SessionStorage;
    use rpi_tools::FileSystem;

    let dir = sessions_root;
    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let fs: Arc<dyn FileSystem> = env.clone();
    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs: fs.clone(),
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });
    claim_session_lock(&meta.path).map_err(BuildError::SessionOpen)?;
    let storage = repo
        .open_by_jsonl_metadata(meta)
        .await
        .map_err(|e| BuildError::SessionOpen(format!("open {}: {e}", meta.path)))?;
    // Native saved sessions predating progressFormat remain read-only to plain
    // storage loaders. Only this locked, not-yet-shared restore opts into writes.
    let storage = storage
        .enable_progress_under_exclusive_lock()
        .await
        .map_err(|e| BuildError::SessionOpen(format!("upgrade {}: {e}", meta.path)))?;
    let storage_arc: Arc<dyn SessionStorage> = Arc::new(storage);
    Ok(RestoredSession {
        session: Session::new(storage_arc, None),
        recorded_cwd: crate::session_cwd::resolve_session_cwd(Path::new(&meta.cwd)),
    })
}

/// A fresh ephemeral in-memory session (no persistence). Used for `--no-session`
/// and for `/new` inside such a run — an ephemeral launch keeps swapping in
/// in-memory sessions, never a JSONL file.
pub(crate) fn ephemeral_session() -> Session {
    let storage = Arc::new(InMemorySessionStorage::new(
        SessionMetadata {
            id: "ephemeral".into(),
            created_at: 0,
            parent_session_id: None,
        },
        Arc::new(SystemClock),
        Arc::new(DefaultIdGenerator::new()),
    ));
    Session::new(storage, None).with_volatile_progress()
}

/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
///
/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
/// Create a fresh JSONL session file under `dir` and wrap it in a `Session`.
///
/// Uses the `JsonlSessionRepo` over an `OsExecutionEnv`-backed `FileSystem`
/// rooted at the cwd, so paths resolve consistently with the tools. Mirrors the
/// TS `SessionManager.create` flow (header write + `JsonlSessionStorage` open).
pub(crate) async fn create_jsonl_session(dir: &Path, cwd: &str) -> Result<Session, String> {
    create_jsonl_session_with_id(dir, cwd, None).await
}

/// `create_jsonl_session` with an explicit id (the `--session-id` fixed-id
/// contract: the file is named with the given id so later `--session-id`
/// launches restore the same session).
pub(crate) async fn create_jsonl_session_with_id(
    dir: &Path,
    cwd: &str,
    id: Option<String>,
) -> Result<Session, String> {
    use rpi_harness::session::jsonl::{
        JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
    };
    use rpi_tools::FileSystem;

    // A dedicated OS env for session-file I/O, rooted at the cwd so the repo's
    // relative-path resolution matches the tool env.
    let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(cwd)));
    let fs: Arc<dyn FileSystem> = env.clone();

    let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
        fs: fs.clone(),
        sessions_root: dir.to_string_lossy().into_owned(),
        clock: Arc::new(SystemClock),
        ids: Arc::new(DefaultIdGenerator::new()),
    });

    let opts = JsonlSessionCreateOptions {
        id, // fresh uuidv7 when None (--session-id passes the fixed id)
        parent_session_id: None,
        cwd: cwd.to_string(),
        metadata: None,
    };
    let storage = repo
        .create_typed(&opts)
        .await
        .map_err(|e| format!("create session: {e}"))?;
    claim_session_lock(&storage.jsonl_metadata().path)
        .map_err(|e| format!("create session: {e}"))?;
    // `JsonlSessionStorage` implements `SessionStorage`; wrap in the facade.
    let storage_arc: Arc<dyn rpi_harness::session::types::SessionStorage> = Arc::new(storage);
    Ok(Session::new(storage_arc, None))
}

/// Read an `--append-system-prompt` target: if it's a readable file path, return
/// its contents; otherwise return `None` and let the caller use the literal.
fn read_append_target(target: &str, sources: &mut Vec<String>) -> Option<String> {
    let path = Path::new(target);
    if path.is_file() {
        read_prompt_source(path, sources)
    } else {
        None
    }
}

/// Record provenance at the successful read, rather than rediscovering files
/// during rendering (which could report a shadowed or unreadable file).
fn read_prompt_source(path: &Path, sources: &mut Vec<String>) -> Option<String> {
    let text = std::fs::read_to_string(path).ok()?;
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    };
    let source = absolute.to_string_lossy().into_owned();
    if !sources.contains(&source) {
        sources.push(source);
    }
    Some(text)
}

#[cfg(test)]
mod goal_outbox_smoke_tests;
#[cfg(all(test, feature = "experimental-native-store"))]
mod native_roundtrip_tests;
#[cfg(all(test, feature = "experimental-native-store"))]
mod native_store_tests;
#[cfg(test)]
mod runtime_session_tests;

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

    #[test]
    fn settlement_bridge_follows_reload_and_releases_its_session_with_the_bus() {
        use rpi_harness::events::{HarnessEvent, HarnessEventBus, RunEndEvent, RunEndOutcome};
        use std::sync::atomic::{AtomicUsize, Ordering};
        static OLD: AtomicUsize = AtomicUsize::new(0);
        static NEW: AtomicUsize = AtomicUsize::new(0);
        extern "C" fn old(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
            OLD.fetch_add(1, Ordering::SeqCst);
            0
        }
        extern "C" fn new(_: rpi_plugin_sdk::StablePluginEvent, _: *mut std::ffi::c_void) -> i32 {
            NEW.fetch_add(1, Ordering::SeqCst);
            0
        }
        let make = |handler: rpi_plugin_sdk::EventHandlerFn| {
            let mut registry = rpi_extensions::ExtensionRegistry::new();
            registry.register_event_handler(
                "settlement".into(),
                rpi_plugin_sdk::EventTag::AgentSettled,
                handler,
                std::ptr::null_mut(),
            );
            ExtensionSession::from_parts(
                Arc::new(registry.snapshot()),
                rpi_extensions::PluginKeepalive::empty(),
                vec![],
                None,
            )
        };
        let sessions = Arc::new(Mutex::new(make(old)));
        let weak = Arc::downgrade(&sessions);
        let bus = HarnessEventBus::new();
        install_extension_settlement_bridge(&bus, sessions.clone());
        let ended = |outcome| {
            HarnessEvent::RunEnd(RunEndEvent {
                lane: "main".into(),
                run_id: "run".into(),
                outcome,
                leaf_id: "leaf".into(),
            })
        };
        bus.emit(&ended(RunEndOutcome::Completed));
        assert_eq!(OLD.load(Ordering::SeqCst), 1);
        *sessions.lock().unwrap() = make(new);
        for outcome in [RunEndOutcome::Aborted, RunEndOutcome::Failed] {
            bus.emit(&ended(outcome));
        }
        assert_eq!(OLD.load(Ordering::SeqCst), 1);
        assert_eq!(NEW.load(Ordering::SeqCst), 2);
        drop(sessions);
        assert!(weak.upgrade().is_some());
        drop(bus);
        assert!(
            weak.upgrade().is_none(),
            "settlement observer must not create an ownership cycle"
        );
    }

    #[tokio::test]
    async fn unauthenticated_packages_are_not_reintroduced_as_legacy_adapters() {
        extern "C" fn request(
            _: rpi_plugin_sdk::StbStringRef,
            _: *mut rpi_plugin_sdk::StbString,
            _: *mut std::ffi::c_void,
        ) -> i32 {
            1
        }
        let mut registry = rpi_extensions::ExtensionRegistry::new();
        for id in ["package", "legacy"] {
            registry.register_provider(rpi_extensions::RegisteredProvider {
                provider_id: id.into(),
                base_url: "http://localhost".into(),
                api_style: "openai-completions".into(),
                request_fn: request,
                stream_fn: None,
                plugin_free_string: rpi_plugin_sdk::callbacks::free_string,
                user_data: std::ptr::null_mut(),
            });
        }
        assert!(registry.apply_declaration_json(&serde_json::json!({"providers":[{
            "id":"package", "requiresAuth":true,
            "models":[rpi_ai::Model::new("model", "Model", rpi_ai::Api::OpenaiCompletions, "package", "http://localhost")]
        }]}).to_string()));
        let session = ExtensionSession::from_parts(
            Arc::new(registry.snapshot()),
            rpi_extensions::PluginKeepalive::empty(),
            vec![],
            None,
        );
        let providers = build_models_with_extensions_for_reload(
            &[],
            &session,
            tokio::runtime::Handle::current(),
        );
        assert_eq!(
            providers
                .iter()
                .map(|provider| provider.id())
                .collect::<Vec<_>>(),
            ["legacy"]
        );
    }
    use crate::args::Args;

    #[test]
    fn loaded_context_paths_track_precedence_and_reload() {
        const CHILD: &str = "RPI_CONTEXT_PATHS_REGRESSION_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let dir = tempfile::tempdir().unwrap();
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "session::tests::loaded_context_paths_track_precedence_and_reload",
                    "--nocapture",
                ])
                .env(CHILD, "1")
                .env(crate::config::CONFIG_DIR_ENV, dir.path())
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "{}\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(async {
                let agent = crate::config::agent_dir().unwrap();
                let cwd = agent.join("project");
                let project_config = cwd.join(".rpi");
                std::fs::create_dir_all(&project_config).unwrap();
                for (path, content) in [
                    (agent.join("SYSTEM.md"), "GLOBAL_BASE"),
                    (agent.join("APPEND_SYSTEM.md"), "GLOBAL_APPEND"),
                    (agent.join("AGENTS.md"), "GLOBAL_INSTRUCTIONS"),
                    (project_config.join("SYSTEM.md"), "PROJECT_BASE"),
                    (project_config.join("APPEND_SYSTEM.md"), "PROJECT_APPEND"),
                    (cwd.join("AGENTS.md"), "PROJECT_INSTRUCTIONS"),
                    (cwd.join("CLAUDE.md"), "SHADOWED_CLAUDE"),
                ] {
                    std::fs::write(path, content).unwrap();
                }
                let resolved = crate::provider::resolve(
                    Some("anthropic"),
                    Some(crate::provider::DEFAULT_MODEL_ID),
                    None,
                    Some("test-key"),
                    None,
                )
                .unwrap();
                let args = Args {
                    no_session: true,
                    no_extensions: true,
                    no_skills: true,
                    no_prompt_templates: true,
                    trust_override: Some(true),
                    ..Default::default()
                };
                let (harness, _events, mut context) =
                    build(&resolved, &args, &cwd, true).await.unwrap();
                let resources = harness.get_resources().await.unwrap();
                let path = |p: PathBuf| p.to_string_lossy().into_owned();
                assert_eq!(
                    &resources.context_files[..2],
                    &[
                        path(project_config.join("SYSTEM.md")),
                        path(project_config.join("APPEND_SYSTEM.md")),
                    ]
                );
                assert!(resources
                    .context_files
                    .contains(&path(agent.join("AGENTS.md"))));
                assert!(resources
                    .context_files
                    .contains(&path(cwd.join("AGENTS.md"))));
                assert!(!resources
                    .context_files
                    .contains(&path(cwd.join("CLAUDE.md"))));
                assert!(!resources
                    .context_files
                    .contains(&path(agent.join("SYSTEM.md"))));
                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
                assert!(prompt.contains("PROJECT_BASE") && prompt.contains("PROJECT_APPEND"));
                assert!(!prompt.contains("GLOBAL_BASE") && !prompt.contains("SHADOWED_CLAUDE"));

                // Removing the selected project files makes reload fall back to
                // globals; removed instruction paths must disappear as well.
                std::fs::remove_file(project_config.join("SYSTEM.md")).unwrap();
                std::fs::remove_file(project_config.join("APPEND_SYSTEM.md")).unwrap();
                std::fs::remove_file(cwd.join("AGENTS.md")).unwrap();
                assert!(
                    !reload_extension_resources(&harness, &context)
                        .await
                        .had_errors
                );
                let resources = harness.get_resources().await.unwrap();
                assert_eq!(
                    &resources.context_files[..2],
                    &[
                        path(agent.join("SYSTEM.md")),
                        path(agent.join("APPEND_SYSTEM.md")),
                    ]
                );
                assert!(resources
                    .context_files
                    .contains(&path(cwd.join("CLAUDE.md"))));
                assert!(!resources
                    .context_files
                    .contains(&path(project_config.join("SYSTEM.md"))));

                // Explicit append files are listed; literal text and overridden
                // discovered base/append files are not invented as file sources.
                let explicit = agent.join("custom-append.md");
                std::fs::write(&explicit, "EXPLICIT_APPEND").unwrap();
                context.args.system_prompt = Some("EXPLICIT_BASE".into());
                context.args.append_system_prompt =
                    vec![path(explicit.clone()), "literal append".into()];
                context.args.no_context_files = true;
                assert!(
                    !reload_extension_resources(&harness, &context)
                        .await
                        .had_errors
                );
                assert_eq!(
                    harness.get_resources().await.unwrap().context_files,
                    vec![path(explicit)]
                );

                // The reload must honor the startup opt-out from project context.
                context.args.system_prompt = None;
                context.args.append_system_prompt.clear();
                context.args.no_context_files = false;
                context.args.trust_override = Some(false);
                assert!(
                    !reload_extension_resources(&harness, &context)
                        .await
                        .had_errors
                );
                assert!(harness
                    .get_resources()
                    .await
                    .unwrap()
                    .context_files
                    .is_empty());
                let prompt = harness.get_system_prompt().await.unwrap().unwrap();
                assert!(
                    !prompt.contains("SHADOWED_CLAUDE") && !prompt.contains("GLOBAL_INSTRUCTIONS")
                );
            });
    }

    #[test]
    fn prompt_source_read_failures_and_literals_do_not_create_file_provenance() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("SYSTEM.md");
        let mut sources = Vec::new();
        assert!(read_prompt_source(&file, &mut sources).is_none());
        std::fs::write(&file, [0xff, 0xfe]).unwrap();
        assert!(read_prompt_source(&file, &mut sources).is_none());
        assert!(read_append_target("literal instructions", &mut sources).is_none());
        assert!(sources.is_empty());
        std::fs::write(&file, "loaded instructions").unwrap();
        assert_eq!(
            read_prompt_source(&file, &mut sources).as_deref(),
            Some("loaded instructions")
        );
        assert!(read_prompt_source(&file, &mut sources).is_some());
        assert_eq!(sources, vec![file.to_string_lossy().into_owned()]);
    }

    extern "C" fn deny_test_tool_call(
        _event: rpi_plugin_sdk::StablePluginEvent,
        _data: *mut std::ffi::c_void,
    ) -> i32 {
        rpi_plugin_sdk::EVENT_HANDLER_ABORT
    }

    async fn invoke_test_tool_hook(
        hook: &rpi_agent::BeforeToolCall,
    ) -> Option<rpi_agent::BeforeToolCallResult> {
        let message = rpi_ai::providers::faux::faux_assistant_message(
            "approval",
            rpi_ai::types::StopReason::ToolUse,
        );
        let rpi_ai::types::Content::ToolCall(call) =
            rpi_ai::types::Content::tool_call("call", "read", serde_json::json!({"path":"x"}))
        else {
            unreachable!()
        };
        hook(
            rpi_agent::BeforeToolCallContext {
                assistant_message: &message,
                tool_call: &call,
                args: &call.arguments,
                context: &rpi_agent::AgentContext::default(),
            },
            tokio_util::sync::CancellationToken::new(),
        )
        .await
    }

    #[tokio::test]
    async fn tool_call_hook_uses_reloaded_session_and_newly_discovered_gate() {
        let sessions = Arc::new(Mutex::new(ExtensionSession::none()));
        let hook =
            extension_tool_call_hook(sessions.clone(), rpi_extensions::UiDialogMailbox::new());
        assert!(invoke_test_tool_hook(&hook).await.is_none());
        for name in ["first-gate", "reloaded-gate"] {
            let mut registry = rpi_extensions::ExtensionRegistry::new();
            registry.register_event_handler(
                name.into(),
                rpi_plugin_sdk::EventTag::ToolCall,
                deny_test_tool_call,
                std::ptr::null_mut(),
            );
            let fresh = ExtensionSession::from_parts(
                Arc::new(registry.snapshot()),
                rpi_extensions::PluginKeepalive::empty(),
                Vec::new(),
                None,
            );
            {
                let mut current = sessions.lock().unwrap();
                if let Some(snapshot) = current.snapshot() {
                    snapshot.active_flag().store(false, Ordering::SeqCst);
                }
                *current = fresh;
            }
            let result = invoke_test_tool_hook(&hook).await.unwrap();
            assert!(result.block);
            assert!(result.reason.unwrap().contains(name));
        }
        *sessions.lock().unwrap() = ExtensionSession::none();
        assert!(invoke_test_tool_hook(&hook).await.is_none());
    }

    /// A unique scratch file for one summary test.
    fn scratch(name: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "rpi-summary-{}-{nanos}-{name}.jsonl",
            std::process::id()
        ));
        path
    }

    #[test]
    fn summary_marks_a_header_only_session_empty() {
        let path = scratch("empty");
        std::fs::write(
            &path,
            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
        )
        .unwrap();
        let summary = summarize_session_file(&path);
        assert!(summary.empty, "a header-only file has nothing to resume");
        assert!(summary.preview.is_none());
        assert_eq!(summary.bytes, std::fs::metadata(&path).unwrap().len());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn summary_reads_the_first_user_prompt_and_name() {
        let path = scratch("content");
        let body = concat!(
            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
            "{\"kind\":\"fact\",\"seq\":1,\"fact\":\"name\",\"name\":\"fix resume picker\"}\n",
            "{\"kind\":\"record\",\"type\":\"operation_started\",\"id\":\"r1\"}\n",
            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"kind\":\"user\",\"role\":\"user\",\"content\":\"read the rpi -r picker\"}}\n",
            "{\"kind\":\"entry\",\"lane\":\"main\",\"type\":\"message\",\"id\":\"e2\",\"message\":{\"kind\":\"assistant\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"second\"}]}}\n",
        );
        std::fs::write(&path, body).unwrap();
        let summary = summarize_session_file(&path);
        assert!(!summary.empty);
        assert_eq!(summary.name.as_deref(), Some("fix resume picker"));
        assert_eq!(summary.preview.as_deref(), Some("read the rpi -r picker"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn summary_extracts_a_block_style_user_prompt() {
        let path = scratch("blocks");
        let body = concat!(
            "{\"kind\":\"header\",\"version\":4,\"id\":\"abc\",\"createdAt\":1,\"cwd\":\"x\"}\n",
            "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"line one\\nline two\"}]}}\n",
        );
        std::fs::write(&path, body).unwrap();
        let summary = summarize_session_file(&path);
        assert_eq!(summary.preview.as_deref(), Some("line one line two"));
        assert_eq!(session_display_label(&summary), "line one line two");
        std::fs::remove_file(&path).ok();
    }

    fn meta_for(path: &Path, id: &str) -> rpi_harness::session::jsonl::JsonlSessionMetadata {
        rpi_harness::session::jsonl::JsonlSessionMetadata {
            id: id.to_string(),
            created_at: 0,
            cwd: ".".to_string(),
            path: path.to_string_lossy().into_owned(),
            modified_at: 0,
            source_format: rpi_harness::session::jsonl::JsonlSourceFormat::V4,
            parent_session_id: None,
            legacy_parent_session_path: None,
            metadata: None,
        }
    }

    #[test]
    fn continue_skips_newer_empty_sessions() {
        let empty = scratch("newest-empty");
        std::fs::write(
            &empty,
            "{\"kind\":\"header\",\"version\":4,\"id\":\"empty\",\"createdAt\":1,\"cwd\":\"x\"}\n",
        )
        .unwrap();
        let content = scratch("older-content");
        std::fs::write(
            &content,
            concat!(
                "{\"kind\":\"header\",\"version\":4,\"id\":\"old\",\"createdAt\":1,\"cwd\":\"x\"}\n",
                "{\"kind\":\"entry\",\"type\":\"message\",\"id\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n",
            ),
        )
        .unwrap();

        let metas = vec![meta_for(&empty, "empty"), meta_for(&content, "old")];
        let picked = first_resumable_session(&metas).expect("a resumable session");
        assert_eq!(picked.id, "old");

        // When every session is empty, fall back to the newest rather than
        // erroring.
        let all_empty = vec![meta_for(&empty, "empty")];
        assert_eq!(first_resumable_session(&all_empty).unwrap().id, "empty");

        std::fs::remove_file(&empty).ok();
        std::fs::remove_file(&content).ok();
    }

    #[tokio::test]
    async fn import_preserves_validates_and_locks_the_recovery_pair() {
        use rpi_harness::session::jsonl::{JsonlSessionStorage, JsonlV4Header};
        use rpi_harness::session::types::{
            AssistantFrameOp, AssistantFrameRecord, RecordBase, SessionStorage,
        };
        let tmp = tempfile::tempdir().unwrap();
        let source = tmp.path().join("source.jsonl");
        let progress = tmp.path().join("source.jsonl.progress.jsonl");
        let fs: Arc<dyn rpi_tools::FileSystem> =
            Arc::new(OsExecutionEnv::with_cwd(tmp.path().into()));
        let storage = JsonlSessionStorage::create(
            fs,
            &source.to_string_lossy(),
            JsonlV4Header::new("import-pair".into(), 1, "/".into(), None, None, None),
            Arc::new(SystemClock),
            Arc::new(DefaultIdGenerator::new()),
        )
        .await
        .unwrap();
        storage
            .append_progress(vec![AssistantFrameRecord {
                base: RecordBase {
                    id: "accepted-prefix".into(),
                    seq: 0,
                    lane: "main".into(),
                    timestamp: 0,
                },
                run_id: "run".into(),
                stream_index: 0,
                op: AssistantFrameOp::Append,
                frame: Some(serde_json::json!({"payload":"keep"})),
            }])
            .await
            .unwrap();
        drop(storage);
        let original = std::fs::read(&progress).unwrap();
        let destination = tmp.path().join("imported");
        let imported = import_session_file(&source, &tmp.path().to_string_lossy(), &destination)
            .await
            .unwrap();
        assert_eq!(
            imported.read_progress("run").await.unwrap()[0].base.id,
            "accepted-prefix"
        );
        assert_eq!(
            std::fs::read(&progress).unwrap(),
            original,
            "import must not repair or mutate its source"
        );
        let lock = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(tmp.path().join("source.jsonl.lock"))
            .unwrap();
        fs2::FileExt::try_lock_exclusive(&lock).unwrap();
        assert!(import_session_file(
            &source,
            &tmp.path().to_string_lossy(),
            &tmp.path().join("busy")
        )
        .await
        .is_err());
        drop(lock);
        let mut corrupt = String::from_utf8(original.clone()).unwrap();
        corrupt = corrupt.replace(
            "\"session_id\":\"import-pair\"",
            "\"session_id\":\"foreign\"",
        );
        assert_ne!(corrupt.as_bytes(), original.as_slice());
        std::fs::write(&progress, corrupt).unwrap();
        assert!(import_session_file(
            &source,
            &tmp.path().to_string_lossy(),
            &tmp.path().join("foreign")
        )
        .await
        .is_err());
        std::fs::remove_file(&progress).unwrap();
        assert!(import_session_file(
            &source,
            &tmp.path().to_string_lossy(),
            &tmp.path().join("missing")
        )
        .await
        .is_err());
    }

    #[test]
    fn list_session_files_sync_walks_the_cwd_subdirectory() {
        let root = std::env::temp_dir().join(format!("rpi-summary-{}-dir", std::process::id()));
        let nested = root.join("--proj--");
        std::fs::create_dir_all(&nested).unwrap();
        let file = nested.join("2026-01-01_a.jsonl");
        std::fs::write(&file, "{}\n").unwrap();
        let sidecar = nested.join("2026-01-01_a.jsonl.progress.jsonl");
        std::fs::write(&sidecar, "{}\n").unwrap();
        let found = list_session_files_sync(&root);
        assert!(found.iter().any(|p| p == &file));
        assert!(!found.contains(&sidecar));
        std::fs::remove_dir_all(&root).ok();
    }

    /// The default CLI tool set plus the `todo` tool its bundled plugins add.
    fn default_prompt_tools() -> Vec<String> {
        BUILTIN_TOOL_NAMES
            .iter()
            .copied()
            .chain(["todo"])
            .map(str::to_owned)
            .collect()
    }

    #[test]
    fn default_prompt_lists_only_the_active_tools() {
        let tools = ["read", "grep", "find", "ls"].map(str::to_owned);
        let p = default_system_prompt_with_tools("/tmp/proj", true, &tools);
        assert!(p.contains("- read  — Read file contents"));
        assert!(p.contains("- grep  — Search file contents"));
        for absent in ["- edit", "- write", "- bash", "- docs", "todo", "Windows"] {
            assert!(
                !p.contains(absent),
                "{absent} must not appear for a read-only run: {p}"
            );
        }
        assert!(p.contains("Re-stating the same plan without acting on it is a bug"));
        let none = default_system_prompt_with_tools("/tmp/proj", false, &[]);
        assert!(none.contains("Available tools:\n(none)"));
    }

    #[test]
    fn default_prompt_mentions_cwd_and_tools() {
        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
        assert!(p.contains("/tmp/proj"));
        assert!(p.contains("read"));
        assert!(p.contains("bash"));
        assert!(p.contains("edit"));
        assert!(p.contains("write"));
        assert!(p.contains("docs"));
        assert!(!p.contains("- grep"));
        assert!(!p.contains("- find"));
        assert!(!p.contains("- ls"));
        assert!(!p.contains("- powershell"));
        assert!(p.contains("Bash/POSIX syntax, also on Windows"));
    }

    #[test]
    fn default_prompt_instructs_language_matching() {
        // A Chinese (or any non-English) user gets a same-language reply
        // without having to ask every turn.
        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
        assert!(
            p.contains("same language as the user's latest message"),
            "the prompt must tell the model to mirror the user's language: {p}"
        );
    }

    #[test]
    fn default_prompt_keeps_working_state_in_the_visible_channel() {
        // Regression guard for the re-plan loop: on openai-compatible providers
        // the assistant's `thinking` blocks are dropped when the next request is
        // built (`providers/openai_completions.rs`: `Content::text_only`), so a
        // plan that lives only in reasoning is re-derived every turn. One
        // observed session paid for that 112 times in a single run, and twice
        // hallucinated the user's input ("The user is greeting me with hello",
        // with no such message). See `docs/llm-repetition-forensics.md` §八.
        let p = default_system_prompt_with_tools("/tmp/proj", false, &default_prompt_tools());
        let lower = p.to_lowercase();
        // The rule must state the mechanism, not just "be clear".
        assert!(
            lower.contains("reasoning is not") && lower.contains("carried into your next turn"),
            "the prompt must explain that reasoning does not survive the turn: {p}"
        );
        // Working state stays visible; extension-specific rules require opt-in.
        assert!(
            lower.contains("visible") && !lower.contains("todo tool"),
            "the prompt must keep state visible without inventing extension rules: {p}"
        );
        // …plus the anti-repetition rule itself.
        assert!(
            lower.contains("re-stating the same plan"),
            "the prompt must call out plan re-statement as a bug: {p}"
        );
        // And the guidance must not instruct re-reading what is already shown.
        assert!(
            lower.contains("already shown earlier"),
            "the prompt must discourage re-fetching known content: {p}"
        );
    }

    #[test]
    fn default_prompt_does_not_claim_reasoning_is_lost_when_it_is_replayed() {
        // `compat.requiresThinkingAsText` (and the native thinking channels of
        // anthropic-messages / openai-responses) DO carry the model's reasoning
        // back on the next request. Telling such a model "reasoning is not
        // carried into your next turn" is false, and the instruction to restate
        // the plan every turn is exactly the busy-work the re-plan analysis
        // measured. The wording must flip with the mechanism.
        let p = default_system_prompt_with_tools("/tmp/proj", true, &default_prompt_tools());
        let lower = p.to_lowercase();
        assert!(
            lower.contains("carried back"),
            "a replaying model must be told its reasoning survives: {p}"
        );
        assert!(
            !lower.contains("reasoning is not"),
            "the replayed variant must not claim reasoning is dropped: {p}"
        );
        assert!(
            lower.contains("do not re-derive"),
            "the replayed variant must forbid re-deriving the plan: {p}"
        );
        assert!(
            lower.contains("do not re-derive") && lower.contains("re-stating the same plan"),
            "the anti-repetition rule must survive the flip: {p}"
        );
        assert!(
            lower.contains("already shown earlier"),
            "the re-read rule must survive the flip: {p}"
        );
    }

    #[test]
    fn default_prompt_states_each_rule_once() {
        // The plan rule, the todo tool and the anti-repetition line used to be
        // spread over two guidelines that repeated each other.
        for replayed in [false, true] {
            let p =
                default_system_prompt_with_tools("/tmp/proj", replayed, &default_prompt_tools());
            for phrase in ["the same plan", "Windows", "guessing"] {
                assert_eq!(p.matches(phrase).count(), 1, "{phrase:?} repeated: {p}");
            }
            assert!(
                !p.contains("todo tool"),
                "extension rules require explicit metadata"
            );
        }
    }

    /// Only side-effect-free tools may be replayed after a crash.
    ///
    /// Regression guard for an inverted default: `ToolReplay` used to default to
    /// `Safe` and the CLI then marked *every* tool `Safe`, so the first time
    /// recovery acted on the flag it would have re-run `bash`/`write`/`edit` and
    /// duplicated their side effects. upstream defaults to `"never"`
    /// (`drive/tools.ts: tool.replay ?? "never"`).
    #[test]
    fn only_read_only_tools_are_replayable() {
        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
        let tools = build_tools(&context, &Args::default());

        let replay_of = |name: &str| {
            tools
                .iter()
                .find(|tool| tool.tool.schema().name == name)
                .map(|tool| tool.replay)
        };

        for read_only in ["read", "docs"] {
            assert_eq!(
                replay_of(read_only),
                Some(ToolReplay::Safe),
                "{read_only} is side-effect free, so recovery may re-run it"
            );
        }
        for mutating in ["bash", "edit", "write", "powershell"] {
            if let Some(replay) = replay_of(mutating) {
                assert_eq!(
                    replay,
                    ToolReplay::Never,
                    "{mutating} must never be replayed: re-running it would duplicate its effect"
                );
            }
        }
    }

    #[test]
    fn default_tools_include_docs_lookup() {
        let env = Arc::new(OsExecutionEnv::with_cwd(PathBuf::from(".")));
        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
        let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
        let context = ExecutionToolContext::new(env_dyn, Some(mut_env));
        let names: Vec<String> = build_tools(&context, &Args::default())
            .iter()
            .map(|tool| tool.tool.schema().name.clone())
            .collect();

        // `docs` is a default capability; the legacy rpi-only lookup tools stay
        // unregistered. Asserted by membership (not exact equality) because
        // `powershell` is Windows-only and `settings.json#defaultTools` may
        // narrow the set in a developer's environment.
        assert!(names.contains(&"docs".to_string()));
        for legacy in ["grep", "find", "ls"] {
            assert!(
                !names.contains(&legacy.to_string()),
                "legacy tool {legacy} should not be registered by default"
            );
        }
    }

    #[test]
    fn reload_settings_preflight_respects_trust() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(cwd.join(".rpi")).unwrap();
        std::fs::write(agent.join("settings.json"), "{}").unwrap();
        std::fs::write(cwd.join(".rpi/settings.json"), "{ malformed").unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
        let args = Args::default();

        let trusted = validate_settings_for_reload(&args, &cwd, true);
        let untrusted = validate_settings_for_reload(&args, &cwd, false);
        assert!(trusted
            .unwrap_err()
            .contains("could not load project settings"));
        assert!(untrusted.is_ok());

        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
        assert!(validate_settings_for_reload(&args, &cwd, false)
            .unwrap_err()
            .contains("could not load global settings"));

        let local_only = Args {
            dev_local_only: true,
            ..Args::default()
        };
        assert!(validate_settings_for_reload(&local_only, &cwd, true).is_ok());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn reload_preserves_live_resources_when_settings_break() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        let skill_dir = tmp.path().join("configured-skills");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: keep-me\ndescription: Reload sentinel\n---\nKeep this skill loaded.",
        )
        .unwrap();
        std::fs::write(
            agent.join("settings.json"),
            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
        )
        .unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        let resolved = crate::provider::resolve(
            Some("anthropic"),
            Some(crate::provider::DEFAULT_MODEL_ID),
            None,
            Some("test-key"),
            None,
        )
        .unwrap();
        let args = Args {
            trust_override: Some(false),
            no_session: true,
            no_extensions: true,
            no_prompt_templates: true,
            no_context_files: true,
            system_prompt: Some("stable system prompt".into()),
            ..Args::default()
        };
        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();
        let before_resources = harness.get_resources().await.unwrap();
        assert_eq!(before_resources.skills.as_ref().unwrap().len(), 1);
        assert_eq!(before_resources.skills.as_ref().unwrap()[0].name, "keep-me");
        let before_prompt = harness.get_system_prompt().await.unwrap();
        let before_tools: Vec<String> = harness
            .get_tools()
            .await
            .unwrap()
            .iter()
            .map(|tool| tool.tool.schema().name.clone())
            .collect();
        let before_bridge = context
            .action_bridge
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .clone();

        std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
        let outcome = reload_extension_resources(&harness, &context).await;

        assert!(outcome.had_warnings);
        assert!(outcome.summary.contains("Settings reload failed"));
        assert!(outcome.summary.contains("could not load global settings"));
        // Hard failure keeps the previous resources; the outcome must not
        // advertise a fresh trust policy either (theme discovery keeps the
        // registry it already matches).
        assert_eq!(outcome.project_trusted, None);
        assert_eq!(harness.get_resources().await.unwrap(), before_resources);
        assert_eq!(harness.get_system_prompt().await.unwrap(), before_prompt);
        let after_tools: Vec<String> = harness
            .get_tools()
            .await
            .unwrap()
            .iter()
            .map(|tool| tool.tool.schema().name.clone())
            .collect();
        assert_eq!(after_tools, before_tools);
        let after_bridge = context
            .action_bridge
            .lock()
            .unwrap()
            .as_ref()
            .unwrap()
            .clone();
        assert!(Arc::ptr_eq(&after_bridge, &before_bridge));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn reload_outcome_carries_the_current_project_trust() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        // Startup snapshot: trusted.
        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
        let resolved = crate::provider::resolve(
            Some("anthropic"),
            Some(crate::provider::DEFAULT_MODEL_ID),
            None,
            Some("test-key"),
            None,
        )
        .unwrap();
        let args = Args {
            no_session: true,
            no_extensions: true,
            no_prompt_templates: true,
            no_context_files: true,
            system_prompt: Some("stable system prompt".into()),
            ..Args::default()
        };
        let (harness, _events, context) = build(&resolved, &args, &cwd, true).await.unwrap();
        assert!(context.project_trusted, "startup snapshot is trusted");

        // /trust no, then /reload: the outcome must report the CURRENT
        // decision, not the immutable startup snapshot.
        crate::config::set_project_trust(&cwd, Some(false)).unwrap();
        let outcome = reload_extension_resources(&harness, &context).await;
        assert!(!outcome.had_errors, "{}", outcome.summary);
        assert_eq!(outcome.project_trusted, Some(false));

        // And the opposite transition back to trusted.
        crate::config::set_project_trust(&cwd, Some(true)).unwrap();
        let outcome = reload_extension_resources(&harness, &context).await;
        assert!(!outcome.had_errors, "{}", outcome.summary);
        assert_eq!(outcome.project_trusted, Some(true));
    }

    #[test]
    fn reload_preparation_rejects_settings_changed_during_derivation() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        let first_skill_dir = tmp.path().join("first-skills");
        let second_skill_dir = tmp.path().join("second-skills");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::fs::write(
            agent.join("settings.json"),
            serde_json::json!({"skillDirs": [first_skill_dir]}).to_string(),
        )
        .unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);
        let args = Args {
            trust_override: Some(false),
            no_extensions: true,
            no_prompt_templates: true,
            ..Args::default()
        };

        let result = prepare_reload_inputs_inner(&args, &cwd, false, || {
            std::fs::write(
                agent.join("settings.json"),
                serde_json::json!({"skillDirs": [second_skill_dir]}).to_string(),
            )
            .unwrap();
        });

        let error = result
            .err()
            .expect("settings mutation must fail preparation");
        assert!(error.contains("settings changed while reload inputs were being prepared"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn reload_uses_frozen_settings_inputs_after_preparation() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        let skill_dir = tmp.path().join("configured-skills");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: frozen-skill\ndescription: Reload sentinel\n---\nFrozen input.",
        )
        .unwrap();
        std::fs::write(
            agent.join("settings.json"),
            serde_json::json!({"skillDirs": [skill_dir]}).to_string(),
        )
        .unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        let resolved = crate::provider::resolve(
            Some("anthropic"),
            Some(crate::provider::DEFAULT_MODEL_ID),
            None,
            Some("test-key"),
            None,
        )
        .unwrap();
        let args = Args {
            trust_override: Some(false),
            no_session: true,
            no_extensions: true,
            no_prompt_templates: true,
            no_context_files: true,
            system_prompt: Some("stable system prompt".into()),
            ..Args::default()
        };
        let (harness, _events, context) = build(&resolved, &args, &cwd, false).await.unwrap();

        let outcome = reload_extension_resources_inner(&harness, &context, || {
            std::fs::write(agent.join("settings.json"), "{ malformed").unwrap();
        })
        .await;

        assert!(!outcome.summary.contains("Settings reload failed"));
        assert_eq!(
            outcome.summary,
            "Reloaded 0 plugin(s), 1 skill(s), 0 prompt(s)."
        );
        let resources = harness.get_resources().await.unwrap();
        let skills = resources.skills.as_ref().unwrap();
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "frozen-skill");
    }

    #[tokio::test]
    async fn reload_resource_paths_include_explicit_skill_and_prompt_files() {
        let tmp = tempfile::tempdir().unwrap();
        let skill_path = tmp.path().join("explicit-skill.md");
        std::fs::write(
            &skill_path,
            "---\nname: explicit-skill\ndescription: Explicit skill\n---\nSkill body",
        )
        .unwrap();
        let prompt_path = tmp.path().join("explicit-prompt.md");
        std::fs::write(
            &prompt_path,
            "---\ndescription: Explicit prompt\n---\nPrompt body",
        )
        .unwrap();

        let args = Args {
            skill: vec![skill_path.clone()],
            prompt_template: vec![prompt_path.clone()],
            ..Args::default()
        };
        let skill_paths = append_reload_resource_paths(Vec::new(), &args.skill, &[], &[], &[]);
        let prompt_paths =
            append_reload_resource_paths(Vec::new(), &args.prompt_template, &[], &[], &[]);
        let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
        let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env;

        let skills = load_skills_with_precedence(&env_dyn, &skill_paths).await;
        assert_eq!(skills.skills.len(), 1, "{:?}", skills.diagnostics);
        assert_eq!(skills.skills[0].name, "explicit-skill");

        let prompts = load_prompt_templates_with_precedence(&env_dyn, &prompt_paths).await;
        assert_eq!(
            prompts.prompt_templates.len(),
            1,
            "{:?}",
            prompts.diagnostics
        );
        assert_eq!(prompts.prompt_templates[0].name, "explicit-prompt");
    }

    #[test]
    fn tool_policy_applies_to_rust_and_js_active_names() {
        let names = vec![
            "read".to_string(),
            "ask_user_question".to_string(),
            "write".to_string(),
        ];

        let args = Args {
            tools: Some(vec!["read".into(), "ask_user_question".into()]),
            ..Args::default()
        };
        assert_eq!(
            filter_active_tool_names(names.clone(), &args),
            vec!["read", "ask_user_question"]
        );

        let args = Args {
            exclude_tools: Some(vec!["ask_user_question".into()]),
            ..Args::default()
        };
        assert_eq!(
            filter_active_tool_names(names.clone(), &args),
            vec!["read", "write"]
        );

        let args = Args {
            no_tools: true,
            ..Args::default()
        };
        assert!(filter_active_tool_names(names, &args).is_empty());
    }

    #[test]
    fn select_ephemeral_when_no_session() {
        let args = Args {
            no_session: true,
            ..Args::default()
        };
        let cwd = Path::new("/tmp");
        assert!(matches!(
            select_session(&args, cwd),
            SessionSelection::Ephemeral
        ));
    }

    #[test]
    fn project_resources_load_by_default_and_allow_explicit_opt_out() {
        let defaults = Args::default();
        assert!(resolve_project_trust(
            &defaults,
            Path::new("C:/definitely-not-a-project")
        ));

        let denied = Args {
            trust_override: Some(false),
            ..Args::default()
        };
        assert!(!resolve_project_trust(
            &denied,
            Path::new("C:/definitely-not-a-project")
        ));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn build_preserves_the_supplied_startup_project_snapshot() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        let resolved = crate::provider::resolve(
            Some("anthropic"),
            Some(crate::provider::DEFAULT_MODEL_ID),
            None,
            Some("test-key"),
            None,
        )
        .unwrap();
        let args = Args {
            trust_override: Some(false),
            no_session: true,
            no_tools: true,
            no_extensions: true,
            no_skills: true,
            no_prompt_templates: true,
            no_context_files: true,
            system_prompt: Some("test prompt".into()),
            ..Args::default()
        };

        let (_, _, context) = build(&resolved, &args, &cwd, true).await.unwrap();

        assert_eq!(context.cwd, cwd);
        assert!(context.project_trusted);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn build_applies_the_name_flag_to_the_session() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let cwd = tmp.path().join("project");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&cwd).unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        let resolved = crate::provider::resolve(
            Some("anthropic"),
            Some(crate::provider::DEFAULT_MODEL_ID),
            None,
            Some("test-key"),
            None,
        )
        .unwrap();
        let args = Args {
            trust_override: Some(false),
            no_tools: true,
            no_extensions: true,
            no_skills: true,
            no_prompt_templates: true,
            no_context_files: true,
            system_prompt: Some("test prompt".into()),
            name: Some("smoke name".into()),
            session_dir: Some(cwd.join("sessions")),
            ..Args::default()
        };

        let (harness, _, _) = build(&resolved, &args, &cwd, true).await.unwrap();
        assert_eq!(
            harness.get_name().await.unwrap().as_deref(),
            Some("smoke name")
        );
    }

    #[test]
    fn select_latest_for_continue_and_resume() {
        let _env = crate::config::test_support::SessionDirEnv::new(None);
        let args = Args {
            continue_session: true,
            ..Args::default()
        };
        let cwd = Path::new("/tmp");
        assert!(matches!(
            select_session(&args, cwd),
            SessionSelection::Latest { .. }
        ));

        let args = Args {
            resume: true,
            ..Args::default()
        };
        assert!(matches!(
            select_session(&args, cwd),
            SessionSelection::Latest { .. }
        ));
    }

    #[test]
    fn select_by_id_for_session_flag() {
        let _env = crate::config::test_support::SessionDirEnv::new(None);
        let args = Args {
            session: Some("01a02ece".into()),
            ..Args::default()
        };
        let cwd = Path::new("/tmp");
        assert!(matches!(
            select_session(&args, cwd),
            SessionSelection::ById { id, .. } if id == "01a02ece"
        ));
    }

    #[test]
    fn select_new_with_custom_dir() {
        let _env = crate::config::test_support::SessionDirEnv::new(None);
        let args = Args {
            session_dir: Some(PathBuf::from("/tmp/sess")),
            ..Args::default()
        };
        let cwd = Path::new("/tmp");
        match select_session(&args, cwd) {
            SessionSelection::New { dir, .. } => assert_eq!(dir, PathBuf::from("/tmp/sess")),
            other => panic!("expected New, got {other:?}"),
        }
    }

    #[test]
    fn select_new_default_dir() {
        let _env = crate::config::test_support::SessionDirEnv::new(None);
        let args = Args::default();
        let cwd = Path::new("/proj");
        match select_session(&args, cwd) {
            SessionSelection::New { dir, .. } => {
                assert_eq!(dir, Path::new("/proj/.rpi/sessions"));
            }
            other => panic!("expected New, got {other:?}"),
        }
    }

    #[test]
    fn default_session_dir_only_uses_rpi() {
        let _env = crate::config::test_support::SessionDirEnv::new(None);
        let tmp = tempfile::tempdir().unwrap();
        let cwd = tmp.path();
        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
        std::fs::create_dir_all(cwd.join(".rpi/sessions")).unwrap();
        assert_eq!(default_session_dir(cwd), cwd.join(".rpi/sessions"));
    }

    #[test]
    fn default_session_dir_uses_env_var() {
        let tmp = tempfile::tempdir().unwrap();
        let cwd = tmp.path();
        let custom = tmp.path().join("custom_sessions");
        let _env = crate::config::test_support::SessionDirEnv::new(Some(&custom));
        assert_eq!(default_session_dir(cwd), custom);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ephemeral_session_builds_roundtrips() {
        // Sanity: the ephemeral path produces a usable Session facade (the
        // harness build itself needs a provider; tested via the integration
        // path in tests/build.rs instead).
        let s = ephemeral_session();
        let leaf = s.get_leaf_id().await;
        assert!(leaf.is_ok());
    }

    // NOTE: `build_tools`/`active_tool_names` integration is exercised by the
    // `tests/build.rs` harness-build test (needs a provider + multi-thread rt).

    /// The exclusion policy, checked against the constants rather than copies.
    ///
    /// `rpi-tools` builds its exclusion from `rpi-plugin-sdk`'s declarations, so
    /// within this repo a rename is a compile error — this test is not the link
    /// between those two crates any more. What it still guards is the part the
    /// compiler cannot see:
    ///
    /// - **The wire values.** `rpi-langfuse` lives in a different repository and
    ///   agrees on the *strings*, not the constant paths. Rewriting a constant's
    ///   value would compile here and silently stop matching there, so the exact
    ///   values are pinned below. Changing one is a deliberate, breaking change to
    ///   a cross-repo contract, and it should fail here first.
    /// - **Coverage.** Every name the SDK declares must actually be excluded.
    /// - **Narrowness.** The user's own configuration must still reach the shell.
    #[test]
    fn host_private_env_matches_the_declared_contract() {
        // 1. The wire values. Pinned literally on purpose: see the doc comment.
        assert_eq!(rpi_plugin_sdk::SESSION_ID_ENV, "RPI_SESSION_ID");
        assert_eq!(
            rpi_plugin_sdk::SUBAGENT_PARENT_ENV,
            [
                "LANGFUSE_PI_PARENT_TRACE_ID",
                "LANGFUSE_PI_PARENT_SPAN_ID",
                "LANGFUSE_PI_PARENT_SESSION_ID",
                "LANGFUSE_PI_PARENT_DEPTH",
            ],
            "these strings are what rpi-langfuse (a different repo) matches; a \
             change here is a breaking cross-repo change, not a refactor"
        );

        // 2. Coverage — derived from the declarations, so a newly added family
        //    member is checked without anyone remembering to extend this test.
        for name in rpi_plugin_sdk::SUBAGENT_PARENT_ENV
            .iter()
            .chain(std::iter::once(&rpi_plugin_sdk::SESSION_ID_ENV))
        {
            assert!(
                rpi_tools::is_host_private_env(name),
                "`{name}` must not reach a spawned shell, but rpi-tools excludes only {:?}",
                rpi_tools::HOST_PRIVATE_ENV
            );
        }

        // 3. Narrowness — these name how the *user* configured the run and are
        //    exactly what a command inside the shell should still see.
        for visible in [
            crate::args::RPI_OFFLINE_ENV,
            crate::config::CONFIG_DIR_ENV,
            "PATH",
        ] {
            assert!(
                !rpi_tools::is_host_private_env(visible),
                "{visible} describes the user's configuration and must still reach the shell"
            );
        }
    }
    #[tokio::test]
    async fn reload_shutdown_joins_all_handlers_even_after_veto() {
        use rpi_plugin_sdk::{EventTag, StablePluginEvent};
        use std::sync::atomic::AtomicUsize;
        static CONTEXTS: rpi_plugin_sdk::handles::ToolHandles<Arc<AtomicUsize>> =
            rpi_plugin_sdk::handles::ToolHandles::new();
        struct ContextOwner(usize);
        impl Drop for ContextOwner {
            fn drop(&mut self) {
                drop(CONTEXTS.remove(self.0 as rpi_plugin_sdk::StepHandle));
            }
        }
        extern "C" fn stop(_: StablePluginEvent, data: *mut std::ffi::c_void) -> i32 {
            let context = CONTEXTS.get(data).expect("live test context");
            let calls = context.lock().clone();
            std::thread::sleep(std::time::Duration::from_millis(20));
            if calls.fetch_add(1, Ordering::SeqCst) == 0 {
                rpi_plugin_sdk::EVENT_HANDLER_ABORT
            } else {
                0
            }
        }
        let calls = Arc::new(AtomicUsize::new(0));
        let context = CONTEXTS.insert(calls.clone());
        let _owner = ContextOwner(context as usize);
        let mut registry = rpi_extensions::ExtensionRegistry::new();
        for name in ["first", "second"] {
            registry.register_event_handler(name.into(), EventTag::SessionShutdown, stop, context);
        }
        super::shutdown_extensions_for_reload(
            Some(Arc::new(registry.snapshot())),
            rpi_extensions::PluginKeepalive::empty(),
        )
        .await
        .unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    // ---- restored-session working directory ----

    /// A restore peek must name the directory the session was created in —
    /// that is the whole point of recording it. Everything downstream (tool
    /// env, system prompt, context files, extensions) keys off the run's cwd,
    /// so a peek that falls back to the launch directory would leave the
    /// resumed agent editing files in whatever directory `rpi` happened to be
    /// started from.
    #[tokio::test]
    async fn a_restored_session_adopts_its_recorded_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("project-a");
        let launch = tmp.path().join("launch-dir");
        let sessions = tmp.path().join("sessions");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir_all(&launch).unwrap();
        std::fs::create_dir_all(&sessions).unwrap();
        create_jsonl_session_with_id(
            &sessions,
            &project.to_string_lossy(),
            Some("cwdadopt01".into()),
        )
        .await
        .unwrap();

        let selection = SessionSelection::ById {
            id: "cwdadopt01".into(),
            dir: sessions.clone(),
        };
        let peeked = peek_restored_session_cwd(&selection, &launch)
            .await
            .expect("a resumable session with a recorded cwd");
        assert_eq!(peeked.recorded, project);
        assert_eq!(peeked.adopted, Some(project));
    }

    /// A recorded directory that no longer exists must NOT be adopted: the run
    /// falls back to the launch cwd, and the peek hands back the record so the
    /// host can say so (instead of the old behaviour of eprintln-ing mid-TUI).
    #[tokio::test]
    async fn a_missing_recorded_directory_is_reported_not_adopted() {
        let tmp = tempfile::tempdir().unwrap();
        let gone = tmp.path().join("project-gone");
        let launch = tmp.path().join("launch-dir");
        let sessions = tmp.path().join("sessions");
        std::fs::create_dir_all(&launch).unwrap();
        std::fs::create_dir_all(&sessions).unwrap();
        create_jsonl_session_with_id(
            &sessions,
            &gone.to_string_lossy(),
            Some("cwdgone001".into()),
        )
        .await
        .unwrap();

        let selection = SessionSelection::ById {
            id: "cwdgone001".into(),
            dir: sessions.clone(),
        };
        let peeked = peek_restored_session_cwd(&selection, &launch)
            .await
            .expect("the session itself is resumable");
        assert_eq!(peeked.recorded, gone);
        assert_eq!(peeked.adopted, None);
        let note = crate::session_cwd::missing_session_cwd_note(&peeked.recorded, &launch);
        assert!(note.contains("no longer exists"), "{note}");
        assert!(note.contains("launch-dir"), "{note}");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn legacy_progress_upgrade_normal_open_runs_and_reopens() {
        use rpi_ai::providers::faux::{FauxProvider, FauxScript};
        use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
        use rpi_harness::session::jsonl::{
            encode_header, JsonlSessionCreateOptions, JsonlSessionRepo, JsonlSessionRepoOptions,
            JsonlV4Header,
        };
        let tmp = tempfile::tempdir().unwrap();
        let sessions = tmp.path().join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        let cwd = tmp.path().to_string_lossy().into_owned();
        let repo = JsonlSessionRepo::with_env_cwd(JsonlSessionRepoOptions {
            fs: Arc::new(OsExecutionEnv::with_cwd(tmp.path().into())),
            sessions_root: sessions.to_string_lossy().into_owned(),
            clock: Arc::new(SystemClock),
            ids: Arc::new(DefaultIdGenerator::new()),
        });
        let fixture = repo
            .create_typed(&JsonlSessionCreateOptions {
                id: Some("legacycli001".into()),
                parent_session_id: None,
                cwd: cwd.clone(),
                metadata: None,
            })
            .await
            .unwrap();
        let path = PathBuf::from(fixture.jsonl_metadata().path);
        drop(fixture);
        let sidecar = PathBuf::from(format!("{}.progress.jsonl", path.display()));
        std::fs::remove_file(&sidecar).unwrap();
        let header = JsonlV4Header::new("legacycli001".into(), 1, cwd.clone(), None, None, None);
        std::fs::write(&path, encode_header(&header)).unwrap();
        assert!(!sidecar.exists());
        for _ in 0..2 {
            let restored = open_session_by_id_in_dir("legacycli001", &cwd, &sessions)
                .await
                .map_err(|e| e.to_string())
                .unwrap();
            assert_eq!(restored.session.storage().metadata().id, "legacycli001");
            let provider =
                FauxProvider::new(FauxScript::new().with_text("continued legacy session"));
            let harness = AgentHarness::create(AgentHarnessOptions {
                model: provider.default_model().clone(),
                models: vec![provider],
                session: restored.session,
                allow_existing_session: true,
                ..Default::default()
            })
            .await
            .unwrap();
            let run = harness.prompt_text("continue", vec![]).await.unwrap();
            assert!(matches!(run.outcome, HarnessRunOutcome::Completed { .. }));
        }
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.lines().next().unwrap().contains("progressFormat"));
        assert!(sidecar.exists());
    }

    /// `open_session` hands back the recorded directory as data (for the
    /// `/session` hot-switch notes) while still opening the session normally.
    #[tokio::test]
    async fn open_session_reports_the_recorded_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path().join("project-open");
        let launch = tmp.path().join("launch-dir");
        let sessions = tmp.path().join("sessions");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::create_dir_all(&launch).unwrap();
        std::fs::create_dir_all(&sessions).unwrap();
        create_jsonl_session_with_id(
            &sessions,
            &project.to_string_lossy(),
            Some("cwdopen001".into()),
        )
        .await
        .unwrap();

        let restored =
            open_session_by_id_in_dir("cwdopen001", &launch.to_string_lossy(), &sessions)
                .await
                .map_err(|error| error.to_string())
                .unwrap();
        assert_eq!(restored.recorded_cwd, Some(project.clone()));
        assert_eq!(restored.session.storage().metadata().id, "cwdopen001");
    }

    /// The session the peek inspected must be the session the build opens.
    ///
    /// `-c` means "the most recent session", and the build lists the directory
    /// again. Another `rpi` (or a `/session` new-session) can write a newer one
    /// between the peek and the build; adopting the peeked session's directory
    /// while opening the newer conversation would run the tools in a directory
    /// that conversation never used. Pinning the resolved id makes the second
    /// listing an exact match instead of a fresh newest-first choice.
    #[tokio::test]
    async fn the_peeked_session_is_the_one_the_build_opens() {
        let tmp = tempfile::tempdir().unwrap();
        let first_project = tmp.path().join("project-first");
        let second_project = tmp.path().join("project-second");
        let launch = tmp.path().join("launch-dir");
        let sessions = tmp.path().join("sessions");
        for dir in [&first_project, &second_project, &launch, &sessions] {
            std::fs::create_dir_all(dir).unwrap();
        }
        create_jsonl_session_with_id(
            &sessions,
            &first_project.to_string_lossy(),
            Some("cwdrace001".into()),
        )
        .await
        .unwrap();

        let mut args = Args {
            continue_session: true,
            session_dir: Some(sessions.clone()),
            ..Default::default()
        };
        let selection = select_session_in_dir(&args, sessions.clone());
        let peeked = peek_restored_session_cwd(&selection, &launch)
            .await
            .expect("a resumable session");
        assert_eq!(peeked.adopted, Some(first_project.clone()));

        // A newer session appears in another project before the build runs.
        create_jsonl_session_with_id(
            &sessions,
            &second_project.to_string_lossy(),
            Some("cwdrace002".into()),
        )
        .await
        .unwrap();

        pin_restored_selection(&mut args, &peeked);
        let pinned = select_session_in_dir(&args, sessions.clone());
        let reopened = resolve_restore_target(&pinned, &launch.to_string_lossy())
            .await
            .unwrap()
            .expect("the pinned session still exists");
        assert_eq!(
            reopened.id, peeked.id,
            "the build must open the session the peek adopted the directory of"
        );
        assert_eq!(reopened.cwd, first_project.to_string_lossy());
    }

    /// Trust must be resolved against the directory it is asked about. A
    /// session recorded in another project must not inherit the launch
    /// directory's decision — that would run an untrusted project's settings,
    /// skills, and context files with trusted privileges.
    #[test]
    fn trust_is_resolved_per_directory() {
        struct RestoreConfigDir(Option<std::ffi::OsString>);

        impl Drop for RestoreConfigDir {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(value) => std::env::set_var(crate::config::CONFIG_DIR_ENV, value),
                    None => std::env::remove_var(crate::config::CONFIG_DIR_ENV),
                }
            }
        }

        let _guard = crate::config::test_support::env_lock().lock().unwrap();
        let _restore = RestoreConfigDir(std::env::var_os(crate::config::CONFIG_DIR_ENV));
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        std::fs::create_dir_all(&agent).unwrap();
        std::env::set_var(crate::config::CONFIG_DIR_ENV, &agent);

        let untrusted = tmp.path().join("project-untrusted");
        let launch = tmp.path().join("project-launch");
        std::fs::create_dir_all(&untrusted).unwrap();
        std::fs::create_dir_all(&launch).unwrap();
        crate::config::set_project_trust(&untrusted, Some(false)).unwrap();

        let args = Args::default();
        assert!(!resolve_project_trust(&args, &untrusted));
        // A directory with no stored decision loads by default.
        assert!(resolve_project_trust(&args, &launch));
    }
}