orchestratectl 0.4.0

Rust CLI for orchestrating AI-agent workflows on a developer's machine.
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
//! `skill` subcommand — list / show / print / install companion AI-skills.
//!
//! Skill files (`SKILL.template.md`) live under
//! `crates/octl-cli/skills/<name>/`. At build time, `build.rs` substitutes
//! `{{CLI_VERSION}}` with the crate's Cargo version and writes the
//! result to `$OUT_DIR/skills/<name>/SKILL.md`. The generated files are
//! embedded into the binary at compile time via `include_str!`, so they
//! version with the CLI. See `AGENTS-AI-FIRST-CLI.md` §15-§17.

use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;

use crate::error::CliError;
use crate::home;
use crate::output::{self, OutputFormat, OutputSpec};

/// One embedded skill: name and full SKILL.md text. The description is
/// parsed lazily from the body's frontmatter so the catalog stays a
/// single source of truth (the SKILL.md file).
struct EmbeddedSkill {
    name: &'static str,
    body: &'static str,
    path_in_repo: &'static str,
}

/// A companion reference file that ships alongside a skill's `SKILL.md`.
/// Claude and pi install it as a sibling in the skill directory. Codex installs
/// it under the shared `_shared/` subdirectory and rewrites declared links to
/// that location.
struct EmbeddedResource {
    filename: &'static str,
    body: &'static str,
    /// The markdown link targets (the payload inside `](…)`) that reference
    /// this companion in the claude-layout skill bodies. On a codex install
    /// each is rewritten to `_shared/<filename>`. Anchoring the rewrite on
    /// the full `](target)` form keeps the shorter sibling target from
    /// matching inside a longer `../owner/target` one.
    claude_link_targets: &'static [&'static str],
}

/// Subdir under the flat codex prompts dir (`~/.codex/prompts/_shared/`)
/// that holds companion reference files. A subdir (not a top-level `.md`)
/// so codex never mistakes a companion for a slash-command prompt, and a
/// single shared location so every skill links to the one copy.
const CODEX_SHARED_SUBDIR: &str = "_shared";

/// Companion resources for a skill, keyed by skill name. Most skills have
/// none. `build.rs` renders every non-`SKILL.template.md` `*.md` file in a
/// skill's directory into `$OUT_DIR/skills/<name>/`, and the matching
/// `include_str!` below embeds it. `cmd_install` writes each resource as a
/// sibling of the skill's `SKILL.md` (claude) or into the `_shared/` subdir
/// (codex) — see `EmbeddedResource` for the layout rationale.
fn resources_for(_name: &str) -> &'static [EmbeddedResource] {
    &[]
}

/// The codex-layout link target for a companion: a single shared path every
/// skill body resolves to, relative to the flat prompts dir.
fn codex_link_target(filename: &str) -> String {
    format!("{CODEX_SHARED_SUBDIR}/{filename}")
}

/// Rewrite a skill body for the target agent. Claude bodies are byte-for-byte
/// the embedded source. Codex bodies get every companion's claude-layout link
/// forms rewritten to the shared `_shared/<filename>` target, so the flat
/// prompts layout resolves the same reference the per-skill claude layout
/// does. The rewrite is anchored on the full `](target)` form and is a no-op
/// for any body that references no companion.
///
/// Scope is deliberately the whole catalog, not just the skill being
/// installed, so cross-skill companion links can resolve to one shared copy.
/// `claude_link_targets` are distinctive prose strings, and the rewrite is
/// pinned by `every_claude_link_target_appears_in_some_skill_body`.
fn render_body_for_agent(agent: &str, body: &'static str) -> Cow<'static, str> {
    if agent != "codex" {
        return Cow::Borrowed(body);
    }
    let mut rendered = Cow::Borrowed(body);
    for skill in SKILLS {
        for resource in resources_for(skill.name) {
            let codex_target = codex_link_target(resource.filename);
            for claude_target in resource.claude_link_targets {
                let from = format!("]({claude_target})");
                if rendered.contains(&from) {
                    let to = format!("]({codex_target})");
                    rendered = Cow::Owned(rendered.replace(&from, &to));
                }
            }
        }
    }
    rendered
}

/// Resolve a codex companion's destination: `<prompts-dir>/_shared/<filename>`,
/// where the prompts dir is the parent of the skill's flat prompt file
/// `skill_path`. A bare relative `skill_path` (empty parent) places the
/// `_shared/` subdir in the current directory.
fn codex_companion_path(skill_path: &Path, filename: &str) -> PathBuf {
    let shared_dir = match skill_path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.join(CODEX_SHARED_SUBDIR),
        _ => PathBuf::from(CODEX_SHARED_SUBDIR),
    };
    shared_dir.join(filename)
}

const SKILLS: &[EmbeddedSkill] = &[
    EmbeddedSkill {
        name: "orchestratectl-overview",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/orchestratectl-overview/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/orchestratectl-overview/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "octl-run-overview",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/octl-run-overview/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/octl-run-overview/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "octl-spawn-spinoff",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/octl-spawn-spinoff/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/octl-spawn-spinoff/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-spinoff",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/worktree-spinoff/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/worktree-spinoff/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-merge",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/worktree-merge/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/worktree-merge/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-research",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/worktree-research/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/worktree-research/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-technical-decision",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/worktree-technical-decision/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/worktree-technical-decision/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-bug-analysis",
        body: include_str!(concat!(
            env!("OUT_DIR"),
            "/skills/worktree-bug-analysis/SKILL.md"
        )),
        path_in_repo: "crates/octl-cli/skills/worktree-bug-analysis/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/worktree/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/worktree/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "worktree-status",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/worktree-status/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/worktree-status/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "stint-start",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/stint-start/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/stint-start/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "stint-handoff",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/stint-handoff/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/stint-handoff/SKILL.template.md",
    },
    EmbeddedSkill {
        name: "fan-out",
        body: include_str!(concat!(env!("OUT_DIR"), "/skills/fan-out/SKILL.md")),
        path_in_repo: "crates/octl-cli/skills/fan-out/SKILL.template.md",
    },
];

/// Binary version embedded at build time. `build.rs` substitutes this
/// into every shipped SKILL.md's `cli_version:` frontmatter, so `skill
/// print` always returns a body whose declared `cli_version` matches the
/// binary that emitted it (AGENTS-AI-FIRST-CLI §17).
const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Skill-format schema version (the version of the SKILL.md frontmatter +
/// body contract itself, distinct from the envelope `schema_version`).
pub const SKILL_SCHEMA_VERSION: u32 = 1;

/// Provenance marker filename. `cmd_install` drops this hidden file into
/// every claude-layout skill directory it writes (`~/.claude/skills/
/// <name>/.orchestratectl-managed`). Its *presence* is the ONLY signal
/// `prune` and the `skill.orphan.*` doctor check use to decide a directory
/// is safe to delete: a user's own hand-authored skill of the same name
/// never carries it, so it is never touched. See `is_managed_skill_dir`.
const MANAGED_MARKER_FILENAME: &str = ".orchestratectl-managed";

/// Public catalog entry used by `version --json` to expose the bundled
/// skill set (AGENTS-AI-FIRST-CLI §17). The on-disk skill is the source
/// of truth for `cli_version`; emit it directly from the parsed
/// frontmatter so the version payload cannot quietly disagree with what
/// `skill print` returns.
#[derive(Debug, Serialize)]
pub struct SkillCatalogEntry {
    pub name: &'static str,
    pub cli_version: String,
    pub schema_version: u32,
}

pub fn catalog() -> Vec<SkillCatalogEntry> {
    SKILLS
        .iter()
        .map(|s| SkillCatalogEntry {
            name: s.name,
            cli_version: parse_frontmatter_field(s.body, "cli_version")
                .unwrap_or_else(|| CLI_VERSION.to_string()),
            schema_version: parse_frontmatter_field(s.body, "schema_version")
                .and_then(|v| v.parse().ok())
                .unwrap_or(SKILL_SCHEMA_VERSION),
        })
        .collect()
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AgentTarget {
    Claude,
    Codex,
    All,
}

/// Names of every skill bundled in this binary. Consumed by `doctor`'s
/// `skill.sync` check so it audits the exact catalog the binary ships.
pub fn bundled_skill_names() -> Vec<&'static str> {
    SKILLS.iter().map(|s| s.name).collect()
}

/// The running binary's version — the authority `skill.sync` compares
/// each on-disk skill's `cli_version` against.
pub fn binary_cli_version() -> &'static str {
    CLI_VERSION
}

/// Default `claude` install path for a skill (`~/.claude/skills/<name>/
/// SKILL.md`). `None` when `HOME` is unset. Used by `doctor` to locate
/// the on-disk copy to compare against the binary.
pub fn claude_default_path(name: &str) -> Option<PathBuf> {
    default_path("claude", name).ok()
}

/// Default `codex` install path for a skill (`~/.codex/prompts/<name>.md`).
/// `None` when `HOME` is unset. The codex layout is FLAT — a skill is a
/// single top-level prompt file, not a per-skill directory. Used by
/// `doctor` to locate the on-disk codex copy to compare against the binary.
pub fn codex_default_path(name: &str) -> Option<PathBuf> {
    default_path("codex", name).ok()
}

/// Read the `cli_version` frontmatter field from an on-disk SKILL.md.
/// `None` when the file is unreadable or has no parseable `cli_version`.
pub fn read_on_disk_cli_version(path: &Path) -> Option<String> {
    let body = fs::read_to_string(path).ok()?;
    parse_frontmatter_field(&body, "cli_version")
}

/// Parse the `cli_version` frontmatter field from an in-memory body (e.g.
/// a companion resource already read off disk). Sibling of
/// [`read_on_disk_cli_version`] for content the caller has in hand.
pub fn cli_version_of(body: &str) -> Option<String> {
    parse_frontmatter_field(body, "cli_version")
}

/// One companion resource bundled alongside a skill's `SKILL.md`, surfaced
/// for the `doctor` `skill.sync.<name>.<file>` companion sub-check: the
/// filename and the embedded (authoritative) body. The expected install
/// path is a sibling of the skill's `SKILL.md` — the doctor derives it from
/// the resolved `SKILL.md` path it already holds.
pub struct CompanionSource {
    pub filename: &'static str,
    pub bundled_body: &'static str,
}

/// Every companion resource bundled for skill `name` (empty for skills that
/// ship none). Consumed by `doctor` to audit that each companion is present
/// and version-synced with the binary, mirroring the SKILL.md `skill.sync`
/// check.
pub fn companion_sources(name: &str) -> Vec<CompanionSource> {
    resources_for(name)
        .iter()
        .map(|r| CompanionSource {
            filename: r.filename,
            bundled_body: r.body,
        })
        .collect()
}

/// Every companion resource any bundled skill ships, deduplicated by
/// filename. Consumed by the codex `doctor` checks: the codex `_shared/`
/// dir is a single shared location every skill's companion lands in, so a
/// companion still referenced by at least one bundled skill is "still
/// bundled" (audited by the forward `skill.sync.codex._shared.<file>`
/// check) rather than an orphan. Sorted by filename for deterministic
/// output.
pub fn all_companion_sources() -> Vec<CompanionSource> {
    let mut seen: HashSet<&'static str> = HashSet::new();
    let mut out: Vec<CompanionSource> = Vec::new();
    for skill in SKILLS {
        for r in resources_for(skill.name) {
            if seen.insert(r.filename) {
                out.push(CompanionSource {
                    filename: r.filename,
                    bundled_body: r.body,
                });
            }
        }
    }
    out.sort_by(|a, b| a.filename.cmp(b.filename));
    out
}

#[derive(Serialize)]
struct SkillSummary {
    name: &'static str,
    description: String,
}

#[derive(Serialize)]
struct ListPayload {
    skills: Vec<SkillSummary>,
}

#[derive(Serialize)]
struct InstallPayload {
    installed: Vec<InstalledFile>,
    /// Names of de-registered managed skill directories that this install
    /// pruned from `~/.claude/skills/`. Empty in every install form except
    /// the full-catalog default-path claude install (see `cmd_install`).
    pruned: Vec<String>,
    /// Orphan companion files this `--force` install removed: companions a
    /// prior binary recorded in a still-registered skill's provenance marker
    /// that the current binary no longer bundles. Reported as
    /// `<skill>/<filename>` so the offending sibling is unambiguous. Empty
    /// unless a default-path claude `--force` install found stale companions.
    pruned_companions: Vec<String>,
}

#[derive(Serialize)]
struct InstalledFile {
    name: &'static str,
    agent: &'static str,
    path: String,
}

pub fn cmd_list(spec: &OutputSpec, warnings: &[String]) -> Result<(), CliError> {
    let skills: Vec<SkillSummary> = SKILLS
        .iter()
        .map(|s| SkillSummary {
            name: s.name,
            description: parse_description(s.body).unwrap_or_default(),
        })
        .collect();
    match spec.format {
        OutputFormat::Json | OutputFormat::Jsonl => {
            output::emit_envelope(&ListPayload { skills }, spec, warnings)?;
        }
        OutputFormat::Text => {
            for s in &skills {
                println!("{}\t{}", s.name, s.description);
            }
            output::emit_text_warnings(warnings);
        }
    }
    Ok(())
}

pub fn cmd_show(name: &str, spec: &OutputSpec, warnings: &[String]) -> Result<(), CliError> {
    let skill = lookup(name)?;
    match spec.format {
        OutputFormat::Json | OutputFormat::Jsonl => {
            #[derive(Serialize)]
            struct ShowPayload<'a> {
                name: &'a str,
                content: &'a str,
            }
            output::emit_envelope(
                &ShowPayload {
                    name: skill.name,
                    content: skill.body,
                },
                spec,
                warnings,
            )?;
        }
        OutputFormat::Text => {
            print!("{}", skill.body);
            if !skill.body.ends_with('\n') {
                println!();
            }
            output::emit_text_warnings(warnings);
        }
    }
    Ok(())
}

/// `skill print <name>` — stream the canonical embedded SKILL.md text
/// to stdout, byte-identical to what `skill install` would persist
/// (AGENTS-AI-FIRST-CLI §16). Pure read; no filesystem mutation.
pub fn cmd_print(name: &str, spec: &OutputSpec, warnings: &[String]) -> Result<(), CliError> {
    let skill = lookup(name)?;
    let cli_version = parse_frontmatter_field(skill.body, "cli_version")
        .unwrap_or_else(|| CLI_VERSION.to_string());
    let schema_version_skill = parse_frontmatter_field(skill.body, "schema_version")
        .and_then(|v| v.parse().ok())
        .unwrap_or(SKILL_SCHEMA_VERSION);
    match spec.format {
        OutputFormat::Json => {
            #[derive(Serialize)]
            struct PrintPayload<'a> {
                /// Skill-print payload schema; bumps independently from
                /// the envelope's `schema_version`.
                schema_version: u32,
                name: &'a str,
                cli_version: &'a str,
                schema_version_skill: u32,
                content: &'a str,
                path_in_repo: &'a str,
            }
            output::emit_envelope(
                &PrintPayload {
                    schema_version: SKILL_SCHEMA_VERSION,
                    name: skill.name,
                    cli_version: &cli_version,
                    schema_version_skill,
                    content: skill.body,
                    path_in_repo: skill.path_in_repo,
                },
                spec,
                warnings,
            )?;
        }
        // §16 contract: text and jsonl both stream the SKILL.md
        // byte-identically. The structured form is opt-in via `--output
        // json`; the default (jsonl) is byte-identity so `skill print`
        // composes with `cat`, `tee`, and shell redirection without any
        // un-wrapping step.
        OutputFormat::Text | OutputFormat::Jsonl => {
            use std::io::Write as _;
            let mut out = std::io::stdout().lock();
            out.write_all(skill.body.as_bytes())
                .map_err(|e| CliError::system("io_error", format!("write stdout: {e}")))?;
            out.flush()
                .map_err(|e| CliError::system("io_error", format!("flush stdout: {e}")))?;
            output::emit_text_warnings(warnings);
        }
    }
    Ok(())
}

