dalo 1.11.1

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

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::fs::MetadataExt;
use std::path::Component;
use std::path::{Path, PathBuf};

use rustix::fs::{CWD, Gid, RenameFlags, Uid, fchown, renameat_with};
use rustix::io::Errno;
use serde::Serialize;
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;

use crate::error::{DaloError, DaloResult};
use crate::git;
use crate::lockfile::LockedInstructionPack;
use crate::source::{SourceConfig, SourceKind};
use crate::store::{self, ApprovalRecord, StorePaths};

const START_MARKER_PREFIX: &str = "<!-- dalo:start ";
const END_MARKER_PREFIX: &str = "<!-- dalo:end ";

/// A versioned instruction pack: standing agent-facing conventions as Markdown.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionPack {
    /// Pack ID.
    pub id: String,
    /// Declared version, when present in frontmatter.
    pub version: Option<String>,
    /// Rendered Markdown body.
    pub body: String,
}

/// Report from enabling or disabling an instruction pack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionPackReport {
    /// Pack ID.
    pub pack_id: String,
    /// Source that owns the pack.
    pub source_id: String,
    /// Instruction-file target affected.
    pub target: PathBuf,
    /// What happened: `enabled`, `disabled`, or `unchanged`.
    pub action: String,
    /// Whether the command ran as dry-run.
    pub dry_run: bool,
    /// Non-fatal recovery detail, such as a malformed block left untouched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
}

/// Preview or result of keeping an edited source-backed block as a local pack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionAdoptReport {
    /// Source-qualified pack being replaced in this target.
    pub source_ref: String,
    /// Local pack ID.
    pub pack_id: String,
    /// Physical instruction target affected.
    pub target: PathBuf,
    /// New pack in the local Git source, left uncommitted for review.
    pub local_path: PathBuf,
    /// Exact source commit from which the active block originated.
    pub source_commit: String,
    /// Adopted Markdown body, without markers or generated metadata.
    pub body: String,
    /// Whether this is a preview without filesystem mutations.
    pub dry_run: bool,
}

/// Report from enabling or disabling one pack across logical agent targets.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionPackBatchReport {
    /// Pack ID.
    pub pack_id: String,
    /// Source that owns the pack.
    pub source_id: String,
    /// De-duplicated physical destination operations.
    pub operations: Vec<InstructionTargetOperationReport>,
    /// Whether the command ran as dry-run.
    pub dry_run: bool,
}

/// One de-duplicated instruction-file operation in a batch report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionTargetOperationReport {
    /// Logical target IDs mapped to this physical destination.
    pub logical_targets: Vec<String>,
    /// Effective physical instruction-file path.
    pub target: PathBuf,
    /// What happened: `enabled`, `disabled`, or `unchanged`.
    pub action: String,
    /// Non-fatal recovery detail, such as a malformed block left untouched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
}

/// One source-backed instruction update performed as part of `dalo sync`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionSyncOperation {
    /// Source that owns the already-active pack.
    pub source_id: String,
    /// Pack ID.
    pub pack_id: String,
    /// Effective physical instruction-file path.
    pub target: PathBuf,
    /// What happened: `refreshed` or `unchanged`.
    pub action: String,
    /// Previously rendered immutable source commit.
    pub previous_commit: String,
    /// Newly rendered immutable source commit.
    pub commit: String,
}

/// Result of reconciling already-active source-backed packs during sync.
#[derive(Debug)]
pub struct InstructionSyncResult {
    /// Updated lock entries, preserving local packs unchanged.
    pub active_instruction_packs: Vec<LockedInstructionPack>,
    /// Source revisions considered by this sync.
    pub operations: Vec<InstructionSyncOperation>,
    /// Packs deactivated because their manifest-derived source was removed.
    pub removal_operations: Vec<InstructionRemovalOperation>,
    /// Target snapshots retained until the companion user lock is committed.
    pub rollback: Option<InstructionRefreshRollback>,
}

/// One active instruction pack removed with its owning source.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionRemovalOperation {
    /// Source that owned the pack.
    pub source_id: String,
    /// Pack ID.
    pub pack_id: String,
    /// Effective physical instruction-file path.
    pub target: PathBuf,
    /// What happened: `removed` or `lock_removed`.
    pub action: String,
    /// Recovery detail when the managed block could not be removed safely.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
}

/// Result of removing active packs whose owning sources are being removed.
#[derive(Debug)]
pub struct InstructionSourceRemovalResult {
    /// Lock entries that remain active after removal.
    pub active_instruction_packs: Vec<LockedInstructionPack>,
    /// Pack removals for human and JSON reporting.
    pub operations: Vec<InstructionRemovalOperation>,
    /// Target snapshots retained until source-removal metadata commits.
    pub rollback: Option<InstructionRefreshRollback>,
}

/// In-memory rollback for instruction target writes awaiting lock commit.
#[derive(Debug)]
pub struct InstructionRefreshRollback {
    prepared: Vec<PreparedInstructionMutation>,
    written: Vec<(usize, TargetIdentity)>,
    _target_locks: Vec<TargetLock>,
}

impl InstructionRefreshRollback {
    /// Restore every instruction target written by the pending sync.
    pub fn restore(self) -> DaloResult<()> {
        let mut failures = Vec::new();
        for (index, identity) in self.written.iter().rev() {
            let mutation = &self.prepared[*index];
            let snapshot = TargetSnapshot {
                target: mutation.snapshot.target.clone(),
                content: mutation.snapshot.content.clone(),
                identity: mutation.snapshot.identity,
            };
            if let Err(error) = restore_target(
                snapshot,
                mutation
                    .rendered
                    .as_deref()
                    .expect("only rendered mutations are recorded as written"),
                *identity,
            ) {
                failures.push(error.to_string());
            }
        }
        if failures.is_empty() {
            Ok(())
        } else {
            Err(DaloError::Io(std::io::Error::other(failures.join("; "))))
        }
    }
}

/// Enable one pack across de-duplicated logical target destinations.
pub fn enable_pack_for_targets(
    paths: &StorePaths,
    selector: &str,
    destinations: &[crate::target::InstructionFileDestination],
    dry_run: bool,
) -> DaloResult<InstructionPackBatchReport> {
    if destinations.is_empty() {
        return Err(DaloError::InvalidArgument {
            reason: "at least one instruction target is required".to_owned(),
        });
    }
    let resolved = resolve_pack(paths, selector)?;
    let marker_id = marker_id(&resolved.source_id, &resolved.pack.id);
    let mut prepared = Vec::with_capacity(destinations.len());
    let mut target_locks = Vec::with_capacity(destinations.len());
    for destination in destinations {
        let target = normalize_target_path(&destination.path)?;
        target_locks.push(acquire_target_lock(paths, &target)?);
        let snapshot = target_snapshot(&target)?;
        let existing = snapshot.content.clone().unwrap_or_default();
        let rendered = render_pack_block(&existing, &marker_id, &resolved.pack.body)?;
        prepared.push(PreparedInstructionMutation {
            logical_targets: destination.logical_targets.clone(),
            target,
            snapshot,
            rendered: Some(rendered),
            action: "enabled".to_owned(),
            warning: None,
        });
    }
    let mut lock = store::read_user_lock(paths)?;
    for mutation in &prepared {
        lock.active_instruction_packs.retain(|entry| {
            !(entry.source_id == resolved.source_id
                && entry.pack_id == resolved.pack.id
                && targets_match(entry, &mutation.target))
        });
        lock.active_instruction_packs.push(LockedInstructionPack {
            pack_id: resolved.pack.id.clone(),
            target: mutation.target.clone(),
            logical_targets: mutation.logical_targets.clone(),
            source_id: resolved.source_id.clone(),
            commit: resolved.commit.clone(),
            version: resolved.pack.version.clone(),
        });
    }
    sort_instruction_lock_entries(&mut lock.active_instruction_packs);
    if !dry_run {
        apply_prepared_instruction_mutations(paths, prepared.as_mut_slice(), &lock)?;
    }
    let operations = prepared
        .into_iter()
        .map(PreparedInstructionMutation::into_report)
        .collect();
    drop(target_locks);
    Ok(InstructionPackBatchReport {
        pack_id: resolved.pack.id,
        source_id: resolved.source_id,
        operations,
        dry_run,
    })
}

/// Disable one pack across de-duplicated logical target destinations.
pub fn disable_pack_for_targets(
    paths: &StorePaths,
    selector: &str,
    destinations: &[crate::target::InstructionFileDestination],
    dry_run: bool,
) -> DaloResult<InstructionPackBatchReport> {
    if destinations.is_empty() {
        return Err(DaloError::InvalidArgument {
            reason: "at least one instruction target is required".to_owned(),
        });
    }
    let (source_id, pack_id) = parse_pack_selector(selector)?;
    let marker_id = marker_id(&source_id, &pack_id);
    let mut lock = store::read_user_lock(paths)?;
    let mut prepared = Vec::with_capacity(destinations.len());
    let mut target_locks = Vec::with_capacity(destinations.len());
    for destination in destinations {
        let target = normalize_target_path(&destination.path)?;
        target_locks.push(acquire_target_lock(paths, &target)?);
        let snapshot = target_snapshot(&target)?;
        let existing = snapshot.content.clone().unwrap_or_default();
        let (block, malformed_error) = match find_block(&existing, &marker_id) {
            Ok(block) => (block, None),
            Err(error) => (None, Some(error.to_string())),
        };
        let has_block = block.is_some();
        let has_lock_entry = lock.active_instruction_packs.iter().any(|entry| {
            entry.source_id == source_id
                && entry.pack_id == pack_id
                && targets_match(entry, &target)
        });
        let warning = malformed_error.map(|error| {
            let lock_action = if has_lock_entry {
                if dry_run {
                    "the lock entry would be removed"
                } else {
                    "the lock entry was removed"
                }
            } else {
                "no matching lock entry was found"
            };
            format!("{error}; target left untouched and {lock_action}")
        });
        let rendered = if warning.is_none() && has_block {
            Some(remove_block(&existing, &marker_id)?)
        } else {
            None
        };
        prepared.push(PreparedInstructionMutation {
            logical_targets: destination.logical_targets.clone(),
            target,
            snapshot,
            rendered,
            action: if has_block || has_lock_entry {
                "disabled".to_owned()
            } else {
                "unchanged".to_owned()
            },
            warning,
        });
    }
    let lock_changed = lock.active_instruction_packs.iter().any(|entry| {
        entry.source_id == source_id
            && entry.pack_id == pack_id
            && prepared
                .iter()
                .any(|mutation| targets_match(entry, &mutation.target))
    });
    lock.active_instruction_packs.retain(|entry| {
        !(entry.source_id == source_id
            && entry.pack_id == pack_id
            && prepared
                .iter()
                .any(|mutation| targets_match(entry, &mutation.target)))
    });
    if !dry_run {
        if lock_changed {
            apply_prepared_instruction_mutations(paths, prepared.as_mut_slice(), &lock)?;
        } else {
            apply_prepared_target_writes(prepared.as_mut_slice())?;
        }
    }
    let operations = prepared
        .into_iter()
        .map(PreparedInstructionMutation::into_report)
        .collect();
    drop(target_locks);
    Ok(InstructionPackBatchReport {
        pack_id,
        source_id,
        operations,
        dry_run,
    })
}

#[derive(Debug)]
struct PendingPackRefresh {
    entry_index: usize,
    old_body: String,
    pack: InstructionPack,
    provenance: PendingPackRefreshProvenance,
}

#[derive(Debug)]
enum PendingPackRefreshProvenance {
    Local,
    Source {
        updated_entry_index: usize,
        previous_commit: String,
        commit: String,
    },
}

#[derive(Debug, Default)]
struct PendingInstructionTargetSync {
    refreshes: Vec<PendingPackRefresh>,
    removal_entry_indexes: Vec<usize>,
}

