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
//! Passive portable plugin package discovery and validation.
//!
//! A plugin package is inert inventory. Discovery never executes provider
//! overlays or reserved active component descriptors.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

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

use crate::agent::AgentResolution;
use crate::config::{PluginPolicyDecision, PluginPolicyLayer, UserConfig};
use crate::hook::{self, HookBindingType, HookDescriptorV1};
use crate::inventory::SourceInventory;
use crate::resolver::Resolution;
use crate::source::SourceConfig;
use crate::team_manifest::{self, StackRequirement, TEAM_MANIFEST_FILE};

#[cfg(test)]
thread_local! {
    static SOURCE_PLUGIN_SCAN_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
pub(crate) fn reset_source_plugin_scan_count() {
    SOURCE_PLUGIN_SCAN_COUNT.with(|count| count.set(0));
}

#[cfg(test)]
pub(crate) fn source_plugin_scan_count() -> usize {
    SOURCE_PLUGIN_SCAN_COUNT.with(std::cell::Cell::get)
}

/// Canonical plugin manifest filename.
pub const PLUGIN_FILE: &str = "PLUGIN.toml";

const MAX_MANIFEST_BYTES: u64 = 1024 * 1024;
const MAX_STRING_BYTES: usize = 16 * 1024;
const MAX_LIST_ENTRIES: usize = 1024;
const MAX_TABLE_DEPTH: usize = 32;
const MAX_PACKAGE_ENTRIES: usize = 4096;
const MAX_PACKAGE_DEPTH: usize = 32;
const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;
const MAX_PACKAGE_BYTES: u64 = 256 * 1024 * 1024;

type PackageFiles = Vec<PackageFile>;

#[derive(Debug, Clone)]
struct PackageFile {
    path: String,
    executable: bool,
    bytes: Vec<u8>,
}

/// Passive plugin inventory for one source.
#[derive(Debug, Clone, Default, Serialize)]
pub struct PluginInventory {
    /// Valid passive plugin packages.
    pub plugins: Vec<PluginRecord>,
    /// Non-fatal malformed-package findings.
    pub warnings: Vec<PluginInventoryWarning>,
}

/// One validated passive plugin package.
#[derive(Debug, Clone, Serialize)]
pub struct PluginRecord {
    /// Source containing the package.
    pub source_id: String,
    /// Canonical identity, `<source-id>:<slot-name>`.
    pub source_ref: String,
    /// Plugin slot name.
    pub slot_name: String,
    /// Optional stable identity.
    pub id: Option<String>,
    /// Human-facing description.
    pub description: String,
    /// Optional authored version.
    pub version: Option<String>,
    /// Package directory.
    pub path: PathBuf,
    /// Canonical manifest path.
    pub manifest_file: PathBuf,
    /// Ordered passive component declarations.
    pub members: Vec<PluginMember>,
    /// Validated active local-tool descriptors. Discovery remains inert.
    pub tools: Vec<ToolRecord>,
    /// Validated hook contracts bound to same-plugin local tools.
    pub hooks: Vec<HookRecord>,
    /// Ordered plugin dependency declarations.
    pub requires: Vec<PluginDependency>,
    /// Inert provider overlays retained for adapter-specific validation.
    pub providers: BTreeMap<String, toml::Value>,
    /// SHA-256 over the complete bounded package tree.
    pub package_hash: String,
}

/// One inert plugin-local hook contract with its exact approval identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HookRecord {
    /// Source-qualified identity, `<source>:<plugin>#hook:<id>`.
    pub source_ref: String,
    /// Closed portable hook descriptor.
    pub descriptor: HookDescriptorV1,
    /// Exact same-plugin tool identity.
    pub tool_source_ref: String,
    /// Referenced invocation-contract hash from #499.
    pub tool_contract_hash: String,
    /// Complete security-relevant hook contract hash.
    pub contract_hash: String,
}

/// One validated plugin-local executable contract. Inventory never executes it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolRecord {
    /// Descriptor schema version.
    pub schema_version: u32,
    /// Plugin-local ID.
    pub id: String,
    /// Source-qualified identity, `<source>:<plugin>#tool:<id>`.
    pub source_ref: String,
    /// Plugin-root-relative executable entry path.
    pub entry: String,
    /// Runtime used to invoke the entry.
    pub runtime: ToolRuntime,
    /// Optional authored runtime version requirement.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_version: Option<String>,
    /// Explicit supported operating systems; empty means every Dalo platform.
    pub platforms: Vec<ToolPlatform>,
    /// Event-independent named input schema.
    pub inputs: Vec<ToolInput>,
    /// Canonical exec-style argument template.
    pub argv: Vec<String>,
    /// Working-directory policy.
    pub cwd: ToolCwd,
    /// Environment variable names admitted into the invocation.
    pub env: Vec<String>,
    /// Portable capability claims.
    pub capabilities: Vec<ToolCapability>,
    /// Whether missing availability blocks the plugin.
    pub availability: ToolAvailability,
    /// Files in the bounded security-relevant closure.
    pub files: Vec<ToolFileRecord>,
    /// Deterministic invocation-contract hash; excludes whole-package provenance.
    pub contract_hash: String,
}

/// Supported local-tool runtime kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolRuntime {
    /// Execute the immutable entry directly, without a shell.
    Executable,
    /// Invoke the immutable entry with `python3`.
    Python,
    /// Invoke the immutable entry with `node`.
    Node,
}

impl std::fmt::Display for ToolRuntime {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Executable => "executable",
            Self::Python => "python",
            Self::Node => "node",
        })
    }
}

impl ToolRuntime {
    /// Runtime executable required on PATH, if any.
    #[must_use]
    pub const fn executable(self) -> Option<&'static str> {
        match self {
            Self::Executable => None,
            Self::Python => Some("python3"),
            Self::Node => Some("node"),
        }
    }
}

/// Portable operating-system requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolPlatform {
    /// Apple macOS.
    Macos,
    /// Linux.
    Linux,
}

/// One named input admitted by the tool-owned argv template.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolInput {
    /// Stable lower-snake input name.
    pub name: String,
    /// Primitive value type.
    #[serde(rename = "type")]
    pub kind: ToolInputType,
    /// Whether callers must supply a value.
    #[serde(default = "default_true")]
    pub required: bool,
}

/// Primitive named-input types supported by descriptor v1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolInputType {
    /// UTF-8 text.
    String,
    /// Filesystem path passed as opaque argument data.
    Path,
    /// Signed integer.
    Integer,
    /// Boolean rendered as `true` or `false`.
    Boolean,
}

/// Working directory used for execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolCwd {
    /// Root of the immutable staged tool closure.
    ToolRoot,
}

/// Portable active-code capability claims.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolCapability {
    /// Read files outside the immutable closure.
    FilesystemRead,
    /// Write files outside the immutable closure.
    FilesystemWrite,
    /// Start child processes.
    Subprocess,
    /// Access the network.
    Network,
}

impl std::fmt::Display for ToolCapability {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::FilesystemRead => "filesystem_read",
            Self::FilesystemWrite => "filesystem_write",
            Self::Subprocess => "subprocess",
            Self::Network => "network",
        })
    }
}

/// Required versus optional tool availability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolAvailability {
    /// Unavailable or unapproved blocks coherent activation.
    Required,
    /// Unavailable or unapproved is a visible omission.
    Optional,
}

impl std::fmt::Display for ToolAvailability {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Required => "required",
            Self::Optional => "optional",
        })
    }
}

/// One regular file participating in the tool contract closure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolFileRecord {
    /// Plugin-root-relative path.
    pub path: String,
    /// Whether the source file had any executable bit.
    pub executable: bool,
    /// SHA-256 of the exact bytes.
    pub content_hash: String,
}

/// One passive plugin member.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginMember {
    /// Authored portable reference.
    #[serde(rename = "ref")]
    pub reference: ComponentReference,
    /// Required, optional, or instruction-only recommended membership.
    pub requirement: MemberRequirement,
    /// Optional agent-to-required-skill inline fallback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback: Option<InlineFallback>,
}

/// One plugin dependency.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginDependency {
    /// Authored plugin reference.
    #[serde(rename = "ref")]
    pub reference: ComponentReference,
    /// Dependency strength.
    pub requirement: DependencyRequirement,
}

/// Parsed portable component reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct ComponentReference {
    /// Component namespace.
    pub kind: ComponentKind,
    /// Exact source ID for a cross-source reference, otherwise `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
    /// Slot or stable-ID selector.
    pub selector: String,
}

impl ComponentReference {
    /// Render the canonical authored grammar.
    #[must_use]
    pub fn as_string(&self) -> String {
        self.source_id.as_ref().map_or_else(
            || format!("{}:{}", self.kind.as_str(), self.selector),
            |source_id| format!("{}:{source_id}:{}", self.kind.as_str(), self.selector),
        )
    }
}

/// Passive component namespaces accepted by schema version 1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComponentKind {
    /// Another plugin package.
    Plugin,
    /// Managed skill.
    Skill,
    /// Canonical agent package.
    Agent,
    /// Instruction pack.
    Instruction,
}

impl ComponentKind {
    /// Stable reference prefix.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Plugin => "plugin",
            Self::Skill => "skill",
            Self::Agent => "agent",
            Self::Instruction => "instruction",
        }
    }
}

/// Membership requirement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemberRequirement {
    /// Missing or inactive blocks plugin coherence.
    Required,
    /// Omission is visible but non-blocking.
    Optional,
    /// Instruction-only recommendation that never activates the pack.
    Recommended,
}

impl std::fmt::Display for MemberRequirement {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Required => "required",
            Self::Optional => "optional",
            Self::Recommended => "recommended",
        })
    }
}

/// Plugin dependency requirement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DependencyRequirement {
    /// Missing or blocked dependency blocks the dependent.
    Required,
    /// Missing dependency is a visible non-blocking omission.
    Optional,
}

/// Authored inline fallback for an agent member.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InlineFallback {
    /// Required skill member used as canonical inline behavior.
    pub skill: ComponentReference,
}

/// One non-fatal plugin inventory warning.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginInventoryWarning {
    /// Stable machine-readable warning code.
    pub code: PluginInventoryWarningCode,
    /// Package or entry path.
    pub path: PathBuf,
    /// Actionable detail.
    pub message: String,
}

/// Plugin inventory warning codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginInventoryWarningCode {
    /// Invalid schema, identity, reference, or a violated safety bound.
    InvalidPackage,
    /// Symlink or unsupported special file in the package boundary.
    UnsafePackageEntry,
    /// Two valid packages declare the same stable identity.
    DuplicateStableId,
    /// A source path could not be read.
    UnreadablePath,
    /// Reserved active-code descriptors are not accepted by the passive slice.
    UnsupportedActiveComponentSchema,
}

impl PluginInventoryWarningCode {
    /// Stable snake-case label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidPackage => "invalid_plugin_package",
            Self::UnsafePackageEntry => "unsafe_plugin_package_entry",
            Self::DuplicateStableId => "duplicate_plugin_stable_id",
            Self::UnreadablePath => "unreadable_plugin_path",
            Self::UnsupportedActiveComponentSchema => "unsupported_active_component_schema",
        }
    }
}