pub fn cmd_install(
    name: Option<&str>,
    agent: AgentTarget,
    dest: Option<PathBuf>,
    force: bool,
    spec: &OutputSpec,
    warnings: &[String],
) -> Result<(), CliError> {
    // §15: `install [<name>]` installs all skills when no name is given.
    let skills: Vec<&'static EmbeddedSkill> = match name {
        Some(n) => vec![lookup(n)?],
        None => SKILLS.iter().collect(),
    };

    // `--dest` is incompatible with `--agent all` and with the implicit
    // install-all form: a single path cannot host multiple installations.
    if dest.is_some() && matches!(agent, AgentTarget::All) {
        return Err(CliError::user(
            "invalid_arguments",
            "--dest cannot be combined with --agent all",
        ));
    }
    if dest.is_some() && skills.len() > 1 {
        return Err(CliError::user(
            "invalid_arguments",
            "--dest requires a skill name; omit --dest to install all skills",
        ));
    }

    // Whether this install dual-homes into pi — the same condition that pushes
    // the pi `PlanItem`s below. When it does, load AND validate the out-of-band
    // provenance record NOW, before any file is written, so a corrupt or
    // future-schema record fails the install fast rather than after mutating the
    // tree (review finding A). The loaded record is threaded to the pi lifecycle
    // block after the writes land.
    let pi_dual_home = dest.is_none() && matches!(agent, AgentTarget::Claude | AgentTarget::All);
    let mut pi_provenance: Option<(PathBuf, PiProvenance)> = None;
    if pi_dual_home {
        if let Some(record_path) = pi_provenance_path() {
            let prov = load_pi_provenance_for_write(&record_path)?;
            pi_provenance = Some((record_path, prov));
        }
    }

    // Build the full plan first, then preflight, then write. This avoids
    // the partial-install retry trap where one of N writes succeeds and a
    // re-run hits refused_overwrite on a different path than the original
    // failure. Each skill contributes its `SKILL.md` plus any companion
    // resources, installed as siblings of the skill's destination.
    let mut plan: Vec<PlanItem> = Vec::new();
    // Claude-layout skill directories this install touches under the
    // default path — each gets the provenance marker stamped after the
    // writes land. Only the default path (`dest.is_none()`) is a real
    // `~/.claude/skills/<name>/` directory we own; a `--dest` custom path
    // is the caller's to manage, so we never litter a marker there.
    let mut mark_dirs: Vec<(&'static str, PathBuf)> = Vec::new();
    for skill in &skills {
        let targets: Vec<(&'static str, PathBuf)> = match (&agent, dest.as_ref()) {
            (AgentTarget::Claude, Some(p)) => vec![("claude", p.clone())],
            (AgentTarget::Codex, Some(p)) => vec![("codex", p.clone())],
            (AgentTarget::Claude, None) => vec![("claude", default_path("claude", skill.name)?)],
            (AgentTarget::Codex, None) => vec![("codex", default_path("codex", skill.name)?)],
            (AgentTarget::All, _) => vec![
                ("claude", default_path("claude", skill.name)?),
                ("codex", default_path("codex", skill.name)?),
            ],
        };
        for (agent_name, path) in targets {
            // Companion resources install per layout (see `EmbeddedResource`):
            // claude gets them as plain siblings of the skill's `SKILL.md`;
            // codex, whose flat prompts dir surfaces every top-level `.md` as
            // a slash-command, gets them in a shared `_shared/` subdir with
            // the skill body's companion links rewritten to point there.
            match agent_name {
                "claude" => {
                    if dest.is_none() {
                        if let Some(parent) = path.parent() {
                            mark_dirs.push((skill.name, parent.to_path_buf()));
                        }
                    }
                    for resource in resources_for(skill.name) {
                        plan.push(PlanItem {
                            agent: agent_name,
                            path: sibling_path(&path, resource.filename),
                            content: Cow::Borrowed(resource.body),
                            kind: PlanKind::Companion {
                                owner: skill.name,
                                filename: resource.filename,
                            },
                        });
                    }
                }
                "codex" => {
                    for resource in resources_for(skill.name) {
                        plan.push(PlanItem {
                            agent: agent_name,
                            path: codex_companion_path(&path, resource.filename),
                            content: Cow::Borrowed(resource.body),
                            kind: PlanKind::Companion {
                                owner: skill.name,
                                filename: resource.filename,
                            },
                        });
                    }
                }
                _ => {}
            }
            let content = render_body_for_agent(agent_name, skill.body);
            plan.push(PlanItem {
                agent: agent_name,
                path,
                content,
                kind: PlanKind::Skill { name: skill.name },
            });
        }

        // Dual-home into pi.dev's skill dir. Whenever the claude layout is
        // installed to its default path, mirror the SAME claude-format
        // `SKILL.md` into `~/.pi/agent/skills/<name>/SKILL.md` so the skill
        // is discoverable under the pi.dev harness (pi loads it and invokes
        // `/skill:name`; bare `/name` cross-references resolve via pi's
        // injected available-skills list, so no link rewrite is needed —
        // only the target). This is an ADDITIONAL target that never alters
        // the claude write.
        //
        // pi uses a PER-SKILL directory, exactly like claude (unlike codex's
        // flat prompts dir), so any companion resource installs as a plain
        // sibling of the pi `SKILL.md`, byte-identical to the claude copy and
        // with no link rewrite. This keeps a skill from aborting under pi when
        // it requires a bundled sibling. The current catalog has no companion
        // resources, but the generic lifecycle remains supported. Mirroring is
        // skipped for a custom `--dest` and for `--agent codex` alone.
        //
        // The pi mirror is intentionally UNMANAGED in-tree: no `.orchestratectl-
        // managed` marker (the pi corpus stays a pure body mirror). Its
        // lifecycle — orphan prune + `doctor` drift for both the `SKILL.md`
        // and its companions — is keyed on the out-of-band provenance record
        // (`state/pi-installed-skills.json`); see the pi block after the write
        // loop and `PiSkillRecord`.
        if dest.is_none() && matches!(agent, AgentTarget::Claude | AgentTarget::All) {
            let pi_skill_path = default_path("pi", skill.name)?;
            for resource in resources_for(skill.name) {
                plan.push(PlanItem {
                    agent: "pi",
                    path: sibling_path(&pi_skill_path, resource.filename),
                    content: Cow::Borrowed(resource.body),
                    kind: PlanKind::Companion {
                        owner: skill.name,
                        filename: resource.filename,
                    },
                });
            }
            plan.push(PlanItem {
                agent: "pi",
                path: pi_skill_path,
                content: Cow::Borrowed(skill.body),
                kind: PlanKind::Skill { name: skill.name },
            });
        }
    }

    let preflight_result = preflight(&plan, force)?;

    // Combine caller-provided warnings (logging init, etc.) with
    // drift-detected ones so the success envelope surfaces both.
    let mut all_warnings: Vec<String> = warnings.to_vec();
    all_warnings.extend(preflight_result.warnings);

    let mut installed = Vec::with_capacity(plan.len());
    // pi files actually written this run. Only files the write loop persisted
    // are recorded in the provenance record below — a `skipped` (present,
    // non-force, divergent) pi file was NOT written, so we carry its prior
    // record forward untouched. A `SKILL.md` write and a companion write are
    // recorded distinctly so the companion lands under its owning skill.
    let mut pi_written: Vec<PiWrite> = Vec::new();
    for item in plan {
        // A pi mirror that preflight chose to leave in place (present, no
        // --force) is skipped outright — NOT written and NOT reported as
        // installed. Falling through to `write_atomic` here would call
        // `persist_noclobber`, hit `EEXIST`, and fail the whole install,
        // which is exactly the divergent-state repair-block F1 fixes.
        if preflight_result.skipped.contains(&item.path) {
            continue;
        }
        // The set of paths approved for overwrite is decided exclusively
        // by preflight — never recomputed from `path.exists()` in this
        // loop. That keeps the persist_noclobber TOCTOU guarantee intact:
        // a file that did not exist at preflight time will refuse to
        // overwrite, even if a concurrent process created it in the
        // window. (Review finding #1.)
        let allow_overwrite = preflight_result.overwrite_allowed.contains(&item.path);
        write_atomic(&item.path, &item.content, allow_overwrite)?;
        if item.agent == "pi" {
            let hash = sha256_hex(item.content.as_bytes());
            match item.kind {
                PlanKind::Skill { name } => {
                    let cli_version = parse_frontmatter_field(&item.content, "cli_version")
                        .unwrap_or_else(|| CLI_VERSION.to_string());
                    pi_written.push(PiWrite::Skill {
                        name,
                        hash,
                        cli_version,
                    });
                }
                PlanKind::Companion { owner, filename } => {
                    pi_written.push(PiWrite::Companion {
                        owner,
                        filename,
                        hash,
                    });
                }
            }
        }
        installed.push(InstalledFile {
            name: item.kind.display_name(),
            agent: item.agent,
            path: item.path.display().to_string(),
        });
    }

    // Stamp every freshly-installed claude-layout directory with the
    // provenance marker (idempotent, always overwritten — it's ours). The
    // marker is what makes later pruning safe, so a write failure here is
    // fatal rather than silent: without it a genuine orphan would never be
    // recognised as managed. Deduplicated because `--agent all` and the
    // install-all form can enumerate the same dir once per skill.
    //
    // The marker also records the exact companion files this binary wrote
    // (`companion:` lines), so a later binary that drops a companion can
    // recognise the lingering file as an ORPHAN it once managed rather than
    // as a user's own note. Before rewriting the marker we read the copy the
    // prior binary left, diff its recorded companions against what this
    // binary bundles, and act on the leftover ORPHANS:
    //
    // - `--force`: remove the orphan companion file (the redeploy intends the
    //   on-disk catalog to mirror the binary) and drop it from the marker.
    // - non-`--force`: leave the file in place but CARRY IT FORWARD in the new
    //   marker, so `doctor` still recognises it as an orphan (and can suggest
    //   the `--force` fix). Rewriting the marker without it would forget the
    //   file forever while it lingers on disk.
    mark_dirs.sort();
    mark_dirs.dedup();
    let mut pruned_companions: Vec<String> = Vec::new();
    for (skill_name, dir) in &mark_dirs {
        let marker_path = dir.join(MANAGED_MARKER_FILENAME);
        let bundled: Vec<&'static str> = resources_for(skill_name)
            .iter()
            .map(|r| r.filename)
            .collect();
        // Start the new record with everything this binary bundles, then
        // reconcile the companions the prior marker recorded.
        let mut recorded: Vec<String> = bundled.iter().copied().map(String::from).collect();
        for prev in read_managed_companions(&marker_path) {
            if bundled.iter().any(|b| *b == prev) {
                continue; // still bundled — already in `recorded`
            }
            // A managed companion this binary no longer ships: an orphan.
            let orphan_path = dir.join(&prev);
            // Only ever touch a regular file we actually wrote — never follow a
            // symlink or recurse into a directory squatting at that name.
            let is_regular =
                fs::symlink_metadata(&orphan_path).is_ok_and(|m| m.file_type().is_file());
            if !is_regular {
                // Nothing safe to clean and nothing on disk to keep tracking:
                // drop it from the marker.
                continue;
            }
            if force {
                match fs::remove_file(&orphan_path) {
                    Ok(()) => {
                        all_warnings.push(format!(
                            "skill_companion_pruned: removed orphan companion '{prev}' for skill '{skill_name}' at {}",
                            orphan_path.display()
                        ));
                        pruned_companions.push(format!("{skill_name}/{prev}"));
                        // dropped from `recorded` → no longer tracked
                    }
                    Err(e) => {
                        all_warnings.push(format!(
                            "skill_companion_prune_failed: could not remove orphan companion '{prev}' for skill '{skill_name}' at {}: {e}",
                            orphan_path.display()
                        ));
                        recorded.push(prev); // still on disk — keep it tracked
                    }
                }
            } else {
                recorded.push(prev); // preserve tracking for doctor
            }
        }
        recorded.sort();
        recorded.dedup();
        write_marker(&marker_path, skill_name, &recorded)?;
    }

    // Prune de-registered managed skills. Scoped to the full-catalog
    // (`name.is_none()`), default-path (`dest.is_none()`), `--force`,
    // claude-targeting install: that is exactly the `skill install --force`
    // redeploy where the caller intends the on-disk catalog to mirror the
    // binary's. `--force` is required so a plain, non-destructive-looking
    // `skill install` can never delete a directory as a side effect. A
    // targeted `skill install <name>` must NEVER nuke the rest of the
    // catalog, so it is excluded too. Only directories carrying a VALID
    // marker (see `is_managed_skill_dir`) AND absent from the shipped
    // catalog are removed — a user's hand-authored or copied skill is
    // spared. A prune failure is a maintenance hiccup, not an install
    // failure: the catalog already landed, so we warn and carry on rather
    // than erroring out with the success payload unreported.
    let mut pruned: Vec<String> = Vec::new();
    let prune_eligible = name.is_none()
        && dest.is_none()
        && force
        && matches!(agent, AgentTarget::Claude | AgentTarget::All);
    if prune_eligible {
        if let Some(root) = claude_skills_root() {
            let registered: HashSet<&str> = SKILLS.iter().map(|s| s.name).collect();
            for (orphan_name, orphan_path) in managed_orphan_dirs(&root, &registered) {
                match fs::remove_dir_all(&orphan_path) {
                    Ok(()) => {
                        all_warnings.push(format!(
                            "skill_pruned: removed de-registered managed skill '{orphan_name}' at {}",
                            orphan_path.display()
                        ));
                        pruned.push(orphan_name);
                    }
                    Err(e) => {
                        all_warnings.push(format!(
                            "skill_prune_failed: could not remove de-registered skill '{orphan_name}' at {}: {e}",
                            orphan_path.display()
                        ));
                    }
                }
            }
        }
    }

    // Codex flat-layout provenance + prune. Codex's prompts dir is flat (no
    // per-skill directory), so a single shared marker at
    // `_shared/.orchestratectl-managed` records which prompts + companions
    // orchestratectl installed there — the only signal that makes codex-side
    // pruning + orphan detection safe. Maintained whenever the codex layout
    // is installed to its DEFAULT path (never for a caller-managed `--dest`).
    // The marker MERGES with any prior record (union) so a targeted
    // single-skill install never forgets the rest of the managed set. Orphan
    // pruning (removing a de-registered prompt/companion) is gated to the
    // full-catalog `--force` redeploy, symmetric with the claude dir prune
    // above; a plain `skill install` never deletes anything as a side effect.
    let codex_default = dest.is_none() && matches!(agent, AgentTarget::Codex | AgentTarget::All);
    if codex_default {
        if let (Some(prompts_root), Some(shared_root)) = (codex_prompts_root(), codex_shared_root())
        {
            let marker_path = shared_root.join(MANAGED_MARKER_FILENAME);

            // Everything this install just wrote to the codex layout: one
            // prompt per skill, plus every companion those skills bundle.
            let mut recorded_prompts: HashSet<String> =
                skills.iter().map(|s| s.name.to_string()).collect();
            let mut recorded_companions: HashSet<String> = skills
                .iter()
                .flat_map(|s| resources_for(s.name))
                .map(|r| r.filename.to_string())
                .collect();
            // Union with the prior marker so a targeted install (or a prune
            // that must recognise a de-registered entry) keeps the full set.
            recorded_prompts.extend(read_marker_records(&marker_path, "prompt"));
            recorded_companions.extend(read_marker_records(&marker_path, "companion"));

            let codex_prune_eligible = name.is_none() && force;
            if codex_prune_eligible {
                let registered: HashSet<&str> = SKILLS.iter().map(|s| s.name).collect();
                let bundled_companions: HashSet<&str> = SKILLS
                    .iter()
                    .flat_map(|s| resources_for(s.name))
                    .map(|r| r.filename)
                    .collect();

                // Orphan codex prompts: recorded but no longer in the catalog.
                let orphan_prompts: Vec<String> = recorded_prompts
                    .iter()
                    .filter(|p| !registered.contains(p.as_str()))
                    .cloned()
                    .collect();
                for orphan in orphan_prompts {
                    let prompt_path = prompts_root.join(format!("{orphan}.md"));
                    match prune_codex_file(
                        &prompt_path,
                        &format!("skill_pruned: removed de-registered managed codex prompt '{orphan}'"),
                        &format!("skill_prune_failed: could not remove de-registered codex prompt '{orphan}'"),
                        &mut all_warnings,
                    ) {
                        CodexPruneOutcome::Removed => {
                            pruned.push(orphan.clone());
                            recorded_prompts.remove(&orphan);
                        }
                        CodexPruneOutcome::Dropped => {
                            recorded_prompts.remove(&orphan);
                        }
                        CodexPruneOutcome::Kept => {}
                    }
                }

                // Orphan codex companions: recorded but no bundled skill ships
                // them any more (the last referrer was removed).
                let orphan_companions: Vec<String> = recorded_companions
                    .iter()
                    .filter(|c| !bundled_companions.contains(c.as_str()))
                    .cloned()
                    .collect();
                for orphan in orphan_companions {
                    let companion_path = shared_root.join(&orphan);
                    match prune_codex_file(
                        &companion_path,
                        &format!("skill_companion_pruned: removed orphan codex companion '_shared/{orphan}'"),
                        &format!("skill_companion_prune_failed: could not remove orphan codex companion '_shared/{orphan}'"),
                        &mut all_warnings,
                    ) {
                        CodexPruneOutcome::Removed => {
                            pruned_companions.push(format!("{CODEX_SHARED_SUBDIR}/{orphan}"));
                            recorded_companions.remove(&orphan);
                        }
                        CodexPruneOutcome::Dropped => {
                            recorded_companions.remove(&orphan);
                        }
                        CodexPruneOutcome::Kept => {}
                    }
                }
            }

            // Persist the reconciled marker. Create `_shared/` first: a codex
            // install of a companion-less skill would not otherwise materialise
            // it, but we still need the marker for later pruning of the flat
            // prompt file. A marker-write failure is fatal (like the claude
            // marker): without it a genuine orphan is never recognised.
            let mut prompts: Vec<String> = recorded_prompts.into_iter().collect();
            prompts.sort();
            let mut companions: Vec<String> = recorded_companions.into_iter().collect();
            companions.sort();
            fs::create_dir_all(&shared_root).map_err(|e| {
                CliError::system(
                    "create_dir_failed",
                    format!("could not create {}: {}", shared_root.display(), e),
                )
            })?;
            write_codex_marker(&marker_path, &prompts, &companions)?;
        }
    }

    // pi.dev mirror lifecycle (out-of-band provenance). Maintained whenever
    // this install dual-homed into pi — i.e. the same condition `cmd_install`
    // used to push the pi `PlanItem`s (default path, claude-format target).
    // Two steps, both keyed SOLELY on the out-of-band record (the pi dir has no
    // in-dir marker):
    //
    //   1. Record every pi mirror we just wrote (union-merged with the prior
    //      record so a targeted single-skill install never forgets the rest of
    //      the managed set — symmetric with the codex marker union).
    //   2. On the full-catalog `--force` redeploy (the same gate as the claude
    //      prune), prune pi mirrors of de-registered skills — but only ones the
    //      record names AND whose on-disk bytes still hash to the recorded value
    //      (strong evidence it is our unmodified copy). A user-taken-over or
    //      hand-authored pi dir is never recorded, so it is not touched.
    //
    // Like the claude/codex marker updates, the record read-modify-write is
    // unlocked: two concurrent `skill install` runs can lose one another's
    // additions (parity debt, not introduced here). Mutation commands are not
    // meant to run concurrently — see `crates/octl-cli/AGENTS.md`.
    if let Some((record_path, mut prov)) = pi_provenance {
        prov.schema_version = PI_PROVENANCE_SCHEMA_VERSION;
        // Record every pi file we just wrote as an independent `files` entry
        // under its owning skill. In the flat per-file model a companion no
        // longer has to attach to a pre-existing body record: it files itself
        // directly (creating the skill entry if the body write was skipped),
        // which removes the pre-flat `pi_companion_unrecorded` edge entirely
        // (issue `pi-provenance-flat-file-model`). A `SKILL.md` write also
        // refreshes the skill's `cli_version`. `skipped` (present, non-force) pi
        // files are absent from `pi_written`, so their prior `files` entries are
        // carried forward untouched.
        for w in &pi_written {
            match w {
                PiWrite::Skill {
                    name,
                    hash,
                    cli_version,
                } => {
                    let rec = prov.skills.entry((*name).to_string()).or_default();
                    rec.cli_version.clone_from(cli_version);
                    rec.files.insert(
                        PI_SKILL_FILENAME.to_string(),
                        PiFileRecord {
                            sha256: hash.clone(),
                            kind: PiFileKind::Skill,
                        },
                    );
                }
                PiWrite::Companion {
                    owner,
                    filename,
                    hash,
                } => {
                    let rec = prov.skills.entry((*owner).to_string()).or_default();
                    rec.files.insert(
                        (*filename).to_string(),
                        PiFileRecord {
                            sha256: hash.clone(),
                            kind: PiFileKind::Companion,
                        },
                    );
                }
            }
        }

        // Reconcile each STILL-REGISTERED installed skill's recorded companions
        // against what this binary now bundles: a companion a prior binary
        // mirrored that the current one dropped is an orphan. Without this, the
        // `skill.orphan.<name>.pi.<file>` doctor check would flag a state its only
        // suggested fix (`skill install <name> --force`) could never clear — a
        // permanent unfixable warning loop (review finding F1). Mirrors the claude
        // `mark_dirs` companion reconciliation. De-registered skills are handled
        // by the prune block below; this handles skills that survive but shed a
        // companion.
        for skill in &skills {
            reconcile_pi_companions(
                skill.name,
                &mut prov,
                force,
                &mut pruned_companions,
                &mut all_warnings,
            );
        }

        if prune_eligible {
            let registered: HashSet<&str> = SKILLS.iter().map(|s| s.name).collect();
            // De-registered names the record still tracks — the only prune
            // candidates. Collected first (from `BTreeMap::keys`, so sorted +
            // deterministic) so we don't mutate `prov.skills` while iterating it.
            // The registered check is case-insensitive as well as exact, symmetric
            // with `managed_orphan_dirs`: on a case-insensitive filesystem (APFS) a
            // corrupt record key that is a case variant of a registered skill would
            // otherwise resolve to that skill's live dir and, if the hash matched,
            // delete a registered mirror (review finding F5).
            let orphan_names: Vec<String> = prov
                .skills
                .keys()
                .filter(|n| {
                    !registered.contains(n.as_str())
                        && !registered.iter().any(|r| r.eq_ignore_ascii_case(n))
                })
                .cloned()
                .collect();
            for orphan in orphan_names {
                // Never let a record-sourced key that is not a single normal path
                // component reach the filesystem (review finding E). It stays in
                // the record (inert — doctor skips it too) but is never acted on.
                if !is_simple_skill_name(&orphan) {
                    all_warnings.push(format!(
                        "pi_provenance_bad_name: ignoring pi provenance entry '{orphan}' (not a simple skill name)"
                    ));
                    continue;
                }
                // `orphan` came straight from `prov.skills.keys()`, so the entry
                // is present — mutate it in place. The prune removes each
                // successfully-handled (deleted / relinquished / absent) file
                // from the record's `files` map and reports whether the body was
                // deleted; a file whose delete FAILED is left in `files` so the
                // entry survives for a retry.
                let rec = prov.skills.get_mut(&orphan).expect("orphan key present");
                let outcome = prune_pi_mirror(&orphan, rec, &mut all_warnings);
                if outcome.body_removed {
                    pruned.push(orphan.clone());
                }
                // Drop the skill entry once every file is accounted for (nothing
                // left tracked); a Kept file keeps the entry so a later redeploy
                // retries and `doctor` still flags the leftover.
                if rec.files.is_empty() {
                    prov.skills.remove(&orphan);
                }
            }
        }

        write_pi_provenance(&record_path, &prov)?;
    }

    // De-registered skills can be pruned from more than one layout (claude,
    // codex, pi) in a single `--force` redeploy, each pushing the same name here.
    // Deduplicate so the `pruned` payload is a set (review finding B).
    pruned.sort();
    pruned.dedup();
    // Symmetric with `pruned`: a `<skill>/<file>` entry can be reported by more
    // than one layout (claude + pi both key companions that way), so normalise
    // the payload to a set.
    pruned_companions.sort();
    pruned_companions.dedup();

    let payload = InstallPayload {
        installed,
        pruned,
        pruned_companions,
    };
    match spec.format {
        OutputFormat::Json | OutputFormat::Jsonl => {
            output::emit_envelope(&payload, spec, &all_warnings)?;
        }
        OutputFormat::Text => {
            for f in &payload.installed {
                println!("installed {} ({}) -> {}", f.name, f.agent, f.path);
            }
            for name in &payload.pruned {
                println!("pruned {name} (de-registered)");
            }
            for entry in &payload.pruned_companions {
                println!("pruned {entry} (orphan companion)");
            }
            output::emit_text_warnings(&all_warnings);
        }
    }
    Ok(())
}