/// Reconcile source-backed packs and migrate legacy local packs in the user lock.
///
/// Source approval is checked again on every sync. The previously rendered
/// managed block must still match its immutable source revision before Dalo
/// will replace it, so revoked trust or external block edits fail closed.
/// Local packs retain their lock provenance and only migrate blocks that match
/// Dalo's exact legacy rendering.
/// Packs owned by manifest-derived sources removed in the same sync are
/// deactivated inside the same target-and-lock transaction.
pub fn refresh_active_packs(
    paths: &StorePaths,
    sources: &[SourceConfig],
    approvals: &[ApprovalRecord],
    active: &[LockedInstructionPack],
    removed_source_ids: &BTreeSet<String>,
    dry_run: bool,
) -> DaloResult<InstructionSyncResult> {
    let mut updated = active
        .iter()
        .filter(|entry| !removed_source_ids.contains(&entry.source_id))
        .cloned()
        .collect::<Vec<_>>();
    let mut grouped = BTreeMap::<PathBuf, PendingInstructionTargetSync>::new();

    for (entry_index, entry) in active.iter().enumerate() {
        if removed_source_ids.contains(&entry.source_id) {
            grouped
                .entry(lock_entry_target_path(paths, &entry.target))
                .or_default()
                .removal_entry_indexes
                .push(entry_index);
            continue;
        }
        let (old_body, pack, provenance) = if entry.source_id == "local" {
            let pack = read_local_pack(paths, &entry.pack_id)?;
            (pack.body.clone(), pack, PendingPackRefreshProvenance::Local)
        } else {
            let source = sources
                .iter()
                .find(|source| source.id == entry.source_id)
                .ok_or_else(|| {
                    DaloError::StateError {
                        reason: format!(
                            "active instruction pack `{}` references missing source `{}`; restore the source or disable the pack",
                            pack_ref(&entry.source_id, &entry.pack_id),
                            entry.source_id
                        ),
                    }
                })?;
            if !source.enabled {
                return Err(DaloError::StateError {
                    reason: format!(
                        "active instruction pack `{}` references disabled source `{}`; enable the source or disable the pack",
                        pack_ref(&entry.source_id, &entry.pack_id),
                        source.id
                    ),
                });
            }
            ensure_instruction_source_approved(paths, source, approvals, Some(&entry.pack_id))?;

            let previous_commit = entry.commit.clone().ok_or_else(|| DaloError::StateError {
                reason: format!(
                    "active instruction pack `{}` has no immutable source provenance; review and re-enable the pack",
                    pack_ref(&entry.source_id, &entry.pack_id)
                ),
            })?;
            let commit = validate_source_pack(paths, source, &entry.pack_id, None)?;
            let pack = read_source_pack(source, &entry.pack_id)?;
            let relative_path = source
                .subpath
                .as_deref()
                .unwrap_or_else(|| Path::new(""))
                .join("instructions")
                .join(format!("{}.md", entry.pack_id));
            let old_body = if previous_commit == commit {
                pack.body.clone()
            } else {
                git::read_file_at_commit(&source.path, &previous_commit, &relative_path).map_err(
                    |error| DaloError::StateError {
                        reason: format!(
                            "could not verify the previously rendered revision of `{}`: {error}; restore the source history or review and re-enable the pack",
                            pack_ref(&entry.source_id, &entry.pack_id)
                        ),
                    },
                )?
            };
            let updated_entry_index = active[..entry_index]
                .iter()
                .filter(|candidate| !removed_source_ids.contains(&candidate.source_id))
                .count();
            (
                old_body,
                pack,
                PendingPackRefreshProvenance::Source {
                    updated_entry_index,
                    previous_commit,
                    commit,
                },
            )
        };
        let target = lock_entry_target_path(paths, &entry.target);
        grouped
            .entry(target)
            .or_default()
            .refreshes
            .push(PendingPackRefresh {
                entry_index,
                old_body,
                pack,
                provenance,
            });
    }

    let mut operations = Vec::new();
    let mut removal_operations = Vec::new();
    let mut prepared = Vec::with_capacity(grouped.len());
    let mut target_locks = Vec::with_capacity(grouped.len());
    for (target, pending) in grouped {
        target_locks.push(acquire_target_lock(paths, &target)?);
        let snapshot = target_snapshot(&target)?;
        let existing = snapshot.content.clone().unwrap_or_default();
        let mut rendered = existing.clone();
        let line_ending = line_ending_for(&existing);

        for entry_index in pending.removal_entry_indexes {
            let entry = &active[entry_index];
            let marker = lock_marker_id(entry);
            let (action, warning) = match find_block(&rendered, &marker) {
                Ok(Some(_)) => {
                    rendered = remove_block(&rendered, &marker)?;
                    ("removed".to_owned(), None)
                }
                Ok(None) => (
                    "lock_removed".to_owned(),
                    Some("managed block was already missing; removed its lock entry".to_owned()),
                ),
                Err(error) => return Err(error),
            };
            removal_operations.push(InstructionRemovalOperation {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: target.clone(),
                action,
                warning,
            });
        }

        for refresh in pending.refreshes {
            let entry = &active[refresh.entry_index];
            let marker = lock_marker_id(entry);
            let expected = render_pack_managed_block_with_line_ending(
                &marker,
                &refresh.old_body,
                line_ending,
            )?;
            let Some((start, end)) = find_block(&existing, &marker)? else {
                return Err(DaloError::StateError {
                    reason: format!(
                        "managed block for `{}` is missing from `{}`; run `dalo status` and review or re-enable the pack",
                        pack_ref(&entry.source_id, &entry.pack_id),
                        target.display()
                    ),
                });
            };
            let actual = &existing[start..end];
            let needs_metadata_migration = actual != expected
                && actual
                    == render_legacy_pack_managed_block_with_line_ending(
                        &marker,
                        &refresh.old_body,
                        line_ending,
                    )?;
            if actual != expected && !needs_metadata_migration {
                return Err(DaloError::StateError {
                    reason: format!(
                        "managed block for `{}` in `{}` changed outside Dalo; run `dalo status` and review or re-enable the pack",
                        pack_ref(&entry.source_id, &entry.pack_id),
                        target.display()
                    ),
                });
            }

            let source_changed = match &refresh.provenance {
                PendingPackRefreshProvenance::Local => false,
                PendingPackRefreshProvenance::Source {
                    previous_commit,
                    commit,
                    ..
                } => previous_commit != commit,
            };
            if source_changed || needs_metadata_migration {
                let next_block = render_pack_managed_block_with_line_ending(
                    &marker,
                    &refresh.pack.body,
                    line_ending,
                )?;
                rendered = render_pack_block(&rendered, &marker, &refresh.pack.body)?;
                if let PendingPackRefreshProvenance::Source {
                    updated_entry_index,
                    previous_commit,
                    commit,
                } = refresh.provenance
                {
                    updated[updated_entry_index].commit = Some(commit.clone());
                    updated[updated_entry_index].version = refresh.pack.version.clone();
                    operations.push(InstructionSyncOperation {
                        source_id: entry.source_id.clone(),
                        pack_id: entry.pack_id.clone(),
                        target: target.clone(),
                        action: if next_block == actual {
                            "unchanged".to_owned()
                        } else {
                            "refreshed".to_owned()
                        },
                        previous_commit,
                        commit,
                    });
                }
            }
        }

        prepared.push(PreparedInstructionMutation {
            logical_targets: Vec::new(),
            target,
            snapshot,
            rendered: (rendered != existing).then_some(rendered),
            action: "refreshed".to_owned(),
            warning: None,
        });
    }
    sort_instruction_lock_entries(&mut updated);
    operations.sort_by(|left, right| {
        left.target
            .cmp(&right.target)
            .then_with(|| left.source_id.cmp(&right.source_id))
            .then_with(|| left.pack_id.cmp(&right.pack_id))
    });
    removal_operations.sort_by(|left, right| {
        left.target
            .cmp(&right.target)
            .then_with(|| left.source_id.cmp(&right.source_id))
            .then_with(|| left.pack_id.cmp(&right.pack_id))
    });

    let rollback = if dry_run {
        None
    } else {
        let written = apply_prepared_target_writes(prepared.as_mut_slice())?;
        Some(InstructionRefreshRollback {
            prepared,
            written,
            _target_locks: target_locks,
        })
    };
    Ok(InstructionSyncResult {
        active_instruction_packs: updated,
        operations,
        removal_operations,
        rollback,
    })
}

/// Remove active managed blocks and lock entries for sources being deleted.
///
/// Missing blocks drop their stale lock entries. Malformed blocks abort before
/// any write so the source and lock retain the ownership provenance needed for
/// recovery. Valid blocks across the same physical target are removed in one
/// conditional write.
pub fn remove_active_packs_for_sources(
    paths: &StorePaths,
    active: &[LockedInstructionPack],
    removed_source_ids: &BTreeSet<String>,
    dry_run: bool,
) -> DaloResult<InstructionSourceRemovalResult> {
    let mut retained = active
        .iter()
        .filter(|entry| !removed_source_ids.contains(&entry.source_id))
        .cloned()
        .collect::<Vec<_>>();
    let mut grouped = BTreeMap::<PathBuf, Vec<&LockedInstructionPack>>::new();
    for entry in active
        .iter()
        .filter(|entry| removed_source_ids.contains(&entry.source_id))
    {
        grouped
            .entry(lock_entry_target_path(paths, &entry.target))
            .or_default()
            .push(entry);
    }

    let mut operations = Vec::new();
    let mut prepared = Vec::with_capacity(grouped.len());
    let mut target_locks = Vec::with_capacity(grouped.len());
    for (target, entries) in grouped {
        target_locks.push(acquire_target_lock(paths, &target)?);
        let snapshot = target_snapshot(&target)?;
        let existing = snapshot.content.clone().unwrap_or_default();
        let mut rendered = existing.clone();
        for entry in entries {
            let marker = lock_marker_id(entry);
            let (action, warning) = match find_block(&rendered, &marker) {
                Ok(Some(_)) => {
                    rendered = remove_block(&rendered, &marker)?;
                    ("removed".to_owned(), None)
                }
                Ok(None) => (
                    "lock_removed".to_owned(),
                    Some("managed block was already missing; removed its lock entry".to_owned()),
                ),
                Err(error) => return Err(error),
            };
            operations.push(InstructionRemovalOperation {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: target.clone(),
                action,
                warning,
            });
        }
        prepared.push(PreparedInstructionMutation {
            logical_targets: Vec::new(),
            target,
            snapshot,
            rendered: (rendered != existing).then_some(rendered),
            action: "removed".to_owned(),
            warning: None,
        });
    }
    sort_instruction_lock_entries(&mut retained);
    operations.sort_by(|left, right| {
        left.target
            .cmp(&right.target)
            .then_with(|| left.source_id.cmp(&right.source_id))
            .then_with(|| left.pack_id.cmp(&right.pack_id))
    });
    let rollback = if dry_run {
        None
    } else {
        let written = apply_prepared_target_writes(prepared.as_mut_slice())?;
        Some(InstructionRefreshRollback {
            prepared,
            written,
            _target_locks: target_locks,
        })
    };
    Ok(InstructionSourceRemovalResult {
        active_instruction_packs: retained,
        operations,
        rollback,
    })
}

#[derive(Debug)]
struct PreparedInstructionMutation {
    logical_targets: Vec<String>,
    target: PathBuf,
    snapshot: TargetSnapshot,
    rendered: Option<String>,
    action: String,
    warning: Option<String>,
}

impl PreparedInstructionMutation {
    fn into_report(self) -> InstructionTargetOperationReport {
        InstructionTargetOperationReport {
            logical_targets: self.logical_targets,
            target: self.target,
            action: self.action,
            warning: self.warning,
        }
    }
}

fn apply_prepared_instruction_mutations(
    paths: &StorePaths,
    prepared: &mut [PreparedInstructionMutation],
    lock: &crate::lockfile::UserLock,
) -> DaloResult<()> {
    let written = apply_prepared_target_writes(prepared)?;
    if let Err(error) = store::write_user_lock(paths, lock) {
        return Err(rollback_prepared_target_writes(prepared, &written, error));
    }
    Ok(())
}

fn apply_prepared_target_writes(
    prepared: &mut [PreparedInstructionMutation],
) -> DaloResult<Vec<(usize, TargetIdentity)>> {
    let mut written = Vec::new();
    for (index, mutation) in prepared.iter().enumerate() {
        let Some(rendered) = mutation.rendered.as_deref() else {
            continue;
        };
        match write_target_if_unchanged(&mutation.snapshot, rendered) {
            Ok(identity) => written.push((index, identity)),
            Err(error) => {
                return Err(rollback_prepared_target_writes(prepared, &written, error));
            }
        }
    }
    Ok(written)
}

fn rollback_prepared_target_writes(
    prepared: &[PreparedInstructionMutation],
    written: &[(usize, TargetIdentity)],
    mut error: DaloError,
) -> DaloError {
    for (index, identity) in written.iter().rev() {
        let mutation = &prepared[*index];
        let snapshot = TargetSnapshot {
            target: mutation.snapshot.target.clone(),
            content: mutation.snapshot.content.clone(),
            identity: mutation.snapshot.identity,
        };
        error = restore_target_after_error(
            snapshot,
            mutation
                .rendered
                .as_deref()
                .expect("only rendered mutations are recorded as written"),
            *identity,
            error,
        );
    }
    error
}

/// Active instruction packs returned by `instructions list`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionPackListReport {
    /// Packs currently rendered into instruction files.
    pub active_instruction_packs: Vec<LockedInstructionPack>,
}

/// Drift detected for an active instruction pack's rendered block.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionBlockDrift {
    /// Source that owns the pack.
    pub source_id: String,
    /// Pack ID.
    pub pack_id: String,
    /// Instruction-file target that should contain the block.
    pub target: PathBuf,
    /// Drift kind.
    pub kind: InstructionBlockDriftKind,
    /// Human-readable detail.
    pub message: String,
}

/// An active pack whose rendered block still uses the pre-1.0 rendering.
///
/// Releases before pack metadata was hidden from agents rendered `version:` and
/// `topics:` lines into the managed block. Those blocks are still accepted, and
/// the next `dalo sync` rewrites them, so this is a migration to announce rather
/// than drift to repair.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LegacyInstructionBlock {
    /// Source that owns the pack.
    pub source_id: String,
    /// Pack ID.
    pub pack_id: String,
    /// Instruction-file target that contains the block.
    pub target: PathBuf,
}

/// Active packs whose rendered block still uses the pre-1.0 rendering.
#[must_use]
pub fn legacy_instruction_blocks(
    paths: &StorePaths,
    sources: &[SourceConfig],
    active: &[LockedInstructionPack],
) -> Vec<LegacyInstructionBlock> {
    let mut legacy = active
        .iter()
        .filter(|entry| renders_legacy_block(paths, sources, entry))
        .map(|entry| LegacyInstructionBlock {
            source_id: entry.source_id.clone(),
            pack_id: entry.pack_id.clone(),
            target: lock_entry_target_path(paths, &entry.target),
        })
        .collect::<Vec<_>>();
    legacy.sort_by(|left, right| {
        left.target
            .cmp(&right.target)
            .then_with(|| left.source_id.cmp(&right.source_id))
            .then_with(|| left.pack_id.cmp(&right.pack_id))
    });
    legacy
}

fn renders_legacy_block(
    paths: &StorePaths,
    sources: &[SourceConfig],
    entry: &LockedInstructionPack,
) -> bool {
    let Ok(pack) = read_pack_for_lock_entry(paths, sources, entry) else {
        return false;
    };
    let Ok(content) = fs::read_to_string(lock_entry_target_path(paths, &entry.target)) else {
        return false;
    };
    let marker_id = lock_marker_id(entry);
    let line_ending = line_ending_for(&content);
    let Ok(current) =
        render_pack_managed_block_with_line_ending(&marker_id, &pack.body, line_ending)
    else {
        return false;
    };
    let Ok(legacy) =
        render_legacy_pack_managed_block_with_line_ending(&marker_id, &pack.body, line_ending)
    else {
        return false;
    };
    if current == legacy {
        return false;
    }
    matches!(
        find_block(&content, &marker_id),
        Ok(Some((start, end))) if content[start..end] == legacy
    )
}

/// Instruction block drift classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InstructionBlockDriftKind {
    /// The expected managed block is absent.
    Missing,
    /// Markers are malformed, duplicated, or unreadable.
    Malformed,
    /// The block exists but no longer matches the current pack body.
    Stale,
    /// The active lock entry points to a pack that cannot be read.
    SourceMissing,
}

fn start_marker(pack_id: &str) -> String {
    format!("{START_MARKER_PREFIX}{pack_id} -->")
}

fn end_marker(pack_id: &str) -> String {
    format!("{END_MARKER_PREFIX}{pack_id} -->")
}

fn pack_ref(source_id: &str, pack_id: &str) -> String {
    format!("{source_id}:{pack_id}")
}

fn marker_id(source_id: &str, pack_id: &str) -> String {
    if source_id == "local" {
        pack_id.to_owned()
    } else {
        pack_ref(source_id, pack_id)
    }
}

fn lock_marker_id(entry: &LockedInstructionPack) -> String {
    marker_id(&entry.source_id, &entry.pack_id)
}

/// Byte offsets `(start, end)` spanning a pack's managed block, markers included.
fn find_block(content: &str, pack_id: &str) -> DaloResult<Option<(usize, usize)>> {
    let start = start_marker(pack_id);
    let end = end_marker(pack_id);
    let starts = content.match_indices(&start).collect::<Vec<_>>();
    let ends = content.match_indices(&end).collect::<Vec<_>>();

    match (starts.as_slice(), ends.as_slice()) {
        ([], []) => Ok(None),
        ([(start_idx, _)], [(end_idx, _)]) if start_idx < end_idx => {
            Ok(Some((*start_idx, end_idx + end.len())))
        }
        ([], _) => Err(DaloError::MalformedInstructionBlock {
            pack_id: pack_id.to_owned(),
            reason: "end marker exists without a matching start marker".to_owned(),
        }),
        (_, []) => Err(DaloError::MalformedInstructionBlock {
            pack_id: pack_id.to_owned(),
            reason: "start marker exists without a matching end marker".to_owned(),
        }),
        _ => Err(DaloError::MalformedInstructionBlock {
            pack_id: pack_id.to_owned(),
            reason: "expected exactly one ordered start/end marker pair".to_owned(),
        }),
    }
}

/// Render `body` into `content` as `pack_id`'s managed block.
///
/// When the block exists, only the bytes between its markers change. When it does
/// not, the block is appended, separated from existing content by a blank line.
/// Rendering the same body twice is idempotent.
pub fn render_block(content: &str, pack_id: &str, body: &str) -> DaloResult<String> {
    let line_ending = line_ending_for(content);
    let block = render_managed_block_with_line_ending(pack_id, body, line_ending)?;
    Ok(match find_block(content, pack_id)? {
        Some((start_idx, end_idx)) => {
            format!("{}{}{}", &content[..start_idx], block, &content[end_idx..])
        }
        None => append_block(content, &block, line_ending),
    })
}

/// Render an instruction pack after removing metadata consumed by Dalo itself.
///
/// The source body remains intact for locks, discovery, and overlap detection;
/// only the managed block omits recognized metadata lines from agent-visible
/// content.
fn render_pack_block(content: &str, pack_id: &str, source_body: &str) -> DaloResult<String> {
    render_block(
        content,
        pack_id,
        &strip_recognized_pack_metadata(source_body),
    )
}