impl std::fmt::Display for PluginInventoryWarningCode {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Manifest {
    schema_version: u32,
    plugin: ManifestPlugin,
    #[serde(default)]
    providers: BTreeMap<String, toml::Value>,
    #[serde(default, rename = "tool")]
    tools: Vec<ManifestTool>,
    #[serde(default, rename = "hook")]
    hooks: Vec<HookDescriptorV1>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestPlugin {
    name: String,
    #[serde(default)]
    id: Option<String>,
    description: String,
    #[serde(default)]
    version: Option<String>,
    #[serde(default)]
    members: Vec<ManifestMember>,
    #[serde(default)]
    requires: Vec<ManifestDependency>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestMember {
    #[serde(rename = "ref")]
    reference: String,
    requirement: MemberRequirement,
    #[serde(default)]
    fallback: Option<ManifestFallback>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestDependency {
    #[serde(rename = "ref")]
    reference: String,
    requirement: DependencyRequirement,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestFallback {
    kind: String,
    skill: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestTool {
    schema_version: u32,
    id: String,
    entry: String,
    runtime: ToolRuntime,
    #[serde(default)]
    runtime_version: Option<String>,
    #[serde(default)]
    platforms: Vec<ToolPlatform>,
    #[serde(default)]
    inputs: Vec<ToolInput>,
    argv: Vec<String>,
    #[serde(default)]
    files: Vec<String>,
    cwd: ToolCwd,
    #[serde(default)]
    env: Vec<String>,
    #[serde(default)]
    capabilities: Vec<ToolCapability>,
    availability: ToolAvailability,
}

const fn default_true() -> bool {
    true
}

/// Scan only exact `plugins/<name>/PLUGIN.toml` packages in one source.
#[must_use]
pub fn scan_source_plugins(source_id: &str, source_root: &Path) -> PluginInventory {
    #[cfg(test)]
    SOURCE_PLUGIN_SCAN_COUNT.with(|count| count.set(count.get() + 1));
    let plugins_root = source_root.join("plugins");
    let metadata = match fs::symlink_metadata(&plugins_root) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return PluginInventory::default();
        }
        Err(error) => {
            return inventory_warning(
                PluginInventoryWarningCode::UnreadablePath,
                plugins_root,
                error.to_string(),
            );
        }
        Ok(metadata) => metadata,
    };
    if metadata.file_type().is_symlink() {
        return inventory_warning(
            PluginInventoryWarningCode::UnsafePackageEntry,
            plugins_root,
            "the source `plugins` directory must not be a symlink".to_owned(),
        );
    }
    if !metadata.is_dir() {
        return inventory_warning(
            PluginInventoryWarningCode::InvalidPackage,
            plugins_root,
            "the source `plugins` path must be a directory".to_owned(),
        );
    }

    let entries = match fs::read_dir(&plugins_root) {
        Ok(entries) => entries,
        Err(error) => {
            return inventory_warning(
                PluginInventoryWarningCode::UnreadablePath,
                plugins_root,
                error.to_string(),
            );
        }
    };
    let mut packages = Vec::new();
    let mut warnings = Vec::new();
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(error) => {
                warnings.push(warning(
                    PluginInventoryWarningCode::UnreadablePath,
                    plugins_root.clone(),
                    error.to_string(),
                ));
                continue;
            }
        };
        let path = entry.path();
        let file_type = match entry.file_type() {
            Ok(file_type) => file_type,
            Err(error) => {
                warnings.push(warning(
                    PluginInventoryWarningCode::UnreadablePath,
                    path,
                    error.to_string(),
                ));
                continue;
            }
        };
        if file_type.is_symlink() {
            warnings.push(warning(
                PluginInventoryWarningCode::UnsafePackageEntry,
                path,
                "plugin package directories must not be symlinks".to_owned(),
            ));
        } else if file_type.is_dir() && path.join(PLUGIN_FILE).exists() {
            packages.push(path);
        }
    }
    packages.sort();

    let mut plugins = Vec::new();
    for package_path in packages {
        match scan_package(source_id, &package_path) {
            Ok(plugin) => plugins.push(plugin),
            Err((code, error)) => warnings.push(warning(code, package_path, error)),
        }
    }
    reject_duplicate_stable_ids(source_id, &mut plugins, &mut warnings);
    plugins.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
    warnings.sort_by(|left, right| {
        left.path
            .cmp(&right.path)
            .then_with(|| left.code.as_str().cmp(right.code.as_str()))
    });
    PluginInventory { plugins, warnings }
}

fn inventory_warning(
    code: PluginInventoryWarningCode,
    path: PathBuf,
    message: String,
) -> PluginInventory {
    PluginInventory {
        plugins: Vec::new(),
        warnings: vec![warning(code, path, message)],
    }
}

fn warning(
    code: PluginInventoryWarningCode,
    path: PathBuf,
    message: String,
) -> PluginInventoryWarning {
    PluginInventoryWarning {
        code,
        path,
        message,
    }
}

fn scan_package(
    source_id: &str,
    package_path: &Path,
) -> Result<PluginRecord, (PluginInventoryWarningCode, String)> {
    let package_name = package_path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| invalid("plugin package directory name must be valid UTF-8"))?;
    if !is_plugin_name(package_name) {
        return Err(invalid(
            "plugin package directory must use lower kebab-case",
        ));
    }
    let entries = collect_package_files(package_path)?;
    let manifest_file = package_path.join(PLUGIN_FILE);
    let manifest_bytes = entries
        .iter()
        .find_map(|entry| (entry.path == PLUGIN_FILE).then_some(entry.bytes.as_slice()))
        .ok_or_else(|| invalid(format!("package is missing {PLUGIN_FILE}")))?;
    if manifest_bytes.len() as u64 > MAX_MANIFEST_BYTES {
        return Err(invalid(format!(
            "{PLUGIN_FILE} exceeds the {MAX_MANIFEST_BYTES}-byte safety limit"
        )));
    }
    let document = std::str::from_utf8(manifest_bytes)
        .map_err(|_| invalid(format!("{PLUGIN_FILE} must be valid UTF-8")))?;
    let value: toml::Value =
        toml::from_str(document).map_err(|error| invalid(format!("invalid TOML: {error}")))?;
    validate_toml_bounds(&value, 0)?;
    let manifest: Manifest = value
        .try_into()
        .map_err(|error| invalid(format!("invalid plugin schema: {error}")))?;
    if manifest.schema_version != 1 {
        return Err(invalid(format!(
            "unsupported plugin schema version {} (supported: 1)",
            manifest.schema_version
        )));
    }
    validate_manifest(package_name, &manifest)?;
    let members = manifest
        .plugin
        .members
        .iter()
        .map(parse_member)
        .collect::<Result<Vec<_>, _>>()?;
    let requires = manifest
        .plugin
        .requires
        .iter()
        .map(parse_dependency)
        .collect::<Result<Vec<_>, _>>()?;
    validate_member_closure(&members)?;
    let plugin_ref = format!("{source_id}:{package_name}");
    let tools = parse_tools(&plugin_ref, &manifest.tools, &entries)?;
    let hooks = parse_hooks(&plugin_ref, &manifest.hooks, &tools)?;
    let package_hash = hash_package_files(&entries);