/// Compare two `cli_version` strings via the `semver` crate. Returns
/// `None` if either side fails to parse as semver — callers treat that
/// as "unversioned / legacy" rather than guessing an ordering.
/// (Review finding #2 — the previous ad-hoc parser inverted prerelease
/// ordering: `1.0.0-alpha > 1.0.0` instead of `<`.)
fn compare_versions(a: &str, b: &str) -> Option<std::cmp::Ordering> {
    let av = semver::Version::parse(a).ok()?;
    let bv = semver::Version::parse(b).ok()?;
    Some(av.cmp(&bv))
}

/// Outcome of the install preflight pass.
///
/// `overwrite_allowed` is the *authoritative* set of paths the write
/// loop is permitted to clobber. Computed once, then never recomputed —
/// see `cmd_install` for the TOCTOU rationale.
///
/// `skipped` is the set of already-present pi-mirror paths a non-`--force`
/// run must leave untouched (see `preflight`'s pi arm). The write loop
/// skips them entirely — it must NOT fall through to `write_atomic`, whose
/// `persist_noclobber` would hit `EEXIST` and fail the whole install. A
/// skipped path is never reported as `installed`.
struct PreflightResult {
    warnings: Vec<String>,
    overwrite_allowed: HashSet<PathBuf>,
    skipped: HashSet<PathBuf>,
}

/// What one [`PlanItem`] writes: a skill's `SKILL.md` body or one of its
/// companion resources. Replaces the pre-flat-model stringly-typed
/// `agent == "pi"` + `pi_companion_of: Option<_>` inference — the pi write loop
/// now matches this enum directly, and any agent's item carries the same
/// classification (a companion always knows its owning skill).
enum PlanKind {
    /// A skill body (`SKILL.md`) for `name`.
    Skill { name: &'static str },
    /// A companion resource `filename` owned by skill `owner`.
    Companion {
        owner: &'static str,
        filename: &'static str,
    },
}

impl PlanKind {
    /// The name the install payload and drift warnings report: the skill name
    /// for a body, the resource filename for a companion.
    fn display_name(&self) -> &'static str {
        match self {
            PlanKind::Skill { name } => name,
            PlanKind::Companion { filename, .. } => filename,
        }
    }
}

/// One file the install will write: a skill's `SKILL.md` or one of its
/// companion resources.
struct PlanItem {
    agent: &'static str,
    path: PathBuf,
    /// Bytes to write. Borrowed for the claude layout and companions (the
    /// embedded source verbatim); owned when a codex body needed companion
    /// links rewritten (see `render_body_for_agent`).
    content: Cow<'static, str>,
    /// Whether this item is a skill body or a companion, and its identifying
    /// name(s). The pi provenance update matches this to file the write under
    /// the right skill (claude/codex companions are tracked by their own
    /// in-tree markers instead, but every item still carries its kind).
    kind: PlanKind,
}

/// Resolve a companion resource's destination: a file named `filename` in
/// the same directory as the skill's `SKILL.md` destination `skill_path`.
/// A bare relative `skill_path` (empty parent, e.g. `--dest SKILL.md`)
/// places the resource in the current directory.
fn sibling_path(skill_path: &Path, filename: &str) -> PathBuf {
    match skill_path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.join(filename),
        _ => PathBuf::from(filename),
    }
}

/// Reject the whole install plan before touching the filesystem when any
/// destination already exists (without `--force`) or appears twice in
/// the plan. Catches the partial-install retry trap noted by the review:
/// without preflight, writing N targets sequentially can leave the user
/// with a half-installed catalog and an ambiguous error on retry.
/// Inspect a destination without following symlinks. Unlike [`Path::exists`],
/// this reports a dangling symlink as present, so `--force` can replace the
/// link itself rather than letting the later atomic rename fail unexpectedly.
fn destination_metadata(path: &Path) -> Result<Option<fs::Metadata>, CliError> {
    match fs::symlink_metadata(path) {
        Ok(metadata) => Ok(Some(metadata)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(CliError::system(
            "metadata_failed",
            format!("could not inspect {}: {error}", path.display()),
        )),
    }
}

fn preflight(plan: &[PlanItem], force: bool) -> Result<PreflightResult, CliError> {
    use std::cmp::Ordering;
    let mut seen: HashSet<&Path> = HashSet::new();
    let mut warnings: Vec<String> = Vec::new();
    let mut overwrite_allowed: HashSet<PathBuf> = HashSet::new();
    let mut skipped: HashSet<PathBuf> = HashSet::new();
    for PlanItem {
        agent,
        path,
        content,
        kind,
    } in plan
    {
        let name = kind.display_name();
        if !seen.insert(path.as_path()) {
            return Err(CliError::user(
                "duplicate_destination",
                format!("destination appears more than once: {}", path.display()),
            )
            .with_invalid_value(path.display().to_string()));
        }
        let destination = destination_metadata(path)?;
        // `symlink_metadata` intentionally classifies a symlink to a directory
        // as a symlink, not a directory: it is a replaceable file destination
        // when `--force` is passed.
        if destination
            .as_ref()
            .is_some_and(|metadata| metadata.file_type().is_dir())
        {
            return Err(CliError::user(
                "invalid_dest",
                format!("destination is a directory: {}", path.display()),
            )
            .with_invalid_value(path.display().to_string()));
        }
        // The pi mirror is a DERIVED copy of the claude SKILL.md, never a
        // first-class target the user asked for. It must not let its own
        // state gate the primary claude install (issue
        // `pidev-dual-home-skills`, review finding F1): a present-and-current
        // pi copy must NOT block re-creating a deleted claude skill, and an
        // unmanaged pi file (no provenance marker) must NOT be clobbered on a
        // plain run merely because it looks older. So:
        //   - absent            → fall through to the normal write path.
        //   - present, --force  → refresh it (overwrite_allowed).
        //   - present, no force → leave it in place (skipped); warn only when
        //                         the on-disk bytes actually differ, so a
        //                         byte-identical mirror is a silent no-op.
        // Trade-off: a non-force claude drift-upgrade leaves a stale pi copy
        // until the next `--force` redeploy — acceptable because the
        // operating policy always deploys with `--force`. Lifecycle
        // (prune + doctor drift) is tracked separately as
        // `pidev-pi-skill-lifecycle`.
        if *agent == "pi" && destination.is_some() {
            if force {
                overwrite_allowed.insert(path.clone());
            } else {
                // Warn unless the on-disk bytes are provably identical to
                // the bundled copy — an unreadable file counts as "differs"
                // so the skip is surfaced rather than silently assumed a
                // no-op.
                if !fs::read(path).is_ok_and(|b| b == content.as_bytes()) {
                    warnings.push(format!(
                        "pi_mirror_skipped: {name} already exists at {} and differs from the bundled copy; left unchanged (pass --force to refresh)",
                        path.display()
                    ));
                }
                skipped.insert(path.clone());
            }
            continue;
        }
        if destination.is_none() {
            // No file → the write loop will refuse to clobber via
            // persist_noclobber. Do not insert into `overwrite_allowed`.
            continue;
        }
        // Existing target: classify by semver-correct `cli_version`
        // drift relative to the running binary (AGENTS-AI-FIRST-CLI §17).
        // An unreadable or unparseable `cli_version` lands in the
        // "legacy / unversioned" arm so we never invent an ordering.
        let on_disk_raw = fs::read_to_string(path)
            .ok()
            .and_then(|s| parse_frontmatter_field(&s, "cli_version"));
        let drift = on_disk_raw
            .as_deref()
            .and_then(|v| compare_versions(v, CLI_VERSION).map(|ord| (v, ord)));
        match drift {
            Some((v, Ordering::Less)) => {
                // Older on disk: install proceeds with a warning so the
                // agent learns the operating manual just moved.
                overwrite_allowed.insert(path.clone());
                warnings.push(format!(
                    "skill_version_drift: {name} on disk is {v}; binary ships {CLI_VERSION}; overwriting"
                ));
            }
            Some((v, Ordering::Greater)) => {
                if !force {
                    return Err(CliError::system(
                        "skill_version_too_new",
                        format!(
                            "{}: on-disk skill is cli_version {} but binary is {}; pass --force to overwrite anyway",
                            path.display(),
                            v,
                            CLI_VERSION
                        ),
                    )
                    .with_invalid_value(path.display().to_string()));
                }
                overwrite_allowed.insert(path.clone());
                warnings.push(format!(
                    "skill_version_drift: {name} on disk is {v} (newer than binary {CLI_VERSION}); --force overwriting"
                ));
            }
            Some((_, Ordering::Equal)) | None => {
                // Either equal versions (already in sync) or no
                // parseable `cli_version` on disk (legacy / unversioned
                // / unreadable). Both require explicit --force; we
                // refuse to invent an overwrite policy.
                if !force {
                    return Err(CliError::system(
                        "refused_overwrite",
                        format!(
                            "{} already exists; pass --force to overwrite",
                            path.display()
                        ),
                    )
                    .with_invalid_value(path.display().to_string()));
                }
                overwrite_allowed.insert(path.clone());
            }
        }
    }
    Ok(PreflightResult {
        warnings,
        overwrite_allowed,
        skipped,
    })
}

fn lookup(name: &str) -> Result<&'static EmbeddedSkill, CliError> {
    SKILLS.iter().find(|s| s.name == name).ok_or_else(|| {
        let available: Vec<&str> = SKILLS.iter().map(|s| s.name).collect();
        CliError::user(
            "skill_not_found",
            format!(
                "no skill named '{}'; available: {}",
                name,
                available.join(", ")
            ),
        )
        .with_invalid_value(name.to_string())
        .with_expected(serde_json::json!({ "one_of": available }))
    })
}

fn default_path(agent: &str, name: &str) -> Result<PathBuf, CliError> {
    let home = std::env::var("HOME").map_err(|_| {
        CliError::system(
            "home_unset",
            "HOME is not set; cannot resolve default install path (pass --dest)",
        )
    })?;
    let base = PathBuf::from(home);
    Ok(match agent {
        "claude" => base.join(".claude/skills").join(name).join("SKILL.md"),
        "codex" => base.join(".codex/prompts").join(format!("{name}.md")),
        // pi.dev discovers skills from a per-skill directory just like
        // claude, only rooted at `~/.pi/agent/skills/`, and invokes them
        // as `/skill:name`. The dual-home mirror writes the same
        // claude-format `SKILL.md` here (see `cmd_install`).
        "pi" => base.join(".pi/agent/skills").join(name).join("SKILL.md"),
        // unreachable in practice — callers only pass the literals above.
        other => {
            return Err(CliError::user(
                "invalid_agent",
                format!("unknown agent '{other}'"),
            ))
        }
    })
}

/// Root of the claude skill-install layout (`~/.claude/skills`). `None`
/// when `HOME` is unset. Both `prune` and the `skill.orphan.*` doctor
/// check scan this directory for managed-but-de-registered skills.
pub fn claude_skills_root() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    Some(PathBuf::from(home).join(".claude/skills"))
}

/// Root of the codex flat prompts layout (`~/.codex/prompts`), where each
/// skill installs as a single top-level `<name>.md`. `None` when `HOME` is
/// unset. Both the codex prune path and the `skill.orphan.codex.*` doctor
/// check resolve prompt files against this root.
pub fn codex_prompts_root() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    Some(PathBuf::from(home).join(".codex/prompts"))
}

/// The codex shared-companion dir (`~/.codex/prompts/_shared`). `None` when
/// `HOME` is unset. Holds the `_shared/<file>` companions AND the single
/// codex provenance marker.
pub fn codex_shared_root() -> Option<PathBuf> {
    codex_prompts_root().map(|p| p.join(CODEX_SHARED_SUBDIR))
}

/// Path to the single codex provenance marker
/// (`~/.codex/prompts/_shared/.orchestratectl-managed`). `None` when `HOME`
/// is unset. Codex's prompts dir is flat, so — unlike claude's per-skill
/// directory marker — ONE shared marker records every prompt + companion
/// orchestratectl installed there. Its presence is what makes codex-side
/// pruning + orphan detection safe: a user's own prompt of the same name is
/// never recorded, so it is never touched.
fn codex_marker_path() -> Option<PathBuf> {
    codex_shared_root().map(|p| p.join(MANAGED_MARKER_FILENAME))
}