#[cfg(test)]
fn render_managed_block(pack_id: &str, body: &str) -> DaloResult<String> {
    render_managed_block_with_line_ending(pack_id, body, "\n")
}

fn render_managed_block_with_line_ending(
    pack_id: &str,
    body: &str,
    line_ending: &str,
) -> DaloResult<String> {
    validate_body_markers(pack_id, body)?;
    let body = normalize_line_endings(
        body.trim_matches(|character| character == '\n' || character == '\r'),
        line_ending,
    );
    Ok(format!(
        "{}{}{}{}{}",
        start_marker(pack_id),
        line_ending,
        body,
        line_ending,
        end_marker(pack_id)
    ))
}

fn render_pack_managed_block_with_line_ending(
    pack_id: &str,
    source_body: &str,
    line_ending: &str,
) -> DaloResult<String> {
    render_managed_block_with_line_ending(
        pack_id,
        &strip_recognized_pack_metadata(source_body),
        line_ending,
    )
}

/// Render the raw source body used by Dalo releases before pack metadata was
/// omitted from agent-visible managed blocks.
fn render_legacy_pack_managed_block_with_line_ending(
    pack_id: &str,
    source_body: &str,
    line_ending: &str,
) -> DaloResult<String> {
    render_managed_block_with_line_ending(pack_id, source_body, line_ending)
}

fn validate_body_markers(pack_id: &str, body: &str) -> DaloResult<()> {
    if body.contains(START_MARKER_PREFIX) || body.contains(END_MARKER_PREFIX) {
        return Err(DaloError::MalformedInstructionBlock {
            pack_id: pack_id.to_owned(),
            reason: "instruction pack body contains dalo managed-block marker text".to_owned(),
        });
    }

    Ok(())
}

/// Check active instruction-pack lock entries against their rendered target blocks.
#[must_use]
pub fn instruction_block_drifts(
    paths: &StorePaths,
    sources: &[SourceConfig],
    active: &[LockedInstructionPack],
) -> Vec<InstructionBlockDrift> {
    let mut drifts = Vec::new();
    for entry in active {
        if let Some(drift) = instruction_block_drift(paths, sources, entry) {
            drifts.push(drift);
        }
    }
    drifts.sort_by(|left, right| {
        left.target
            .cmp(&right.target)
            .then_with(|| left.source_id.cmp(&right.source_id))
            .then_with(|| left.pack_id.cmp(&right.pack_id))
    });
    drifts
}

fn instruction_block_drift(
    paths: &StorePaths,
    sources: &[SourceConfig],
    entry: &LockedInstructionPack,
) -> Option<InstructionBlockDrift> {
    let target = lock_entry_target_path(paths, &entry.target);
    let pack = match read_pack_for_lock_entry(paths, sources, entry) {
        Ok(pack) => pack,
        Err(error) => {
            return Some(InstructionBlockDrift {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: entry.target.clone(),
                kind: InstructionBlockDriftKind::SourceMissing,
                message: format!("active instruction pack source could not be read: {error}"),
            });
        }
    };
    let content = match fs::read_to_string(&target) {
        Ok(content) => content,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Some(InstructionBlockDrift {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: entry.target.clone(),
                kind: InstructionBlockDriftKind::Missing,
                message: "instruction target file is missing".to_owned(),
            });
        }
        Err(error) => {
            return Some(InstructionBlockDrift {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: entry.target.clone(),
                kind: InstructionBlockDriftKind::Malformed,
                message: format!("instruction target file could not be read: {error}"),
            });
        }
    };
    let marker_id = lock_marker_id(entry);
    let expected = match render_pack_managed_block_with_line_ending(
        &marker_id,
        &pack.body,
        line_ending_for(&content),
    ) {
        Ok(block) => block,
        Err(error) => {
            return Some(InstructionBlockDrift {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: entry.target.clone(),
                kind: InstructionBlockDriftKind::SourceMissing,
                message: format!("active instruction pack body is invalid: {error}"),
            });
        }
    };
    let legacy_expected = match render_legacy_pack_managed_block_with_line_ending(
        &marker_id,
        &pack.body,
        line_ending_for(&content),
    ) {
        Ok(block) => block,
        Err(error) => {
            return Some(InstructionBlockDrift {
                source_id: entry.source_id.clone(),
                pack_id: entry.pack_id.clone(),
                target: entry.target.clone(),
                kind: InstructionBlockDriftKind::SourceMissing,
                message: format!("active instruction pack body is invalid: {error}"),
            });
        }
    };
    match find_block(&content, &marker_id) {
        Ok(Some((start_idx, end_idx)))
            if content[start_idx..end_idx] == expected
                || content[start_idx..end_idx] == legacy_expected =>
        {
            None
        }
        Ok(Some(_)) => Some(InstructionBlockDrift {
            source_id: entry.source_id.clone(),
            pack_id: entry.pack_id.clone(),
            target: entry.target.clone(),
            kind: InstructionBlockDriftKind::Stale,
            message: "instruction block does not match current pack body".to_owned(),
        }),
        Ok(None) => Some(InstructionBlockDrift {
            source_id: entry.source_id.clone(),
            pack_id: entry.pack_id.clone(),
            target: entry.target.clone(),
            kind: InstructionBlockDriftKind::Missing,
            message: "instruction block is missing from target file".to_owned(),
        }),
        Err(error) => Some(InstructionBlockDrift {
            source_id: entry.source_id.clone(),
            pack_id: entry.pack_id.clone(),
            target: entry.target.clone(),
            kind: InstructionBlockDriftKind::Malformed,
            message: error.to_string(),
        }),
    }
}

fn lock_entry_target_path(paths: &StorePaths, target: &Path) -> PathBuf {
    if target.is_absolute() {
        target.to_path_buf()
    } else {
        lexically_normalize(&paths.root.join(target))
    }
}

fn read_pack_for_lock_entry(
    paths: &StorePaths,
    sources: &[SourceConfig],
    entry: &LockedInstructionPack,
) -> DaloResult<InstructionPack> {
    if entry.source_id == "local" {
        return read_local_pack(paths, &entry.pack_id);
    }

    let Some(source) = sources.iter().find(|source| source.id == entry.source_id) else {
        return Err(DaloError::unknown_source(
            entry.source_id.clone(),
            sources.iter().map(|source| source.id.clone()).collect(),
        ));
    };
    if !source.enabled {
        return Err(DaloError::StateError {
            reason: format!("instruction pack source `{}` is disabled", source.id),
        });
    }
    validate_source_pack(paths, source, &entry.pack_id, entry.commit.as_deref())?;
    read_source_pack(source, &entry.pack_id)
}

fn append_block(content: &str, block: &str, line_ending: &str) -> String {
    if content.is_empty() {
        return format!("{block}{line_ending}");
    }
    // Normalize the seam to exactly one blank line before the appended block.
    let double_line_ending = format!("{line_ending}{line_ending}");
    let separator = if content.ends_with(&double_line_ending) {
        ""
    } else if content.ends_with(line_ending) {
        line_ending
    } else {
        return format!("{content}{line_ending}{line_ending}{block}{line_ending}");
    };
    format!("{content}{separator}{block}{line_ending}")
}

/// Remove `pack_id`'s managed block, preserving content outside it. A single
/// separating newline on each side of the block is also dropped so removal leaves
/// no blank gap where the block used to be.
pub fn remove_block(content: &str, pack_id: &str) -> DaloResult<String> {
    let Some((start_idx, end_idx)) = find_block(content, pack_id)? else {
        return Ok(content.to_owned());
    };
    let line_ending = line_ending_for(content);
    let before_raw = &content[..start_idx];
    let (before, before_had_line_ending) = strip_line_ending_suffix(before_raw, line_ending);
    let after_raw = &content[end_idx..];
    let (after, _) = strip_line_ending_prefix(after_raw, line_ending);
    Ok(match (before.is_empty(), after.is_empty()) {
        (true, _) => after.to_owned(),
        (_, true) if before_had_line_ending => format!("{before}{line_ending}"),
        (_, true) => before.to_owned(),
        _ if before.ends_with(line_ending) || after.starts_with(line_ending) => {
            format!("{before}{after}")
        }
        _ => format!("{before}{line_ending}{after}"),
    })
}

fn line_ending_for(content: &str) -> &'static str {
    let crlf_count = content.match_indices("\r\n").count();
    let bytes = content.as_bytes();
    let lf_count = bytes
        .iter()
        .enumerate()
        .filter(|(index, byte)| {
            **byte == b'\n' && (*index == 0 || bytes[index.saturating_sub(1)] != b'\r')
        })
        .count();
    if crlf_count > lf_count { "\r\n" } else { "\n" }
}

fn normalize_line_endings(content: &str, line_ending: &str) -> String {
    content
        .replace("\r\n", "\n")
        .replace('\r', "\n")
        .replace('\n', line_ending)
}

fn strip_line_ending_suffix<'a>(content: &'a str, line_ending: &str) -> (&'a str, bool) {
    if let Some(stripped) = content.strip_suffix(line_ending) {
        return (stripped, true);
    }
    if line_ending != "\r\n"
        && let Some(stripped) = content.strip_suffix("\r\n")
    {
        return (stripped, true);
    }
    if let Some(stripped) = content.strip_suffix('\n') {
        return (stripped, true);
    }
    (content, false)
}

fn strip_line_ending_prefix<'a>(content: &'a str, line_ending: &str) -> (&'a str, bool) {
    if let Some(stripped) = content.strip_prefix(line_ending) {
        return (stripped, true);
    }
    if line_ending != "\r\n"
        && let Some(stripped) = content.strip_prefix("\r\n")
    {
        return (stripped, true);
    }
    if let Some(stripped) = content.strip_prefix('\n') {
        return (stripped, true);
    }
    (content, false)
}

/// Whether `content` contains `pack_id`'s managed block.
#[must_use]
pub fn has_block(content: &str, pack_id: &str) -> bool {
    find_block(content, pack_id).is_ok_and(|block| block.is_some())
}

/// Validate a pack ID (same character rules as a source ID).
fn is_valid_pack_id(pack_id: &str) -> bool {
    !pack_id.is_empty()
        && pack_id != "."
        && pack_id != ".."
        && pack_id.chars().all(|character| {
            character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-')
        })
}

/// Optional `version:` line in the pack's leading lines.
fn parse_version(body: &str) -> Option<String> {
    body.lines()
        .take(5)
        .find_map(|line| line.trim().strip_prefix("version:"))
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// Remove the leading metadata lines Dalo recognizes from agent-visible output.
///
/// Metadata is recognized by the same bounded scans as `parse_version` and
/// `parse_topics`. Source line endings and all other content stay unchanged.
fn strip_recognized_pack_metadata(body: &str) -> String {
    let version_line = body.lines().take(5).position(|line| {
        line.trim()
            .strip_prefix("version:")
            .is_some_and(|value| !value.trim().is_empty())
    });
    let topics_line = body.lines().take(8).position(|line| {
        let trimmed = line.trim();
        trimmed.strip_prefix("topics:").is_some() || trimmed.strip_prefix("tags:").is_some()
    });

    body.split_inclusive('\n')
        .enumerate()
        .filter(|(index, _)| Some(*index) != version_line && Some(*index) != topics_line)
        .map(|(_, line)| line)
        .collect()
}

/// Read a user-authored pack from `local/instructions/<id>.md`.
pub fn read_local_pack(paths: &StorePaths, pack_id: &str) -> DaloResult<InstructionPack> {
    if !is_valid_pack_id(pack_id) {
        return Err(DaloError::InvalidSourceId {
            id: pack_id.to_owned(),
            reason: "instruction pack id must be `[A-Za-z0-9._-]` and not `.`/`..`".to_owned(),
        });
    }
    read_pack_from_dir(&paths.local_instructions_dir, pack_id)
}

#[derive(Debug)]
struct ResolvedInstructionPack {
    pack: InstructionPack,
    source_id: String,
    commit: Option<String>,
}

fn parse_pack_selector(selector: &str) -> DaloResult<(String, String)> {
    let (source_id, pack_id) = selector
        .split_once(':')
        .map_or(("local", selector), |(source_id, pack_id)| {
            (source_id, pack_id)
        });
    if source_id.is_empty() || !is_valid_pack_id(pack_id) {
        return Err(DaloError::InvalidArgument {
            reason: "instruction pack references must use `<source>:<pack>` or a local `<pack>`; pack IDs must match `[A-Za-z0-9._-]` and not be `.`/`..`"
                .to_owned(),
        });
    }
    Ok((source_id.to_owned(), pack_id.to_owned()))
}

fn resolve_pack(paths: &StorePaths, selector: &str) -> DaloResult<ResolvedInstructionPack> {
    let (source_id, pack_id) = parse_pack_selector(selector)?;
    if source_id == "local" {
        return Ok(ResolvedInstructionPack {
            pack: read_local_pack(paths, &pack_id)?,
            source_id,
            commit: None,
        });
    }

    let config = store::read_config(paths)?;
    let source = config
        .sources
        .iter()
        .find(|source| source.id == source_id)
        .ok_or_else(|| {
            DaloError::unknown_source(
                source_id.clone(),
                config
                    .sources
                    .iter()
                    .map(|source| source.id.clone())
                    .collect(),
            )
        })?;
    if !source.enabled {
        return Err(DaloError::StateError {
            reason: format!(
                "instruction pack source `{source_id}` is disabled; enable the source before activating `{selector}`"
            ),
        });
    }
    let approvals = store::read_approvals(paths)?;
    ensure_instruction_source_approved(paths, source, &approvals.approvals, Some(&pack_id))?;
    let commit = validate_source_pack(paths, source, &pack_id, None)?;
    Ok(ResolvedInstructionPack {
        pack: read_source_pack(source, &pack_id)?,
        source_id,
        commit: Some(commit),
    })
}

fn ensure_instruction_source_approved(
    paths: &StorePaths,
    source: &SourceConfig,
    approvals: &[ApprovalRecord],
    pack_id: Option<&str>,
) -> DaloResult<()> {
    // A project declaration approves skills only. Source trust in a project
    // store never approves an instruction pack; it needs an explicit source
    // approval like any other untrusted source.
    let trusted = source.trusted && !crate::project::is_project_store(&paths.root);
    if trusted
        || approvals
            .iter()
            .any(|approval| approval.scope == "source" && approval.value == source.id)
    {
        return Ok(());
    }
    let subject = pack_id.map_or_else(
        || format!("source `{}`", source.id),
        |pack_id| format!("instruction pack `{}`", pack_ref(&source.id, pack_id)),
    );
    Err(DaloError::StateError {
        reason: format!(
            "approval for {subject} is missing or was revoked; review the source and run `dalo approve source {}`",
            source.id
        ),
    })
}

fn validate_source_pack(
    paths: &StorePaths,
    source: &SourceConfig,
    pack_id: &str,
    expected_commit: Option<&str>,
) -> DaloResult<String> {
    if git::is_dirty(&source.path)? {
        return Err(DaloError::DirtySource {
            source_id: source.id.clone(),
            path: source.path.clone(),
        });
    }
    let pack_path = crate::source::scoped_source_root(&source.path, source.subpath.as_deref())?
        .join("instructions")
        .join(format!("{pack_id}.md"));
    let metadata = fs::symlink_metadata(&pack_path)
        .map_err(|_| source_instruction_pack_not_found(source, pack_id))?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(DaloError::StateError {
            reason: format!(
                "instruction pack `{}` must be a regular, non-symlink file",
                pack_ref(&source.id, pack_id)
            ),
        });
    }
    if !git::is_tracked_file(&source.path, &pack_path)? {
        return Err(DaloError::StateError {
            reason: format!(
                "instruction pack `{}` is not tracked by its source commit; commit it before enabling the pack",
                pack_ref(&source.id, pack_id)
            ),
        });
    }
    let commit = git::rev_parse_head(&source.path)?;
    if let Some(expected) = expected_commit
        && expected != commit
    {
        return Err(DaloError::StateError {
            reason: format!(
                "instruction pack `{}` was enabled from commit `{expected}`, but the source checkout is now `{commit}`; review and re-enable the pack",
                pack_ref(&source.id, pack_id)
            ),
        });
    }
    if source.kind == SourceKind::Catalog {
        let source_lock = crate::catalog::read_source_lock(paths)?;
        let locked_commit = source_lock
            .catalog(&source.id)
            .map(|locked| locked.commit.as_str())
            .ok_or_else(|| DaloError::StateError {
                reason: format!(
                    "catalog source `{}` has no pinned source-lock entry; run `dalo source refresh {}` before enabling instructions",
                    source.id, source.id
                ),
            })?;
        if locked_commit != commit {
            return Err(DaloError::StateError {
                reason: format!(
                    "catalog source `{}` checkout `{commit}` does not match its pinned commit `{locked_commit}`",
                    source.id
                ),
            });
        }
    }
    Ok(commit)
}