    Ok(PluginRecord {
        source_id: source_id.to_owned(),
        source_ref: plugin_ref,
        slot_name: package_name.to_owned(),
        id: manifest.plugin.id,
        description: manifest.plugin.description,
        version: manifest.plugin.version,
        path: package_path.to_path_buf(),
        manifest_file,
        members,
        tools,
        hooks,
        requires,
        providers: manifest.providers,
        package_hash,
    })
}

fn parse_hooks(
    plugin_ref: &str,
    descriptors: &[HookDescriptorV1],
    tools: &[ToolRecord],
) -> Result<Vec<HookRecord>, (PluginInventoryWarningCode, String)> {
    if descriptors.len() > MAX_LIST_ENTRIES {
        return Err(invalid(format!(
            "plugin declares more than {MAX_LIST_ENTRIES} hooks"
        )));
    }
    let mut ids = BTreeSet::new();
    let mut hooks = Vec::with_capacity(descriptors.len());
    for descriptor in descriptors {
        if descriptor.schema_version != 1 {
            return Err((
                PluginInventoryWarningCode::UnsupportedActiveComponentSchema,
                format!(
                    "hook `{}` uses unsupported descriptor schema {} (supported: 1)",
                    descriptor.id, descriptor.schema_version
                ),
            ));
        }
        hook::validate_descriptor(descriptor).map_err(invalid)?;
        if !ids.insert(descriptor.id.as_str()) {
            return Err(invalid(format!(
                "plugin contains duplicate hook ID `{}`",
                descriptor.id
            )));
        }
        let tool = tools
            .iter()
            .find(|candidate| candidate.id == descriptor.tool)
            .ok_or_else(|| {
                invalid(format!(
                    "hook `{}` references missing same-plugin tool `{}`",
                    descriptor.id, descriptor.tool
                ))
            })?;
        let tool_inputs = tool
            .inputs
            .iter()
            .map(|input| (input.name.as_str(), input))
            .collect::<BTreeMap<_, _>>();
        for binding in &descriptor.bindings {
            let input = tool_inputs.get(binding.input.as_str()).ok_or_else(|| {
                invalid(format!(
                    "hook `{}` binds unknown tool input `{}`",
                    descriptor.id, binding.input
                ))
            })?;
            let expected = match input.kind {
                ToolInputType::String => Some(HookBindingType::String),
                ToolInputType::Path => Some(HookBindingType::Path),
                ToolInputType::Boolean => Some(HookBindingType::Boolean),
                ToolInputType::Integer => None,
            };
            if expected != Some(binding.field.input_type()) {
                return Err(invalid(format!(
                    "hook `{}` field `{}` is incompatible with tool input `{}`",
                    descriptor.id,
                    binding.field.as_str(),
                    binding.input
                )));
            }
        }
        for input in tool.inputs.iter().filter(|input| input.required) {
            if !descriptor
                .bindings
                .iter()
                .any(|binding| binding.input == input.name)
            {
                return Err(invalid(format!(
                    "hook `{}` does not bind required tool input `{}`",
                    descriptor.id, input.name
                )));
            }
        }
        let source_ref = format!("{plugin_ref}#hook:{}", descriptor.id);
        let contract_hash = hook::contract_hash(
            &source_ref,
            descriptor,
            &tool.source_ref,
            &tool.contract_hash,
        );
        hooks.push(HookRecord {
            source_ref,
            descriptor: descriptor.clone(),
            tool_source_ref: tool.source_ref.clone(),
            tool_contract_hash: tool.contract_hash.clone(),
            contract_hash,
        });
    }
    hooks.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
    Ok(hooks)
}

fn invalid(message: impl Into<String>) -> (PluginInventoryWarningCode, String) {
    (PluginInventoryWarningCode::InvalidPackage, message.into())
}

fn validate_manifest(
    package_name: &str,
    manifest: &Manifest,
) -> Result<(), (PluginInventoryWarningCode, String)> {
    let plugin = &manifest.plugin;
    if plugin.name != package_name {
        return Err(invalid(format!(
            "plugin.name `{}` must equal package directory `{package_name}`",
            plugin.name
        )));
    }
    if plugin.description.trim().is_empty() {
        return Err(invalid("plugin.description must not be empty"));
    }
    if let Some(id) = &plugin.id
        && !is_stable_id(id)
    {
        return Err(invalid(
            "plugin.id must be 1-128 ASCII lower-case characters using dots or hyphens as separators",
        ));
    }
    if plugin.members.len() > MAX_LIST_ENTRIES || plugin.requires.len() > MAX_LIST_ENTRIES {
        return Err(invalid(format!(
            "plugin lists may contain at most {MAX_LIST_ENTRIES} entries"
        )));
    }
    let member_refs = plugin
        .members
        .iter()
        .map(|member| member.reference.as_str())
        .collect::<BTreeSet<_>>();
    if member_refs.len() != plugin.members.len() {
        return Err(invalid("plugin contains duplicate member declarations"));
    }
    let dependency_refs = plugin
        .requires
        .iter()
        .map(|dependency| dependency.reference.as_str())
        .collect::<BTreeSet<_>>();
    if dependency_refs.len() != plugin.requires.len() {
        return Err(invalid("plugin contains duplicate dependency declarations"));
    }
    Ok(())
}

fn parse_member(
    member: &ManifestMember,
) -> Result<PluginMember, (PluginInventoryWarningCode, String)> {
    let reference = parse_reference(&member.reference)?;
    if reference.kind == ComponentKind::Plugin {
        return Err(invalid(
            "plugin members may reference only skill, agent, or instruction components",
        ));
    }
    if member.requirement == MemberRequirement::Recommended
        && reference.kind != ComponentKind::Instruction
    {
        return Err(invalid(
            "recommended membership is valid only for instructions",
        ));
    }
    let fallback = member
        .fallback
        .as_ref()
        .map(|fallback| {
            if reference.kind != ComponentKind::Agent {
                return Err(invalid("fallback is valid only for agent members"));
            }
            if fallback.kind != "inline" {
                return Err(invalid("fallback.kind must be `inline`"));
            }
            let skill = parse_reference(&fallback.skill)?;
            if skill.kind != ComponentKind::Skill {
                return Err(invalid("inline fallback must reference a skill"));
            }
            Ok(InlineFallback { skill })
        })
        .transpose()?;
    Ok(PluginMember {
        reference,
        requirement: member.requirement,
        fallback,
    })
}

fn parse_dependency(
    dependency: &ManifestDependency,
) -> Result<PluginDependency, (PluginInventoryWarningCode, String)> {
    let reference = parse_reference(&dependency.reference)?;
    if reference.kind != ComponentKind::Plugin {
        return Err(invalid(
            "plugin.requires entries must use plugin references",
        ));
    }
    Ok(PluginDependency {
        reference,
        requirement: dependency.requirement,
    })
}

fn parse_reference(
    reference: &str,
) -> Result<ComponentReference, (PluginInventoryWarningCode, String)> {
    let parts = reference.split(':').collect::<Vec<_>>();
    if !(parts.len() == 2 || parts.len() == 3) || parts.iter().any(|part| part.is_empty()) {
        return Err(invalid(format!("invalid portable reference `{reference}`")));
    }
    let kind = match parts[0] {
        "plugin" => ComponentKind::Plugin,
        "skill" => ComponentKind::Skill,
        "agent" => ComponentKind::Agent,
        "instruction" => ComponentKind::Instruction,
        _ => return Err(invalid(format!("unknown reference kind in `{reference}`"))),
    };
    let (source_id, selector) = if parts.len() == 3 {
        if !is_reference_atom(parts[1]) {
            return Err(invalid(format!("invalid source ID in `{reference}`")));
        }
        (Some(parts[1].to_owned()), parts[2])
    } else {
        (None, parts[1])
    };
    if !is_reference_atom(selector) {
        return Err(invalid(format!("invalid selector in `{reference}`")));
    }
    Ok(ComponentReference {
        kind,
        source_id,
        selector: selector.to_owned(),
    })
}

fn validate_member_closure(
    members: &[PluginMember],
) -> Result<(), (PluginInventoryWarningCode, String)> {
    let required_skills = members
        .iter()
        .filter(|member| {
            member.reference.kind == ComponentKind::Skill
                && member.requirement == MemberRequirement::Required
        })
        .map(|member| &member.reference)
        .collect::<BTreeSet<_>>();
    for fallback in members.iter().filter_map(|member| member.fallback.as_ref()) {
        if !required_skills.contains(&fallback.skill) {
            return Err(invalid(format!(
                "inline fallback `{}` must also be a required skill member",
                fallback.skill.as_string()
            )));
        }
    }
    Ok(())
}

fn parse_tools(
    plugin_ref: &str,
    descriptors: &[ManifestTool],
    package_files: &PackageFiles,
) -> Result<Vec<ToolRecord>, (PluginInventoryWarningCode, String)> {
    if descriptors.len() > MAX_LIST_ENTRIES {
        return Err(invalid(format!(
            "plugin declares more than {MAX_LIST_ENTRIES} tools"
        )));
    }
    let mut ids = BTreeSet::new();
    let mut tools = Vec::with_capacity(descriptors.len());
    for descriptor in descriptors {
        if descriptor.schema_version != 1 {
            return Err((
                PluginInventoryWarningCode::UnsupportedActiveComponentSchema,
                format!(
                    "tool `{}` uses unsupported descriptor schema {} (supported: 1)",
                    descriptor.id, descriptor.schema_version
                ),
            ));
        }
        if !is_plugin_name(&descriptor.id) {
            return Err(invalid("tool.id must use lower kebab-case"));
        }
        if !ids.insert(descriptor.id.as_str()) {
            return Err(invalid(format!(
                "plugin contains duplicate tool ID `{}`",
                descriptor.id
            )));
        }
        let entry = validate_tool_path(&descriptor.entry)?;
        if descriptor.files.len() > MAX_LIST_ENTRIES {
            return Err(invalid(format!(
                "tool `{}` declares too many closure files",
                descriptor.id
            )));
        }
        if descriptor.argv.len() > MAX_LIST_ENTRIES {
            return Err(invalid(format!(
                "tool `{}` argv template is too large",
                descriptor.id
            )));
        }
        let mut input_names = BTreeSet::new();
        for input in &descriptor.inputs {
            if !is_input_name(&input.name) || !input_names.insert(input.name.as_str()) {
                return Err(invalid(format!(
                    "tool `{}` input names must be unique lower_snake_case values",
                    descriptor.id
                )));
            }
        }
        for argument in &descriptor.argv {
            if argument.len() > MAX_STRING_BYTES {
                return Err(invalid(format!(
                    "tool `{}` contains an oversized argv element",
                    descriptor.id
                )));
            }
            if let Some(name) = argument
                .strip_prefix("${input.")
                .and_then(|value| value.strip_suffix('}'))
            {
                if !input_names.contains(name) {
                    return Err(invalid(format!(
                        "tool `{}` argv references unknown input `{name}`",
                        descriptor.id
                    )));
                }
            } else if argument.contains("${") {
                return Err(invalid(format!(
                    "tool `{}` uses an unsafe placeholder; v1 accepts only whole-token `${{input.name}}` values",
                    descriptor.id
                )));
            }
        }
        if let Some(version) = &descriptor.runtime_version
            && (version.is_empty()
                || version.len() > 128
                || !version.bytes().all(|byte| {
                    byte.is_ascii_alphanumeric()
                        || matches!(byte, b'.' | b'-' | b'+' | b'<' | b'>' | b'=' | b' ')
                }))
        {
            return Err(invalid(format!(
                "tool `{}` has an invalid runtime_version requirement",
                descriptor.id
            )));
        }
        let mut platforms = descriptor.platforms.clone();
        platforms.sort();
        platforms.dedup();
        let mut env = descriptor.env.clone();
        env.sort();
        env.dedup();
        if env.len() != descriptor.env.len() || env.iter().any(|name| !is_env_name(name)) {
            return Err(invalid(format!(
                "tool `{}` env values must be unique portable environment names",
                descriptor.id
            )));
        }
        let mut capabilities = descriptor.capabilities.clone();
        capabilities.sort();
        capabilities.dedup();

        let mut closure_paths = BTreeSet::from([entry.clone()]);
        for path in &descriptor.files {
            let path = validate_tool_path(path)?;
            if !closure_paths.insert(path) {
                return Err(invalid(format!(
                    "tool `{}` contains a duplicate closure path",
                    descriptor.id
                )));
            }
        }
        let mut files = Vec::with_capacity(closure_paths.len());
        for path in closure_paths {
            let package_file = package_files
                .iter()
                .find(|candidate| candidate.path == path)
                .ok_or_else(|| {
                    invalid(format!(
                        "tool `{}` references missing regular file `{path}`",
                        descriptor.id
                    ))
                })?;
            files.push(ToolFileRecord {
                path,
                executable: package_file.executable,
                content_hash: hash_bytes(&package_file.bytes),
            });
        }
        if descriptor.runtime == ToolRuntime::Executable
            && !files
                .iter()
                .find(|file| file.path == entry)
                .is_some_and(|file| file.executable)
        {
            return Err(invalid(format!(
                "tool `{}` executable entry is not marked executable",
                descriptor.id
            )));
        }
        let source_ref = format!("{plugin_ref}#tool:{}", descriptor.id);
        let mut record = ToolRecord {
            schema_version: descriptor.schema_version,
            id: descriptor.id.clone(),
            source_ref,
            entry,
            runtime: descriptor.runtime,
            runtime_version: descriptor.runtime_version.clone(),
            platforms,
            inputs: descriptor.inputs.clone(),
            argv: descriptor.argv.clone(),
            cwd: descriptor.cwd,
            env,
            capabilities,
            availability: descriptor.availability,
            files,
            contract_hash: String::new(),
        };
        record.contract_hash = hash_tool_contract(&record);
        tools.push(record);
    }
    tools.sort_by(|left, right| left.id.cmp(&right.id));
    Ok(tools)
}

fn validate_tool_path(path: &str) -> Result<String, (PluginInventoryWarningCode, String)> {
    if path.is_empty() || path.len() > MAX_STRING_BYTES || path.contains('\\') {
        return Err(invalid(
            "tool paths must be non-empty portable relative paths",
        ));
    }
    let candidate = Path::new(path);
    if candidate.is_absolute()
        || candidate.components().any(|part| {
            !matches!(part, std::path::Component::Normal(_)) || part.as_os_str().to_str().is_none()
        })
    {
        return Err(invalid(format!(
            "tool path `{path}` must stay lexically inside the plugin package"
        )));
    }
    Ok(candidate
        .components()
        .map(|part| part.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/"))
}

fn is_input_name(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
        && value.as_bytes()[0].is_ascii_lowercase()
        && !value.ends_with('_')
        && !value.contains("__")
}

fn is_env_name(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && (value.as_bytes()[0].is_ascii_uppercase() || value.as_bytes()[0] == b'_')
        && value
            .bytes()
            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')
}

fn hash_bytes(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    digest.iter().map(|byte| format!("{byte:02x}")).collect()
}

fn hash_tool_contract(tool: &ToolRecord) -> String {
    let mut hash = Sha256::new();
    hash.update(b"dalo-tool-contract-v1\0");
    hash_contract_value(&mut hash, &tool.source_ref);
    hash_contract_value(&mut hash, &tool.schema_version.to_string());
    hash_contract_value(&mut hash, &tool.entry);
    hash_contract_value(&mut hash, &format!("{:?}", tool.runtime));
    hash_contract_value(&mut hash, tool.runtime_version.as_deref().unwrap_or(""));
    for platform in &tool.platforms {
        hash_contract_value(&mut hash, &format!("platform:{platform:?}"));
    }
    for input in &tool.inputs {
        hash_contract_value(
            &mut hash,
            &format!("input:{}:{:?}:{}", input.name, input.kind, input.required),
        );
    }
    for argument in &tool.argv {
        hash_contract_value(&mut hash, &format!("argv:{argument}"));
    }
    hash_contract_value(&mut hash, &format!("cwd:{:?}", tool.cwd));
    for name in &tool.env {
        hash_contract_value(&mut hash, &format!("env:{name}"));
    }
    for capability in &tool.capabilities {
        hash_contract_value(&mut hash, &format!("capability:{capability:?}"));
    }
    hash_contract_value(&mut hash, &format!("availability:{:?}", tool.availability));
    for file in &tool.files {
        hash_contract_value(
            &mut hash,
            &format!(
                "file:{}:{}:{}",
                file.path, file.executable, file.content_hash
            ),
        );
    }
    hash.finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Length-prefixed framing shared by every contract hash in this crate.
pub(crate) fn hash_contract_value(hash: &mut Sha256, value: &str) {
    hash.update((value.len() as u64).to_be_bytes());
    hash.update(value.as_bytes());
}

fn validate_toml_bounds(
    value: &toml::Value,
    depth: usize,
) -> Result<(), (PluginInventoryWarningCode, String)> {
    if depth > MAX_TABLE_DEPTH {
        return Err(invalid(format!(
            "TOML nesting exceeds {MAX_TABLE_DEPTH} levels"
        )));
    }
    match value {
        toml::Value::String(value) if value.len() > MAX_STRING_BYTES => Err(invalid(format!(
            "TOML string exceeds {MAX_STRING_BYTES} bytes"
        ))),
        toml::Value::Array(values) => {
            if values.len() > MAX_LIST_ENTRIES {
                return Err(invalid(format!(
                    "TOML list exceeds {MAX_LIST_ENTRIES} entries"
                )));
            }
            for value in values {
                validate_toml_bounds(value, depth + 1)?;
            }
            Ok(())
        }
        toml::Value::Table(values) => {
            if values.len() > MAX_LIST_ENTRIES {
                return Err(invalid(format!(
                    "TOML table exceeds {MAX_LIST_ENTRIES} entries"
                )));
            }
            for (key, value) in values {
                if key.len() > MAX_STRING_BYTES {
                    return Err(invalid(format!(
                        "TOML key exceeds {MAX_STRING_BYTES} bytes"
                    )));
                }
                validate_toml_bounds(value, depth + 1)?;
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

fn collect_package_files(
    package_path: &Path,
) -> Result<PackageFiles, (PluginInventoryWarningCode, String)> {
    let mut files = Vec::new();
    let mut entry_count = 0;
    let mut total_bytes = 0_u64;
    collect_package_files_inner(
        package_path,
        package_path,
        0,
        &mut files,
        &mut entry_count,
        &mut total_bytes,
    )?;
    files.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(files)
}

fn collect_package_files_inner(
    package_root: &Path,
    current: &Path,
    depth: usize,
    files: &mut PackageFiles,
    entry_count: &mut usize,
    total_bytes: &mut u64,
) -> Result<(), (PluginInventoryWarningCode, String)> {
    if depth > MAX_PACKAGE_DEPTH {
        return Err(invalid(format!(
            "package exceeds {MAX_PACKAGE_DEPTH} directory levels"
        )));
    }
    let mut entries = fs::read_dir(current)
        .map_err(|error| {
            (
                PluginInventoryWarningCode::UnreadablePath,
                error.to_string(),
            )
        })?
        .map(|entry| {
            entry.map_err(|error| {
                (
                    PluginInventoryWarningCode::UnreadablePath,
                    error.to_string(),
                )
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        *entry_count += 1;
        if *entry_count > MAX_PACKAGE_ENTRIES {
            return Err(invalid(format!(
                "package exceeds {MAX_PACKAGE_ENTRIES} entries"
            )));
        }
        let path = entry.path();
        let file_type = entry.file_type().map_err(|error| {
            (
                PluginInventoryWarningCode::UnreadablePath,
                error.to_string(),
            )
        })?;
        if file_type.is_symlink() {
            return Err((
                PluginInventoryWarningCode::UnsafePackageEntry,
                format!("package contains symlink `{}`", path.display()),
            ));
        }
        if file_type.is_dir() {
            collect_package_files_inner(
                package_root,
                &path,
                depth + 1,
                files,
                entry_count,
                total_bytes,
            )?;
            continue;
        }
        if !file_type.is_file() {
            return Err((
                PluginInventoryWarningCode::UnsafePackageEntry,
                format!(
                    "package contains unsupported special file `{}`",
                    path.display()
                ),
            ));
        }
        let metadata = entry.metadata().map_err(|error| {
            (
                PluginInventoryWarningCode::UnreadablePath,
                error.to_string(),
            )
        })?;
        if metadata.len() > MAX_FILE_BYTES {
            return Err(invalid(format!(
                "file `{}` exceeds {MAX_FILE_BYTES} bytes",
                path.display()
            )));
        }
        let relative = relative_package_path(package_root, &path)?;
        let executable = metadata.permissions().mode() & 0o111 != 0;
        let bytes = fs::read(&path).map_err(|error| {
            (
                PluginInventoryWarningCode::UnreadablePath,
                error.to_string(),
            )
        })?;
        if bytes.len() as u64 > MAX_FILE_BYTES {
            return Err(invalid(format!(
                "file `{}` exceeded {MAX_FILE_BYTES} bytes while being read",
                path.display()
            )));
        }
        *total_bytes = total_bytes
            .checked_add(bytes.len() as u64)
            .ok_or_else(|| invalid("package byte count overflowed"))?;
        if *total_bytes > MAX_PACKAGE_BYTES {
            return Err(invalid(format!(
                "package exceeds {MAX_PACKAGE_BYTES} total bytes"
            )));
        }
        files.push(PackageFile {
            path: relative,
            executable,
            bytes,
        });
    }
    Ok(())
}

fn relative_package_path(
    package_root: &Path,
    path: &Path,
) -> Result<String, (PluginInventoryWarningCode, String)> {
    let relative = path
        .strip_prefix(package_root)
        .map_err(|_| invalid("package entry escaped its package root"))?;
    let mut parts = Vec::new();
    for part in relative.components() {
        let std::path::Component::Normal(part) = part else {
            return Err(invalid("package contains a non-normal path component"));
        };
        parts.push(
            part.to_str()
                .ok_or_else(|| invalid("package entry path must be valid UTF-8"))?,
        );
    }
    Ok(parts.join("/"))
}

fn hash_package_files(entries: &PackageFiles) -> String {
    let mut hash = Sha256::new();
    hash.update(b"dalo-plugin-package-v1\0");
    for entry in entries {
        hash.update((entry.path.len() as u64).to_be_bytes());
        hash.update(entry.path.as_bytes());
        hash.update(*b"f");
        hash.update([u8::from(entry.executable)]);
        hash.update((entry.bytes.len() as u64).to_be_bytes());
        hash.update(&entry.bytes);
    }
    hash.finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

fn reject_duplicate_stable_ids(
    source_id: &str,
    plugins: &mut Vec<PluginRecord>,
    warnings: &mut Vec<PluginInventoryWarning>,
) {
    let mut paths_by_id = BTreeMap::<String, Vec<PathBuf>>::new();
    for plugin in plugins.iter() {
        if let Some(id) = &plugin.id {
            paths_by_id
                .entry(id.clone())
                .or_default()
                .push(plugin.path.clone());
        }
    }
    let duplicated = paths_by_id
        .into_iter()
        .filter(|(_, paths)| paths.len() > 1)
        .collect::<Vec<_>>();
    for (id, paths) in duplicated {
        for path in paths {
            warnings.push(warning(
                PluginInventoryWarningCode::DuplicateStableId,
                path,
                format!("source `{source_id}` contains multiple plugins with stable ID `{id}`"),
            ));
        }
        plugins.retain(|plugin| plugin.id.as_deref() != Some(id.as_str()));
    }
}

/// Lower kebab-case name rule shared by plugin slots, tool IDs, and binary IDs.
pub(crate) fn is_plugin_name(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        && !value.starts_with('-')
        && !value.ends_with('-')
        && !value.contains("--")
}

fn is_stable_id(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && value.is_ascii()
        && value.bytes().all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
        })
        && value
            .bytes()
            .next()
            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
        && value
            .bytes()
            .last()
            .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
        && !value.contains("..")
        && !value.contains("--")
        && !value.contains(".-")
        && !value.contains("-.")
}

fn is_reference_atom(value: &str) -> bool {
    !value.is_empty() && value.len() <= MAX_STRING_BYTES && !value.contains([':', '#', '/', '\\'])
}

/// Source of selected plugin intent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SelectionOriginKind {
    /// Authored team stack manifest.
    Stack,
    /// Additive local user selection.
    Direct,
    /// Reachable dependency from another selected plugin.
    Dependency,
}

/// Strength retained on one selection origin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SelectionStrength {
    /// Optional dependency intent.
    Optional,
    /// Recommended authored-stack intent.
    Recommended,
    /// Required stack, direct, or dependency intent.
    Required,
}

/// Provenance for one selected plugin identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SelectionOrigin {
    /// Origin namespace.
    pub kind: SelectionOriginKind,
    /// Manifest source, local config, or declaring plugin identity.
    pub declared_by: String,
    /// Strength contributed by this origin.
    pub requirement: SelectionStrength,
}

/// Canonical plugin state before target adapters run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginState {
    /// Selected passive package with a coherent required closure.
    Selected,
    /// Required dependency or component is not coherent.
    Blocked,
    /// Selected intent suppressed by an explicit local policy.
    Declined,
    /// Selected candidate lost its plugin slot to a higher-precedence candidate.
    Shadowed,
}

impl std::fmt::Display for PluginState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Selected => "selected",
            Self::Blocked => "blocked",
            Self::Declined => "declined",
            Self::Shadowed => "shadowed",
        })
    }
}

/// Passive component availability state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginComponentState {
    /// Component passed its independent activation boundary.
    Active,
    /// Component exists but still needs its scoped approval.
    PendingApproval,
    /// Component exists but lost its own namespace slot.
    Shadowed,
    /// Component exists but its own closure is blocked.
    Blocked,
    /// Canonical component is present in the exact requested source.
    Available,
    /// Instruction is present but remains independently inactive.
    Inactive,
    /// Reference matched no component.
    Missing,
    /// Slot and stable-ID lookup matched different components.
    Ambiguous,
}

impl std::fmt::Display for PluginComponentState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Active => "active",
            Self::PendingApproval => "pending_approval",
            Self::Shadowed => "shadowed",
            Self::Blocked => "blocked",
            Self::Available => "available",
            Self::Inactive => "inactive",
            Self::Missing => "missing",
            Self::Ambiguous => "ambiguous",
        })
    }
}