/// Codex prompt names the shared provenance marker records as
/// orchestratectl-managed (sorted, deduped). Empty when `HOME` is unset or
/// the marker is absent/unreadable — which is precisely the signal that
/// orchestratectl does not manage codex on this host (e.g. a claude-only
/// install), so `doctor` emits no codex checks and a claude-primary tree
/// stays 0-warn.
pub fn codex_managed_prompts() -> Vec<String> {
    let Some(marker) = codex_marker_path() else {
        return Vec::new();
    };
    let mut v = read_marker_records(&marker, "prompt");
    v.sort();
    v.dedup();
    v
}

/// Companion filenames the shared codex provenance marker records as
/// managed — the `_shared/<file>` companions orchestratectl installed
/// (sorted, deduped). Empty under the same conditions as
/// [`codex_managed_prompts`].
pub fn codex_managed_companions() -> Vec<String> {
    let Some(marker) = codex_marker_path() else {
        return Vec::new();
    };
    let mut v = read_marker_records(&marker, "companion");
    v.sort();
    v.dedup();
    v
}

// ---------------------------------------------------------------------------
// pi.dev mirror lifecycle (out-of-band provenance).
//
// The pi mirror (`~/.pi/agent/skills/<name>/SKILL.md`, written by `cmd_install`)
// deliberately carries NO in-dir `.orchestratectl-managed` marker — the
// `pidev-dual-home-skills` contract forbids one so the pi corpus stays a pure
// skill-body mirror. Without an in-dir provenance signal we cannot tell an
// orchestratectl-written pi dir from a user's own hand-authored pi skill, so a
// naive "pi orphan" prune/warn would false-positive on every user skill.
//
// The provenance therefore lives OUT-OF-BAND, in a single JSON record under the
// orchestratectl state root (`<root>/state/pi-installed-skills.json`), keyed by
// skill name → a flat per-file map (`files: { <relpath>: { sha256, kind } }`)
// of every mirrored file we last wrote (the `SKILL.md` body AND each companion
// sibling), plus the skill's `cli_version`. It is the SOLE authority for two
// safety-critical decisions:
//
//   - prune (issue task 2): a pi mirror is a prune candidate only if its name is
//     recorded here AND the on-disk bytes still hash to the recorded value (proof
//     it is our unmodified copy). A user-taken-over or hand-authored pi dir is
//     never recorded, so it is never touched.
//   - `doctor` drift (issue task 3): the recorded set gates the `skill.sync.
//     <name>.pi` / `skill.orphan.<name>.pi` checks, so a host that never dual-
//     homed into pi emits no pi checks and stays 0-warn.

/// Schema version of the pi provenance record. Bumped independently of the
/// SKILL.md and envelope schema versions if the record's shape ever changes.
///
/// **v3** flattened the record to a per-file model: each skill entry became
/// `{ cli_version, files: { <relpath>: { sha256, kind } } }`, where every
/// mirrored file — the `SKILL.md` body AND each companion sibling — is tracked
/// as one independent `PiFileRecord`. Before v3 the body was a privileged
/// ownership root (`{ sha256, cli_version, companions: { <file>: sha } }`) that
/// nested companions under it, which forced several lifecycle edge-case
/// point-fixes (a companion written while the body write was skipped had no
/// record to attach to; prune coupled companion cleanup to body divergence).
/// The flat model makes ownership/relinquish/retry decisions per file and
/// removes those couplings (issue `pi-provenance-flat-file-model`).
///
/// **v2** (superseded) added the per-skill `companions` map to v1's bare
/// `{ sha256, cli_version }`. The v3 upgrade reads both legacy shapes: on load a
/// record whose `files` map is empty is reconstructed from the legacy
/// `sha256`/`companions` fields (see `RawPiSkillRecord`), so v1 and v2 records
/// keep working. The bump is deliberate: keeping the number at 2 would let an
/// OLDER binary read a v3 record, silently drop the unknown `files` field on its
/// next rewrite, and — still seeing a schema it accepts — overwrite it, erasing
/// tracking for every mirror. Writing v3 makes that older binary reject the
/// record via `load_pi_provenance_for_write`'s `schema_too_new` guard (fail
/// closed) instead of laundering the field away. The `<=` load check keeps old
/// v1/v2 records readable here.
const PI_PROVENANCE_SCHEMA_VERSION: u32 = 3;

/// Relpath key under which a skill's `SKILL.md` body is tracked in a
/// [`PiSkillRecord`]'s `files` map. It is the filename component of every
/// `pi_default_path` (`~/.pi/agent/skills/<name>/SKILL.md`), so the on-disk
/// sibling a `files` entry names resolves by joining it to the skill's pi dir —
/// identical to how a companion relpath resolves.
const PI_SKILL_FILENAME: &str = "SKILL.md";

/// Whether one tracked pi file is the skill's `SKILL.md` body or a companion
/// sibling. In the flat model the body is no longer an ownership root — it is
/// one `PiFileRecord` like any other — but the kind is still recorded so the
/// prune orders companion deletes before the body (keeping the per-skill dir
/// emptyable) and `doctor` can classify a body-vs-companion drift.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum PiFileKind {
    Skill,
    Companion,
}

/// One mirrored pi file orchestratectl wrote (the `SKILL.md` body OR a companion
/// sibling), tracked independently in its owning skill's `files` map.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct PiFileRecord {
    /// Lowercase-hex SHA-256 of the bytes we wrote to
    /// `~/.pi/agent/skills/<name>/<relpath>`. Divergence from the on-disk bytes
    /// means the user (or a newer/older binary) has since changed the file — the
    /// prune/reconcile paths refuse to delete such a copy.
    sha256: String,
    /// Whether this file is the skill body (`SKILL.md`) or a companion sibling.
    kind: PiFileKind,
}

/// Flat per-file provenance for one pi mirror: which files orchestratectl wrote
/// under `~/.pi/agent/skills/<name>/` and their content hash + kind. Replaces
/// the pre-v3 body-owns-companions nesting so every file's
/// ownership/relinquish/retry decision is independent.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(from = "RawPiSkillRecord")]
struct PiSkillRecord {
    /// The `cli_version` frontmatter of the `SKILL.md` bytes we last wrote,
    /// retained for human/debug inspection of the record. `doctor` classifies
    /// drift from the ON-DISK `cli_version` (more accurate than the last-written
    /// one), so it does not read this field today. Empty when only a companion
    /// was ever recorded for the skill (the body write was skipped).
    #[serde(skip_serializing_if = "String::is_empty")]
    cli_version: String,
    /// Every mirrored file, keyed relpath (`SKILL.md` or a companion filename) →
    /// its content hash + kind. The body carries no special status; it is the
    /// `PI_SKILL_FILENAME` entry with `kind: Skill`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    files: BTreeMap<String, PiFileRecord>,
}

/// Deserialize shim that reads BOTH the v3 `files` shape and the legacy v1/v2
/// `sha256`/`companions` fields, so an older on-disk record upgrades in place on
/// load (see [`PI_PROVENANCE_SCHEMA_VERSION`]). `From<RawPiSkillRecord>` folds
/// the legacy fields into the flat `files` map only when `files` is empty (a
/// genuine v1/v2 record), so a v3 record round-trips untouched.
#[derive(Debug, Clone, Default, Deserialize)]
struct RawPiSkillRecord {
    #[serde(default)]
    cli_version: String,
    #[serde(default)]
    files: BTreeMap<String, PiFileRecord>,
    /// Legacy v1/v2 body hash. `Option` so an absent field (v3) is distinguished
    /// from a legacy empty-string body hash.
    #[serde(default)]
    sha256: Option<String>,
    /// Legacy v2 companions map (filename → hash).
    #[serde(default)]
    companions: BTreeMap<String, String>,
}

impl From<RawPiSkillRecord> for PiSkillRecord {
    fn from(raw: RawPiSkillRecord) -> Self {
        // A v3 record already carries `files`; take it verbatim. A legacy v1/v2
        // record has an empty `files` — reconstruct it from the body `sha256`
        // and the `companions` map so tracking survives the upgrade.
        if !raw.files.is_empty() {
            return PiSkillRecord {
                cli_version: raw.cli_version,
                files: raw.files,
            };
        }
        let mut files: BTreeMap<String, PiFileRecord> = BTreeMap::new();
        // Drop an EMPTY legacy body hash rather than minting a fake `SKILL.md`
        // entry with `sha256: ""` — a pre-flat `pi_companion_unrecorded` edge
        // (or a hand-edit) could leave one, and an empty-hash body entry would
        // make `doctor`'s same-version content check spuriously report the real
        // on-disk body as "differs from the copy orchestratectl wrote".
        if let Some(sha256) = raw.sha256.filter(|s| !s.is_empty()) {
            files.insert(
                PI_SKILL_FILENAME.to_string(),
                PiFileRecord {
                    sha256,
                    kind: PiFileKind::Skill,
                },
            );
        }
        for (filename, sha256) in raw.companions {
            // Same empty-hash guard as the body; also never let a legacy
            // companion keyed `SKILL.md` (any case) alias/overwrite the body
            // entry or mis-kind it as a companion (which the prune's
            // stale-companion path could then delete as the actual body).
            if sha256.is_empty() || filename.eq_ignore_ascii_case(PI_SKILL_FILENAME) {
                continue;
            }
            files.insert(
                filename,
                PiFileRecord {
                    sha256,
                    kind: PiFileKind::Companion,
                },
            );
        }
        PiSkillRecord {
            cli_version: raw.cli_version,
            files,
        }
    }
}

impl PiSkillRecord {
    /// The recorded hash of the skill's `SKILL.md` body, if it is tracked. `None`
    /// when only a companion was ever recorded (the body write was skipped).
    fn body_hash(&self) -> Option<&str> {
        self.files
            .get(PI_SKILL_FILENAME)
            .filter(|f| f.kind == PiFileKind::Skill)
            .map(|f| f.sha256.as_str())
    }

    /// The tracked companion relpaths (every `files` entry that is not the body),
    /// sorted (the `BTreeMap` iterates in key order).
    fn companion_names(&self) -> Vec<String> {
        self.files
            .iter()
            .filter(|(_, f)| f.kind == PiFileKind::Companion)
            .map(|(name, _)| name.clone())
            .collect()
    }
}

/// The out-of-band pi provenance record: which pi mirrors orchestratectl wrote
/// and their content hash + version. A `BTreeMap` keeps the on-disk JSON
/// deterministic (sorted keys) so a redeploy that changes nothing produces
/// byte-identical output.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct PiProvenance {
    schema_version: u32,
    skills: BTreeMap<String, PiSkillRecord>,
}

/// Lowercase-hex SHA-256 of `bytes`. Used to fingerprint a pi `SKILL.md` for
/// the provenance record and to verify a prune candidate is still our copy.
fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut out = String::with_capacity(digest.len() * 2);
    for b in digest {
        use std::fmt::Write as _;
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// Root of the pi.dev skill-mirror layout (`~/.pi/agent/skills`). `None` when
/// `HOME` is unset. Sibling of [`claude_skills_root`]; the pi prune uses it to
/// assert a per-skill dir it is about to `remove_dir` really sits directly under
/// the corpus root before touching it.
fn pi_skills_root() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    Some(PathBuf::from(home).join(".pi/agent/skills"))
}

/// Default pi mirror path for a skill (`~/.pi/agent/skills/<name>/SKILL.md`).
/// `None` when `HOME` is unset. Used by `doctor` to locate the on-disk pi copy
/// to compare against the binary, and by the prune path to resolve a
/// de-registered mirror.
pub fn pi_default_path(name: &str) -> Option<PathBuf> {
    default_path("pi", name).ok()
}

/// True when `name` is a single normal path component — no `/`, no `.`/`..`, not
/// absolute, not empty. Every real catalog skill name has this shape. The
/// provenance record is persisted, mutable JSON: a corrupt/hand-edited key like
/// `"../../.bashrc"` or an absolute path deserialized and then `join`ed into a
/// filesystem path would let the prune/doctor act OUTSIDE the pi corpus (the one
/// `record-key → fs-path → remove_file` path that has no other binding check —
/// claude/codex instead enumerate real directory entries, which are
/// single-component for free). Validating here gives the pi path the same rigor
/// as `managed_orphan_dirs` (review finding E). Non-matching names are skipped,
/// never acted on.
///
/// Reused for record-sourced companion FILENAMES too (e.g. `AGENTS-EXECUTION-
/// DAG.md`): the contract is the same "single normal path component", so the
/// name reads skill-specific but the check is exactly what a companion filename
/// needs before it is joined into a per-skill dir.
pub fn is_simple_skill_name(name: &str) -> bool {
    let mut components = Path::new(name).components();
    matches!(
        (components.next(), components.next()),
        (Some(std::path::Component::Normal(_)), None)
    )
}

/// Path to the single out-of-band pi provenance record
/// (`<orchestratectl-root>/state/pi-installed-skills.json`). `None` when the
/// root cannot be resolved (neither `$ORCHESTRATECTL_HOME` nor `$HOME` set).
/// Deliberately rooted at the orchestratectl STATE dir, not `~/.pi` — the pi
/// corpus must stay a pure body mirror with no orchestratectl bookkeeping in it.
fn pi_provenance_path() -> Option<PathBuf> {
    home::root_dir()
        .ok()
        .map(|root| root.join("state").join("pi-installed-skills.json"))
}

/// LENIENT read for the READ-ONLY doctor path: a missing, unreadable,
/// unparseable, OR future-schema record yields an empty [`PiProvenance`], so
/// `doctor` simply emits no pi checks rather than auditing a record it cannot
/// trust. NEVER use this on the install mutation path — that must fail loudly
/// instead of laundering a corrupt record into an empty one it then overwrites
/// (see [`load_pi_provenance_for_write`]).
fn read_pi_provenance(path: &Path) -> PiProvenance {
    let Ok(body) = fs::read_to_string(path) else {
        return PiProvenance::default();
    };
    match serde_json::from_str::<PiProvenance>(&body) {
        Ok(p) if p.schema_version <= PI_PROVENANCE_SCHEMA_VERSION => p,
        _ => PiProvenance::default(),
    }
}

/// STRICT load for the install MUTATION path. Distinguishes:
///
///   - absent (`NotFound`) → `Ok(default)` — a first install starts fresh.
///   - unreadable / unparseable / `schema_version` NEWER than this binary
///     understands → `Err`.
///
/// so an install NEVER silently launders a corrupt or future-schema record into
/// an empty one and then overwrites it — which would erase tracking for EVERY
/// other managed pi mirror (the record is the sole authority; there is no in-dir
/// fallback). The record is loaded and validated BEFORE any file is written, so
/// a corrupt record fails the install fast rather than after mutating the tree
/// (review finding A). The trusted state root does not rescue this: a partial
/// write (power loss / ENOSPC mid-persist), a version rollback, or a manual edit
/// are all ordinary causes.
fn load_pi_provenance_for_write(path: &Path) -> Result<PiProvenance, CliError> {
    let body = match fs::read_to_string(path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(PiProvenance::default()),
        Err(e) => {
            return Err(CliError::system(
                "pi_provenance_unreadable",
                format!(
                    "could not read pi provenance record {}: {e}; back it up and remove it to re-initialise",
                    path.display()
                ),
            ))
        }
    };
    let prov: PiProvenance = serde_json::from_str(&body).map_err(|e| {
        CliError::system(
            "pi_provenance_corrupt",
            format!(
                "pi provenance record {} is not valid JSON ({e}); refusing to overwrite it (that would erase tracking for every managed pi mirror). Back it up and remove it to re-initialise.",
                path.display()
            ),
        )
    })?;
    if prov.schema_version > PI_PROVENANCE_SCHEMA_VERSION {
        return Err(CliError::system(
            "pi_provenance_schema_too_new",
            format!(
                "pi provenance record {} uses schema {} but this binary understands only {}; refusing to overwrite it. Upgrade orchestratectl.",
                path.display(),
                prov.schema_version,
                PI_PROVENANCE_SCHEMA_VERSION
            ),
        ));
    }
    Ok(prov)
}

/// Write the pi provenance record atomically. The `state/` dir is created if
/// absent. `write_atomic` with `force = true` renames a fresh tempfile over the
/// destination, which atomically replaces whatever name is there — including a
/// squatting symlink — with the regular file, so no symlink target is ever
/// clobbered. A write failure is fatal to the install (symmetric with the
/// claude/codex marker writes): without a current record a genuine pi orphan is
/// never recognised.
fn write_pi_provenance(path: &Path, prov: &PiProvenance) -> Result<(), CliError> {
    let body = serde_json::to_string_pretty(prov).map_err(|e| {
        CliError::system(
            "pi_provenance_serialize_failed",
            format!("could not serialize pi provenance record: {e}"),
        )
    })?;
    write_atomic(path, &body, true)
}