fn read_pack_from_dir(dir: &Path, pack_id: &str) -> DaloResult<InstructionPack> {
    let path = dir.join(format!("{pack_id}.md"));
    let body = fs::read_to_string(&path).map_err(|_| DaloError::InstructionPackNotFound {
        pack_id: pack_id.to_owned(),
        path: path.clone(),
    })?;
    Ok(InstructionPack {
        id: pack_id.to_owned(),
        version: parse_version(&body),
        body,
    })
}

fn read_source_pack(source: &SourceConfig, pack_id: &str) -> DaloResult<InstructionPack> {
    let dir = crate::source::scoped_source_root(&source.path, source.subpath.as_deref())?
        .join("instructions");
    let path = dir.join(format!("{pack_id}.md"));
    let body = fs::read_to_string(&path)
        .map_err(|_| source_instruction_pack_not_found(source, pack_id))?;
    Ok(InstructionPack {
        id: pack_id.to_owned(),
        version: parse_version(&body),
        body,
    })
}

fn source_instruction_pack_not_found(source: &SourceConfig, pack_id: &str) -> DaloError {
    let mut packs = Vec::new();
    let source_root = crate::source::scoped_source_root(&source.path, source.subpath.as_deref())
        .unwrap_or_else(|_| source.path.clone());
    scan_pack_dir(
        &source_root.join("instructions"),
        &source.id,
        &BTreeSet::new(),
        &mut packs,
    );
    DaloError::source_instruction_pack_not_found(
        pack_ref(&source.id, pack_id),
        pack_id,
        packs.into_iter().map(|pack| pack.id).collect(),
    )
}

/// Enable a local or source-qualified pack: render its managed block into `target` and record it in
/// the user lock. Idempotent: enabling an already-active pack re-renders the block
/// and updates the lock entry in place.
pub fn enable_pack(
    paths: &StorePaths,
    selector: &str,
    target: &Path,
    dry_run: bool,
) -> DaloResult<InstructionPackReport> {
    enable_pack_with_logical_targets(paths, selector, target, &[], dry_run)
}

fn enable_pack_with_logical_targets(
    paths: &StorePaths,
    selector: &str,
    target: &Path,
    logical_targets: &[String],
    dry_run: bool,
) -> DaloResult<InstructionPackReport> {
    enable_pack_with_lock_writer(
        paths,
        selector,
        target,
        logical_targets,
        dry_run,
        store::write_user_lock,
    )
}

fn enable_pack_with_lock_writer<F>(
    paths: &StorePaths,
    selector: &str,
    target: &Path,
    logical_targets: &[String],
    dry_run: bool,
    write_lock: F,
) -> DaloResult<InstructionPackReport>
where
    F: FnOnce(&StorePaths, &crate::lockfile::UserLock) -> DaloResult<()>,
{
    let target = normalize_target_path(target)?;
    let resolved = resolve_pack(paths, selector)?;
    let pack = resolved.pack;
    let marker_id = marker_id(&resolved.source_id, &pack.id);
    let mut lock = store::read_user_lock(paths)?;
    let _target_lock = acquire_target_lock(paths, &target)?;
    let snapshot = target_snapshot(&target)?;
    let existing = snapshot.content.clone().unwrap_or_default();
    let rendered = render_pack_block(&existing, &marker_id, &pack.body)?;
    if !dry_run {
        lock.active_instruction_packs.retain(|entry| {
            !(entry.source_id == resolved.source_id
                && entry.pack_id == pack.id
                && targets_match(entry, &target))
        });
        lock.active_instruction_packs.push(LockedInstructionPack {
            pack_id: pack.id.clone(),
            target: target.clone(),
            logical_targets: logical_targets.to_vec(),
            source_id: resolved.source_id.clone(),
            commit: resolved.commit,
            version: pack.version,
        });
        sort_instruction_lock_entries(&mut lock.active_instruction_packs);
        let written_identity = write_target_if_unchanged(&snapshot, &rendered)?;
        if let Err(error) = write_lock(paths, &lock) {
            return Err(restore_target_after_error(
                snapshot,
                &rendered,
                written_identity,
                error,
            ));
        }
    }

    Ok(InstructionPackReport {
        pack_id: pack.id,
        source_id: resolved.source_id,
        target,
        action: "enabled".to_owned(),
        dry_run,
        warning: None,
    })
}

fn sort_instruction_lock_entries(entries: &mut [LockedInstructionPack]) {
    entries.sort_by(|left, right| {
        left.source_id
            .cmp(&right.source_id)
            .then_with(|| left.pack_id.cmp(&right.pack_id))
            .then(left.target.cmp(&right.target))
    });
}

/// Adopt an edited active source-backed block into a new local pack.
///
/// Replaces only this target's managed markers and lock entry. The local Git
/// source is left uncommitted; other targets and the upstream source stay intact.
/// Refuses existing local packs, ambiguous targets, dirty sources and blocks
/// whose content cannot be represented by the existing pack renderer.
/// The caller must hold the store lock for a real mutation.
pub fn adopt_pack(
    paths: &StorePaths,
    selector: &str,
    target: Option<&Path>,
    dry_run: bool,
) -> DaloResult<InstructionAdoptReport> {
    adopt_pack_with_lock_writer(paths, selector, target, dry_run, store::write_user_lock)
}

fn adopt_pack_with_lock_writer<F>(
    paths: &StorePaths,
    selector: &str,
    target: Option<&Path>,
    dry_run: bool,
    write_lock: F,
) -> DaloResult<InstructionAdoptReport>
where
    F: FnOnce(&StorePaths, &crate::lockfile::UserLock) -> DaloResult<()>,
{
    let (source_id, pack_id) = parse_pack_selector(selector)?;
    if source_id == "local" {
        return Err(adopt_blocked(
            "adopt requires a source-qualified team or catalog pack; edit an existing local pack directly",
        ));
    }
    let requested_target = target.map(normalize_target_path).transpose()?;
    let mut lock = store::read_user_lock(paths)?;
    let mut matches = Vec::new();
    for (index, entry) in lock.active_instruction_packs.iter().enumerate() {
        let target = lock_entry_target_path(paths, &entry.target);
        if entry.source_id == source_id
            && entry.pack_id == pack_id
            && requested_target.as_ref().is_none_or(|requested| {
                target == *requested
                    || fs::canonicalize(&target)
                        .ok()
                        .zip(fs::canonicalize(requested).ok())
                        .is_some_and(|(left, right)| left == right)
            })
        {
            matches.push((index, target));
        }
    }
    if matches.len() != 1 {
        return Err(adopt_blocked(if matches.is_empty() {
            "no matching active instruction pack; specify an active source-qualified pack and target file"
        } else {
            "pack is active in several files; specify one target FILE to adopt"
        }));
    }
    let (entry_index, target) = matches
        .pop()
        .expect("exactly one active target was checked");
    let entry = &lock.active_instruction_packs[entry_index];
    let resolved = resolve_pack(paths, selector)?;
    let source_commit = entry
        .commit
        .as_ref()
        .ok_or_else(|| adopt_blocked("active source pack has no commit provenance"))?;
    if resolved.commit.as_ref() != Some(source_commit) {
        return Err(adopt_blocked(
            "source revision changed since activation; review and re-enable the source pack before adoption",
        ));
    }
    let _target_lock = if dry_run {
        None
    } else {
        Some(acquire_target_lock(paths, &target)?)
    };
    let snapshot = target_snapshot(&target)?;
    let content = snapshot
        .content
        .as_deref()
        .ok_or_else(|| adopt_blocked("instruction target is missing"))?;
    let marker = lock_marker_id(entry);
    let (start, end) = find_block(content, &marker)?
        .ok_or_else(|| adopt_blocked("active managed block is missing"))?;
    if (start != 0 && !content[..start].ends_with('\n'))
        || (end != content.len()
            && !content[end..].starts_with('\n')
            && !content[end..].starts_with("\r\n"))
    {
        return Err(adopt_blocked("managed markers must occupy their own lines"));
    }
    let line_ending = line_ending_for(content);
    let expected =
        render_pack_managed_block_with_line_ending(&marker, &resolved.pack.body, line_ending)?;
    let legacy = render_legacy_pack_managed_block_with_line_ending(
        &marker,
        &resolved.pack.body,
        line_ending,
    )?;
    if content[start..end] == expected || content[start..end] == legacy {
        return Err(adopt_blocked("managed block has no edits to adopt"));
    }
    let body = content[start + start_marker(&marker).len()..end - end_marker(&marker).len()]
        .strip_prefix(line_ending)
        .and_then(|body| body.strip_suffix(line_ending))
        .ok_or_else(|| adopt_blocked("managed markers must occupy their own lines"))?;
    validate_body_markers(&marker, body)?;
    if body.trim().is_empty() {
        return Err(adopt_blocked("edited instruction body is empty"));
    }
    let local_marker = marker_id("local", &pack_id);
    if find_block(content, &local_marker)?.is_some()
        || lock.active_instruction_packs.iter().any(|candidate| {
            candidate.source_id == "local"
                && candidate.pack_id == pack_id
                && targets_match(candidate, &target)
        })
    {
        return Err(adopt_blocked(
            "target already has an active local block for this pack",
        ));
    }
    let local_content = format!("version: 1\n\n{body}\n");
    let local_block =
        render_pack_managed_block_with_line_ending(&local_marker, &local_content, line_ending)?;
    let renamed_block = format!(
        "{}{line_ending}{body}{line_ending}{}",
        start_marker(&local_marker),
        end_marker(&local_marker)
    );
    if local_block != renamed_block {
        return Err(adopt_blocked(
            "edited body cannot be rendered without changing content; check leading metadata and blank lines before adoption",
        ));
    }
    for directory in [&paths.local_dir, &paths.local_instructions_dir] {
        let metadata = fs::symlink_metadata(directory)?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            return Err(adopt_blocked(
                "local instruction directories must be real, non-symlink directories",
            ));
        }
    }
    let local_path = paths.local_instructions_dir.join(format!("{pack_id}.md"));
    match fs::symlink_metadata(&local_path) {
        Ok(_) => {
            return Err(adopt_blocked(format!(
                "local pack `{}` already exists; adoption never overwrites it",
                local_path.display()
            )));
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(error.into()),
    }
    let report = InstructionAdoptReport {
        source_ref: pack_ref(&source_id, &pack_id),
        pack_id: pack_id.clone(),
        target: target.clone(),
        local_path: local_path.clone(),
        source_commit: source_commit.clone(),
        body: body.to_owned(),
        dry_run,
    };
    if dry_run {
        return Ok(report);
    }
    let mut rendered = String::with_capacity(content.len());
    rendered.push_str(&content[..start]);
    rendered.push_str(&local_block);
    rendered.push_str(&content[end..]);
    // Stage in the destination directory, then publish without replacing any
    // concurrently created file. Retain identity for conservative rollback.
    let mut temp = NamedTempFile::new_in(&paths.local_instructions_dir)?;
    temp.write_all(local_content.as_bytes())?;
    temp.as_file().sync_all()?;
    let file = temp
        .persist_noclobber(&local_path)
        .map_err(|error| DaloError::Io(error.error))?;
    let identity = target_identity(&file.metadata()?);
    lock.active_instruction_packs[entry_index] = LockedInstructionPack {
        source_id: "local".to_owned(),
        pack_id,
        target,
        logical_targets: lock.active_instruction_packs[entry_index]
            .logical_targets
            .clone(),
        commit: None,
        version: Some("1".to_owned()),
    };
    sort_instruction_lock_entries(&mut lock.active_instruction_packs);
    let result = match sync_target_parent(&paths.local_instructions_dir)
        .and_then(|()| write_target_if_unchanged(&snapshot, &rendered))
    {
        Ok(written_identity) => match write_lock(paths, &lock) {
            Ok(()) => Ok(()),
            Err(error) => match restore_target(snapshot, &rendered, written_identity) {
                Ok(()) => Err(error),
                Err(restore_error) => {
                    return Err(adopt_blocked(format!(
                        "{error}; target restoration failed: {restore_error}; adopted pack was retained at `{}` for recovery",
                        local_path.display()
                    )));
                }
            },
        },
        Err(error) => Err(error),
    };
    if let Err(error) = result {
        if let Err(cleanup_error) = remove_adopted_pack(&local_path, identity, &local_content) {
            return Err(adopt_blocked(format!(
                "{error}; could not roll back local pack: {cleanup_error}"
            )));
        }
        return Err(error);
    }
    Ok(report)
}

fn adopt_blocked(reason: impl Into<String>) -> DaloError {
    DaloError::StateError {
        reason: reason.into(),
    }
}

fn remove_adopted_pack(path: &Path, identity: TargetIdentity, content: &str) -> DaloResult<()> {
    if fs::symlink_metadata(path)?.file_type().is_symlink()
        || !target_has_identity_and_content(path, identity, content)?
    {
        return Err(adopt_blocked(
            "local pack changed during rollback; newer content was preserved",
        ));
    }
    remove_target_if_unchanged(path, identity, content)
}

/// Disable a pack: remove its managed block from `target` and drop its lock entry.
pub fn disable_pack(
    paths: &StorePaths,
    selector: &str,
    target: &Path,
    dry_run: bool,
) -> DaloResult<InstructionPackReport> {
    disable_pack_with_lock_writer(paths, selector, target, dry_run, store::write_user_lock)
}

fn disable_pack_with_lock_writer<F>(
    paths: &StorePaths,
    selector: &str,
    target: &Path,
    dry_run: bool,
    write_lock: F,
) -> DaloResult<InstructionPackReport>
where
    F: FnOnce(&StorePaths, &crate::lockfile::UserLock) -> DaloResult<()>,
{
    let (source_id, pack_id) = parse_pack_selector(selector)?;
    let marker_id = marker_id(&source_id, &pack_id);
    let target = normalize_target_path(target)?;
    let mut lock = store::read_user_lock(paths)?;
    let _target_lock = acquire_target_lock(paths, &target)?;
    let snapshot = target_snapshot(&target)?;
    let existing = snapshot.content.clone().unwrap_or_default();
    let (block, malformed_error) = match find_block(&existing, &marker_id) {
        Ok(block) => (block, None),
        Err(error) => (None, Some(error.to_string())),
    };
    let has_block = block.is_some();
    let before = lock.active_instruction_packs.len();
    let has_lock_entry = lock.active_instruction_packs.iter().any(|entry| {
        entry.source_id == source_id && entry.pack_id == pack_id && targets_match(entry, &target)
    });
    let warning = malformed_error.map(|error| {
        let lock_action = if has_lock_entry {
            if dry_run {
                "the lock entry would be removed"
            } else {
                "the lock entry was removed"
            }
        } else {
            "no matching lock entry was found"
        };
        format!("{error}; target left untouched and {lock_action}")
    });

    let updated = if warning.is_none() && has_block {
        Some(remove_block(&existing, &marker_id)?)
    } else {
        None
    };
    let action = if has_block || has_lock_entry {
        "disabled"
    } else {
        "unchanged"
    };

    lock.active_instruction_packs.retain(|entry| {
        !(entry.source_id == source_id && entry.pack_id == pack_id && targets_match(entry, &target))
    });
    if !dry_run {
        if let Some(updated) = updated {
            let written_identity = write_target_if_unchanged(&snapshot, &updated)?;
            if lock.active_instruction_packs.len() != before
                && let Err(error) = write_lock(paths, &lock)
            {
                return Err(restore_target_after_error(
                    snapshot,
                    &updated,
                    written_identity,
                    error,
                ));
            }
        } else if lock.active_instruction_packs.len() != before {
            write_lock(paths, &lock)?;
        }
    }

    Ok(InstructionPackReport {
        pack_id,
        source_id,
        target,
        action: action.to_owned(),
        dry_run,
        warning,
    })
}