/// Evaluated passive member in canonical structured output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedPluginMember {
    /// Authored portable reference.
    pub reference: String,
    /// Membership requirement.
    pub requirement: MemberRequirement,
    /// Availability without granting activation.
    pub state: PluginComponentState,
    /// Canonical source-qualified component identity when resolved.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolved_ref: Option<String>,
    /// Authored required-skill inline fallback for an agent member.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback: Option<String>,
}

/// Canonical dependency outcome retained for planning and display.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedPluginDependency {
    /// Authored plugin reference.
    pub reference: String,
    /// Dependency requirement.
    pub requirement: DependencyRequirement,
    /// Exact dependency outcome.
    pub state: PluginDependencyState,
    /// Canonical identity when reference lookup succeeded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_ref: Option<String>,
}

/// Canonical plugin dependency state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginDependencyState {
    /// Dependency is the selected winner of its plugin slot.
    Selected,
    /// Dependency candidate exists but lost its plugin slot.
    Shadowed,
    /// Dependency is suppressed by explicit local policy.
    Declined,
    /// Exact source contained no matching plugin.
    Missing,
    /// Slot and stable-ID lookup selected different packages.
    Ambiguous,
}

impl std::fmt::Display for PluginDependencyState {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Selected => "selected",
            Self::Shadowed => "shadowed",
            Self::Declined => "declined",
            Self::Missing => "missing",
            Self::Ambiguous => "ambiguous",
        })
    }
}

/// One canonical selected or shadowed plugin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolvedPlugin {
    /// Canonical `<source-id>:<slot-name>` identity.
    pub source_ref: String,
    /// Plugin slot name.
    pub slot_name: String,
    /// Stable optional identity.
    pub id: Option<String>,
    /// Source priority used for deterministic winner selection.
    pub source_priority: i32,
    /// Complete package-tree hash.
    pub package_hash: String,
    /// Effective passive closure hash, excluding selection provenance.
    pub closure_hash: String,
    /// All retained selection origins.
    pub origins: Vec<SelectionOrigin>,
    /// Applied policy decisions, retained outside the closure hash.
    pub policies: Vec<AppliedPluginPolicy>,
    /// Canonical state.
    pub state: PluginState,
    /// Winning identity for a shadowed candidate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shadowed_by: Option<String>,
    /// Passive component findings.
    pub members: Vec<ResolvedPluginMember>,
    /// Canonical dependency outcomes.
    pub dependencies: Vec<ResolvedPluginDependency>,
    /// Deterministic blocking reasons.
    pub blocking_reasons: Vec<String>,
}