/// The skill names the pi provenance record lists as orchestratectl-managed,
/// each with its recorded content hash (sorted by name). Empty
/// when `HOME`/root is unset or the record is absent — precisely the signal
/// that orchestratectl does not manage a pi mirror on this host, so `doctor`
/// emits no pi checks. Consumed by the `skill.sync.<name>.pi` /
/// `skill.orphan.<name>.pi` doctor checks.
pub fn pi_managed_skills() -> Vec<PiManagedSkill> {
    let Some(path) = pi_provenance_path() else {
        return Vec::new();
    };
    let prov = read_pi_provenance(&path);
    let mut out: Vec<PiManagedSkill> = prov
        .skills
        .into_iter()
        .map(|(name, rec)| {
            // The doctor's same-version-edit check compares the on-disk
            // `SKILL.md` hash against the recorded body hash. `None` when only a
            // companion was ever recorded (the body write was skipped) — doctor
            // must then NOT fabricate a body hash and claim the real on-disk body
            // "differs from the copy orchestratectl wrote". Companions are
            // surfaced regardless.
            PiManagedSkill {
                name,
                sha256: rec.body_hash().map(str::to_string),
                companions: rec.companion_names(),
            }
        })
        .collect();
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// One managed pi mirror surfaced to `doctor`: the skill name plus the content
/// hash orchestratectl recorded when it last wrote the mirror. The hash lets the
/// drift check detect a same-version local edit (on-disk bytes no longer match
/// what we wrote) without holding the bundled body. (The record also carries the
/// written `cli_version`, but the doctor reads the on-disk `cli_version` for a
/// more accurate drift classification, so it is not surfaced here.)
pub struct PiManagedSkill {
    pub name: String,
    /// The recorded `SKILL.md` body hash, or `None` when the record tracks only
    /// companions (the body write was skipped). `doctor` skips the same-version
    /// content-edit sub-check when this is `None` rather than comparing the real
    /// on-disk body against a fabricated empty hash.
    pub sha256: Option<String>,
    /// Companion filenames the provenance record lists as mirrored beside this
    /// skill's pi `SKILL.md` (sorted). Used by `doctor` to detect a companion
    /// the binary dropped but the record still tracks (`skill.orphan.<name>.pi.
    /// <file>`); the forward drift check compares on-disk companions to the
    /// bundled bodies directly, so it does not need this list.
    pub companions: Vec<String>,
}

/// SHA-256 (lowercase hex) of the file at `path`, or `None` if it cannot be
/// read. Exposed for `doctor` to compare an on-disk pi `SKILL.md` against the
/// hash the provenance record holds.
pub fn file_sha256(path: &Path) -> Option<String> {
    fs::read(path).ok().map(|b| sha256_hex(&b))
}

/// True when `dir` is a claude-layout skill directory that orchestratectl
/// installed. The guard is deliberately strict — its `true` is the SOLE
/// authorization for a recursive `remove_dir_all`, so it must never yield
/// a false positive on a user's own directory. Three conditions must ALL
/// hold:
///
/// 1. The marker is a **regular file** (`symlink_metadata`, which does not
///    follow links) — a planted `.orchestratectl-managed` *symlink* cannot
///    make a directory look managed.
/// 2. The marker carries the `managed-by: orchestratectl` stamp.
/// 3. The marker's recorded `skill_name` equals this directory's name.
///    This binding is what makes `cp -r managed-skill my-copy` safe: the
///    copy's marker still names the ORIGINAL skill, so it never matches
///    `my-copy` and the copy is spared.
fn is_managed_skill_dir(dir: &Path) -> bool {
    let Some(dir_name) = dir.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    let marker = dir.join(MANAGED_MARKER_FILENAME);
    let Ok(meta) = fs::symlink_metadata(&marker) else {
        return false;
    };
    if !meta.file_type().is_file() {
        return false;
    }
    let Ok(content) = fs::read_to_string(&marker) else {
        return false;
    };
    let mut has_stamp = false;
    let mut name_matches = false;
    for line in content.lines() {
        let line = line.trim();
        if line == "managed-by: orchestratectl" {
            has_stamp = true;
        } else if let Some(rest) = line.strip_prefix("skill_name:") {
            name_matches = rest.trim() == dir_name;
        }
    }
    has_stamp && name_matches
}

/// Write (or overwrite) the provenance marker for skill `skill_name` at
/// `path`. The recorded `skill_name` is what `is_managed_skill_dir` binds
/// against, so a copied-and-renamed skill is never mistaken for an orphan.
/// `companions` are the companion filenames this install manages in the
/// directory, each recorded on its own `companion:` line so a later binary
/// that drops one can recognise the leftover file as an orphan it once
/// installed (see `orphan_companions` and the `cmd_install` prune loop).
/// The parent directory already exists (the SKILL.md write created it), so
/// this is a plain overwrite; the marker is always ours. If a symlink is
/// squatting at the marker path we unlink it first so `fs::write` cannot
/// clobber the link's target (an arbitrary-file overwrite within the
/// user's permissions).
fn write_marker(path: &Path, skill_name: &str, companions: &[String]) -> Result<(), CliError> {
    clear_marker_symlink(path)?;
    let mut body = format!(
        "managed-by: orchestratectl\ncli_version: {CLI_VERSION}\nskill_name: {skill_name}\n"
    );
    for companion in companions {
        body.push_str("companion: ");
        body.push_str(companion);
        body.push('\n');
    }
    fs::write(path, body).map_err(|e| {
        CliError::system(
            "marker_write_failed",
            format!(
                "could not write provenance marker {}: {}",
                path.display(),
                e
            ),
        )
    })
}

/// Write (or overwrite) the SINGLE codex provenance marker at `path`
/// (`~/.codex/prompts/_shared/.orchestratectl-managed`). Unlike the claude
/// per-skill marker, this one records the flat layout's whole managed set:
/// a `prompt:` line per installed codex skill and a `companion:` line per
/// installed `_shared/<file>`. That is the only signal that makes codex
/// pruning safe (a user's own prompt is never listed). A squatting symlink
/// is unlinked first so `fs::write` cannot clobber the link's target.
fn write_codex_marker(
    path: &Path,
    prompts: &[String],
    companions: &[String],
) -> Result<(), CliError> {
    clear_marker_symlink(path)?;
    let mut body = format!("managed-by: orchestratectl\ncli_version: {CLI_VERSION}\n");
    for prompt in prompts {
        body.push_str("prompt: ");
        body.push_str(prompt);
        body.push('\n');
    }
    for companion in companions {
        body.push_str("companion: ");
        body.push_str(companion);
        body.push('\n');
    }
    fs::write(path, body).map_err(|e| {
        CliError::system(
            "marker_write_failed",
            format!(
                "could not write codex provenance marker {}: {}",
                path.display(),
                e
            ),
        )
    })
}

/// If a symlink squats at the marker `path`, unlink it so a subsequent
/// `fs::write` cannot clobber the link's target (an arbitrary-file
/// overwrite within the user's permissions). A regular file is left for the
/// write to overwrite in place — the marker is always ours.
fn clear_marker_symlink(path: &Path) -> Result<(), CliError> {
    if let Ok(meta) = fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() {
            fs::remove_file(path).map_err(|e| {
                CliError::system(
                    "marker_write_failed",
                    format!(
                        "could not clear stale marker symlink {}: {}",
                        path.display(),
                        e
                    ),
                )
            })?;
        }
    }
    Ok(())
}

/// Scan `skills_root` for managed skill directories whose name is NOT in
/// `registered`. These are directories orchestratectl installed (they
/// carry a valid provenance marker naming that same directory) but the
/// running binary no longer ships — renamed or removed bundled skills,
/// safe to prune. Directories without a valid marker (a user's own skills)
/// are never returned. Result is sorted by name for deterministic output.
/// An unreadable root, or an unreadable entry, is skipped rather than
/// guessed at — the prune path must always err toward NOT deleting.
fn managed_orphan_dirs(skills_root: &Path, registered: &HashSet<&str>) -> Vec<(String, PathBuf)> {
    let Ok(entries) = fs::read_dir(skills_root) else {
        return Vec::new();
    };
    let mut orphans: Vec<(String, PathBuf)> = Vec::new();
    for entry in entries {
        let Ok(entry) = entry else { continue };
        // `file_type()` is an lstat: it never follows a symlink. A
        // symlinked entry — even one pointing at a real directory — is
        // rejected so `remove_dir_all` can never traverse a link out of
        // the skills root and delete an unrelated tree.
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if !file_type.is_dir() || file_type.is_symlink() {
            continue;
        }
        let path = entry.path();
        let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        // Never prune a directory that matches a registered skill —
        // exactly, OR case-insensitively (a differently-cased alias on a
        // case-insensitive filesystem, e.g. macOS APFS, resolves to the
        // same on-disk directory a fresh install just wrote).
        if registered
            .iter()
            .any(|r| *r == dir_name || r.eq_ignore_ascii_case(dir_name))
        {
            continue;
        }
        if is_managed_skill_dir(&path) {
            orphans.push((dir_name.to_string(), path.clone()));
        }
    }
    orphans.sort();
    orphans
}

/// What [`prune_codex_file`] did with an orphan file, so the caller can
/// keep the marker's recorded set in step: `Removed` (deleted → drop it +
/// report it pruned), `Dropped` (nothing safe on disk to delete → stop
/// tracking it), or `Kept` (delete failed → still on disk → keep tracking).
enum CodexPruneOutcome {
    Removed,
    Dropped,
    Kept,
}

/// Delete one orphaned codex file (a de-registered prompt or companion),
/// mirroring the claude orphan-companion prune's safety: only ever remove a
/// REGULAR file we manage — never follow a symlink or recurse into a
/// directory squatting at that name. An absent/symlink/dir target yields
/// `Dropped` (nothing to clean, so stop tracking it); a successful unlink
/// yields `Removed`; a failed unlink warns and yields `Kept` so the marker
/// keeps tracking the still-present file.
fn prune_codex_file(
    path: &Path,
    removed_warning: &str,
    failed_warning: &str,
    warnings: &mut Vec<String>,
) -> CodexPruneOutcome {
    let is_regular = fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file());
    if !is_regular {
        return CodexPruneOutcome::Dropped;
    }
    match fs::remove_file(path) {
        Ok(()) => {
            warnings.push(format!("{removed_warning} at {}", path.display()));
            CodexPruneOutcome::Removed
        }
        Err(e) => {
            warnings.push(format!("{failed_warning} at {}: {e}", path.display()));
            CodexPruneOutcome::Kept
        }
    }
}

/// One pi file the install's write loop actually persisted this run, tagged so
/// the provenance update files it correctly under its owning skill's flat
/// `files` map: a `SKILL.md` body (`kind: Skill`, also refreshing the skill's
/// `cli_version`) or a companion (`kind: Companion`). Only persisted files
/// appear here — a `skipped` (present, non-force) pi file is absent, so its
/// prior `files` entry is carried forward untouched.
enum PiWrite {
    Skill {
        name: &'static str,
        hash: String,
        cli_version: String,
    },
    Companion {
        owner: &'static str,
        filename: &'static str,
        hash: String,
    },
}

/// Summary of a de-registered skill's flat-file prune, so the caller can update
/// the record + `pruned` payload. Every file the prune handled (deleted /
/// relinquished / absent) is removed from the record's `files` map in place; a
/// file whose delete FAILED is left in `files` so the entry survives for a
/// retry. `body_removed` is true when the skill's `SKILL.md` was our unmodified
/// copy and was deleted — the signal to report the skill in the `pruned` list.
#[derive(Default)]
struct PiPruneSummary {
    body_removed: bool,
}

/// Prune the pi mirror for a de-registered skill `name`, keyed SOLELY on the
/// out-of-band provenance record (the pi dir carries no in-dir marker). Flat
/// per-file model: each tracked file in `rec.files` is handled independently —
/// its own ownership/relinquish/retry decision, no privileged body — so a
/// diverged `SKILL.md` no longer forces the companions to be left behind (issue
/// `pi-provenance-flat-file-model`). Safety is layered exactly like the
/// claude/codex orphan prunes:
///
///   - Resolve `~/.pi/agent/skills/<name>/`; a `HOME`-unset root clears the
///     record's `files` (nothing we can locate) so the caller drops the entry.
///   - Each file: `symlink_metadata` (never follows a link) → only a REGULAR
///     file whose bytes hash to the recorded value is deleted; a symlink, a
///     squatting dir, or a user-edited (diverged) copy is left untouched and
///     relinquished (dropped from tracking); a failed delete keeps the file
///     tracked for a retry.
///   - Companions are handled BEFORE the `SKILL.md` so the per-skill dir can
///     empty out; the body no longer defers on a companion failure (that
///     coupling is gone — a Kept companion simply stays tracked). The body is
///     cleaned even when a companion delete failed (never stranded, since it
///     stays in the record). Finally the now-possibly-empty per-skill dir is
///     best-effort removed (never a recursive `remove_dir_all` — a user sibling,
///     or a surviving diverged/Kept file, keeps the dir).
fn prune_pi_mirror(
    name: &str,
    rec: &mut PiSkillRecord,
    warnings: &mut Vec<String>,
) -> PiPruneSummary {
    let Some(dir) = pi_default_path(name).and_then(|p| p.parent().map(Path::to_path_buf)) else {
        // Cannot locate the mirror (HOME unset — usually transient, e.g. a
        // misconfigured cron/sudo invocation). We cannot prove the files are
        // gone or diverged, so we must NOT delete tracking: leave `rec.files`
        // intact so a later run with HOME set can still prune/audit them. The
        // caller keeps the entry (files non-empty) and reports nothing pruned.
        return PiPruneSummary::default();
    };
    prune_pi_mirror_at(name, &dir, pi_skills_root().as_deref(), rec, warnings)
}

/// Path-taking core of [`prune_pi_mirror`], split out so the safety logic is
/// unit-testable against a tempdir without touching `$HOME`. `dir` is the pi
/// per-skill directory; `skills_root` is the expected pi corpus root, and the
/// empty-dir cleanup only fires when `dir` is exactly `<skills_root>/<name>/`.
fn prune_pi_mirror_at(
    name: &str,
    dir: &Path,
    skills_root: Option<&Path>,
    rec: &mut PiSkillRecord,
    warnings: &mut Vec<String>,
) -> PiPruneSummary {
    // Companions FIRST (before the body) so the per-skill dir can empty out.
    // Collect relpaths up front so we can mutate `rec.files` inside the loop.
    for filename in rec.companion_names() {
        if !is_simple_skill_name(&filename) {
            warnings.push(format!(
                "pi_provenance_bad_name: ignoring pi companion entry '{filename}' for skill '{name}' (not a simple filename)"
            ));
            rec.files.remove(&filename);
            continue;
        }
        let recorded_hash = rec.files[&filename].sha256.clone();
        match prune_pi_companion(name, &dir.join(&filename), &recorded_hash, warnings) {
            // Delete failed while the file is still present: keep it tracked so a
            // later redeploy retries and `doctor` keeps flagging it.
            PiCompanionOutcome::Kept => {}
            // Deleted, absent, relinquished (symlink/dir/diverged): stop tracking.
            _ => {
                rec.files.remove(&filename);
            }
        }
    }

    // Then the body (`SKILL.md`), if it is still tracked.
    let mut body_removed = false;
    if let Some(recorded_hash) = rec.body_hash().map(str::to_string) {
        let body_path = dir.join(PI_SKILL_FILENAME);
        match prune_pi_body(name, &body_path, &recorded_hash, warnings) {
            PiCompanionOutcome::Removed => {
                body_removed = true;
                rec.files.remove(PI_SKILL_FILENAME);
            }
            PiCompanionOutcome::Kept => {}
            // Absent / symlink / dir / diverged: relinquish tracking.
            _ => {
                rec.files.remove(PI_SKILL_FILENAME);
            }
        }
    }

    // Best-effort clean the now-possibly-empty per-skill dir (a user sibling or a
    // surviving diverged/Kept file keeps it via the non-recursive `remove_dir`).
    remove_empty_pi_skill_dir(Some(dir), skills_root, name);

    PiPruneSummary { body_removed }
}

/// Prune ONE de-registered pi `SKILL.md` body, mirroring [`prune_pi_companion`]'s
/// safety (regular-file + hash-match before delete) but with body-specific
/// warning strings. Returns the shared [`PiCompanionOutcome`] so the caller
/// classifies it identically to a companion: `Removed` (our copy, deleted),
/// `Absent` (nothing on disk), `NonRegular` (symlink/dir left), `Diverged`
/// (user-edited, left), `Kept` (delete/read failed while present → retry).
fn prune_pi_body(
    name: &str,
    path: &Path,
    recorded_hash: &str,
    warnings: &mut Vec<String>,
) -> PiCompanionOutcome {
    match fs::symlink_metadata(path) {
        // Only a genuine NotFound relinquishes tracking. A transient metadata
        // error (PermissionDenied, I/O) must NOT be mistaken for absence — that
        // would permanently drop tracking of a file that may still exist — so it
        // defers the whole prune (`Kept`) for a retry.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PiCompanionOutcome::Absent,
        Err(e) => {
            warnings.push(format!(
                "pi_mirror_prune_failed: could not inspect de-registered pi mirror '{name}' at {}: {e}",
                path.display()
            ));
            return PiCompanionOutcome::Kept;
        }
        Ok(m) if !m.file_type().is_file() => {
            // A symlink or squatting dir at the body path: never followed/deleted.
            // Narrate it (mirrors the companion path) so a leftover is visible.
            warnings.push(format!(
                "pi_mirror_left: de-registered pi mirror '{name}' at {} is not a regular file (symlink or directory); leaving it in place",
                path.display()
            ));
            return PiCompanionOutcome::NonRegular;
        }
        Ok(_) => {}
    }
    match fs::read(path) {
        Ok(bytes) if sha256_hex(&bytes) == recorded_hash => match fs::remove_file(path) {
            Ok(()) => {
                warnings.push(format!(
                    "pi_mirror_pruned: removed de-registered pi mirror '{name}' at {}",
                    path.display()
                ));
                PiCompanionOutcome::Removed
            }
            Err(e) => {
                warnings.push(format!(
                    "pi_mirror_prune_failed: could not remove de-registered pi mirror '{name}' at {}: {e}",
                    path.display()
                ));
                PiCompanionOutcome::Kept
            }
        },
        Ok(_) => {
            warnings.push(format!(
                "pi_mirror_diverged: de-registered pi mirror '{name}' at {} was modified since orchestratectl wrote it; leaving it in place and no longer tracking it",
                path.display()
            ));
            PiCompanionOutcome::Diverged
        }
        Err(e) => {
            warnings.push(format!(
                "pi_mirror_prune_failed: could not read de-registered pi mirror '{name}' at {}: {e}",
                path.display()
            ));
            PiCompanionOutcome::Kept
        }
    }
}