fn normalize_target_path(target: &Path) -> DaloResult<PathBuf> {
    let absolute = store::absolute_path(target)?;
    Ok(lexically_normalize(&absolute))
}

fn targets_match(entry: &LockedInstructionPack, target: &Path) -> bool {
    entry.target == target
        || (entry.target.is_relative()
            && normalize_target_path(&entry.target).is_ok_and(|normalized| normalized == target))
        || (entry.target.is_absolute()
            && fs::canonicalize(&entry.target)
                .ok()
                .zip(fs::canonicalize(target).ok())
                .is_some_and(|(left, right)| left == right))
}

fn lexically_normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            Component::RootDir => normalized.push(component.as_os_str()),
            Component::Normal(segment) => normalized.push(segment),
        }
    }
    normalized
}

#[cfg(test)]
fn read_target(target: &Path) -> DaloResult<String> {
    match fs::read_to_string(target) {
        Ok(content) => Ok(content),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(error) => Err(error.into()),
    }
}

#[derive(Debug)]
struct TargetSnapshot {
    target: PathBuf,
    content: Option<String>,
    identity: Option<TargetIdentity>,
}

/// Stable identity for a target inode. A path can be replaced by another file
/// while an operation is in flight; checking this identity prevents rollback
/// from touching the replacement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TargetIdentity {
    device: u64,
    inode: u64,
}

/// File metadata that must survive an inode replacement.
#[derive(Debug)]
struct TargetAttributes {
    permissions: fs::Permissions,
    owner: TargetOwner,
}

/// Unix ownership for an instruction target.
#[derive(Debug, Clone, Copy)]
struct TargetOwner {
    uid: u32,
    gid: u32,
}

fn target_identity(metadata: &fs::Metadata) -> TargetIdentity {
    TargetIdentity {
        device: metadata.dev(),
        inode: metadata.ino(),
    }
}

fn target_attributes(metadata: &fs::Metadata) -> TargetAttributes {
    TargetAttributes {
        permissions: metadata.permissions(),
        owner: TargetOwner {
            uid: metadata.uid(),
            gid: metadata.gid(),
        },
    }
}

/// Advisory lock held while a target is read, rendered, replaced, or rolled back.
/// The lock is keyed by the normalized target path and intentionally lives in the
/// Dalo store so missing targets can be serialized before their first write.
#[derive(Debug)]
struct TargetLock {
    _file: fs::File,
}

fn acquire_target_lock(paths: &StorePaths, target: &Path) -> DaloResult<TargetLock> {
    let digest = Sha256::digest(target.to_string_lossy().as_bytes());
    let suffix = digest
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<String>();
    let path = paths.root.join(format!(".target-{suffix}.lock"));
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)?;
    file.lock()?;
    Ok(TargetLock { _file: file })
}

fn target_snapshot(target: &Path) -> DaloResult<TargetSnapshot> {
    let target = writable_target_path(target)?;
    match fs::read_to_string(&target) {
        Ok(content) => {
            let metadata = fs::metadata(&target)?;
            Ok(TargetSnapshot {
                target,
                content: Some(content),
                identity: Some(target_identity(&metadata)),
            })
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(TargetSnapshot {
            target,
            content: None,
            identity: None,
        }),
        Err(error) => Err(error.into()),
    }
}

fn write_target_if_unchanged(
    snapshot: &TargetSnapshot,
    content: &str,
) -> DaloResult<TargetIdentity> {
    let mut file = match snapshot.identity {
        Some(_) => Some(
            OpenOptions::new()
                .read(true)
                .write(true)
                .open(&snapshot.target)
                .map_err(|error| {
                    if error.kind() == std::io::ErrorKind::NotFound {
                        target_changed(snapshot)
                    } else {
                        error.into()
                    }
                })?,
        ),
        None => None,
    };
    let permissions = if let Some(file) = file.as_mut() {
        // The target-specific store lock serializes Dalo operations. This
        // inode lock also cooperates with editors that use advisory locks;
        // identity and content checks below detect other completed edits.
        file.lock()?;
        let metadata = file.metadata()?;
        if snapshot
            .identity
            .is_some_and(|expected| expected != target_identity(&metadata))
            || read_locked_target(file)? != snapshot.content.as_deref().unwrap_or_default()
        {
            return Err(target_changed(snapshot));
        }
        Some(target_attributes(&metadata))
    } else {
        None
    };

    replace_target_if_unchanged(snapshot, content, permissions)?;
    let metadata = fs::metadata(&snapshot.target)?;
    let identity = target_identity(&metadata);
    if !target_has_identity_and_content(&snapshot.target, identity, content)? {
        return Err(target_changed(snapshot));
    }
    Ok(identity)
}

fn read_locked_target(file: &mut fs::File) -> DaloResult<String> {
    file.seek(SeekFrom::Start(0))?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

/// Replace the target only if it still matches the pre-render snapshot.
///
/// The temporary file shares the target's directory, so `persist` is a rename
/// on the same filesystem. The target is never truncated in place: a crash
/// before the rename leaves the user's previous content intact, while a crash
/// after it leaves either the complete old file or the complete new file.
fn replace_target_if_unchanged(
    snapshot: &TargetSnapshot,
    content: &str,
    attributes: Option<TargetAttributes>,
) -> DaloResult<()> {
    replace_target_if_unchanged_with(snapshot, content, attributes, || Ok(()), sync_target_parent)
}

fn replace_target_if_unchanged_with<BeforeReplace, SyncParent>(
    snapshot: &TargetSnapshot,
    content: &str,
    attributes: Option<TargetAttributes>,
    before_replace: BeforeReplace,
    sync_parent: SyncParent,
) -> DaloResult<()>
where
    BeforeReplace: FnOnce() -> DaloResult<()>,
    SyncParent: Fn(&Path) -> DaloResult<()>,
{
    replace_target_if_unchanged_with_file_operations(
        snapshot,
        content,
        attributes,
        before_replace,
        sync_parent,
        exchange_paths,
        restore_temp_ownership,
    )
}

fn replace_target_if_unchanged_with_file_operations<
    BeforeReplace,
    SyncParent,
    ExchangePaths,
    RestoreOwnership,
>(
    snapshot: &TargetSnapshot,
    content: &str,
    attributes: Option<TargetAttributes>,
    before_replace: BeforeReplace,
    sync_parent: SyncParent,
    exchange_paths: ExchangePaths,
    restore_ownership: RestoreOwnership,
) -> DaloResult<()>
where
    BeforeReplace: FnOnce() -> DaloResult<()>,
    SyncParent: Fn(&Path) -> DaloResult<()>,
    ExchangePaths: Fn(&Path, &Path) -> rustix::io::Result<()>,
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    let parent = snapshot
        .target
        .parent()
        .ok_or_else(|| DaloError::InvalidArgument {
            reason: format!(
                "instruction target `{}` has no parent directory",
                snapshot.target.display()
            ),
        })?;
    let temp_file = stage_target_content(parent, content, attributes.as_ref(), &restore_ownership)?;
    before_replace()?;
    let operations = TargetReplacementOperations {
        sync_parent: &sync_parent,
        exchange_paths: &exchange_paths,
        restore_ownership: &restore_ownership,
    };

    if snapshot.identity.is_some() {
        replace_existing_target(
            snapshot,
            content,
            parent,
            temp_file,
            attributes.as_ref(),
            &operations,
        )
    } else {
        replace_missing_target(snapshot, content, parent, temp_file, operations.sync_parent)
    }
}

struct TargetReplacementOperations<'a, SyncParent, ExchangePaths, RestoreOwnership> {
    sync_parent: &'a SyncParent,
    exchange_paths: &'a ExchangePaths,
    restore_ownership: &'a RestoreOwnership,
}

fn stage_target_content<RestoreOwnership>(
    parent: &Path,
    content: &str,
    attributes: Option<&TargetAttributes>,
    restore_ownership: &RestoreOwnership,
) -> DaloResult<NamedTempFile>
where
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    let mut temp_file = NamedTempFile::new_in(parent)?;
    if let Some(attributes) = attributes {
        // `chown` can clear permission bits, so set ownership before the mode.
        // An EPERM only means the caller cannot preserve foreign ownership; the
        // existing target was already opened for writing before reaching here.
        match restore_ownership(temp_file.as_file(), attributes.owner) {
            Ok(()) | Err(Errno::PERM) => {}
            Err(error) => return Err(std::io::Error::from(error).into()),
        }
        temp_file
            .as_file()
            .set_permissions(attributes.permissions.clone())?;
    }
    temp_file.write_all(content.as_bytes())?;
    temp_file.flush()?;
    temp_file.as_file().sync_all()?;
    Ok(temp_file)
}

fn restore_temp_ownership(file: &fs::File, owner: TargetOwner) -> rustix::io::Result<()> {
    fchown(
        file,
        Some(Uid::from_raw(owner.uid)),
        Some(Gid::from_raw(owner.gid)),
    )
}

/// Atomically swap the staged content with an existing target. The displaced
/// file remains at the temporary path until its identity and content have been
/// verified, so a concurrent pathname replacement is restored instead of lost.
fn replace_existing_target<SyncParent, ExchangePaths, RestoreOwnership>(
    snapshot: &TargetSnapshot,
    content: &str,
    parent: &Path,
    temp_file: NamedTempFile,
    attributes: Option<&TargetAttributes>,
    operations: &TargetReplacementOperations<'_, SyncParent, ExchangePaths, RestoreOwnership>,
) -> DaloResult<()>
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
    ExchangePaths: Fn(&Path, &Path) -> rustix::io::Result<()>,
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    let staged_identity = target_identity(&temp_file.as_file().metadata()?);
    let temp_path = temp_file.into_temp_path();
    match (operations.exchange_paths)(&temp_path, &snapshot.target) {
        Ok(()) => {}
        Err(Errno::INVAL | Errno::NOTSUP) => {
            return replace_existing_target_without_exchange(
                snapshot,
                content,
                parent,
                staged_identity,
                temp_path,
                attributes,
                operations,
            );
        }
        Err(error) => return Err(std::io::Error::from(error).into()),
    }

    if !path_matches_snapshot(&temp_path, snapshot)? {
        return Err(restore_exchanged_target(
            snapshot,
            content,
            staged_identity,
            temp_path,
            parent,
            operations,
            target_changed(snapshot),
        ));
    }
    if let Err(error) = (operations.sync_parent)(parent) {
        return Err(restore_exchanged_target(
            snapshot,
            content,
            staged_identity,
            temp_path,
            parent,
            operations,
            error,
        ));
    }
    Ok(())
}

/// Replace an existing target on filesystems without an exchange rename.
///
/// This verifies the snapshot immediately before a normal same-directory rename.
/// Unlike an exchange, the rename cannot detect a pathname replacement in the
/// tiny interval after that check, so this path is reserved for filesystems that
/// reject exchange semantics altogether.
fn replace_existing_target_without_exchange<SyncParent, ExchangePaths, RestoreOwnership>(
    snapshot: &TargetSnapshot,
    content: &str,
    parent: &Path,
    staged_identity: TargetIdentity,
    temp_path: tempfile::TempPath,
    attributes: Option<&TargetAttributes>,
    operations: &TargetReplacementOperations<'_, SyncParent, ExchangePaths, RestoreOwnership>,
) -> DaloResult<()>
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
    ExchangePaths: Fn(&Path, &Path) -> rustix::io::Result<()>,
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    if !path_matches_snapshot(&snapshot.target, snapshot)? {
        return Err(target_changed(snapshot));
    }
    fs::rename(&temp_path, &snapshot.target)?;
    if let Err(error) = (operations.sync_parent)(parent) {
        return Err(restore_renamed_target(
            snapshot,
            content,
            staged_identity,
            parent,
            attributes,
            operations,
            error,
        ));
    }
    Ok(())
}

fn replace_missing_target<SyncParent>(
    snapshot: &TargetSnapshot,
    content: &str,
    parent: &Path,
    temp_file: NamedTempFile,
    sync_parent: &SyncParent,
) -> DaloResult<()>
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
{
    let staged_identity = target_identity(&temp_file.as_file().metadata()?);
    temp_file
        .persist_noclobber(&snapshot.target)
        .map_err(|error| {
            if error.error.kind() == std::io::ErrorKind::AlreadyExists {
                target_changed(snapshot)
            } else {
                error.error.into()
            }
        })?;
    if let Err(error) = sync_parent(parent) {
        return Err(restore_new_target_after_sync_failure(
            snapshot,
            content,
            staged_identity,
            parent,
            sync_parent,
            error,
        ));
    }
    Ok(())
}

fn exchange_paths(left: &Path, right: &Path) -> rustix::io::Result<()> {
    renameat_with(CWD, left, CWD, right, RenameFlags::EXCHANGE)
}

fn restore_exchanged_target<SyncParent, ExchangePaths, RestoreOwnership>(
    snapshot: &TargetSnapshot,
    content: &str,
    staged_identity: TargetIdentity,
    temp_path: tempfile::TempPath,
    parent: &Path,
    operations: &TargetReplacementOperations<'_, SyncParent, ExchangePaths, RestoreOwnership>,
    original_error: DaloError,
) -> DaloError
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
    ExchangePaths: Fn(&Path, &Path) -> rustix::io::Result<()>,
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    // Do not make a check-then-exchange decision here: an external editor can
    // replace the target between those two operations. Exchange first, then
    // inspect the displaced file. If it is no longer the staged file, retain
    // it for recovery rather than dropping user-authored content.
    if let Err(error) = (operations.exchange_paths)(&temp_path, &snapshot.target) {
        return retain_recovery_path(
            temp_path,
            format!(
                "{original_error}; also failed to restore instruction target `{}`: {}",
                snapshot.target.display(),
                std::io::Error::from(error),
            ),
        );
    }
    if !target_has_identity_and_content(&temp_path, staged_identity, content).unwrap_or(false) {
        return match temp_path.keep() {
            Ok(recovery_path) => DaloError::Io(std::io::Error::other(format!(
                "{original_error}; instruction target changed again and its newer contents were retained at `{}`",
                recovery_path.display()
            ))),
            Err(error) => DaloError::Io(std::io::Error::other(format!(
                "{original_error}; also failed to retain instruction target contents after a concurrent change: {}",
                error.error
            ))),
        };
    }
    match (operations.sync_parent)(parent) {
        Ok(()) => original_error,
        Err(restore_error) => DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to restore instruction target `{}`: {restore_error}",
            snapshot.target.display()
        ))),
    }
}