/// One applied local policy decision with its audit provenance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppliedPluginPolicy {
    /// Persisted local layer.
    pub layer: PluginPolicyLayer,
    /// Stable rule identity.
    pub rule_id: String,
    /// Version-2 policy decision.
    pub decision: PluginPolicyDecision,
    /// Human audit context; excluded from closure hashing.
    pub reason: String,
}

/// Machine-readable plugin resolution diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginDiagnostic {
    /// Stable diagnostic code.
    pub code: PluginDiagnosticCode,
    /// Affected authored reference or canonical identity.
    pub subject: String,
    /// Actionable detail.
    pub message: String,
}

/// Plugin resolution diagnostic codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginDiagnosticCode {
    /// Authored stack could not be parsed or did not identify its source.
    InvalidStackSelection,
    /// Selected plugin or dependency does not exist in the exact source.
    MissingPlugin,
    /// Slot and stable identity select different packages.
    AmbiguousPluginReference,
    /// Required plugin dependencies contain a cycle.
    RequiredDependencyCycle,
    /// A selected candidate lost its global plugin slot.
    ShadowedPlugin,
    /// Required member is missing or inactive.
    RequiredMemberBlocked,
    /// Explicit local decline retained selection intent.
    DeclinedPlugin,
}

impl std::fmt::Display for PluginDiagnosticCode {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::InvalidStackSelection => "invalid_stack_selection",
            Self::MissingPlugin => "missing_plugin",
            Self::AmbiguousPluginReference => "ambiguous_plugin_reference",
            Self::RequiredDependencyCycle => "required_dependency_cycle",
            Self::ShadowedPlugin => "shadowed_plugin",
            Self::RequiredMemberBlocked => "required_member_blocked",
            Self::DeclinedPlugin => "declined_plugin",
        })
    }
}

/// Deterministic target-independent passive plugin resolution.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct PluginResolution {
    /// Reachable selected and shadowed plugin candidates.
    pub plugins: Vec<ResolvedPlugin>,
    /// Typed graph and coherence diagnostics.
    pub diagnostics: Vec<PluginDiagnostic>,
}

/// Safe read-only candidate summary used by plugin list/show.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginCandidate {
    /// Canonical source-qualified identity.
    pub source_ref: String,
    /// Plugin slot name.
    pub slot_name: String,
    /// Optional stable identity.
    pub id: Option<String>,
    /// Human-facing description.
    pub description: String,
    /// Optional authored version.
    pub version: Option<String>,
    /// Package directory.
    pub path: PathBuf,
    /// Complete bounded package hash.
    pub package_hash: String,
    /// Passive members.
    pub members: Vec<PluginMember>,
    /// Inert validated local-tool contracts.
    pub tools: Vec<ToolRecord>,
    /// Inert validated hook contracts.
    pub hooks: Vec<HookRecord>,
    /// Plugin dependencies.
    pub requires: Vec<PluginDependency>,
    /// Provider overlay names; overlay values remain adapter-private.
    pub provider_overlays: Vec<String>,
}

/// Read-only plugin list report including unselected offers and selected state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginListReport {
    /// Every valid candidate in enabled source order, then identity order.
    pub candidates: Vec<PluginCandidate>,
    /// Canonical selected graph.
    pub resolution: PluginResolution,
}

/// Read-only detail for one exact candidate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PluginShowReport {
    /// Candidate package metadata.
    pub candidate: PluginCandidate,
    /// Selected state when the candidate is reachable, otherwise `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selected: Option<ResolvedPlugin>,
}

/// Build a deterministic safe candidate list without exposing provider overlay
/// values that may contain source-authored secrets.
#[must_use]
pub fn list_report(
    sources: &[SourceConfig],
    inventories: &[SourceInventory],
    resolution: PluginResolution,
) -> PluginListReport {
    let priorities = sources
        .iter()
        .filter(|source| source.enabled)
        .map(|source| (source.id.as_str(), source.priority))
        .collect::<BTreeMap<_, _>>();
    let mut candidates = inventories
        .iter()
        .flat_map(|inventory| &inventory.plugins)
        .map(candidate_summary)
        .collect::<Vec<_>>();
    candidates.sort_by(|left, right| {
        priorities
            .get(
                left.source_ref
                    .split_once(':')
                    .map_or("", |(source, _)| source),
            )
            .unwrap_or(&i32::MAX)
            .cmp(
                priorities
                    .get(
                        right
                            .source_ref
                            .split_once(':')
                            .map_or("", |(source, _)| source),
                    )
                    .unwrap_or(&i32::MAX),
            )
            .then_with(|| left.source_ref.cmp(&right.source_ref))
    });
    PluginListReport {
        candidates,
        resolution,
    }
}

/// Build read-only detail for a normalized candidate identity.
#[must_use]
pub fn show_report(
    identity: &str,
    inventories: &[SourceInventory],
    resolution: &PluginResolution,
) -> Option<PluginShowReport> {
    let record = inventories
        .iter()
        .flat_map(|inventory| &inventory.plugins)
        .find(|plugin| plugin.source_ref == identity)?;
    Some(PluginShowReport {
        candidate: candidate_summary(record),
        selected: resolution
            .plugins
            .iter()
            .find(|plugin| plugin.source_ref == identity)
            .cloned(),
    })
}

fn candidate_summary(record: &PluginRecord) -> PluginCandidate {
    PluginCandidate {
        source_ref: record.source_ref.clone(),
        slot_name: record.slot_name.clone(),
        id: record.id.clone(),
        description: record.description.clone(),
        version: record.version.clone(),
        path: record.path.clone(),
        package_hash: record.package_hash.clone(),
        members: record.members.clone(),
        tools: record.tools.clone(),
        hooks: record.hooks.clone(),
        requires: record.requires.clone(),
        provider_overlays: record.providers.keys().cloned().collect(),
    }
}

#[derive(Debug, Clone)]
struct CandidateIndex<'a> {
    by_source: BTreeMap<&'a str, Vec<&'a PluginRecord>>,
    source_priority: BTreeMap<&'a str, i32>,
}

/// Resolve authored stack and direct-user plugin intent without target input.
#[must_use]
pub fn resolve_plugins(config: &UserConfig, inventories: &[SourceInventory]) -> PluginResolution {
    let index = candidate_index(&config.sources, inventories);
    let mut diagnostics = Vec::new();
    let mut roots = BTreeSet::new();
    let mut origins = BTreeMap::<String, BTreeSet<SelectionOrigin>>::new();

    for reference in &config.plugins.direct {
        add_root(
            reference,
            SelectionOrigin {
                kind: SelectionOriginKind::Direct,
                declared_by: "user_config".to_owned(),
                requirement: SelectionStrength::Required,
            },
            &index,
            &mut roots,
            &mut origins,
            &mut diagnostics,
        );
    }
    for source in config.sources.iter().filter(|source| source.enabled) {
        let source_root =
            match crate::source::scoped_source_root(&source.path, source.subpath.as_deref()) {
                Ok(root) => root,
                Err(error) => {
                    diagnostics.push(PluginDiagnostic {
                        code: PluginDiagnosticCode::InvalidStackSelection,
                        subject: source.id.clone(),
                        message: error.to_string(),
                    });
                    continue;
                }
            };
        let path = source_root.join(TEAM_MANIFEST_FILE);
        let manifest = match team_manifest::read_manifest(&path) {
            Ok(Some(manifest)) => manifest,
            Ok(None) => continue,
            Err(error) => {
                diagnostics.push(PluginDiagnostic {
                    code: PluginDiagnosticCode::InvalidStackSelection,
                    subject: source.id.clone(),
                    message: error.to_string(),
                });
                continue;
            }
        };
        let Some(selection) = manifest.selection else {
            continue;
        };
        if manifest
            .source
            .as_ref()
            .and_then(|metadata| metadata.id.as_deref())
            != Some(source.id.as_str())
        {
            diagnostics.push(PluginDiagnostic {
                code: PluginDiagnosticCode::InvalidStackSelection,
                subject: source.id.clone(),
                message: "[source].id must match the configured source when [selection] is present"
                    .to_owned(),
            });
            continue;
        }
        let mut seen = BTreeSet::new();
        for selected in selection.plugins {
            if !seen.insert(selected.reference.clone()) {
                diagnostics.push(PluginDiagnostic {
                    code: PluginDiagnosticCode::InvalidStackSelection,
                    subject: selected.reference,
                    message: "duplicate plugin selection in one manifest".to_owned(),
                });
                continue;
            }
            add_root(
                &selected.reference,
                SelectionOrigin {
                    kind: SelectionOriginKind::Stack,
                    declared_by: source.id.clone(),
                    requirement: match selected.requirement {
                        StackRequirement::Required => SelectionStrength::Required,
                        StackRequirement::Recommended => SelectionStrength::Recommended,
                    },
                },
                &index,
                &mut roots,
                &mut origins,
                &mut diagnostics,
            );
        }
    }

    let mut reachable = roots.clone();
    loop {
        let winners = winner_map(&reachable, &index);
        let mut next = roots.clone();
        let mut queue = winners.values().cloned().collect::<Vec<_>>();
        queue.sort();
        while let Some(identity) = queue.pop() {
            let Some(plugin) = plugin_by_identity(&identity, &index) else {
                continue;
            };
            for dependency in &plugin.requires {
                match resolve_component_reference(&dependency.reference, &plugin.source_id, &index)
                {
                    ReferenceMatch::One(candidate) => {
                        let dependency_id = candidate.source_ref.clone();
                        origins
                            .entry(dependency_id.clone())
                            .or_default()
                            .insert(SelectionOrigin {
                                kind: SelectionOriginKind::Dependency,
                                declared_by: plugin.source_ref.clone(),
                                requirement: match dependency.requirement {
                                    DependencyRequirement::Required => SelectionStrength::Required,
                                    DependencyRequirement::Optional => SelectionStrength::Optional,
                                },
                            });
                        if next.insert(dependency_id.clone()) {
                            queue.push(dependency_id);
                        }
                    }
                    ReferenceMatch::Missing
                        if dependency.requirement == DependencyRequirement::Required =>
                    {
                        diagnostics.push(PluginDiagnostic {
                            code: PluginDiagnosticCode::MissingPlugin,
                            subject: plugin.source_ref.clone(),
                            message: format!(
                                "required dependency `{}` is missing",
                                dependency.reference.as_string()
                            ),
                        });
                    }
                    ReferenceMatch::Ambiguous
                        if dependency.requirement == DependencyRequirement::Required =>
                    {
                        diagnostics.push(PluginDiagnostic {
                            code: PluginDiagnosticCode::AmbiguousPluginReference,
                            subject: plugin.source_ref.clone(),
                            message: format!(
                                "required dependency `{}` is ambiguous",
                                dependency.reference.as_string()
                            ),
                        });
                    }
                    _ => {}
                }
            }
        }
        if next == reachable {
            break;
        }
        reachable = next;
    }

    let winners = winner_map(&reachable, &index);
    let cycles = required_cycle_nodes(&winners, &index);
    for cycle in &cycles {
        diagnostics.push(PluginDiagnostic {
            code: PluginDiagnosticCode::RequiredDependencyCycle,
            subject: cycle.join(","),
            message: format!("required plugin dependency cycle: {}", cycle.join(" -> ")),
        });
    }
    let cycle_nodes = cycles.iter().flatten().cloned().collect::<BTreeSet<_>>();
    let mut policies = applied_policies(config, &index, &mut diagnostics);
    let declined = policies.keys().cloned().collect::<BTreeSet<_>>();
    let mut resolved = Vec::new();
    for identity in &reachable {
        let Some(plugin) = plugin_by_identity(identity, &index) else {
            continue;
        };
        let winner = winners.get(&plugin.slot_name).cloned();
        let shadowed_by = winner
            .as_ref()
            .filter(|winner| *winner != identity)
            .cloned();
        let mut blocking_reasons = Vec::new();
        let members = evaluate_members(plugin, &config.sources, inventories, &mut blocking_reasons);
        for reason in &blocking_reasons {
            diagnostics.push(PluginDiagnostic {
                code: PluginDiagnosticCode::RequiredMemberBlocked,
                subject: identity.clone(),
                message: reason.clone(),
            });
        }
        let dependencies = plugin
            .requires
            .iter()
            .map(|dependency| {
                let (state, resolved_ref) = match resolve_component_reference(
                    &dependency.reference,
                    &plugin.source_id,
                    &index,
                ) {
                    ReferenceMatch::One(target) => {
                        let state = if winners.get(&target.slot_name) != Some(&target.source_ref) {
                            PluginDependencyState::Shadowed
                        } else if declined.contains(&target.source_ref) {
                            PluginDependencyState::Declined
                        } else {
                            PluginDependencyState::Selected
                        };
                        (state, Some(target.source_ref.clone()))
                    }
                    ReferenceMatch::Missing => (PluginDependencyState::Missing, None),
                    ReferenceMatch::Ambiguous => (PluginDependencyState::Ambiguous, None),
                };
                if dependency.requirement == DependencyRequirement::Required
                    && state != PluginDependencyState::Selected
                {
                    blocking_reasons.push(
                        format!(
                            "required dependency `{}` is {state}",
                            dependency.reference.as_string()
                        )
                        .to_lowercase(),
                    );
                }
                ResolvedPluginDependency {
                    reference: dependency.reference.as_string(),
                    requirement: dependency.requirement,
                    state,
                    resolved_ref,
                }
            })
            .collect::<Vec<_>>();
        if cycle_nodes.contains(identity) {
            blocking_reasons.push("required dependency cycle".to_owned());
        }
        let state = if shadowed_by.is_some() {
            PluginState::Shadowed
        } else if policies.contains_key(identity) {
            PluginState::Declined
        } else if blocking_reasons.is_empty() {
            PluginState::Selected
        } else {
            PluginState::Blocked
        };
        if let Some(winner) = &shadowed_by {
            diagnostics.push(PluginDiagnostic {
                code: PluginDiagnosticCode::ShadowedPlugin,
                subject: identity.clone(),
                message: format!("selected plugin is shadowed by `{winner}`"),
            });
        }
        let closure_hash = closure_hash(
            plugin,
            &members,
            &dependencies,
            &blocking_reasons,
            state,
            &winners,
            &index,
        );
        resolved.push(ResolvedPlugin {
            source_ref: identity.clone(),
            slot_name: plugin.slot_name.clone(),
            id: plugin.id.clone(),
            source_priority: *index
                .source_priority
                .get(plugin.source_id.as_str())
                .unwrap_or(&i32::MAX),
            package_hash: plugin.package_hash.clone(),
            closure_hash,
            origins: origins
                .remove(identity)
                .unwrap_or_default()
                .into_iter()
                .collect(),
            policies: policies.remove(identity).unwrap_or_default(),
            state,
            shadowed_by,
            members,
            dependencies,
            blocking_reasons,
        });
    }
    resolved.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
    diagnostics.sort_by(|left, right| {
        left.subject
            .cmp(&right.subject)
            .then_with(|| format!("{:?}", left.code).cmp(&format!("{:?}", right.code)))
            .then_with(|| left.message.cmp(&right.message))
    });
    diagnostics.dedup();
    PluginResolution {
        plugins: resolved,
        diagnostics,
    }
}