/// Best-effort removal of a now-orphaned per-skill pi dir if it is empty. We only
/// ever wrote `SKILL.md` + our companions into it, but a user may have added
/// their own sibling (or a diverged companion may remain) — `remove_dir`
/// (non-recursive) fails on a non-empty dir, so anything we did not clean is
/// preserved and the dir left be. Guarded on `parent` sitting DIRECTLY under the
/// pi skills root (`<root>/<name>/`), so even an unexpected `pi_default_path`
/// result can never point `remove_dir` at an arbitrary directory — the pi
/// analogue of claude's `is_managed_skill_dir` name-binding (review finding D).
fn remove_empty_pi_skill_dir(parent: Option<&Path>, skills_root: Option<&Path>, name: &str) {
    if let (Some(parent), Some(root)) = (parent, skills_root) {
        if parent.parent() == Some(root)
            && parent.file_name().and_then(|n| n.to_str()) == Some(name)
        {
            let _ = fs::remove_dir(parent);
        }
    }
}

/// What [`prune_pi_companion`] / [`prune_pi_body`] did with ONE tracked file, so
/// the flat prune can update the record per file: `Removed` (our unmodified
/// copy, deleted → drop from tracking), `Absent` (positively `NotFound` → drop),
/// `NonRegular` (a symlink / squatting dir left in place → drop), `Diverged` (a
/// user-edited copy left in place → drop), or `Kept` (a metadata/read/delete
/// error while the file may still be present → KEEP tracking so a later redeploy
/// retries and `doctor` keeps flagging it). In the flat model a `Kept` companion
/// no longer defers the body delete — it simply stays tracked (never stranded,
/// since it remains in the record).
#[derive(PartialEq, Eq)]
enum PiCompanionOutcome {
    Removed,
    Absent,
    NonRegular,
    Diverged,
    Kept,
}

/// Best-effort removal of ONE recorded pi companion sibling during a
/// de-registered skill's prune. Mirrors the SKILL.md safety: only a REGULAR
/// file whose bytes hash to `recorded_hash` is deleted — a symlink, a squatting
/// dir, an unreadable file, or a user-edited copy is left untouched (and thus
/// keeps the parent dir non-empty so `remove_dir` spares it). Warnings narrate
/// every case where a file is LEFT behind (a squatting non-regular path, a
/// diverged copy, or a failed delete) so a leftover is visible; a plain-absent
/// companion is silent (nothing to narrate). Returns the outcome so the caller
/// can defer the body delete on `Kept`.
fn prune_pi_companion(
    skill: &str,
    path: &Path,
    recorded_hash: &str,
    warnings: &mut Vec<String>,
) -> PiCompanionOutcome {
    match fs::symlink_metadata(path) {
        // NotFound relinquishes tracking; a transient metadata error keeps the
        // companion tracked for a retry rather than mistaking it for absence.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PiCompanionOutcome::Absent,
        Err(e) => {
            warnings.push(format!(
                "pi_companion_prune_failed: could not inspect companion of de-registered pi skill '{skill}' at {}: {e}",
                path.display()
            ));
            return PiCompanionOutcome::Kept;
        }
        Ok(m) if !m.file_type().is_file() => {
            warnings.push(format!(
                "pi_companion_left: companion of de-registered pi skill '{skill}' at {} is not a regular file (symlink or directory); leaving it in place",
                path.display()
            ));
            return PiCompanionOutcome::NonRegular;
        }
        Ok(_) => {}
    }
    match fs::read(path) {
        Ok(bytes) if sha256_hex(&bytes) == recorded_hash => match fs::remove_file(path) {
            Ok(()) => {
                warnings.push(format!(
                    "pi_companion_pruned: removed companion of de-registered pi skill '{skill}' at {}",
                    path.display()
                ));
                PiCompanionOutcome::Removed
            }
            Err(e) => {
                warnings.push(format!(
                    "pi_companion_prune_failed: could not remove companion of de-registered pi skill '{skill}' at {}: {e}",
                    path.display()
                ));
                PiCompanionOutcome::Kept
            }
        },
        Ok(_) => {
            warnings.push(format!(
                "pi_companion_diverged: companion of de-registered pi skill '{skill}' at {} was modified since orchestratectl wrote it; leaving it in place",
                path.display()
            ));
            PiCompanionOutcome::Diverged
        }
        Err(e) => {
            warnings.push(format!(
                "pi_companion_prune_failed: could not read companion of de-registered pi skill '{skill}' at {}: {e}",
                path.display()
            ));
            PiCompanionOutcome::Kept
        }
    }
}

/// Reconcile ONE still-registered skill's recorded pi companions against what
/// this binary now bundles: a companion a prior binary mirrored that the current
/// one no longer ships is an orphan. Without this, the `skill.orphan.<name>.pi.
/// <file>` doctor check would flag a state its only suggested fix (`skill install
/// <name> --force`) could never clear — a permanent, unfixable warning loop
/// (review finding F1). Symmetric with the claude `mark_dirs` companion
/// reconciliation, but keyed on the out-of-band record (no in-dir marker):
///
///   - non-`--force`: the stale entry is LEFT in the record so `doctor` keeps
///     surfacing it (and its `--force` fix now genuinely clears it).
///   - `--force`: remove the on-disk file only when it is our unmodified copy
///     (regular + hash match); report it in `pruned_companions` and drop it from
///     the record. A diverged / non-regular / absent file is left on disk but
///     dropped from tracking (we relinquish a copy we no longer recognise). A
///     failed delete keeps the entry tracked so a later redeploy retries.
fn reconcile_pi_companions(
    skill_name: &str,
    prov: &mut PiProvenance,
    force: bool,
    pruned_companions: &mut Vec<String>,
    warnings: &mut Vec<String>,
) {
    let Some(rec) = prov.skills.get_mut(skill_name) else {
        return;
    };
    let Some(dir) = pi_default_path(skill_name).and_then(|p| p.parent().map(Path::to_path_buf))
    else {
        return;
    };
    reconcile_pi_companions_at(skill_name, rec, &dir, force, pruned_companions, warnings);
}

/// Path-taking core of [`reconcile_pi_companions`], split out so the logic is
/// unit-testable against a tempdir without touching `$HOME`. `dir` is the pi
/// per-skill directory the companions live in.
fn reconcile_pi_companions_at(
    skill_name: &str,
    rec: &mut PiSkillRecord,
    dir: &Path,
    force: bool,
    pruned_companions: &mut Vec<String>,
    warnings: &mut Vec<String>,
) {
    let bundled: HashSet<&str> = resources_for(skill_name)
        .iter()
        .map(|r| r.filename)
        .collect();
    // Stale = a tracked COMPANION file the binary no longer bundles. The body
    // (`kind: Skill`) is never stale here — it is reconciled by the write loop
    // (a still-registered skill always re-writes its `SKILL.md`).
    let stale: Vec<String> = rec
        .files
        .iter()
        .filter(|(f, r)| r.kind == PiFileKind::Companion && !bundled.contains(f.as_str()))
        .map(|(f, _)| f.clone())
        .collect();
    if stale.is_empty() {
        return;
    }
    // Non-force: keep every stale entry so `doctor` keeps flagging it; the
    // `--force` fix it suggests is what actually clears it.
    if !force {
        return;
    }
    for filename in stale {
        if !is_simple_skill_name(&filename) {
            warnings.push(format!(
                "pi_provenance_bad_name: ignoring pi companion entry '{filename}' for skill '{skill_name}' (not a simple filename)"
            ));
            rec.files.remove(&filename);
            continue;
        }
        let recorded_hash = rec.files[&filename].sha256.clone();
        let path = dir.join(&filename);
        // Classify the on-disk file. A metadata/read ERROR (PermissionDenied,
        // I/O) is NOT the same as absence or divergence — relinquishing on a
        // transient error would permanently drop tracking of a file that may
        // still be ours. So a hard error KEEPS the entry tracked for a retry;
        // only a positively-determined absent / non-regular / diverged file is
        // relinquished, and only a verified-our-copy is deleted.
        enum Classified {
            OurCopy,
            NotOurs,
            Error(std::io::Error),
        }
        let classified = match fs::symlink_metadata(&path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Classified::NotOurs,
            Err(e) => Classified::Error(e),
            Ok(m) if !m.file_type().is_file() => Classified::NotOurs,
            Ok(_) => match fs::read(&path) {
                Ok(b) if sha256_hex(&b) == recorded_hash => Classified::OurCopy,
                Ok(_) => Classified::NotOurs,
                Err(e) => Classified::Error(e),
            },
        };
        if let Classified::Error(e) = classified {
            warnings.push(format!(
                "skill_companion_prune_failed: could not inspect orphan pi companion '{filename}' for skill '{skill_name}' at {}: {e}",
                path.display()
            ));
            continue; // keep the entry tracked so a later redeploy retries
        }
        let is_our_copy = matches!(classified, Classified::OurCopy);
        if is_our_copy {
            match fs::remove_file(&path) {
                Ok(()) => {
                    warnings.push(format!(
                        "skill_companion_pruned: removed orphan pi companion '{filename}' for skill '{skill_name}' at {}",
                        path.display()
                    ));
                    pruned_companions.push(format!("{skill_name}/{filename}"));
                    rec.files.remove(&filename);
                }
                Err(e) => {
                    // Still on disk — keep tracking so a later redeploy retries and
                    // `doctor` keeps flagging it.
                    warnings.push(format!(
                        "skill_companion_prune_failed: could not remove orphan pi companion '{filename}' for skill '{skill_name}' at {}: {e}",
                        path.display()
                    ));
                }
            }
        } else {
            // Absent / non-regular / diverged: not our unmodified copy. Leave any
            // file in place and relinquish tracking rather than delete something we
            // no longer recognise as ours.
            warnings.push(format!(
                "pi_companion_relinquished: orphan pi companion '{filename}' for skill '{skill_name}' at {} is not our unmodified copy; no longer tracking it",
                path.display()
            ));
            rec.files.remove(&filename);
        }
    }
}

/// Managed-but-de-registered skill directories under the claude install
/// root, as `(name, path)` pairs sorted by name. Consumed by the
/// `skill.orphan.*` doctor check. Empty when `HOME` is unset or the root
/// is unreadable.
pub fn managed_orphans() -> Vec<(String, PathBuf)> {
    let Some(root) = claude_skills_root() else {
        return Vec::new();
    };
    let registered: HashSet<&str> = SKILLS.iter().map(|s| s.name).collect();
    managed_orphan_dirs(&root, &registered)
}

/// The companion filenames a provenance marker records as managed (the
/// `companion:` lines). Empty when the marker is unreadable or records
/// none. Blank values are dropped. Sibling of the `skill_name:`/stamp
/// parsing in `is_managed_skill_dir`, but for the companion sub-records.
fn read_managed_companions(marker_path: &Path) -> Vec<String> {
    read_marker_records(marker_path, "companion")
}

/// The trimmed values of every `<key>:` line in a marker file (blanks
/// dropped). Shared by the claude marker's `companion:` reader and the
/// codex marker's `prompt:` / `companion:` readers, so all three parse the
/// same line shape identically. Unreadable / absent marker → empty.
fn read_marker_records(marker_path: &Path, key: &str) -> Vec<String> {
    let Ok(content) = fs::read_to_string(marker_path) else {
        return Vec::new();
    };
    let prefix = format!("{key}:");
    content
        .lines()
        .filter_map(|line| line.trim().strip_prefix(prefix.as_str()))
        .map(|rest| rest.trim().to_string())
        .filter(|value| !value.is_empty())
        .collect()
}

/// Companion files recorded as managed in `<skill_dir>`'s provenance marker
/// that the current binary no longer bundles AND that still exist on disk —
/// the orphan companions a prior binary installed and this one dropped.
/// Filenames only (sorted, deduped); the caller joins `skill_dir` to report
/// or remove them. Consumed by the `skill.orphan.<name>.<file>` doctor
/// check. A still-bundled companion is never returned (it is audited by the
/// `skill.sync.<name>.<file>` forward check instead), and a user's own file
/// that the marker never recorded is never returned (that is what keeps this
/// from false-positiving on a hand-dropped note). Presence is probed with
/// `symlink_metadata` so a planted symlink is not followed.
pub fn orphan_companions(skill_name: &str, skill_dir: &Path) -> Vec<String> {
    let bundled: HashSet<&str> = resources_for(skill_name)
        .iter()
        .map(|r| r.filename)
        .collect();
    let marker_path = skill_dir.join(MANAGED_MARKER_FILENAME);
    let mut orphans: Vec<String> = read_managed_companions(&marker_path)
        .into_iter()
        .filter(|name| !bundled.contains(name.as_str()))
        .filter(|name| fs::symlink_metadata(skill_dir.join(name)).is_ok())
        .collect();
    orphans.sort();
    orphans.dedup();
    orphans
}

/// Empty parent from `PathBuf::parent()` means a bare relative filename
/// (e.g. `--dest SKILL.md`). Treat that as the current directory rather
/// than failing `create_dir_all("")`.
fn normalized_parent(path: &Path) -> Option<&Path> {
    match path.parent() {
        Some(p) if p.as_os_str().is_empty() => Some(Path::new(".")),
        Some(p) => Some(p),
        None => None,
    }
}

fn write_atomic(path: &Path, content: &str, force: bool) -> Result<(), CliError> {
    let parent = normalized_parent(path).ok_or_else(|| {
        CliError::user(
            "invalid_dest",
            format!("destination has no parent directory: {}", path.display()),
        )
    })?;
    fs::create_dir_all(parent).map_err(|e| {
        CliError::system(
            "create_dir_failed",
            format!("could not create {}: {}", parent.display(), e),
        )
    })?;

    let mut tmp = NamedTempFile::new_in(parent).map_err(|e| {
        CliError::system(
            "tempfile_failed",
            format!("could not create tempfile in {}: {}", parent.display(), e),
        )
    })?;
    tmp.write_all(content.as_bytes())
        .map_err(|e| CliError::system("write_failed", format!("could not write tempfile: {e}")))?;
    tmp.as_file_mut()
        .sync_all()
        .map_err(|e| CliError::system("fsync_failed", format!("could not fsync tempfile: {e}")))?;

    // `persist_noclobber` makes the non-force case TOCTOU-safe: the rename
    // refuses to clobber via the kernel rather than via an earlier
    // `path.exists()` check. The preflight pass above still runs so we
    // surface the friendly `refused_overwrite` envelope early; this is
    // the belt-and-braces guard against a race between preflight and
    // persist.
    let persist_result = if force {
        tmp.persist(path).map(|_| ())
    } else {
        tmp.persist_noclobber(path).map(|_| ())
    };
    persist_result.map_err(|e| {
        // tempfile's PersistError wraps EEXIST; surface the canonical
        // refused_overwrite envelope so callers can branch on the code.
        let kind = e.error.kind();
        if !force && kind == std::io::ErrorKind::AlreadyExists {
            CliError::system(
                "refused_overwrite",
                format!(
                    "{} already exists; pass --force to overwrite",
                    path.display()
                ),
            )
            .with_invalid_value(path.display().to_string())
        } else {
            CliError::system(
                "rename_failed",
                format!("could not rename into place {}: {}", path.display(), e),
            )
        }
    })
}

/// Extract the `description:` field from YAML-ish frontmatter at the top
/// of a SKILL.md.
///
/// Frontmatter is everything between a leading `---` line and the next
/// `---` line. We parse line-by-line (handling both `\n` and `\r\n` line
/// endings via `str::lines`) and accept `key: value` / `key : value`
/// pairs. Quoted values have their surrounding `"` or `'` stripped. This
/// is not a full YAML parser — multi-line scalars and nested maps are
/// out of scope — but it covers every shape our SKILL.md frontmatter is
/// allowed to take.
fn parse_description(body: &str) -> Option<String> {
    parse_frontmatter_field(body, "description")
}