fn restore_renamed_target<SyncParent, ExchangePaths, RestoreOwnership>(
    snapshot: &TargetSnapshot,
    written_content: &str,
    written_identity: TargetIdentity,
    parent: &Path,
    attributes: Option<&TargetAttributes>,
    operations: &TargetReplacementOperations<'_, SyncParent, ExchangePaths, RestoreOwnership>,
    original_error: DaloError,
) -> DaloError
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
    ExchangePaths: Fn(&Path, &Path) -> rustix::io::Result<()>,
    RestoreOwnership: Fn(&fs::File, TargetOwner) -> rustix::io::Result<()>,
{
    if !target_has_identity_and_content(&snapshot.target, written_identity, written_content)
        .unwrap_or(false)
    {
        return DaloError::Io(std::io::Error::other(format!(
            "{original_error}; instruction target changed during rollback; newer content was left untouched"
        )));
    }
    let Some(original_content) = snapshot.content.as_deref() else {
        return DaloError::Io(std::io::Error::other(format!(
            "{original_error}; instruction target was unexpectedly missing its rollback snapshot"
        )));
    };
    let temp_file = match stage_target_content(
        parent,
        original_content,
        attributes,
        operations.restore_ownership,
    ) {
        Ok(file) => file,
        Err(error) => {
            return DaloError::Io(std::io::Error::other(format!(
                "{original_error}; also failed to stage instruction target rollback: {error}"
            )));
        }
    };
    if !target_has_identity_and_content(&snapshot.target, written_identity, written_content)
        .unwrap_or(false)
    {
        return DaloError::Io(std::io::Error::other(format!(
            "{original_error}; instruction target changed during rollback; newer content was left untouched"
        )));
    }
    if let Err(error) = fs::rename(temp_file.into_temp_path(), &snapshot.target) {
        return DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to restore instruction target `{}`: {error}",
            snapshot.target.display()
        )));
    }
    match (operations.sync_parent)(parent) {
        Ok(()) => original_error,
        Err(restore_error) => DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to restore instruction target `{}`: {restore_error}",
            snapshot.target.display()
        ))),
    }
}

fn restore_new_target_after_sync_failure<SyncParent>(
    snapshot: &TargetSnapshot,
    content: &str,
    staged_identity: TargetIdentity,
    parent: &Path,
    sync_parent: &SyncParent,
    original_error: DaloError,
) -> DaloError
where
    SyncParent: Fn(&Path) -> DaloResult<()>,
{
    // Moving the target to a private same-directory path makes it absent in
    // one pathname operation. Inspect the displaced file afterwards so a
    // concurrent replacement is preserved for recovery, never removed.
    let recovery_file = match NamedTempFile::new_in(parent) {
        Ok(file) => file,
        Err(error) => {
            return DaloError::Io(std::io::Error::other(format!(
                "{original_error}; also failed to prepare removal of instruction target `{}`: {error}",
                snapshot.target.display()
            )));
        }
    };
    let recovery_path = recovery_file.into_temp_path();
    if let Err(restore_error) = fs::rename(&snapshot.target, &recovery_path) {
        return DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to remove instruction target `{}`: {restore_error}",
            snapshot.target.display()
        )));
    }
    if !target_has_identity_and_content(&recovery_path, staged_identity, content).unwrap_or(false) {
        return retain_recovery_path(
            recovery_path,
            format!(
                "{original_error}; instruction target changed again and its newer contents were retained"
            ),
        );
    }
    match sync_parent(parent) {
        Ok(()) => original_error,
        Err(restore_error) => DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to remove instruction target `{}`: {restore_error}",
            snapshot.target.display()
        ))),
    }
}

/// Remove a target created by Dalo only if it still has the expected inode and
/// content. Moving it aside first prevents a concurrent replacement from being
/// unlinked; that replacement is retained at the recovery path instead.
fn remove_target_if_unchanged(
    target: &Path,
    expected_identity: TargetIdentity,
    expected_content: &str,
) -> DaloResult<()> {
    remove_target_if_unchanged_with(
        target,
        expected_identity,
        expected_content,
        || Ok(()),
        sync_target_parent,
    )
}

fn remove_target_if_unchanged_with<BeforeRemove, SyncParent>(
    target: &Path,
    expected_identity: TargetIdentity,
    expected_content: &str,
    before_remove: BeforeRemove,
    sync_parent: SyncParent,
) -> DaloResult<()>
where
    BeforeRemove: FnOnce() -> DaloResult<()>,
    SyncParent: Fn(&Path) -> DaloResult<()>,
{
    let parent = target.parent().ok_or_else(|| DaloError::InvalidArgument {
        reason: format!(
            "instruction target `{}` has no parent directory",
            target.display()
        ),
    })?;
    let recovery_path = NamedTempFile::new_in(parent)?.into_temp_path();
    before_remove()?;
    fs::rename(target, &recovery_path)?;

    // Once the target has been moved aside, every verification failure must be
    // treated as a concurrent replacement. Propagating a read error here would
    // drop `recovery_path` and unlink the only remaining copy of that file.
    let is_dalo_target =
        target_has_identity_and_content(&recovery_path, expected_identity, expected_content)
            .unwrap_or(false);
    let sync_result = sync_parent(parent);
    if !is_dalo_target {
        let message = match sync_result {
            Ok(()) => "instruction target changed during rollback; newer contents were retained"
                .to_owned(),
            Err(error) => format!(
                "instruction target changed during rollback; newer contents were retained after parent sync failed: {error}"
            ),
        };
        return Err(retain_recovery_path(recovery_path, message));
    }
    sync_result
}

fn retain_recovery_path(temp_path: tempfile::TempPath, message: String) -> DaloError {
    match temp_path.keep() {
        Ok(path) => DaloError::Io(std::io::Error::other(format!(
            "{message}; contents were retained at `{}`",
            path.display()
        ))),
        Err(error) => DaloError::Io(std::io::Error::other(format!(
            "{message}; also failed to retain instruction target contents: {}",
            error.error
        ))),
    }
}

fn path_matches_snapshot(path: &Path, snapshot: &TargetSnapshot) -> DaloResult<bool> {
    match fs::metadata(path) {
        Ok(metadata) => {
            let Some(expected) = snapshot.identity else {
                return Ok(false);
            };
            Ok(target_identity(&metadata) == expected
                && fs::read_to_string(path)? == snapshot.content.as_deref().unwrap_or_default())
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            Ok(snapshot.identity.is_none())
        }
        Err(error) => Err(error.into()),
    }
}

fn target_has_identity_and_content(
    target: &Path,
    expected_identity: TargetIdentity,
    expected_content: &str,
) -> DaloResult<bool> {
    match fs::metadata(target) {
        Ok(metadata) => Ok(target_identity(&metadata) == expected_identity
            && fs::read_to_string(target)? == expected_content),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error.into()),
    }
}

fn target_changed(snapshot: &TargetSnapshot) -> DaloError {
    DaloError::InstructionTargetChanged {
        path: snapshot.target.clone(),
    }
}

fn sync_target_parent(parent: &Path) -> DaloResult<()> {
    fs::File::open(parent)?.sync_all()?;
    Ok(())
}

fn restore_target_after_error(
    snapshot: TargetSnapshot,
    written_content: &str,
    written_identity: TargetIdentity,
    original_error: DaloError,
) -> DaloError {
    let target = snapshot.target.clone();
    match restore_target(snapshot, written_content, written_identity) {
        Ok(()) => original_error,
        Err(restore_error) => DaloError::Io(std::io::Error::other(format!(
            "{original_error}; also failed to restore instruction target `{}`: {restore_error}",
            target.display()
        ))),
    }
}

fn restore_target(
    snapshot: TargetSnapshot,
    written_content: &str,
    written_identity: TargetIdentity,
) -> DaloResult<()> {
    let target = snapshot.target.clone();
    match OpenOptions::new().read(true).write(true).open(&target) {
        Ok(file) => (|| -> DaloResult<()> {
            file.lock()?;
            if !target_has_identity_and_content(&target, written_identity, written_content)? {
                return Err(std::io::Error::other(
                    "instruction target changed during rollback; newer content was left untouched",
                )
                .into());
            }
            if let Some(content) = snapshot.content {
                let written_snapshot = TargetSnapshot {
                    target: target.clone(),
                    content: Some(written_content.to_owned()),
                    identity: Some(written_identity),
                };
                replace_target_if_unchanged(
                    &written_snapshot,
                    &content,
                    Some(target_attributes(&file.metadata()?)),
                )
            } else {
                drop(file);
                remove_target_if_unchanged(&target, written_identity, written_content)
            }
        })(),
        Err(error)
            if error.kind() == std::io::ErrorKind::NotFound && snapshot.content.is_none() =>
        {
            Ok(())
        }
        Err(error) => Err(error.into()),
    }
}

fn writable_target_path(target: &Path) -> DaloResult<PathBuf> {
    match fs::symlink_metadata(target) {
        Ok(metadata) if metadata.file_type().is_symlink() => Ok(fs::canonicalize(target)?),
        Ok(_) => Ok(target.to_path_buf()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(target.to_path_buf()),
        Err(error) => Err(error.into()),
    }
}

/// A discovered instruction pack (read-only inventory entry).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DiscoveredPack {
    /// Pack ID.
    pub id: String,
    /// Source the pack was discovered in.
    pub source_id: String,
    /// Declared version, when present.
    pub version: Option<String>,
    /// Declared topics/tags.
    pub topics: Vec<String>,
    /// Whether the pack is currently enabled (active in the user lock).
    pub enabled: bool,
}

impl DiscoveredPack {
    /// Source-qualified pack ref.
    #[must_use]
    pub fn pack_ref(&self) -> String {
        format!("{}:{}", self.source_id, self.id)
    }
}

/// A topic overlap between two active instruction packs (advisory).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TopicOverlap {
    /// The two overlapping pack refs.
    pub packs: [String; 2],
    /// The topics they share.
    pub topics: Vec<String>,
}

/// Discover instruction packs across the local store and configured sources.
///
/// Read-only: never materializes a pack. A pack is `enabled` when an active lock
/// entry matches its source and ID.
#[must_use]
pub fn discover_packs(
    paths: &StorePaths,
    sources: &[SourceConfig],
    active: &[LockedInstructionPack],
) -> Vec<DiscoveredPack> {
    let enabled: BTreeSet<(&str, &str)> = active
        .iter()
        .map(|entry| (entry.source_id.as_str(), entry.pack_id.as_str()))
        .collect();
    let mut packs = Vec::new();
    scan_pack_dir(&paths.local_instructions_dir, "local", &enabled, &mut packs);
    for source in sources {
        // The local source's instructions dir is the one scanned above; skip it so
        // local packs are not counted twice.
        if source.kind == SourceKind::Local {
            continue;
        }
        let Ok(source_root) =
            crate::source::scoped_source_root(&source.path, source.subpath.as_deref())
        else {
            continue;
        };
        scan_pack_dir(
            &source_root.join("instructions"),
            &source.id,
            &enabled,
            &mut packs,
        );
    }
    packs.sort_by(|left, right| {
        left.source_id
            .cmp(&right.source_id)
            .then_with(|| left.id.cmp(&right.id))
    });
    packs
}

fn scan_pack_dir(
    dir: &Path,
    source_id: &str,
    enabled: &BTreeSet<(&str, &str)>,
    out: &mut Vec<DiscoveredPack>,
) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("md") {
            continue;
        }
        let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
            continue;
        };
        if !is_valid_pack_id(id) {
            continue;
        }
        let body = fs::read_to_string(&path).unwrap_or_default();
        out.push(DiscoveredPack {
            id: id.to_owned(),
            source_id: source_id.to_owned(),
            version: parse_version(&body),
            topics: parse_topics(&body),
            enabled: enabled.contains(&(source_id, id)),
        });
    }
}

/// Optional `topics:`/`tags:` line in the pack's leading lines (comma-separated).
fn parse_topics(body: &str) -> Vec<String> {
    body.lines()
        .take(8)
        .find_map(|line| {
            let trimmed = line.trim();
            trimmed
                .strip_prefix("topics:")
                .or_else(|| trimmed.strip_prefix("tags:"))
        })
        .map(|value| {
            value
                .split(',')
                .map(|topic| topic.trim().to_owned())
                .filter(|topic| !topic.is_empty())
                .collect()
        })
        .unwrap_or_default()
}