/// Normalize a source-qualified slot or stable-ID selector to canonical plugin
/// identity without changing selection state.
pub fn normalize_plugin_reference(
    config: &UserConfig,
    inventories: &[SourceInventory],
    reference: &str,
) -> Result<String, String> {
    let index = candidate_index(&config.sources, inventories);
    match resolve_qualified(reference, &index) {
        ReferenceMatch::One(plugin) => Ok(plugin.source_ref.clone()),
        ReferenceMatch::Missing => Err(format!(
            "plugin `{reference}` does not exist in the exact configured source"
        )),
        ReferenceMatch::Ambiguous => Err(format!(
            "plugin `{reference}` is ambiguous between a slot and stable ID"
        )),
    }
}

/// Project existing component activation facts onto the canonical plugin graph.
/// This operation never grants approval or enables an instruction pack.
pub fn apply_component_resolution(
    plugins: &mut PluginResolution,
    skills: &Resolution,
    agents: &AgentResolution,
    active_instructions: &BTreeSet<String>,
) {
    for plugin in &mut plugins.plugins {
        let previous_member_states = plugin
            .members
            .iter()
            .map(|member| member.state)
            .collect::<Vec<_>>();
        let previous_state = plugin.state;
        plugin
            .blocking_reasons
            .retain(|reason| !reason.starts_with("required member `"));
        for member in &mut plugin.members {
            let Some(identity) = member.resolved_ref.as_deref() else {
                continue;
            };
            member.state = if member.reference.starts_with("skill:") {
                if skills
                    .active_skills
                    .iter()
                    .any(|skill| skill.source_ref == identity)
                {
                    PluginComponentState::Active
                } else if skills
                    .pending_approval_skills
                    .iter()
                    .any(|skill| skill.source_ref == identity)
                {
                    PluginComponentState::PendingApproval
                } else if skills
                    .blocked_skills
                    .iter()
                    .any(|skill| skill.skill.source_ref == identity)
                {
                    PluginComponentState::Blocked
                } else if skills
                    .unlinked_skills
                    .iter()
                    .any(|skill| skill.skill.source_ref == identity)
                {
                    PluginComponentState::Shadowed
                } else {
                    PluginComponentState::Available
                }
            } else if member.reference.starts_with("agent:") {
                if agents
                    .active_agents
                    .iter()
                    .any(|agent| agent.agent.source_ref == identity)
                {
                    PluginComponentState::Active
                } else if agents
                    .pending_approval_agents
                    .iter()
                    .any(|agent| agent.agent.source_ref == identity)
                {
                    PluginComponentState::PendingApproval
                } else if agents
                    .shadowed_agents
                    .iter()
                    .any(|agent| agent.agent.agent.source_ref == identity)
                {
                    PluginComponentState::Shadowed
                } else {
                    PluginComponentState::Available
                }
            } else if active_instructions.contains(identity) {
                PluginComponentState::Active
            } else {
                PluginComponentState::Inactive
            };
            if member.requirement == MemberRequirement::Required
                && member.state != PluginComponentState::Active
            {
                plugin.blocking_reasons.push(
                    format!("required member `{}` is {}", member.reference, member.state)
                        .to_lowercase(),
                );
            }
        }
        plugin.blocking_reasons.sort();
        plugin.blocking_reasons.dedup();
        if !matches!(plugin.state, PluginState::Shadowed | PluginState::Declined) {
            plugin.state = if plugin.blocking_reasons.is_empty() {
                PluginState::Selected
            } else {
                PluginState::Blocked
            };
        }
        let changed = previous_state != plugin.state
            || previous_member_states
                .iter()
                .zip(&plugin.members)
                .any(|(previous, member)| *previous != member.state);
        if !changed {
            continue;
        }
        let mut hash = Sha256::new();
        hash.update(b"dalo-plugin-activation-closure-v1\0");
        hash.update(&plugin.closure_hash);
        for member in &plugin.members {
            hash.update([0]);
            hash.update(&member.reference);
            hash.update(format!("{:?}{:?}", member.requirement, member.state));
            if let Some(identity) = &member.resolved_ref {
                hash.update(identity);
            }
        }
        plugin.closure_hash = hash
            .finalize()
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect();
    }
}

fn candidate_index<'a>(
    sources: &'a [SourceConfig],
    inventories: &'a [SourceInventory],
) -> CandidateIndex<'a> {
    let enabled = sources
        .iter()
        .filter(|source| source.enabled)
        .map(|source| (source.id.as_str(), source.priority))
        .collect::<BTreeMap<_, _>>();
    let mut by_source = BTreeMap::<&str, Vec<&PluginRecord>>::new();
    for inventory in inventories {
        if enabled.contains_key(inventory.source_id.as_str()) {
            by_source
                .entry(inventory.source_id.as_str())
                .or_default()
                .extend(&inventory.plugins);
        }
    }
    for plugins in by_source.values_mut() {
        plugins.sort_by(|left, right| left.source_ref.cmp(&right.source_ref));
    }
    CandidateIndex {
        by_source,
        source_priority: enabled,
    }
}

enum ReferenceMatch<'a> {
    One(&'a PluginRecord),
    Missing,
    Ambiguous,
}

fn resolve_qualified<'a>(reference: &str, index: &'a CandidateIndex<'a>) -> ReferenceMatch<'a> {
    let mut parts = reference.split(':');
    let (Some(source), Some(selector), None) = (parts.next(), parts.next(), parts.next()) else {
        return ReferenceMatch::Missing;
    };
    resolve_selector(source, selector, index)
}

fn resolve_component_reference<'a>(
    reference: &ComponentReference,
    declaring_source: &str,
    index: &'a CandidateIndex<'a>,
) -> ReferenceMatch<'a> {
    let source = reference.source_id.as_deref().unwrap_or(declaring_source);
    resolve_selector(source, &reference.selector, index)
}

fn resolve_selector<'a>(
    source: &str,
    selector: &str,
    index: &'a CandidateIndex<'a>,
) -> ReferenceMatch<'a> {
    let Some(candidates) = index.by_source.get(source) else {
        return ReferenceMatch::Missing;
    };
    let slot = candidates
        .iter()
        .copied()
        .find(|plugin| plugin.slot_name == selector);
    let stable = candidates
        .iter()
        .copied()
        .find(|plugin| plugin.id.as_deref() == Some(selector));
    match (slot, stable) {
        (Some(left), Some(right)) if left.source_ref != right.source_ref => {
            ReferenceMatch::Ambiguous
        }
        (Some(plugin), _) | (_, Some(plugin)) => ReferenceMatch::One(plugin),
        _ => ReferenceMatch::Missing,
    }
}

fn add_root(
    reference: &str,
    origin: SelectionOrigin,
    index: &CandidateIndex<'_>,
    roots: &mut BTreeSet<String>,
    origins: &mut BTreeMap<String, BTreeSet<SelectionOrigin>>,
    diagnostics: &mut Vec<PluginDiagnostic>,
) {
    match resolve_qualified(reference, index) {
        ReferenceMatch::One(plugin) => {
            roots.insert(plugin.source_ref.clone());
            origins
                .entry(plugin.source_ref.clone())
                .or_default()
                .insert(origin);
        }
        ReferenceMatch::Missing => diagnostics.push(PluginDiagnostic {
            code: PluginDiagnosticCode::MissingPlugin,
            subject: reference.to_owned(),
            message: "selected plugin does not exist in the exact source".to_owned(),
        }),
        ReferenceMatch::Ambiguous => diagnostics.push(PluginDiagnostic {
            code: PluginDiagnosticCode::AmbiguousPluginReference,
            subject: reference.to_owned(),
            message: "selector matches different slot and stable-ID candidates".to_owned(),
        }),
    }
}

fn plugin_by_identity<'a>(
    identity: &str,
    index: &'a CandidateIndex<'a>,
) -> Option<&'a PluginRecord> {
    index
        .by_source
        .values()
        .flatten()
        .copied()
        .find(|plugin| plugin.source_ref == identity)
}