/// Generic line-oriented frontmatter field extractor. Same constraints
/// as `parse_description`: top-level `---` fence, `key: value` shape,
/// single-line scalars only. Strips surrounding `"` / `'` quotes from
/// the value.
fn parse_frontmatter_field(body: &str, field: &str) -> Option<String> {
    let body = body.strip_prefix('\u{feff}').unwrap_or(body);
    let mut lines = body.lines();
    if lines.next()?.trim_end() != "---" {
        return None;
    }
    for line in lines {
        if line.trim_end() == "---" {
            return None;
        }
        let Some((key, value)) = line.split_once(':') else {
            continue;
        };
        if key.trim() == field {
            let v = value.trim();
            let v = v
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .or_else(|| v.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
                .unwrap_or(v);
            return Some(v.to_string());
        }
    }
    None
}

/// Extract the `name:` field from frontmatter, same rules as
/// `parse_description`. Only consumed by the build-time consistency
/// test that pins catalog name == frontmatter name.
#[cfg(test)]
fn parse_name(body: &str) -> Option<String> {
    parse_frontmatter_field(body, "name")
}

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

    /// A `SKILL.md` body file record with the given hash (`kind: Skill`).
    fn skill_file(hash: String) -> PiFileRecord {
        PiFileRecord {
            sha256: hash,
            kind: PiFileKind::Skill,
        }
    }

    /// A companion file record with the given hash (`kind: Companion`).
    fn companion_file(hash: String) -> PiFileRecord {
        PiFileRecord {
            sha256: hash,
            kind: PiFileKind::Companion,
        }
    }

    /// Build a `PiSkillRecord` from a body hash + companion `(filename, hash)`
    /// pairs — the flat-model test constructor.
    fn skill_record(
        cli_version: &str,
        body_hash: Option<String>,
        companions: &[(&str, String)],
    ) -> PiSkillRecord {
        let mut files: BTreeMap<String, PiFileRecord> = BTreeMap::new();
        if let Some(h) = body_hash {
            files.insert(PI_SKILL_FILENAME.to_string(), skill_file(h));
        }
        for (name, hash) in companions {
            files.insert((*name).to_string(), companion_file(hash.clone()));
        }
        PiSkillRecord {
            cli_version: cli_version.to_string(),
            files,
        }
    }

    #[test]
    fn every_embedded_skill_has_a_description_and_matching_name() {
        // Guards against frontmatter drift: if someone edits a SKILL.md
        // and breaks the `description:` line, `skill list` would silently
        // emit an empty string. Fail the build instead. Also pin
        // `name` equality between the catalog entry and the frontmatter
        // so a rename in one place can't quietly desync from the other.
        // (Review finding #5: extended to pin `cli_version` ==
        // CLI_VERSION and parseable `schema_version` so silent fallbacks
        // in `catalog()` and `cmd_print()` can't mask a broken template.)
        for s in SKILLS {
            let d = parse_description(s.body)
                .unwrap_or_else(|| panic!("skill {} missing description", s.name));
            assert!(!d.is_empty(), "skill {} has empty description", s.name);
            let n = parse_name(s.body).unwrap_or_else(|| panic!("skill {} missing name", s.name));
            assert_eq!(
                n, s.name,
                "catalog name {:?} does not match frontmatter name {:?}",
                s.name, n
            );
            let cli = parse_frontmatter_field(s.body, "cli_version")
                .unwrap_or_else(|| panic!("skill {} missing cli_version", s.name));
            assert_eq!(
                cli, CLI_VERSION,
                "skill {} cli_version {:?} does not match binary {:?}",
                s.name, cli, CLI_VERSION
            );
            let schema = parse_frontmatter_field(s.body, "schema_version")
                .unwrap_or_else(|| panic!("skill {} missing schema_version", s.name));
            let parsed: u32 = schema.parse().unwrap_or_else(|_| {
                panic!(
                    "skill {} has unparseable schema_version {:?}",
                    s.name, schema
                )
            });
            assert_eq!(
                parsed, SKILL_SCHEMA_VERSION,
                "skill {} schema_version {} != {}",
                s.name, parsed, SKILL_SCHEMA_VERSION
            );
            assert!(
                !s.body.contains("{{CLI_VERSION}}"),
                "skill {} still contains unrendered {{{{CLI_VERSION}}}} placeholder",
                s.name
            );
        }
    }

    #[test]
    fn every_companion_resource_is_rendered_and_version_pinned() {
        // The doctor `skill.sync.<name>.<file>` OK arm reports a companion
        // as "matching the bundled content for binary <CLI_VERSION>". That
        // claim only holds if the embedded companion body is fully rendered
        // (no leftover `{{CLI_VERSION}}` placeholder) and — when it carries
        // `cli_version` frontmatter at all — pins it to this binary's
        // version. Guard both here so a companion template can't silently
        // ship stale or unrendered.
        for name in SKILLS.iter().map(|s| s.name) {
            for r in resources_for(name) {
                assert!(
                    !r.body.contains("{{CLI_VERSION}}"),
                    "companion {} for skill {} still contains an unrendered {{{{CLI_VERSION}}}} placeholder",
                    r.filename,
                    name
                );
                if let Some(v) = parse_frontmatter_field(r.body, "cli_version") {
                    assert_eq!(
                        v, CLI_VERSION,
                        "companion {} for skill {} declares cli_version {:?}, binary is {:?}",
                        r.filename, name, v, CLI_VERSION
                    );
                }
            }
        }
    }

    #[test]
    fn every_claude_link_target_appears_in_some_skill_body() {
        // The codex rewrite is a literal `](target)` string replacement. If a
        // companion's `claude_link_target` ever drifts from the actual link
        // text in the skill bodies (a rename, a reflow), the rewrite silently
        // no-ops and codex ships a body still pointing at the un-resolvable
        // claude-layout path. Pin every declared target to real link text so
        // that drift fails the build instead of shipping a broken prompt.
        for skill in SKILLS {
            for r in resources_for(skill.name) {
                for target in r.claude_link_targets {
                    let needle = format!("]({target})");
                    assert!(
                        SKILLS.iter().any(|s| s.body.contains(&needle)),
                        "no skill body contains link {needle:?} declared for companion {} of {}",
                        r.filename,
                        skill.name
                    );
                }
            }
        }
    }

    #[test]
    fn render_body_for_claude_is_byte_identical_and_borrowed() {
        // The claude layout must be entirely unaffected by the codex rewrite:
        // every claude body is the embedded source, returned borrowed (no
        // reallocation, no byte change).
        for s in SKILLS {
            let rendered = render_body_for_agent("claude", s.body);
            assert!(
                matches!(rendered, Cow::Borrowed(_)),
                "claude body for {} was reallocated",
                s.name
            );
            assert_eq!(
                &*rendered, s.body,
                "claude body for {} was modified",
                s.name
            );
        }
    }

    #[test]
    fn render_body_for_codex_without_companion_links_is_noop() {
        // A codex body that references no companion is returned borrowed and
        // unchanged — the global rewrite table only touches bodies that carry
        // a declared link form.
        let no_links = SKILLS
            .iter()
            .find(|s| s.name == "octl-spawn-spinoff")
            .unwrap();
        let rendered = render_body_for_agent("codex", no_links.body);
        assert!(matches!(rendered, Cow::Borrowed(_)));
        assert_eq!(&*rendered, no_links.body);
    }

    #[test]
    fn stint_skills_pin_issuectl_dag_cutover() {
        for name in ["stint-start", "stint-handoff"] {
            let body = SKILLS.iter().find(|s| s.name == name).unwrap().body;
            assert!(body.contains("issuectl dag --json"), "{name}");
            for forbidden in [
                "AGENTS-EXECUTION-DAG.md",
                "execution-dag:begin",
                "execution-dag:end",
                "comm -3",
                "GLOBAL HEAD-OF-LINE",
                "collision:",
            ] {
                assert!(
                    !body.contains(forbidden),
                    "{name} still contains retired DAG notation {forbidden:?}"
                );
            }
        }
        for name in ["stint-start", "stint-handoff"] {
            let skill = SKILLS.iter().find(|s| s.name == name).unwrap();
            assert!(skill.body.contains("--reservations"), "{name}");
        }
    }

    #[test]
    fn codex_companion_path_derives_shared_subdir() {
        // Default layout: sibling `_shared/` next to the flat prompt file.
        assert_eq!(
            codex_companion_path(Path::new("/home/u/.codex/prompts/stint-start.md"), "X.md"),
            PathBuf::from("/home/u/.codex/prompts/_shared/X.md")
        );
        // Nested relative dest.
        assert_eq!(
            codex_companion_path(Path::new("out/prompts/s.md"), "X.md"),
            PathBuf::from("out/prompts/_shared/X.md")
        );
        // Bare-relative dest (empty parent): `_shared/` in the current dir,
        // which is where the flat prompt file itself lands — the rewritten
        // `_shared/X.md` link resolves relative to it.
        assert_eq!(
            codex_companion_path(Path::new("s.md"), "X.md"),
            PathBuf::from("_shared/X.md")
        );
    }

    #[test]
    fn write_marker_records_companions_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join(MANAGED_MARKER_FILENAME);
        write_marker(
            &marker,
            "stint-start",
            &["A.md".to_string(), "B.md".to_string()],
        )
        .unwrap();
        let recorded = read_managed_companions(&marker);
        assert_eq!(recorded, vec!["A.md".to_string(), "B.md".to_string()]);
        // A markerless dir records nothing.
        assert!(read_managed_companions(&dir.path().join("nope")).is_empty());
    }

    #[test]
    fn orphan_companions_flags_dropped_but_not_bundled() {
        // Simulate a prior binary that installed a companion this binary no
        // longer ships. The dropped file lingers and the marker still records it.
        let skill = "stint-start";
        let dir = tempfile::tempdir().unwrap();
        write_marker(
            &dir.path().join(MANAGED_MARKER_FILENAME),
            skill,
            &["OLD-COMPANION.md".to_string()],
        )
        .unwrap();
        fs::write(dir.path().join("OLD-COMPANION.md"), "stale").unwrap();

        let orphans = orphan_companions(skill, dir.path());
        assert_eq!(
            orphans,
            vec!["OLD-COMPANION.md".to_string()],
            "only the dropped-but-recorded companion is an orphan"
        );
    }

    #[test]
    fn orphan_companions_ignores_unrecorded_user_file() {
        // A file a user dropped into the managed dir that the marker never
        // recorded must NOT be flagged — that is the false-positive the
        // marker-based design exists to avoid.
        let skill = "stint-start";
        let bundled: Vec<String> = resources_for(skill)
            .iter()
            .map(|r| r.filename.to_string())
            .collect();
        let dir = tempfile::tempdir().unwrap();
        // Marker records only the bundled companions (a clean install).
        write_marker(&dir.path().join(MANAGED_MARKER_FILENAME), skill, &bundled).unwrap();
        // User drops their own note — never recorded in the marker.
        fs::write(dir.path().join("my-note.md"), "mine").unwrap();

        assert!(
            orphan_companions(skill, dir.path()).is_empty(),
            "an unrecorded user file is not an orphan"
        );
    }

    #[test]
    fn orphan_companions_ignores_recorded_but_absent_file() {
        // The marker records an orphan whose file was already removed: nothing
        // to clean, so it is not reported (a WARN with no fixable target would
        // be noise).
        let skill = "stint-start";
        let bundled: Vec<String> = resources_for(skill)
            .iter()
            .map(|r| r.filename.to_string())
            .collect();
        let dir = tempfile::tempdir().unwrap();
        let mut recorded = bundled.clone();
        recorded.push("GONE.md".to_string());
        write_marker(&dir.path().join(MANAGED_MARKER_FILENAME), skill, &recorded).unwrap();
        // `GONE.md` is NOT written to disk.
        assert!(orphan_companions(skill, dir.path()).is_empty());
    }

    #[test]
    fn codex_marker_records_prompts_and_companions_read_back() {
        // The single codex marker records both `prompt:` and `companion:`
        // lines; each key's reader returns only its own records.
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join(MANAGED_MARKER_FILENAME);
        write_codex_marker(
            &marker,
            &["stint-start".to_string(), "worktree-code".to_string()],
            &["REFERENCE.md".to_string()],
        )
        .unwrap();
        assert_eq!(
            read_marker_records(&marker, "prompt"),
            vec!["stint-start".to_string(), "worktree-code".to_string()]
        );
        assert_eq!(
            read_marker_records(&marker, "companion"),
            vec!["REFERENCE.md".to_string()]
        );
        // An absent marker records nothing for either key.
        let missing = dir.path().join("nope");
        assert!(read_marker_records(&missing, "prompt").is_empty());
        assert!(read_marker_records(&missing, "companion").is_empty());
    }

    #[test]
    fn all_companion_sources_dedupes_by_filename() {
        // Every declared companion filename is unique and the list is sorted;
        // the shared `_shared/` layout depends on one entry per filename.
        let sources = all_companion_sources();
        let mut names: Vec<&str> = sources.iter().map(|c| c.filename).collect();
        let mut sorted = names.clone();
        sorted.sort_unstable();
        assert_eq!(
            names, sorted,
            "companion sources must be sorted by filename"
        );
        names.dedup();
        assert_eq!(
            names.len(),
            sources.len(),
            "companion filenames must be unique across skills"
        );
    }

    #[test]
    fn prune_codex_file_outcomes() {
        let dir = tempfile::tempdir().unwrap();
        let mut warnings: Vec<String> = Vec::new();

        // A regular file is removed.
        let regular = dir.path().join("gone.md");
        fs::write(&regular, "stale").unwrap();
        assert!(matches!(
            prune_codex_file(&regular, "removed", "failed", &mut warnings),
            CodexPruneOutcome::Removed
        ));
        assert!(!regular.exists(), "file must be gone after Removed");
        assert!(warnings[0].starts_with("removed at "));

        // An absent file yields Dropped (nothing to clean).
        let absent = dir.path().join("never.md");
        assert!(matches!(
            prune_codex_file(&absent, "removed", "failed", &mut warnings),
            CodexPruneOutcome::Dropped
        ));

        // A directory squatting at the path is never removed (Dropped, not a
        // recursive delete).
        let squat = dir.path().join("squat.md");
        fs::create_dir(&squat).unwrap();
        assert!(matches!(
            prune_codex_file(&squat, "removed", "failed", &mut warnings),
            CodexPruneOutcome::Dropped
        ));
        assert!(squat.is_dir(), "a squatting dir must be left intact");
    }

    #[test]
    fn compare_versions_handles_semver_ordering() {
        use std::cmp::Ordering;
        // Pre-release is *less than* the release.
        assert_eq!(
            compare_versions("1.0.0-alpha", "1.0.0"),
            Some(Ordering::Less)
        );
        assert_eq!(
            compare_versions("1.0.0", "1.0.0-alpha"),
            Some(Ordering::Greater)
        );
        // Standard numeric ordering.
        assert_eq!(compare_versions("1.10.0", "1.9.0"), Some(Ordering::Greater));
        assert_eq!(compare_versions("0.0.1", "0.0.1"), Some(Ordering::Equal));
        // Unparseable → None so callers route to the legacy arm.
        assert_eq!(compare_versions("banana", "1.0.0"), None);
        assert_eq!(compare_versions("1.0.0", "1.x"), None);
        assert_eq!(compare_versions("{{CLI_VERSION}}", "1.0.0"), None);
    }

    #[test]
    fn parse_description_extracts_value() {
        let body = "---\nname: foo\ndescription: a short blurb\nversion: 1\n---\n\n# body\n";
        assert_eq!(parse_description(body).as_deref(), Some("a short blurb"));
    }

    #[test]
    fn parse_description_handles_crlf() {
        let body = "---\r\nname: foo\r\ndescription: blurb\r\n---\r\n";
        assert_eq!(parse_description(body).as_deref(), Some("blurb"));
    }

    #[test]
    fn parse_description_strips_quotes() {
        let body = "---\ndescription: \"quoted blurb\"\n---\n";
        assert_eq!(parse_description(body).as_deref(), Some("quoted blurb"));
    }

    #[test]
    fn parse_description_returns_none_without_frontmatter() {
        assert_eq!(parse_description("# just a heading\n"), None);
    }

    #[test]
    fn parse_description_returns_none_when_field_absent() {
        let body = "---\nname: foo\nversion: 1\n---\n";
        assert_eq!(parse_description(body), None);
    }

    /// Every bundled skill's `description:` frontmatter must fit pi.dev's
    /// 1024-*character* limit — pi warns on load past it and drops the
    /// overflow, degrading skill selection (issue
    /// `stint-skill-desc-over-pi-limit`). Counted in Unicode scalar values,
    /// not bytes, because the descriptions carry multi-byte glyphs (ä, →).
    #[test]
    fn bundled_descriptions_fit_pi_char_limit() {
        const PI_DESCRIPTION_LIMIT: usize = 1024;
        for skill in SKILLS {
            let desc = parse_description(skill.body)
                .unwrap_or_else(|| panic!("skill {} has no description", skill.name));
            let chars = desc.chars().count();
            assert!(
                chars <= PI_DESCRIPTION_LIMIT,
                "skill {} description is {chars} chars (> {PI_DESCRIPTION_LIMIT} pi.dev limit)",
                skill.name
            );
        }
    }

    #[test]
    fn sha256_hex_is_deterministic_and_lowercase() {
        let a = sha256_hex(b"hello");
        assert_eq!(a, sha256_hex(b"hello"));
        assert_ne!(a, sha256_hex(b"world"));
        assert_eq!(a.len(), 64);
        assert!(a
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
        // Known vector for "hello".
        assert_eq!(
            a,
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn pi_provenance_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state").join("pi-installed-skills.json");
        let mut prov = PiProvenance {
            schema_version: PI_PROVENANCE_SCHEMA_VERSION,
            skills: BTreeMap::new(),
        };
        prov.skills.insert(
            "stint-start".to_string(),
            skill_record("0.1.7", Some(sha256_hex(b"body-a")), &[]),
        );
        // Parent dir does not exist yet — the write must create `state/`.
        write_pi_provenance(&path, &prov).unwrap();
        let read_back = read_pi_provenance(&path);
        assert_eq!(read_back.schema_version, PI_PROVENANCE_SCHEMA_VERSION);
        assert_eq!(
            read_back
                .skills
                .get("stint-start")
                .and_then(|r| r.body_hash().map(str::to_string)),
            Some(sha256_hex(b"body-a"))
        );
    }

    #[test]
    fn read_pi_provenance_tolerates_missing_and_garbage() {
        let dir = tempfile::tempdir().unwrap();
        // Missing file → empty default.
        let missing = dir.path().join("nope.json");
        assert!(read_pi_provenance(&missing).skills.is_empty());
        // Unparseable content → empty default (err toward NOT managing).
        let garbage = dir.path().join("garbage.json");
        fs::write(&garbage, "{ not json").unwrap();
        assert!(read_pi_provenance(&garbage).skills.is_empty());
        // Future-schema record → lenient reader treats it as empty (doctor
        // must not audit a record a newer binary wrote).
        let future = dir.path().join("future.json");
        fs::write(&future, r#"{"schema_version":999,"skills":{}}"#).unwrap();
        assert!(read_pi_provenance(&future).skills.is_empty());
    }

    #[test]
    fn load_pi_provenance_for_write_fails_closed_on_corruption() {
        let dir = tempfile::tempdir().unwrap();
        // Missing → Ok(empty): a first install starts fresh.
        let missing = dir.path().join("nope.json");
        assert!(load_pi_provenance_for_write(&missing)
            .unwrap()
            .skills
            .is_empty());
        // Unparseable → Err (never launder + overwrite, which would erase all
        // tracking).
        let garbage = dir.path().join("garbage.json");
        fs::write(&garbage, "{ not json").unwrap();
        let err = load_pi_provenance_for_write(&garbage).unwrap_err();
        assert_eq!(err.code, "pi_provenance_corrupt");
        // Future schema → Err (an older binary must not downgrade-overwrite it).
        let future = dir.path().join("future.json");
        fs::write(&future, r#"{"schema_version":999,"skills":{}}"#).unwrap();
        let err = load_pi_provenance_for_write(&future).unwrap_err();
        assert_eq!(err.code, "pi_provenance_schema_too_new");
    }

    #[test]
    fn is_simple_skill_name_rejects_traversal_and_absolute() {
        assert!(is_simple_skill_name("stint-start"));
        assert!(is_simple_skill_name("worktree-code"));
        assert!(!is_simple_skill_name("../../.bashrc"));
        assert!(!is_simple_skill_name("a/b"));
        assert!(!is_simple_skill_name("/etc/passwd"));
        assert!(!is_simple_skill_name(".."));
        assert!(!is_simple_skill_name(""));
    }

    #[test]
    fn write_pi_provenance_replaces_squatting_symlink() {
        // A symlink squatting at the record path must be replaced by the atomic
        // rename, never followed to clobber its target.
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("victim.txt");
        fs::write(&target, "precious").unwrap();
        let record = dir.path().join("pi-installed-skills.json");
        std::os::unix::fs::symlink(&target, &record).unwrap();

        let prov = PiProvenance {
            schema_version: PI_PROVENANCE_SCHEMA_VERSION,
            skills: BTreeMap::new(),
        };
        write_pi_provenance(&record, &prov).unwrap();

        // The victim is untouched; the record path is now a regular file.
        assert_eq!(fs::read_to_string(&target).unwrap(), "precious");
        assert!(fs::symlink_metadata(&record).unwrap().file_type().is_file());
    }

    #[test]
    fn prune_pi_mirror_removes_our_unmodified_copy_and_empty_dir() {
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        let body = b"---\nname: old-skill\n---\nbody\n";
        fs::write(&mirror, body).unwrap();

        let mut rec = skill_record("0.1.0", Some(sha256_hex(body)), &[]);
        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(summary.body_removed);
        assert!(rec.files.is_empty(), "record fully cleared");
        assert!(!mirror.exists(), "mirror file must be gone");
        assert!(
            !skill_dir.exists(),
            "empty per-skill dir must be cleaned up"
        );
        assert!(warnings.iter().any(|w| w.starts_with("pi_mirror_pruned:")));
    }

    #[test]
    fn prune_pi_mirror_removes_recorded_companions_then_empty_dir() {
        // A de-registered skill's recorded companions are removed alongside its
        // SKILL.md so the per-skill dir empties out. A companion that has since
        // diverged from what we wrote is LEFT in place (and keeps the dir).
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        let body = b"---\nname: old-skill\n---\nbody\n";
        fs::write(&mirror, body).unwrap();
        let comp_body = b"companion payload\n";
        fs::write(skill_dir.join("REFERENCE.md"), comp_body).unwrap();
        // A second recorded companion the user has since edited: must survive.
        fs::write(skill_dir.join("EDITED.md"), b"user changed this").unwrap();

        let mut rec = skill_record(
            "0.1.0",
            Some(sha256_hex(body)),
            &[
                ("REFERENCE.md", sha256_hex(comp_body)),
                ("EDITED.md", sha256_hex(b"original edited body")),
            ],
        );

        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(summary.body_removed);
        assert!(!mirror.exists(), "SKILL.md removed");
        assert!(
            !skill_dir.join("REFERENCE.md").exists(),
            "our unmodified companion is removed"
        );
        assert!(
            skill_dir.join("EDITED.md").exists(),
            "a diverged companion is preserved"
        );
        // The dir is NOT empty (the diverged companion remains), so it survives.
        assert!(skill_dir.exists(), "dir with a surviving companion is kept");
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_companion_pruned:")));
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_companion_diverged:")));
    }

    #[test]
    fn prune_pi_mirror_removes_all_matching_companions_and_empty_dir() {
        // When every recorded companion is our unmodified copy, both it and the
        // SKILL.md are removed and the now-empty dir is cleaned up.
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        let body = b"body\n";
        fs::write(&mirror, body).unwrap();
        let c1 = b"c1\n";
        let c2 = b"c2\n";
        fs::write(skill_dir.join("A.md"), c1).unwrap();
        fs::write(skill_dir.join("B.md"), c2).unwrap();
        let mut rec = skill_record(
            "0.1.0",
            Some(sha256_hex(body)),
            &[("A.md", sha256_hex(c1)), ("B.md", sha256_hex(c2))],
        );

        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(summary.body_removed);
        assert!(rec.files.is_empty(), "record fully cleared");
        assert!(!skill_dir.exists(), "fully-cleaned dir must be removed");
    }

    #[test]
    fn prune_pi_mirror_cleans_companions_when_skill_md_absent() {
        // A prior partial prune left the SKILL.md gone but a recorded companion
        // behind. The prune must still clean the companion (never strand it) and
        // remove the now-empty dir. The body was already gone (absent), so
        // `body_removed` is false and the record clears out.
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let comp = b"companion\n";
        fs::write(skill_dir.join("C.md"), comp).unwrap();
        // Record still tracks the (now-absent) body plus the leftover companion.
        let mut rec = skill_record(
            "0.1.0",
            Some("irrelevant-body-hash".to_string()),
            &[("C.md", sha256_hex(comp))],
        );

        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed, "absent body was not deleted by us");
        assert!(
            rec.files.is_empty(),
            "record cleared (companion + absent body)"
        );
        assert!(
            !skill_dir.join("C.md").exists(),
            "recorded companion cleaned even with an absent SKILL.md"
        );
        assert!(!skill_dir.exists(), "now-empty dir removed");
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_companion_pruned:")));
    }

    #[test]
    fn prune_pi_mirror_diverged_body_still_prunes_unmodified_companion() {
        // Flat per-file model: a user-edited SKILL.md is relinquished (left in
        // place, dropped from tracking), but an UNMODIFIED companion is still our
        // copy and IS pruned — the body's divergence no longer shields the
        // companions (issue `pi-provenance-flat-file-model`). The surviving
        // diverged body keeps the dir.
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        fs::write(&mirror, b"user edited body").unwrap();
        let comp = b"companion\n";
        fs::write(skill_dir.join("C.md"), comp).unwrap();
        let mut rec = skill_record(
            "0.1.0",
            Some(sha256_hex(b"the body we originally wrote")),
            &[("C.md", sha256_hex(comp))],
        );

        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed, "diverged body is not deleted");
        assert!(mirror.exists(), "diverged body is left in place");
        assert!(
            !skill_dir.join("C.md").exists(),
            "an unmodified companion is pruned even though the body diverged"
        );
        assert!(
            skill_dir.exists(),
            "the surviving diverged body keeps the dir"
        );
        assert!(
            rec.files.is_empty(),
            "both files relinquished/pruned from tracking"
        );
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_mirror_diverged:")));
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_companion_pruned:")));
    }

    #[test]
    fn reconcile_pi_companions_force_removes_dropped_companion() {
        // A still-registered skill whose record tracks companions the binary no
        // longer bundles: under --force every orphan is removed from disk and record.
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();
        // The fixture carries two companions from the prior catalog.
        let dag = b"dag body\n";
        let old = b"old body\n";
        fs::write(dir.join("REFERENCE.md"), dag).unwrap();
        fs::write(dir.join("OLD.md"), old).unwrap();

        let mut rec = skill_record(
            CLI_VERSION,
            Some(sha256_hex(b"skill body")),
            &[
                ("REFERENCE.md", sha256_hex(dag)),
                ("OLD.md", sha256_hex(old)),
            ],
        );

        let mut pruned = Vec::new();
        let mut warnings = Vec::new();
        reconcile_pi_companions_at(
            "stint-start",
            &mut rec,
            dir,
            true,
            &mut pruned,
            &mut warnings,
        );

        assert_eq!(
            pruned,
            vec![
                "stint-start/OLD.md".to_string(),
                "stint-start/REFERENCE.md".to_string(),
            ]
        );
        assert!(!rec.files.contains_key("REFERENCE.md"));
        assert!(!rec.files.contains_key("OLD.md"));
        assert!(!dir.join("OLD.md").exists());
        assert!(!dir.join("REFERENCE.md").exists());
    }

    #[test]
    fn reconcile_pi_companions_non_force_keeps_orphan_tracked() {
        // Without --force the stale companion is LEFT tracked so `doctor` keeps
        // flagging it (its --force fix is what clears it).
        let dir = tempfile::tempdir().unwrap();
        let dir = dir.path();
        fs::write(dir.join("OLD.md"), b"old\n").unwrap();

        let mut rec = skill_record(
            CLI_VERSION,
            Some(sha256_hex(b"body")),
            &[("OLD.md", sha256_hex(b"old\n"))],
        );

        let mut pruned = Vec::new();
        let mut warnings = Vec::new();
        reconcile_pi_companions_at(
            "stint-start",
            &mut rec,
            dir,
            false,
            &mut pruned,
            &mut warnings,
        );

        assert!(pruned.is_empty(), "non-force prunes nothing");
        assert!(
            rec.files.contains_key("OLD.md"),
            "orphan stays tracked without --force"
        );
        assert!(dir.join("OLD.md").exists(), "orphan file left on disk");
    }

    #[test]
    fn pi_provenance_v1_record_reads_and_upgrades_to_v3() {
        // A legacy v1 record (bare `sha256`/`cli_version`, no companions) upgrades
        // in place on load: the body `sha256` becomes the `SKILL.md` file entry,
        // and a fresh write stamps the current schema (v3, flat `files`).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state").join("pi-installed-skills.json");
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(
            &path,
            r#"{"schema_version":1,"skills":{"stint-start":{"sha256":"aa","cli_version":"0.1.0"}}}"#,
        )
        .unwrap();
        let mut prov = load_pi_provenance_for_write(&path).unwrap();
        assert_eq!(prov.schema_version, 1, "read preserves the on-disk version");
        let rec = &prov.skills["stint-start"];
        assert_eq!(
            rec.body_hash(),
            Some("aa"),
            "legacy body hash upgraded to a Skill file"
        );
        assert!(rec.companion_names().is_empty(), "v1 had no companions");
        // A write stamps the current (v3) schema with the flat `files` shape.
        prov.schema_version = PI_PROVENANCE_SCHEMA_VERSION;
        write_pi_provenance(&path, &prov).unwrap();
        let reread: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(reread["schema_version"], 3);
        assert_eq!(
            reread["skills"]["stint-start"]["files"]["SKILL.md"]["sha256"],
            "aa"
        );
        assert_eq!(
            reread["skills"]["stint-start"]["files"]["SKILL.md"]["kind"],
            "skill"
        );
    }

    #[test]
    fn pi_provenance_v2_record_upgrades_companions_to_files() {
        // A v2 record (body `sha256` + `companions` map) upgrades so the body and
        // each companion become independent `files` entries with the right kind.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pi.json");
        fs::write(
            &path,
            r#"{"schema_version":2,"skills":{"stint-start":{"sha256":"bb","cli_version":"0.1.0","companions":{"REFERENCE.md":"cc"}}}}"#,
        )
        .unwrap();
        let prov = load_pi_provenance_for_write(&path).unwrap();
        let rec = &prov.skills["stint-start"];
        assert_eq!(rec.body_hash(), Some("bb"));
        assert_eq!(rec.companion_names(), vec!["REFERENCE.md".to_string()]);
        assert_eq!(rec.files["REFERENCE.md"].kind, PiFileKind::Companion);
    }

    #[test]
    fn pi_upgrade_drops_empty_legacy_hashes_and_skill_md_companion() {
        // A legacy record with an empty body hash must NOT mint a fake `SKILL.md`
        // entry (which would make doctor spuriously flag the real body as
        // "differs"); an empty companion hash is dropped; and a legacy companion
        // keyed `SKILL.md` (any case) must never alias/overwrite the body entry.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pi.json");
        fs::write(
            &path,
            r#"{"schema_version":2,"skills":{"s":{"sha256":"","cli_version":"0.1.0","companions":{"REFERENCE.md":"aa","EMPTY.md":"","SKILL.md":"bb","skill.md":"cc"}}}}"#,
        )
        .unwrap();
        let prov = load_pi_provenance_for_write(&path).unwrap();
        let rec = &prov.skills["s"];
        assert_eq!(
            rec.body_hash(),
            None,
            "empty legacy body hash → no body entry"
        );
        assert_eq!(
            rec.companion_names(),
            vec!["REFERENCE.md".to_string()],
            "empty-hash and SKILL.md-aliasing companions are dropped"
        );
    }

    #[test]
    fn pi_managed_skills_body_hash_is_none_for_companion_only_record() {
        // A companion-only record (body write skipped) surfaces `sha256: None`
        // rather than an empty string, so doctor skips the content-edit check.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("state").join("pi-installed-skills.json");
        let mut prov = PiProvenance {
            schema_version: PI_PROVENANCE_SCHEMA_VERSION,
            skills: BTreeMap::new(),
        };
        prov.skills.insert(
            "s".to_string(),
            skill_record("", None, &[("C.md", sha256_hex(b"c"))]),
        );
        write_pi_provenance(&path, &prov).unwrap();
        // Point pi_managed_skills at this record via ORCHESTRATECTL_HOME.
        let read = read_pi_provenance(&path);
        let rec = &read.skills["s"];
        assert_eq!(rec.body_hash(), None);
        assert_eq!(rec.companion_names(), vec!["C.md".to_string()]);
    }

    #[test]
    fn pi_provenance_v3_record_round_trips_untouched() {
        // A native v3 record with a `files` map is taken verbatim (the legacy
        // upgrade only fires when `files` is empty).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pi.json");
        fs::write(
            &path,
            r#"{"schema_version":3,"skills":{"s":{"cli_version":"1.0.0","files":{"SKILL.md":{"sha256":"dd","kind":"skill"},"C.md":{"sha256":"ee","kind":"companion"}}}}}"#,
        )
        .unwrap();
        let prov = load_pi_provenance_for_write(&path).unwrap();
        let rec = &prov.skills["s"];
        assert_eq!(rec.body_hash(), Some("dd"));
        assert_eq!(rec.files["C.md"].sha256, "ee");
        assert_eq!(rec.files["C.md"].kind, PiFileKind::Companion);
    }

    #[test]
    fn prune_pi_mirror_preserves_dir_with_user_sibling() {
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        let body = b"our body\n";
        fs::write(&mirror, body).unwrap();
        // A user-added sibling in the same dir.
        fs::write(skill_dir.join("notes.md"), "mine").unwrap();

        let mut rec = skill_record("0.1.0", Some(sha256_hex(body)), &[]);
        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(summary.body_removed);
        assert!(rec.files.is_empty(), "our body relinquished from tracking");
        assert!(!mirror.exists(), "our SKILL.md is removed");
        assert!(skill_dir.exists(), "non-empty dir is preserved");
        assert!(skill_dir.join("notes.md").exists(), "user sibling survives");
    }

    #[test]
    fn prune_pi_mirror_refuses_diverged_copy() {
        let root = tempfile::tempdir().unwrap();
        let skill_dir = root.path().join("old-skill");
        fs::create_dir_all(&skill_dir).unwrap();
        let mirror = skill_dir.join("SKILL.md");
        fs::write(&mirror, b"user has edited this").unwrap();

        // Recorded hash is of the ORIGINAL body we wrote, which no longer matches.
        let mut rec = skill_record("0.1.0", Some(sha256_hex(b"original body")), &[]);
        let mut warnings = Vec::new();
        let summary = prune_pi_mirror_at(
            "old-skill",
            &skill_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed, "a diverged copy is not deleted");
        assert!(
            rec.files.is_empty(),
            "the diverged body is relinquished from tracking"
        );
        assert!(
            mirror.exists(),
            "a diverged (user-owned) copy is NOT deleted"
        );
        assert!(warnings
            .iter()
            .any(|w| w.starts_with("pi_mirror_diverged:")));
    }

    #[test]
    fn prune_pi_mirror_drops_absent_symlink_and_dir() {
        let root = tempfile::tempdir().unwrap();
        let mut warnings = Vec::new();

        // Absent body: a per-skill dir that does not exist. Nothing to delete;
        // the record clears and nothing is reported removed.
        let mut rec = skill_record("0.1.0", Some("anyhash".to_string()), &[]);
        let summary = prune_pi_mirror_at(
            "gone",
            &root.path().join("gone"),
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed);
        assert!(rec.files.is_empty(), "absent body dropped from tracking");

        // A directory squatting where SKILL.md should be is never removed.
        let squat_dir = root.path().join("squat");
        fs::create_dir_all(squat_dir.join(PI_SKILL_FILENAME)).unwrap();
        let mut rec = skill_record("0.1.0", Some("anyhash".to_string()), &[]);
        let summary = prune_pi_mirror_at(
            "squat",
            &squat_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed);
        assert!(
            squat_dir.join(PI_SKILL_FILENAME).is_dir(),
            "a squatting dir must be left intact"
        );

        // A symlink at the body path is never followed/deleted.
        let link_dir = root.path().join("linked");
        fs::create_dir_all(&link_dir).unwrap();
        let real = root.path().join("real.md");
        fs::write(&real, b"body").unwrap();
        std::os::unix::fs::symlink(&real, link_dir.join(PI_SKILL_FILENAME)).unwrap();
        let mut rec = skill_record("0.1.0", Some(sha256_hex(b"body")), &[]);
        let summary = prune_pi_mirror_at(
            "linked",
            &link_dir,
            Some(root.path()),
            &mut rec,
            &mut warnings,
        );
        assert!(!summary.body_removed);
        assert!(
            link_dir.join(PI_SKILL_FILENAME).exists(),
            "the symlink is left intact"
        );
        assert!(real.exists(), "the symlink target is untouched");
    }
}