/// Detect declared-topic overlaps among active packs. Advisory only: overlaps
/// never block materialization.
#[must_use]
pub fn topic_overlaps(active: &[DiscoveredPack]) -> Vec<TopicOverlap> {
    let mut overlaps = Vec::new();
    for (index, left) in active.iter().enumerate() {
        for right in active.iter().skip(index + 1) {
            let mut shared: Vec<String> = left
                .topics
                .iter()
                .filter(|topic| right.topics.contains(topic))
                .cloned()
                .collect();
            if !shared.is_empty() {
                shared.sort();
                shared.dedup();
                overlaps.push(TopicOverlap {
                    packs: [left.pack_ref(), right.pack_ref()],
                    topics: shared,
                });
            }
        }
    }
    overlaps
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};

    use super::*;
    use proptest::prelude::*;

    const PACK: &str = "house-style";

    #[test]
    fn render_block_should_append_when_absent_and_be_idempotent() {
        let original = "# Project\n\nNotes.\n";
        let once = render_block(original, PACK, "Use tabs.").expect("render should succeed");
        assert!(has_block(&once, PACK));
        assert!(once.starts_with("# Project\n\nNotes.\n"));
        // A second render with the same body changes nothing.
        let twice = render_block(&once, PACK, "Use tabs.").expect("render should succeed");
        assert_eq!(once, twice);
    }

    #[test]
    fn render_block_should_preserve_crlf_line_endings() {
        let original = "# Project\r\n\r\nNotes.\r\n";
        let rendered =
            render_block(original, PACK, "Use tabs.\nSecond line.").expect("render should succeed");

        assert!(rendered.contains("<!-- dalo:start house-style -->\r\n"));
        assert!(rendered.contains("Use tabs.\r\nSecond line."));
        assert!(!rendered.replace("\r\n", "").contains('\n'));
    }

    #[test]
    fn render_block_should_only_touch_bytes_inside_markers() {
        let original = "TOP CONTENT\n\n<!-- dalo:start house-style -->\nold\n<!-- dalo:end house-style -->\n\nBOTTOM CONTENT\n";
        let updated = render_block(original, PACK, "new body").expect("render should succeed");
        // Everything outside the block is byte-identical.
        assert!(updated.starts_with("TOP CONTENT\n\n"));
        assert!(updated.ends_with("\n\nBOTTOM CONTENT\n"));
        assert!(updated.contains("new body"));
        assert!(!updated.contains("old"));
    }

    proptest! {
        #[test]
        fn render_block_should_preserve_surrounding_text_and_stay_idempotent(
            prefix in "[A-Za-z0-9 ._\\n-]{0,80}",
            body in "[A-Za-z0-9 ._\\n-]{0,80}",
            suffix in "[A-Za-z0-9 ._\\n-]{0,80}",
        ) {
            let original = format!(
                "{}{}\\nold body\\n{}{}",
                prefix,
                start_marker(PACK),
                end_marker(PACK),
                suffix
            );

            let rendered = render_block(&original, PACK, &body).expect("render should succeed");
            prop_assert!(rendered.starts_with(&prefix));
            prop_assert!(rendered.ends_with(&suffix));
            prop_assert_eq!(
                render_block(&rendered, PACK, &body).expect("rerender should succeed"),
                rendered
            );
        }
    }

    #[test]
    fn remove_block_should_preserve_surrounding_content() {
        let original = "# Header\n\nIntro.\n";
        let rendered = render_block(original, PACK, "Body.").expect("render should succeed");
        let removed = remove_block(&rendered, PACK).expect("remove should succeed");
        assert!(!has_block(&removed, PACK));
        // The user-owned content survives the round trip.
        assert!(removed.contains("# Header"));
        assert!(removed.contains("Intro."));
        assert!(!removed.contains("dalo:start"));
    }

    #[test]
    fn remove_block_should_keep_content_on_both_sides() {
        let original = "ABOVE\n\n<!-- dalo:start house-style -->\nbody\n<!-- dalo:end house-style -->\n\nBELOW\n";
        let removed = remove_block(original, PACK).expect("remove should succeed");
        assert!(removed.contains("ABOVE"));
        assert!(removed.contains("BELOW"));
        assert!(!removed.contains("dalo:"));
    }

    #[test]
    fn remove_block_should_preserve_crlf_seams() {
        let original = "ABOVE\r\n\r\n<!-- dalo:start house-style -->\r\nbody\r\n<!-- dalo:end house-style -->\r\n\r\nBELOW\r\n";
        let removed = remove_block(original, PACK).expect("remove should succeed");

        assert_eq!(removed, "ABOVE\r\n\r\nBELOW\r\n");
    }

    #[test]
    fn remove_block_should_noop_when_absent() {
        let original = "# Header\n\nNo blocks here.\n";
        assert_eq!(
            remove_block(original, PACK).expect("remove should succeed"),
            original
        );
    }

    #[test]
    fn render_block_should_reject_malformed_markers() {
        let malformed = "# Header\n\n<!-- dalo:start house-style -->\nmissing end\n";
        let error = render_block(malformed, PACK, "Body.").expect_err("render should fail");

        assert!(matches!(error, DaloError::MalformedInstructionBlock { .. }));
    }

    #[test]
    fn render_block_should_reject_duplicate_start_markers() {
        let malformed = format!(
            "# Header\n\n{}\nold\n{}\nsecond\n{}\n",
            start_marker(PACK),
            start_marker(PACK),
            end_marker(PACK)
        );

        let error = render_block(&malformed, PACK, "Body.").expect_err("render should fail");

        assert!(matches!(error, DaloError::MalformedInstructionBlock { .. }));
    }

    #[test]
    fn render_block_should_reject_end_before_start() {
        let malformed = format!(
            "# Header\n\n{}\nold\n{}\n",
            end_marker(PACK),
            start_marker(PACK)
        );

        let error = render_block(&malformed, PACK, "Body.").expect_err("render should fail");

        assert!(matches!(error, DaloError::MalformedInstructionBlock { .. }));
    }

    #[test]
    fn render_block_should_replace_user_edits_inside_managed_block() {
        let rendered = render_block("# Header\n", PACK, "Original body.")
            .expect("initial render should succeed");
        let edited = rendered.replace("Original body.", "User edit inside block.");

        let updated =
            render_block(&edited, PACK, "Original body.").expect("rerender should succeed");

        assert_eq!(updated, rendered);
        assert!(!updated.contains("User edit inside block."));
    }

    #[test]
    fn render_block_should_handle_existing_block_at_eof_without_trailing_newline() {
        let content = format!("{}\nOld body\n{}", start_marker(PACK), end_marker(PACK));

        let updated = render_block(&content, PACK, "New body").expect("render should succeed");

        assert_eq!(updated, render_managed_block(PACK, "New body").unwrap());
    }

    #[test]
    fn render_block_should_reject_same_id_marker_in_body() {
        let body = format!("Do not emit this marker:\n{}\n", end_marker(PACK));

        let error = render_block("# Header\n", PACK, &body).expect_err("render should fail");

        assert_body_marker_error(error, PACK);
    }

    #[test]
    fn render_block_should_reject_different_id_marker_in_body() {
        let body = format!(
            "Example for another pack:\n{}\n",
            start_marker("other-pack")
        );

        let error = render_block("# Header\n", PACK, &body).expect_err("render should fail");

        assert_body_marker_error(error, PACK);
    }

    #[test]
    fn enable_pack_should_reject_marker_body_without_rewriting_target() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp.path().join("store");
        let target = temp.path().join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("store should be initialized");
        let paths = StorePaths::new(store_root);
        fs::write(
            paths.local_instructions_dir.join(format!("{PACK}.md")),
            format!("Before\n{}\nAfter\n", start_marker("other-pack")),
        )
        .expect("pack should be written");
        fs::write(&target, "user-owned content\n").expect("target should be seeded");

        let error = enable_pack(&paths, PACK, &target, false).expect_err("enable should fail");

        assert_body_marker_error(error, PACK);
        assert_eq!(
            fs::read_to_string(&target).expect("target should be readable"),
            "user-owned content\n"
        );
        let lock = store::read_user_lock(&paths).expect("lock should be readable");
        assert!(lock.active_instruction_packs.is_empty());
    }

    #[test]
    fn adoption_failure_should_restore_target_and_preserve_concurrent_edits() {
        for concurrent_edit in ["none", "pack", "target"] {
            let temp = tempfile::tempdir().unwrap();
            let paths = StorePaths::new(temp.path().join("store"));
            store::init_store(paths.root.clone(), false).unwrap();
            let repo = temp.path().join("team");
            fs::create_dir_all(repo.join("instructions")).unwrap();
            fs::write(repo.join("instructions/style.md"), "Team body\n").unwrap();
            git::init_repo(&repo).unwrap();
            let output = std::process::Command::new("git")
                .current_dir(&repo)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_NOSYSTEM", "1")
                .env_remove("GIT_CONFIG_COUNT")
                .env_remove("GIT_CONFIG_PARAMETERS")
                .args(["add", "."])
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
            let output = std::process::Command::new("git")
                .current_dir(&repo)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_NOSYSTEM", "1")
                .env_remove("GIT_CONFIG_COUNT")
                .env_remove("GIT_CONFIG_PARAMETERS")
                .args([
                    "-c",
                    "user.name=Test",
                    "-c",
                    "user.email=test@example.com",
                    "commit",
                    "-qm",
                    "test: source fixture",
                ])
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
            crate::source::add_team_source(&paths, "team", repo.to_str().unwrap(), None, false)
                .unwrap();
            let target = temp.path().join("AGENTS.md");
            enable_pack(&paths, "team:style", &target, false).unwrap();
            let edited = fs::read_to_string(&target)
                .unwrap()
                .replace("Team body", "Local body");
            fs::write(&target, &edited).unwrap();
            let before_lock = fs::read(&paths.lock_file).unwrap();
            let local_path = paths.local_instructions_dir.join("style.md");
            let error = adopt_pack_with_lock_writer(&paths, "team:style", None, false, |_, _| {
                match concurrent_edit {
                    "pack" => fs::write(&local_path, "Newer local content").unwrap(),
                    "target" => fs::write(&target, "Newer target content").unwrap(),
                    _ => {}
                }
                Err(DaloError::Io(std::io::Error::other("lock write failed")))
            })
            .unwrap_err();
            assert!(error.to_string().contains("lock write failed"));
            assert_eq!(fs::read(&paths.lock_file).unwrap(), before_lock);
            match concurrent_edit {
                "none" => {
                    assert_eq!(fs::read_to_string(&target).unwrap(), edited);
                    assert!(!local_path.exists());
                }
                "pack" => {
                    assert_eq!(fs::read_to_string(&target).unwrap(), edited);
                    assert_eq!(
                        fs::read_to_string(&local_path).unwrap(),
                        "Newer local content"
                    );
                }
                "target" => {
                    assert_eq!(fs::read_to_string(&target).unwrap(), "Newer target content");
                    assert!(
                        fs::read_to_string(&local_path)
                            .unwrap()
                            .contains("Local body")
                    );
                    assert!(error.to_string().contains("retained"));
                }
                _ => unreachable!(),
            }
        }
    }

    #[test]
    fn enable_pack_should_restore_target_when_lock_write_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp.path().join("store");
        let target = temp.path().join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("store should be initialized");
        let paths = StorePaths::new(store_root);
        fs::write(
            paths.local_instructions_dir.join(format!("{PACK}.md")),
            "Body\n",
        )
        .expect("pack should be written");
        fs::write(&target, "user-owned content\n").expect("target should be seeded");

        let error = enable_pack_with_lock_writer(&paths, PACK, &target, &[], false, |_, _| {
            Err(DaloError::Io(std::io::Error::other("lock write failed")))
        })
        .expect_err("lock write failure should fail enable");

        assert!(matches!(error, DaloError::Io(_)));
        assert_eq!(
            fs::read_to_string(&target).expect("target should be readable"),
            "user-owned content\n"
        );
        assert!(
            store::read_user_lock(&paths)
                .expect("lock should be readable")
                .active_instruction_packs
                .is_empty()
        );
    }

    #[test]
    fn enable_pack_should_atomically_replace_only_the_managed_block() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp.path().join("store");
        let target = temp.path().join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("store should be initialized");
        let paths = StorePaths::new(store_root);
        fs::write(
            paths.local_instructions_dir.join(format!("{PACK}.md")),
            "new managed instructions\n",
        )
        .expect("pack should be written");
        let marker = marker_id("local", PACK);
        let original = format!(
            "# User heading\n\n{}\nold managed instructions\n{}\n\nUser footer\n",
            start_marker(&marker),
            end_marker(&marker)
        );
        fs::write(&target, &original).expect("target should be seeded");
        let before_inode = fs::metadata(&target)
            .expect("target metadata should be readable")
            .ino();

        enable_pack(&paths, PACK, &target, false).expect("pack should enable");

        let updated = fs::read_to_string(&target).expect("target should be readable");
        assert_eq!(
            updated,
            render_block(&original, &marker, "new managed instructions\n")
                .expect("render should succeed")
        );
        assert!(updated.starts_with("# User heading\n\n"));
        assert!(updated.ends_with("\n\nUser footer\n"));
        assert_ne!(
            before_inode,
            fs::metadata(&target)
                .expect("target metadata should be readable")
                .ino()
        );
    }

    #[test]
    fn disable_pack_should_restore_target_when_lock_write_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp.path().join("store");
        let target = temp.path().join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("store should be initialized");
        let paths = StorePaths::new(store_root);
        fs::write(
            paths.local_instructions_dir.join(format!("{PACK}.md")),
            "Body\n",
        )
        .expect("pack should be written");
        enable_pack(&paths, PACK, &target, false).expect("pack should enable");
        let before = fs::read_to_string(&target).expect("target should be readable");

        let error = disable_pack_with_lock_writer(&paths, PACK, &target, false, |_, _| {
            Err(DaloError::Io(std::io::Error::other("lock write failed")))
        })
        .expect_err("lock write failure should fail disable");

        assert!(matches!(error, DaloError::Io(_)));
        assert_eq!(fs::read_to_string(&target).unwrap(), before);
        assert_eq!(
            store::read_user_lock(&paths)
                .expect("lock should be readable")
                .active_instruction_packs
                .len(),
            1
        );
    }

    #[test]
    fn disable_pack_should_remove_lock_and_leave_malformed_target_untouched() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp.path().join("store");
        let target = temp.path().join("AGENTS.md");
        store::init_store(store_root.clone(), false).expect("store should be initialized");
        let paths = StorePaths::new(store_root);
        fs::write(
            paths.local_instructions_dir.join(format!("{PACK}.md")),
            "Body\n",
        )
        .expect("pack should be written");
        fs::write(&target, "user-owned content\n").expect("target should be seeded");
        enable_pack(&paths, PACK, &target, false).expect("pack should enable");

        let malformed = format!(
            "user-owned content\n\n{}\nmissing end\n",
            start_marker(PACK)
        );
        fs::write(&target, &malformed).expect("malformed target should be written");

        let report = disable_pack(&paths, PACK, &target, false)
            .expect("disable should recover the malformed block lock");

        assert_eq!(report.action, "disabled");
        assert!(
            report
                .warning
                .as_deref()
                .is_some_and(|warning| warning.contains("target left untouched"))
        );
        assert_eq!(fs::read_to_string(&target).unwrap(), malformed);
        assert!(
            store::read_user_lock(&paths)
                .unwrap()
                .active_instruction_packs
                .is_empty()
        );
    }

    #[test]
    fn instruction_rollback_should_report_restore_failure() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let occupied_target = temp.path().join("AGENTS.md");
        fs::create_dir(&occupied_target).expect("target directory should be created");
        let snapshot = TargetSnapshot {
            target: occupied_target.clone(),
            content: Some("previous content\n".to_owned()),
            identity: Some(TargetIdentity {
                device: 0,
                inode: 0,
            }),
        };

        let error = restore_target_after_error(
            snapshot,
            "new content",
            TargetIdentity {
                device: 0,
                inode: 0,
            },
            DaloError::Io(std::io::Error::other("lock write failed")),
        );
        let message = error.to_string();

        assert!(message.contains("lock write failed"));
        assert!(message.contains("also failed to restore instruction target"));
        assert!(message.contains(&occupied_target.display().to_string()));
    }

    #[test]
    fn instruction_refresh_rollback_should_restore_written_targets() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let mut prepared = vec![PreparedInstructionMutation {
            logical_targets: Vec::new(),
            target: target.clone(),
            snapshot,
            rendered: Some("after\n".to_owned()),
            action: "refreshed".to_owned(),
            warning: None,
        }];
        let written = apply_prepared_target_writes(&mut prepared)
            .expect("instruction refresh should be written");
        let rollback = InstructionRefreshRollback {
            prepared,
            written,
            _target_locks: Vec::new(),
        };

        rollback.restore().expect("rollback should restore target");

        assert_eq!(fs::read_to_string(target).unwrap(), "before\n");
    }

    #[test]
    fn batch_write_should_roll_back_earlier_targets_after_a_later_concurrent_edit() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let first = temp.path().join("AGENTS.md");
        let second = temp.path().join("CLAUDE.md");
        fs::write(&first, "first before\n").expect("first target should be seeded");
        fs::write(&second, "second before\n").expect("second target should be seeded");
        let first_snapshot = target_snapshot(&first).expect("first snapshot should be readable");
        let second_snapshot = target_snapshot(&second).expect("second snapshot should be readable");
        fs::write(&second, "external edit\n").expect("second target should be edited");
        let mut prepared = vec![
            PreparedInstructionMutation {
                logical_targets: vec!["codex".to_owned()],
                target: first.clone(),
                snapshot: first_snapshot,
                rendered: Some("first after\n".to_owned()),
                action: "enabled".to_owned(),
                warning: None,
            },
            PreparedInstructionMutation {
                logical_targets: vec!["claude".to_owned()],
                target: second.clone(),
                snapshot: second_snapshot,
                rendered: Some("second after\n".to_owned()),
                action: "enabled".to_owned(),
                warning: None,
            },
        ];

        let error = apply_prepared_target_writes(&mut prepared)
            .expect_err("concurrent edit should fail the batch");

        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert_eq!(fs::read_to_string(first).unwrap(), "first before\n");
        assert_eq!(fs::read_to_string(second).unwrap(), "external edit\n");
    }

    #[test]
    fn write_target_if_unchanged_should_preserve_external_edit() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        fs::write(&target, "external edit\n").expect("target should be edited");

        let error = write_target_if_unchanged(&snapshot, "dalo output\n")
            .expect_err("external edit should block replacement");
        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert_eq!(fs::read_to_string(&target).unwrap(), "external edit\n");
    }

    #[test]
    fn write_target_if_unchanged_should_reject_replaced_file() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        fs::write(&replacement, "external edit\n").expect("replacement should be written");
        fs::rename(&replacement, &target).expect("replacement should be installed");

        let error = write_target_if_unchanged(&snapshot, "dalo output\n")
            .expect_err("replaced target should block replacement");
        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert_eq!(fs::read_to_string(&target).unwrap(), "external edit\n");
    }

    #[test]
    fn replacement_should_restore_a_pathname_change_that_races_the_swap() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        fs::write(&replacement, "external edit\n").expect("replacement should be written");

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || {
                fs::rename(&replacement, &target)?;
                Ok(())
            },
            sync_target_parent,
        )
        .expect_err("pathname change should block replacement");

        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert_eq!(fs::read_to_string(&target).unwrap(), "external edit\n");
        assert_eq!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .count(),
            1
        );
    }

    #[test]
    fn replacement_should_restore_the_target_when_directory_sync_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |parent| {
                if sync_calls.replace(1) == 0 {
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    sync_target_parent(parent)
                }
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert_eq!(fs::read_to_string(&target).unwrap(), "before\n");
    }

    #[test]
    fn replacement_should_retain_an_edit_that_races_sync_failure_rollback() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |_| {
                if sync_calls.replace(1) == 0 {
                    fs::write(&replacement, "external edit\n")?;
                    fs::rename(&replacement, &target)?;
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    Ok(())
                }
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert_eq!(fs::read_to_string(&target).unwrap(), "before\n");
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read_to_string(entry.path()).ok().as_deref()
                    == Some("external edit\n"))
        );
    }

    #[test]
    fn replacement_should_retain_the_displaced_file_when_rollback_exchange_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |_| {
                if sync_calls.replace(1) == 0 {
                    fs::remove_file(&target)?;
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    Ok(())
                }
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert!(!target.exists());
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read_to_string(entry.path()).ok().as_deref() == Some("before\n"))
        );
    }

    #[test]
    fn missing_target_replacement_should_remove_the_new_file_when_directory_sync_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |parent| {
                if sync_calls.replace(1) == 0 {
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    sync_target_parent(parent)
                }
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert!(!target.exists());
    }

    #[test]
    fn missing_target_replacement_should_retain_an_edit_that_races_rollback() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |_| {
                if sync_calls.replace(1) == 0 {
                    fs::write(&replacement, "external edit\n")?;
                    fs::rename(&replacement, &target)?;
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    Ok(())
                }
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert!(!target.exists());
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read_to_string(entry.path()).ok().as_deref()
                    == Some("external edit\n"))
        );
    }

    #[test]
    fn missing_target_replacement_should_retain_an_edit_when_rollback_sync_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |_| {
                if sync_calls.replace(1) == 0 {
                    fs::write(&replacement, "external edit\n")?;
                    fs::rename(&replacement, &target)?;
                }
                Err(DaloError::Io(std::io::Error::other(
                    "directory sync failed",
                )))
            },
        )
        .expect_err("directory sync failure should fail replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert!(!target.exists());
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read_to_string(entry.path()).ok().as_deref()
                    == Some("external edit\n"))
        );
    }

    #[test]
    fn write_target_if_unchanged_should_reject_a_removed_file() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        fs::remove_file(&target).expect("target should be removed");

        let error = write_target_if_unchanged(&snapshot, "dalo output\n")
            .expect_err("removed target should block replacement");

        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert!(!target.exists());
    }

    #[test]
    fn rollback_should_not_restore_over_newer_external_content() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let written_identity = write_target_if_unchanged(&snapshot, "dalo output\n")
            .expect("dalo output should be written");
        fs::write(&target, "newer external edit\n").expect("target should be edited");

        let error = restore_target_after_error(
            snapshot,
            "dalo output\n",
            written_identity,
            DaloError::Io(std::io::Error::other("lock write failed")),
        );

        assert!(
            error
                .to_string()
                .contains("newer content was left untouched")
        );
        assert_eq!(
            fs::read_to_string(&target).unwrap(),
            "newer external edit\n"
        );
    }

    #[test]
    fn rollback_should_not_restore_over_replaced_file_with_same_content() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let written_identity = write_target_if_unchanged(&snapshot, "dalo output\n")
            .expect("dalo output should be written");
        fs::write(&replacement, "dalo output\n").expect("replacement should be written");
        fs::rename(&replacement, &target).expect("replacement should be installed");

        let error = restore_target_after_error(
            snapshot,
            "dalo output\n",
            written_identity,
            DaloError::Io(std::io::Error::other("lock write failed")),
        );

        assert!(
            error
                .to_string()
                .contains("newer content was left untouched")
        );
        assert_eq!(fs::read_to_string(&target).unwrap(), "dalo output\n");
    }

    #[test]
    fn rollback_removal_should_retain_an_edit_that_races_rename_aside() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "dalo output\n").expect("target should be seeded");
        let written_identity =
            target_identity(&fs::metadata(&target).expect("target metadata should be readable"));
        fs::write(&replacement, "external edit\n").expect("replacement should be written");

        let error = remove_target_if_unchanged_with(
            &target,
            written_identity,
            "dalo output\n",
            || {
                fs::rename(&replacement, &target)?;
                Ok(())
            },
            sync_target_parent,
        )
        .expect_err("concurrent replacement should not be removed");

        assert!(error.to_string().contains("contents were retained at"));
        assert!(!target.exists());
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read_to_string(entry.path()).ok().as_deref()
                    == Some("external edit\n"))
        );
    }

    #[test]
    fn rollback_removal_should_retain_non_utf8_replacement() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        let replacement = temp.path().join("AGENTS.md.external");
        fs::write(&target, "dalo output\n").expect("target should be seeded");
        let written_identity =
            target_identity(&fs::metadata(&target).expect("target metadata should be readable"));
        let replacement_bytes = [0xff, 0xfe, 0xfd];
        fs::write(&replacement, replacement_bytes).expect("replacement should be written");

        let error = remove_target_if_unchanged_with(
            &target,
            written_identity,
            "dalo output\n",
            || {
                fs::rename(&replacement, &target)?;
                Ok(())
            },
            sync_target_parent,
        )
        .expect_err("non-UTF-8 replacement should be retained");

        assert!(error.to_string().contains("contents were retained at"));
        assert!(!target.exists());
        assert!(
            fs::read_dir(temp.path())
                .expect("parent directory should be readable")
                .filter_map(Result::ok)
                .any(|entry| fs::read(entry.path()).ok().as_deref() == Some(&replacement_bytes))
        );
    }

    #[test]
    fn parse_version_should_read_leading_version_line() {
        assert_eq!(
            parse_version("version: 1.2.0\n\n# Body\n"),
            Some("1.2.0".to_owned())
        );
        assert_eq!(parse_version("# Body only\n"), None);
    }

    #[test]
    fn is_valid_pack_id_should_reject_traversal() {
        assert!(is_valid_pack_id("house-style"));
        assert!(!is_valid_pack_id(".."));
        assert!(!is_valid_pack_id("bad/slash"));
        assert!(!is_valid_pack_id(""));
    }

    #[test]
    fn parse_topics_should_split_comma_separated_tags() {
        assert_eq!(
            parse_topics("topics: review, formatting, git\n\n# Body\n"),
            vec!["review", "formatting", "git"]
        );
        assert_eq!(parse_topics("tags: a,b\n"), vec!["a", "b"]);
        assert!(parse_topics("# No topics\n").is_empty());
    }

    fn discovered(id: &str, source: &str, topics: &[&str], enabled: bool) -> DiscoveredPack {
        DiscoveredPack {
            id: id.to_owned(),
            source_id: source.to_owned(),
            version: None,
            topics: topics.iter().map(|topic| (*topic).to_owned()).collect(),
            enabled,
        }
    }

    #[test]
    fn topic_overlaps_should_name_both_packs_sharing_a_topic() {
        let active = vec![
            discovered("style", "local", &["formatting", "tone"], true),
            discovered("format", "team", &["formatting"], true),
        ];
        let overlaps = topic_overlaps(&active);
        assert_eq!(overlaps.len(), 1);
        assert_eq!(
            overlaps[0].packs,
            ["local:style".to_owned(), "team:format".to_owned()]
        );
        assert_eq!(overlaps[0].topics, vec!["formatting".to_owned()]);
    }

    #[test]
    fn topic_overlaps_should_ignore_disjoint_topics() {
        let active = vec![
            discovered("a", "local", &["security"], true),
            discovered("b", "team", &["formatting"], true),
        ];
        assert!(topic_overlaps(&active).is_empty());
    }

    #[test]
    fn discover_packs_should_find_local_packs_and_mark_enabled() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let paths = StorePaths::new(temp.path().to_path_buf());
        fs::create_dir_all(&paths.local_instructions_dir).expect("dir should be created");
        fs::write(
            paths.local_instructions_dir.join("house.md"),
            "topics: x\n\nBody\n",
        )
        .expect("pack should be written");
        let active = vec![LockedInstructionPack {
            pack_id: "house".to_owned(),
            target: PathBuf::from("/tmp/AGENTS.md"),
            logical_targets: Vec::new(),
            source_id: "local".to_owned(),
            commit: None,
            version: None,
        }];

        let packs = discover_packs(&paths, &[], &active);
        assert_eq!(packs.len(), 1);
        assert_eq!(packs[0].id, "house");
        assert!(packs[0].enabled);
        assert_eq!(packs[0].topics, vec!["x".to_owned()]);
    }

    #[test]
    fn read_target_should_treat_missing_file_as_empty_only() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let missing = temp.path().join("AGENTS.md");

        assert_eq!(
            read_target(&missing).expect("missing target should read as empty"),
            ""
        );
    }

    #[test]
    fn write_target_if_unchanged_should_replace_file_via_temp_rename() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let before_inode = fs::metadata(&target)
            .expect("target metadata should be readable")
            .ino();

        write_target_if_unchanged(&snapshot, "new\n").expect("target should be written");

        assert_eq!(
            fs::read_to_string(&target).expect("target should be readable"),
            "new\n"
        );
        let after_inode = fs::metadata(&target)
            .expect("target metadata should be readable")
            .ino();
        assert_ne!(before_inode, after_inode);
        assert_eq!(
            fs::read_dir(temp.path())
                .expect("parent dir should be readable")
                .count(),
            1
        );
    }

    #[test]
    fn write_target_if_unchanged_should_preserve_existing_permissions() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        fs::set_permissions(&target, fs::Permissions::from_mode(0o644))
            .expect("permissions should be set");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");

        write_target_if_unchanged(&snapshot, "new\n").expect("target should be written");

        let mode = fs::metadata(&target)
            .expect("target metadata should be readable")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o644);
    }

    #[test]
    fn write_target_if_unchanged_should_preserve_existing_owner_and_group() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        let before = fs::metadata(&target).expect("target metadata should be readable");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");

        write_target_if_unchanged(&snapshot, "new\n").expect("target should be written");

        let after = fs::metadata(&target).expect("target metadata should be readable");
        assert_eq!(after.uid(), before.uid());
        assert_eq!(after.gid(), before.gid());
    }

    #[test]
    fn replacement_should_fall_back_when_exchange_is_unsupported() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let exchange_calls = Cell::new(0);

        replace_target_if_unchanged_with_file_operations(
            &snapshot,
            "new\n",
            None,
            || Ok(()),
            sync_target_parent,
            |_, _| {
                exchange_calls.set(exchange_calls.get() + 1);
                Err(Errno::INVAL)
            },
            restore_temp_ownership,
        )
        .expect("unsupported exchange should fall back to rename");

        assert_eq!(exchange_calls.get(), 1);
        assert_eq!(fs::read_to_string(target).unwrap(), "new\n");
    }

    #[test]
    fn fallback_replacement_should_reject_a_changed_target() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");

        let error = replace_target_if_unchanged_with_file_operations(
            &snapshot,
            "dalo output\n",
            None,
            || {
                fs::write(&target, "external edit\n")?;
                Ok(())
            },
            sync_target_parent,
            |_, _| Err(Errno::INVAL),
            restore_temp_ownership,
        )
        .expect_err("fallback should reject a changed target");

        assert!(matches!(error, DaloError::InstructionTargetChanged { .. }));
        assert_eq!(fs::read_to_string(target).unwrap(), "external edit\n");
    }

    #[test]
    fn fallback_replacement_should_restore_target_when_directory_sync_fails() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "before\n").expect("target should be seeded");
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let sync_calls = Cell::new(0);

        let error = replace_target_if_unchanged_with_file_operations(
            &snapshot,
            "dalo output\n",
            None,
            || Ok(()),
            |parent| {
                if sync_calls.replace(1) == 0 {
                    Err(DaloError::Io(std::io::Error::other(
                        "directory sync failed",
                    )))
                } else {
                    sync_target_parent(parent)
                }
            },
            |_, _| Err(Errno::NOTSUP),
            restore_temp_ownership,
        )
        .expect_err("directory sync failure should restore fallback replacement");

        assert!(error.to_string().contains("directory sync failed"));
        assert_eq!(fs::read_to_string(target).unwrap(), "before\n");
    }

    #[test]
    fn replacement_should_ignore_eprem_while_restoring_ownership() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        let metadata = fs::metadata(&target).expect("target metadata should be readable");
        let attributes = target_attributes(&metadata);
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");
        let ownership_calls = Cell::new(0);

        replace_target_if_unchanged_with_file_operations(
            &snapshot,
            "new\n",
            Some(attributes),
            || Ok(()),
            sync_target_parent,
            |_, _| Err(Errno::INVAL),
            |_, _| {
                ownership_calls.set(ownership_calls.get() + 1);
                Err(Errno::PERM)
            },
        )
        .expect("EPERM should not block a writable target replacement");

        assert_eq!(ownership_calls.get(), 1);
        assert_eq!(fs::read_to_string(target).unwrap(), "new\n");
    }

    #[test]
    fn replacement_should_reject_unexpected_ownership_errors_before_mutating() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let target = temp.path().join("AGENTS.md");
        fs::write(&target, "old\n").expect("target should be seeded");
        let metadata = fs::metadata(&target).expect("target metadata should be readable");
        let before_identity = target_identity(&metadata);
        let snapshot = target_snapshot(&target).expect("snapshot should be readable");

        let error = replace_target_if_unchanged_with_file_operations(
            &snapshot,
            "new\n",
            Some(target_attributes(&metadata)),
            || Ok(()),
            sync_target_parent,
            |_, _| Err(Errno::INVAL),
            |_, _| Err(Errno::ACCESS),
        )
        .expect_err("unexpected ownership error should block replacement");

        let DaloError::Io(error) = error else {
            panic!("unexpected ownership error should remain an I/O error");
        };
        assert_eq!(error.raw_os_error(), Some(Errno::ACCESS.raw_os_error()));
        assert_eq!(fs::read_to_string(&target).unwrap(), "old\n");
        assert_eq!(
            target_identity(&fs::metadata(&target).expect("target metadata should be readable")),
            before_identity
        );
    }

    #[test]
    fn write_target_if_unchanged_should_write_through_symlinked_target() {
        let temp = tempfile::tempdir().expect("tempdir should be created");
        let canonical_target = temp.path().join("AGENTS.md");
        let symlink_target = temp.path().join("CLAUDE.md");
        fs::write(&canonical_target, "old\n").expect("target should be seeded");
        symlink(&canonical_target, &symlink_target).expect("symlink should be created");
        let snapshot = target_snapshot(&symlink_target).expect("snapshot should be readable");

        write_target_if_unchanged(&snapshot, "new\n").expect("target should be written");

        assert!(
            fs::symlink_metadata(&symlink_target)
                .expect("symlink metadata should be readable")
                .file_type()
                .is_symlink()
        );
        assert_eq!(
            fs::read_to_string(&canonical_target).expect("canonical target should be readable"),
            "new\n"
        );
    }

    fn assert_body_marker_error(error: DaloError, pack_id: &str) {
        let DaloError::MalformedInstructionBlock {
            pack_id: actual,
            reason,
        } = error
        else {
            panic!("expected malformed instruction block error");
        };
        assert_eq!(actual, pack_id);
        assert!(reason.contains("body contains dalo managed-block marker"));
    }
}