fn winner_map(
    reachable: &BTreeSet<String>,
    index: &CandidateIndex<'_>,
) -> BTreeMap<String, String> {
    let mut groups = BTreeMap::<String, Vec<&PluginRecord>>::new();
    for identity in reachable {
        if let Some(plugin) = plugin_by_identity(identity, index) {
            groups
                .entry(plugin.slot_name.clone())
                .or_default()
                .push(plugin);
        }
    }
    groups
        .into_iter()
        .map(|(slot, mut plugins)| {
            plugins.sort_by(|left, right| {
                index
                    .source_priority
                    .get(left.source_id.as_str())
                    .unwrap_or(&i32::MAX)
                    .cmp(
                        index
                            .source_priority
                            .get(right.source_id.as_str())
                            .unwrap_or(&i32::MAX),
                    )
                    .then_with(|| left.source_id.cmp(&right.source_id))
            });
            (slot, plugins[0].source_ref.clone())
        })
        .collect()
}

fn required_cycle_nodes(
    winners: &BTreeMap<String, String>,
    index: &CandidateIndex<'_>,
) -> Vec<Vec<String>> {
    let winner_ids = winners.values().cloned().collect::<BTreeSet<_>>();
    let mut graph = BTreeMap::<String, Vec<String>>::new();
    for identity in &winner_ids {
        let Some(plugin) = plugin_by_identity(identity, index) else {
            continue;
        };
        let mut edges = Vec::new();
        for dependency in plugin
            .requires
            .iter()
            .filter(|dependency| dependency.requirement == DependencyRequirement::Required)
        {
            if let ReferenceMatch::One(target) =
                resolve_component_reference(&dependency.reference, &plugin.source_id, index)
                && winner_ids.contains(&target.source_ref)
            {
                edges.push(target.source_ref.clone());
            }
        }
        edges.sort();
        graph.insert(identity.clone(), edges);
    }
    let mut cycles = BTreeSet::<Vec<String>>::new();
    for start in graph.keys() {
        find_cycles(
            start,
            start,
            &graph,
            &mut Vec::new(),
            &mut BTreeSet::new(),
            &mut cycles,
        );
    }
    cycles.into_iter().collect()
}

fn find_cycles(
    start: &str,
    current: &str,
    graph: &BTreeMap<String, Vec<String>>,
    path: &mut Vec<String>,
    visiting: &mut BTreeSet<String>,
    cycles: &mut BTreeSet<Vec<String>>,
) {
    if !visiting.insert(current.to_owned()) {
        return;
    }
    path.push(current.to_owned());
    for next in graph.get(current).into_iter().flatten() {
        if next == start {
            let mut cycle = path.clone();
            cycle.sort();
            cycle.dedup();
            cycles.insert(cycle);
        } else {
            find_cycles(start, next, graph, path, visiting, cycles);
        }
    }
    path.pop();
    visiting.remove(current);
}

fn applied_policies(
    config: &UserConfig,
    index: &CandidateIndex<'_>,
    diagnostics: &mut Vec<PluginDiagnostic>,
) -> BTreeMap<String, Vec<AppliedPluginPolicy>> {
    let mut applied = BTreeMap::<String, Vec<AppliedPluginPolicy>>::new();
    for policy in &config.plugin_policy {
        if policy.decision == PluginPolicyDecision::Decline
            && let ReferenceMatch::One(plugin) = resolve_qualified(&policy.plugin, index)
        {
            applied
                .entry(plugin.source_ref.clone())
                .or_default()
                .push(AppliedPluginPolicy {
                    layer: policy.layer,
                    rule_id: policy.rule_id.clone(),
                    decision: policy.decision,
                    reason: policy.reason.clone(),
                });
            diagnostics.push(PluginDiagnostic {
                code: PluginDiagnosticCode::DeclinedPlugin,
                subject: plugin.source_ref.clone(),
                message: policy.reason.clone(),
            });
        }
    }
    for policies in applied.values_mut() {
        policies.sort_by(|left, right| left.rule_id.cmp(&right.rule_id));
    }
    applied
}

fn evaluate_members(
    plugin: &PluginRecord,
    sources: &[SourceConfig],
    inventories: &[SourceInventory],
    blocking: &mut Vec<String>,
) -> Vec<ResolvedPluginMember> {
    plugin
        .members
        .iter()
        .map(|member| {
            let source = member
                .reference
                .source_id
                .as_deref()
                .unwrap_or(&plugin.source_id);
            let (state, resolved_ref) = match member.reference.kind {
                ComponentKind::Skill => resolve_asset(
                    source,
                    &member.reference.selector,
                    inventories,
                    |inventory| {
                        inventory
                            .skills
                            .iter()
                            .map(|skill| {
                                (
                                    &skill.slot_name,
                                    skill.id.as_ref(),
                                    skill.source_ref.as_str(),
                                )
                            })
                            .collect()
                    },
                ),
                ComponentKind::Agent => resolve_asset(
                    source,
                    &member.reference.selector,
                    inventories,
                    |inventory| {
                        inventory
                            .agents
                            .iter()
                            .map(|agent| {
                                (
                                    &agent.slot_name,
                                    agent.id.as_ref(),
                                    agent.source_ref.as_str(),
                                )
                            })
                            .collect()
                    },
                ),
                ComponentKind::Instruction => {
                    let available = sources
                        .iter()
                        .find(|candidate| candidate.enabled && candidate.id == source)
                        .map(|candidate| {
                            candidate
                                .path
                                .join("instructions")
                                .join(format!("{}.md", member.reference.selector))
                                .is_file()
                        })
                        .unwrap_or(false);
                    if available {
                        (
                            PluginComponentState::Inactive,
                            Some(format!("{source}:{}", member.reference.selector)),
                        )
                    } else {
                        (PluginComponentState::Missing, None)
                    }
                }
                ComponentKind::Plugin => (PluginComponentState::Missing, None),
            };
            if member.requirement == MemberRequirement::Required
                && matches!(
                    state,
                    PluginComponentState::Missing
                        | PluginComponentState::Ambiguous
                        | PluginComponentState::Inactive
                )
            {
                blocking.push(
                    format!(
                        "required member `{}` is {}",
                        member.reference.as_string(),
                        state
                    )
                    .to_lowercase(),
                );
            }
            ResolvedPluginMember {
                reference: member.reference.as_string(),
                requirement: member.requirement,
                state,
                resolved_ref,
                fallback: member
                    .fallback
                    .as_ref()
                    .map(|fallback| fallback.skill.as_string()),
            }
        })
        .collect()
}

fn resolve_asset<'a, F>(
    source: &str,
    selector: &str,
    inventories: &'a [SourceInventory],
    collect: F,
) -> (PluginComponentState, Option<String>)
where
    F: Fn(&'a SourceInventory) -> Vec<(&'a String, Option<&'a String>, &'a str)>,
{
    let Some(inventory) = inventories
        .iter()
        .find(|inventory| inventory.source_id == source)
    else {
        return (PluginComponentState::Missing, None);
    };
    let candidates = collect(inventory);
    let slot = candidates
        .iter()
        .find(|(name, _, _)| name.as_str() == selector)
        .map(|(_, _, identity)| *identity);
    let stable = candidates
        .iter()
        .find(|(_, id, _)| id.is_some_and(|id| id == selector))
        .map(|(_, _, identity)| *identity);
    match (slot, stable) {
        (Some(left), Some(right)) if left != right => (PluginComponentState::Ambiguous, None),
        (Some(identity), _) | (_, Some(identity)) => {
            (PluginComponentState::Available, Some(identity.to_owned()))
        }
        _ => (PluginComponentState::Missing, None),
    }
}

fn closure_hash(
    plugin: &PluginRecord,
    members: &[ResolvedPluginMember],
    dependencies: &[ResolvedPluginDependency],
    blocking: &[String],
    state: PluginState,
    winners: &BTreeMap<String, String>,
    index: &CandidateIndex<'_>,
) -> String {
    let mut hash = Sha256::new();
    hash.update(b"dalo-plugin-closure-v1\0");
    hash.update(&plugin.source_ref);
    hash.update([0]);
    hash.update(&plugin.package_hash);
    for dependency in &plugin.requires {
        hash.update([0]);
        hash.update(dependency.reference.as_string());
        hash.update(format!("{:?}", dependency.requirement));
        if let ReferenceMatch::One(target) =
            resolve_component_reference(&dependency.reference, &plugin.source_id, index)
        {
            hash.update(&target.source_ref);
            if winners.get(&target.slot_name) == Some(&target.source_ref) {
                hash.update(b"winner");
            }
        }
    }
    for member in members {
        hash.update([0]);
        hash.update(&member.reference);
        hash.update(format!("{:?}{:?}", member.requirement, member.state));
        if let Some(identity) = &member.resolved_ref {
            hash.update(identity);
        }
    }
    for dependency in dependencies {
        hash.update([0]);
        hash.update(&dependency.reference);
        hash.update(format!(
            "{:?}{:?}",
            dependency.requirement, dependency.state
        ));
        if let Some(identity) = &dependency.resolved_ref {
            hash.update(identity);
        }
    }
    for reason in blocking {
        hash.update([0]);
        hash.update(reason);
    }
    hash.update(format!("{:?}", state));
    hash.finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{PluginConfig, Settings};
    use crate::inventory;
    use crate::source::{SourceConfig, SourceKind};
    use tempfile::TempDir;

    fn write_plugin(root: &Path, name: &str, manifest: &str) -> PathBuf {
        let package = root.join("plugins").join(name);
        fs::create_dir_all(&package).unwrap();
        fs::write(package.join(PLUGIN_FILE), manifest).unwrap();
        package
    }

    fn valid_manifest(name: &str) -> String {
        format!(
            r#"schema_version = 1
[plugin]
name = "{name}"
id = "dev.example.{name}"
description = "Example"

[[plugin.members]]
ref = "skill:core"
requirement = "required"

[[plugin.members]]
ref = "agent:reviewer"
requirement = "optional"
[plugin.members.fallback]
kind = "inline"
skill = "skill:core"

[[plugin.requires]]
ref = "plugin:base"
requirement = "optional"
"#
        )
    }

    fn source(id: &str, path: &Path, priority: i32) -> SourceConfig {
        SourceConfig {
            id: id.to_owned(),
            kind: SourceKind::Team,
            path: path.to_path_buf(),
            subpath: None,
            priority,
            namespace: None,
            enabled: true,
            trusted: false,
            url: None,
            branch: None,
            update_policy: None,
            selection: Vec::new(),
            declared_by: None,
            declared_ref: None,
        }
    }

    fn config(sources: Vec<SourceConfig>, direct: &[&str]) -> UserConfig {
        UserConfig {
            version: crate::config::CONFIG_VERSION,
            settings: Settings {
                autosync: false,
                sync_interval: None,
            },
            sources,
            plugins: PluginConfig {
                direct: direct.iter().map(|value| (*value).to_owned()).collect(),
            },
            plugin_policy: Vec::new(),
            project_selections: None,
        }
    }

    #[test]
    fn discovers_exact_valid_packages_and_hashes_support_files() {
        let temp = TempDir::new().unwrap();
        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
        fs::write(package.join("README.md"), "one").unwrap();
        write_plugin(
            &temp.path().join("nested"),
            "ignored",
            &valid_manifest("ignored"),
        );
        let first = scan_source_plugins("team", temp.path());
        assert_eq!(first.plugins.len(), 1);
        assert!(first.warnings.is_empty());
        fs::write(package.join("README.md"), "two").unwrap();
        let second = scan_source_plugins("team", temp.path());
        assert_ne!(
            first.plugins[0].package_hash,
            second.plugins[0].package_hash
        );
    }

    #[test]
    fn plugin_support_files_are_not_discovered_as_standalone_skills() {
        let temp = TempDir::new().unwrap();
        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
        let embedded = package.join("embedded");
        fs::create_dir_all(&embedded).unwrap();
        fs::write(embedded.join("SKILL.md"), "# Inert support file\n").unwrap();

        let inventory = inventory::scan_source("team", temp.path()).unwrap();

        assert!(inventory.skills.is_empty());
        assert_eq!(inventory.plugins.len(), 1);
    }

    #[test]
    fn invalid_sibling_does_not_hide_valid_package() {
        let temp = TempDir::new().unwrap();
        write_plugin(temp.path(), "valid", &valid_manifest("valid"));
        write_plugin(temp.path(), "broken", "schema_version = 99\n");
        let inventory = scan_source_plugins("team", temp.path());
        assert_eq!(inventory.plugins.len(), 1);
        assert_eq!(inventory.warnings.len(), 1);
        assert_eq!(
            inventory.warnings[0].code,
            PluginInventoryWarningCode::InvalidPackage
        );
    }

    #[test]
    fn unsupported_hook_descriptor_versions_block_package() {
        let temp = TempDir::new().unwrap();
        let manifest = format!(
            "{}\n[[hook]]\nschema_version = 99\nid = \"future\"\ntool = \"detector\"\nsubject = \"tool_call\"\nphase = \"before\"\neffect = \"allow_deny\"\nrequirement = \"required\"\ntimeout_ms = 2000\nfailure_policy = \"fail_closed\"\nretry = \"never\"\nerror_visibility = \"model_and_user\"\nblocking_scope = \"matched_event\"\n",
            valid_manifest("example")
        );
        write_plugin(temp.path(), "example", &manifest);
        let inventory = scan_source_plugins("team", temp.path());
        assert!(inventory.plugins.is_empty());
        assert_eq!(
            inventory.warnings[0].code,
            PluginInventoryWarningCode::UnsupportedActiveComponentSchema
        );
    }

    #[test]
    fn hook_descriptor_binds_an_exact_same_plugin_tool_contract() {
        let temp = TempDir::new().unwrap();
        let manifest = format!(
            r#"{}

[[hook]]
schema_version = 1
id = "protect-bash"
tool = "detector"
subject = "tool_call"
phase = "before"
effect = "allow_deny"
requirement = "required"
timeout_ms = 2000
failure_policy = "fail_closed"
retry = "never"
error_visibility = "model_and_user"
blocking_scope = "matched_event"
bindings = [{{ input = "path", field = "session.cwd" }}]
matcher = {{ tool_names = ["Bash"] }}
"#,
            tool_manifest("example", "\"${input.path}\"")
        );
        let package = write_plugin(temp.path(), "example", &manifest);
        write_tool_files(&package);

        let inventory = scan_source_plugins("team", temp.path());
        assert!(inventory.warnings.is_empty(), "{:?}", inventory.warnings);
        let hook = &inventory.plugins[0].hooks[0];
        assert_eq!(hook.source_ref, "team:example#hook:protect-bash");
        assert_eq!(hook.tool_source_ref, "team:example#tool:detector");
        assert_eq!(hook.contract_hash.len(), 64);
    }

    fn tool_manifest(name: &str, argv: &str) -> String {
        format!(
            r#"{}
[[tool]]
schema_version = 1
id = "detector"
entry = "bin/detect.py"
runtime = "python"
runtime_version = ">=3.11"
platforms = ["macos", "linux"]
argv = ["--path", {argv}]
files = ["lib/rules.txt"]
cwd = "tool_root"
env = ["DALO_LOG"]
capabilities = ["filesystem_read"]
availability = "required"

[[tool.inputs]]
name = "path"
type = "path"
required = true
"#,
            valid_manifest(name)
        )
    }

    fn write_tool_files(package: &Path) {
        fs::create_dir_all(package.join("bin")).unwrap();
        fs::create_dir_all(package.join("lib")).unwrap();
        fs::write(package.join("bin/detect.py"), b"print('ok')\n").unwrap();
        fs::write(package.join("lib/rules.txt"), b"rules\n").unwrap();
    }

    #[test]
    fn discovers_tool_and_hashes_only_security_relevant_closure() {
        let temp = TempDir::new().unwrap();
        let package = write_plugin(
            temp.path(),
            "example",
            &tool_manifest("example", r#""${input.path}""#),
        );
        write_tool_files(&package);
        fs::write(package.join("README.md"), "one").unwrap();
        let first = scan_source_plugins("team", temp.path());
        assert!(first.warnings.is_empty(), "{:?}", first.warnings);
        assert_eq!(first.plugins[0].tools.len(), 1);
        let contract = first.plugins[0].tools[0].contract_hash.clone();
        let package_hash = first.plugins[0].package_hash.clone();

        fs::write(package.join("README.md"), "two").unwrap();
        let second = scan_source_plugins("team", temp.path());
        assert_eq!(second.plugins[0].tools[0].contract_hash, contract);
        assert_ne!(second.plugins[0].package_hash, package_hash);

        fs::write(package.join("lib/rules.txt"), "changed").unwrap();
        let third = scan_source_plugins("team", temp.path());
        assert_ne!(third.plugins[0].tools[0].contract_hash, contract);
    }

    #[test]
    fn rejects_path_escape_and_partial_or_unknown_placeholders() {
        let temp = TempDir::new().unwrap();
        let package = write_plugin(
            temp.path(),
            "escape",
            &tool_manifest("escape", r#""prefix-${input.path}""#),
        );
        write_tool_files(&package);
        let placeholder = scan_source_plugins("team", temp.path());
        assert!(placeholder.plugins.is_empty());
        assert!(
            placeholder.warnings[0]
                .message
                .contains("unsafe placeholder")
        );

        let package = write_plugin(
            temp.path(),
            "outside",
            &tool_manifest("outside", r#""${input.path}""#)
                .replace("bin/detect.py", "../detect.py"),
        );
        write_tool_files(&package);
        let escaped = scan_source_plugins("team", temp.path());
        assert!(
            escaped
                .warnings
                .iter()
                .any(|warning| warning.path.ends_with("outside")
                    && warning.message.contains("inside"))
        );
    }

    #[test]
    fn descriptor_input_or_argv_drift_invalidates_contract() {
        let temp = TempDir::new().unwrap();
        let package = write_plugin(
            temp.path(),
            "example",
            &tool_manifest("example", r#""${input.path}""#),
        );
        write_tool_files(&package);
        let first = scan_source_plugins("team", temp.path());
        let contract = first.plugins[0].tools[0].contract_hash.clone();
        fs::write(
            package.join(PLUGIN_FILE),
            tool_manifest("example", r#""${input.path}", "--strict""#),
        )
        .unwrap();
        let second = scan_source_plugins("team", temp.path());
        assert_ne!(second.plugins[0].tools[0].contract_hash, contract);
    }

    #[test]
    fn fallback_must_name_required_skill_member() {
        let temp = TempDir::new().unwrap();
        let manifest = valid_manifest("example")
            .replace("requirement = \"required\"", "requirement = \"optional\"");
        write_plugin(temp.path(), "example", &manifest);
        let inventory = scan_source_plugins("team", temp.path());
        assert!(inventory.plugins.is_empty());
        assert!(
            inventory.warnings[0]
                .message
                .contains("required skill member")
        );
    }

    #[test]
    fn duplicate_stable_ids_invalidate_both_packages() {
        let temp = TempDir::new().unwrap();
        let first = valid_manifest("first").replace("dev.example.first", "dev.example.shared");
        let second = valid_manifest("second").replace("dev.example.second", "dev.example.shared");
        write_plugin(temp.path(), "first", &first);
        write_plugin(temp.path(), "second", &second);
        let inventory = scan_source_plugins("team", temp.path());
        assert!(inventory.plugins.is_empty());
        assert_eq!(inventory.warnings.len(), 2);
        assert!(
            inventory
                .warnings
                .iter()
                .all(|warning| warning.code == PluginInventoryWarningCode::DuplicateStableId)
        );
    }

    #[cfg(unix)]
    #[test]
    fn symlink_in_package_is_blocking() {
        use std::os::unix::fs::symlink;
        let temp = TempDir::new().unwrap();
        let package = write_plugin(temp.path(), "example", &valid_manifest("example"));
        symlink(temp.path(), package.join("escape")).unwrap();
        let inventory = scan_source_plugins("team", temp.path());
        assert!(inventory.plugins.is_empty());
        assert_eq!(
            inventory.warnings[0].code,
            PluginInventoryWarningCode::UnsafePackageEntry
        );
    }

    #[test]
    fn resolves_exact_cross_source_dependency_and_deterministic_winner() {
        let temp = TempDir::new().unwrap();
        let one = temp.path().join("one");
        let two = temp.path().join("two");
        let root_manifest = valid_manifest("shared")
            .replace("plugin:base", "plugin:two:base")
            .replace("requirement = \"optional\"", "requirement = \"required\"");
        write_plugin(&one, "shared", &root_manifest);
        write_plugin(&two, "base", &valid_manifest("base"));
        write_plugin(&two, "shared", &valid_manifest("shared"));
        let sources = vec![source("one", &one, 20), source("two", &two, 10)];
        let inventories = sources
            .iter()
            .map(|source| inventory::scan_source(&source.id, &source.path).unwrap())
            .collect::<Vec<_>>();
        let config = config(sources, &["one:shared", "two:shared"]);

        let resolution = resolve_plugins(&config, &inventories);

        assert_eq!(resolution.plugins.len(), 3);
        let one_shared = resolution
            .plugins
            .iter()
            .find(|plugin| plugin.source_ref == "one:shared")
            .unwrap();
        assert_eq!(one_shared.state, PluginState::Shadowed);
        assert_eq!(one_shared.shadowed_by.as_deref(), Some("two:shared"));
        assert!(
            resolution
                .plugins
                .iter()
                .any(|plugin| plugin.source_ref == "two:base")
        );
        assert_eq!(
            serde_json::to_string(&resolution).unwrap(),
            serde_json::to_string(&resolve_plugins(&config, &inventories)).unwrap()
        );
    }

    #[test]
    fn required_dependency_cycle_blocks_every_cycle_member() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("team");
        let alpha = valid_manifest("alpha")
            .replace("plugin:base", "plugin:beta")
            .replace("requirement = \"optional\"", "requirement = \"required\"");
        let beta = valid_manifest("beta")
            .replace("plugin:base", "plugin:alpha")
            .replace("requirement = \"optional\"", "requirement = \"required\"");
        write_plugin(&root, "alpha", &alpha);
        write_plugin(&root, "beta", &beta);
        let sources = vec![source("team", &root, 10)];
        let inventories = vec![inventory::scan_source("team", &root).unwrap()];

        let resolution = resolve_plugins(&config(sources, &["team:alpha"]), &inventories);

        assert!(
            resolution
                .plugins
                .iter()
                .all(|plugin| plugin.state == PluginState::Blocked)
        );
        assert_eq!(
            resolution
                .diagnostics
                .iter()
                .filter(
                    |diagnostic| diagnostic.code == PluginDiagnosticCode::RequiredDependencyCycle
                )
                .count(),
            1
        );
    }

    #[test]
    fn slot_stable_id_confusion_is_blocking() {
        let temp = TempDir::new().unwrap();
        let root = temp.path().join("team");
        let slot = valid_manifest("foo").replace("dev.example.foo", "dev.example.slot");
        let stable = valid_manifest("other").replace("dev.example.other", "foo");
        write_plugin(&root, "foo", &slot);
        write_plugin(&root, "other", &stable);
        let sources = vec![source("team", &root, 10)];
        let inventories = vec![inventory::scan_source("team", &root).unwrap()];

        let resolution = resolve_plugins(&config(sources, &["team:foo"]), &inventories);

        assert!(resolution.plugins.is_empty());
        assert_eq!(
            resolution.diagnostics[0].code,
            PluginDiagnosticCode::AmbiguousPluginReference
        );
    }
}