elasticctl-api 0.6.2

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

use crate::content_codec::{self, ContentFormat};
use crate::fleet::integration_policies::{
    self, IntegrationPackageSpec, IntegrationPolicyDetail, IntegrationPolicySpec,
    IntegrationPolicySummary,
};
use crate::fleet::{agent_policies, agent_policy_ops};
use crate::ops::{ExportOutcome, MutationPlan};
use elasticctl_core::{Error, ErrorKind, Result, Transport};
use serde::Serialize;
use serde_json::{Map, Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};

const PAGE_SIZE: u64 = 1000;
const IMPORT_RACE_WARNING: &str =
    "warning  Fleet can change after the final recheck and before the write";
const DELETE_RACE_WARNING: &str =
    "warning  Fleet can change after the final recheck and before the write";

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IntegrationPolicyFilter {
    pub search: Option<String>,
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct IntegrationPolicyList {
    pub total: u64,
    pub integration_policies: Vec<IntegrationPolicySummary>,
    pub truncated: bool,
}

/// A resolved selector retains the one-object response for later operations.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedIntegrationPolicy {
    pub(crate) summary: IntegrationPolicySummary,
    pub(crate) item: Map<String, Value>,
}

/// Strictly reduced package installation state. Fleet's public status decoder
/// intentionally preserves registry text for agent-policy orchestration; an
/// integration dependency must not accept an ambiguous state.
#[derive(Debug, Clone, PartialEq, Eq)]
enum PackageDependencyState {
    Installed { version: String },
    NotInstalled,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PackageDependencySnapshot {
    name: String,
    state: PackageDependencyState,
}

/// Exact package-defined secret variables. The companion `known_*` maps are
/// deliberately private implementation detail: a configured value is safe
/// only after Fleet metadata proves it has a definition.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct SecretSchema {
    package_vars: BTreeSet<String>,
    input_vars: BTreeMap<String, BTreeSet<String>>,
    stream_vars: BTreeMap<(String, String), BTreeSet<String>>,
}

#[derive(Debug, Clone, Default)]
struct KnownSchema {
    package_vars: BTreeSet<String>,
    input_vars: BTreeMap<String, BTreeSet<String>>,
    stream_vars: BTreeMap<(String, String), BTreeSet<String>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct VariableDefinitions {
    known: BTreeSet<String>,
    secrets: BTreeSet<String>,
}

#[derive(Debug)]
struct TemplateDefinitions {
    inputs: BTreeMap<String, String>,
    datasets: BTreeSet<String>,
}

/// A locally decoded import artifact. Its canonical specifications are kept
/// private so callers can retain a validated source across context setup
/// without being able to alter what remote planning will use.
pub struct IntegrationPolicyImportArtifact {
    source: PathBuf,
    canonical: Vec<IntegrationPolicySpec>,
}

impl fmt::Debug for IntegrationPolicyImportArtifact {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IntegrationPolicyImportArtifact")
            .field("policy_count", &self.canonical.len())
            .finish()
    }
}

/// What `plan_import` preflights and `apply_import` rechecks. Only guard
/// presentation is public: the canonical artifact, effective specifications,
/// and Fleet snapshots never cross the API boundary.
#[derive(Clone, PartialEq)]
pub struct IntegrationPolicyImportPlan {
    pub preview: MutationPlan,
    pub skipped: Vec<Value>,
    pub package_installs: Vec<String>,
    pub total: usize,
    source: PathBuf,
    host: String,
    space: String,
    canonical: Vec<IntegrationPolicySpec>,
    name_owners: BTreeMap<String, BTreeSet<String>>,
    name_owners_snapshot: BTreeMap<String, BTreeSet<String>>,
    parent_snapshots: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    skipped_snapshot: Vec<Value>,
    // Exact get-by-id results from before import classification. This covers
    // every canonical id, so a mutable target or skipped row cannot turn an
    // absent policy into an existing one (or the reverse).
    existing_snapshot: BTreeMap<String, Option<Map<String, Value>>>,
    targets: Vec<IntegrationPolicyImportTarget>,
    package_groups: BTreeMap<String, IntegrationPackageGroup>,
    overwrite: bool,
    skip_existing: bool,
}

impl fmt::Debug for IntegrationPolicyImportPlan {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IntegrationPolicyImportPlan")
            .field("target_count", &self.preview.targets.len())
            .field("skipped_count", &self.skipped.len())
            .field("package_install_count", &self.package_installs.len())
            .field("existing_snapshot_count", &self.existing_snapshot.len())
            .field("total", &self.total)
            .finish()
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct IntegrationPolicyImportReport {
    pub applied: bool,
    pub succeeded: Vec<Value>,
    pub unchanged: Vec<Value>,
    pub skipped: Vec<Value>,
    pub failed: Vec<Value>,
    pub total: usize,
    pub affected_agents: u64,
    pub package_installs: Vec<String>,
}

/// A safe, fully preflighted integration-policy deletion. Only the guard
/// presentation and count are public: Fleet snapshots and package metadata can
/// include configuration values, so they remain private to the API layer.
#[derive(Clone, PartialEq)]
pub struct IntegrationPolicyDeletePlan {
    pub preview: MutationPlan,
    pub total: usize,
    host: String,
    host_snapshot: String,
    space: String,
    space_snapshot: String,
    parent_snapshots: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    parent_snapshots_snapshot: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    targets: Vec<IntegrationPolicyDeleteTarget>,
}

impl fmt::Debug for IntegrationPolicyDeletePlan {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("IntegrationPolicyDeletePlan")
            .field("target_count", &self.targets.len())
            .field("total", &self.total)
            .finish()
    }
}

/// The result of applying an integration-policy deletion plan.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct IntegrationPolicyDeleteReport {
    pub applied: bool,
    pub deleted: Vec<Value>,
    pub failed: Vec<Value>,
    pub total: usize,
    pub affected_agents: u64,
}

#[derive(Debug, Clone, PartialEq)]
struct IntegrationPolicyImportTarget {
    effective: IntegrationPolicySpec,
    current: Option<IntegrationPolicyCurrentSnapshot>,
    parents: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    replacement_body: Option<Value>,
}

#[derive(Debug, Clone, PartialEq)]
struct IntegrationPolicyCurrentSnapshot {
    item: Map<String, Value>,
    spec: IntegrationPolicySpec,
    parent_ids: Vec<String>,
}

/// Private execution facts for one stable-id delete. The raw item detects a
/// Fleet change before deletion; the normalized policy and metadata prove that
/// no secret or environment-bound configuration has crossed the guard.
#[derive(Clone, PartialEq)]
struct IntegrationPolicyDeleteTarget {
    id: String,
    name: String,
    item: Map<String, Value>,
    item_snapshot: Map<String, Value>,
    spec: IntegrationPolicySpec,
    spec_snapshot: IntegrationPolicySpec,
    parents: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    package: IntegrationPackageSpec,
    dependency: PackageDependencySnapshot,
    dependency_snapshot: PackageDependencySnapshot,
    metadata: Map<String, Value>,
    metadata_snapshot: Map<String, Value>,
}

/// One package coordinate is shared by every pending policy that uses it.
/// `*_snapshot` copies are deliberate: plan validation compares the retained
/// exact Fleet response with the mutable execution expectation before it ever
/// starts remote work.
#[derive(Debug, Clone, PartialEq)]
struct IntegrationPackageGroup {
    package: IntegrationPackageSpec,
    state: PackageDependencySnapshot,
    state_snapshot: PackageDependencySnapshot,
    metadata: Map<String, Value>,
    metadata_snapshot: Map<String, Value>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ImportAction {
    Create,
    Replace,
    Unchanged,
}

/// Collect all measured pages then sort by stable id locally.
pub async fn collect(transport: &Transport) -> Result<Vec<Map<String, Value>>> {
    let mut page_number = 1;
    let mut total = None;
    let mut items = Vec::new();
    let mut ids = BTreeSet::new();
    loop {
        let page = integration_policies::list_page(transport, page_number).await?;
        if page.page != page_number || page.per_page != PAGE_SIZE {
            return Err(http(
                "decoding integration policies list: unexpected page metadata",
            ));
        }
        if page.items.len() as u64 > PAGE_SIZE {
            return Err(http(
                "decoding integration policies list: page returned more items than requested",
            ));
        }
        match total {
            Some(expected) if expected != page.total => {
                return Err(http(
                    "decoding integration policies list: total changed while paging",
                ));
            }
            Some(_) => {}
            None => total = Some(page.total),
        }
        let page_len = page.items.len() as u64;
        for item in page.items {
            let id = required_string(&item, "id", "integration policies list")?;
            if !ids.insert(id.clone()) {
                return Err(http(format!(
                    "decoding integration policies list: duplicate integration policy id '{id}'"
                )));
            }
            items.push(item);
        }
        let expected = total.expect("first page sets total");
        if items.len() as u64 >= expected {
            break;
        }
        if page_len != PAGE_SIZE {
            return Err(http(
                "decoding integration policies list: page was short before total",
            ));
        }
        page_number += 1;
    }
    if items.len() as u64 > total.unwrap_or_default() {
        return Err(http(
            "decoding integration policies list: returned more items than total",
        ));
    }
    items.sort_by(|left, right| left["id"].as_str().cmp(&right["id"].as_str()));
    Ok(items)
}

/// List with local case-insensitive search and post-sort limiting.
pub async fn list_op(
    transport: &Transport,
    filter: &IntegrationPolicyFilter,
) -> Result<IntegrationPolicyList> {
    let items = collect(transport).await?;
    let total = items.len() as u64;
    let needle = filter.search.as_ref().map(|value| value.to_lowercase());
    let mut integration_policies = Vec::new();
    for item in &items {
        let summary = summary_from_item(item)?;
        if needle.as_ref().is_none_or(|needle| {
            summary.id.to_lowercase().contains(needle)
                || summary.name.to_lowercase().contains(needle)
        }) {
            integration_policies.push(summary);
        }
    }
    let limit = filter.limit.unwrap_or(usize::MAX);
    let truncated = integration_policies.len() > limit;
    integration_policies.truncate(limit);
    Ok(IntegrationPolicyList {
        total,
        integration_policies,
        truncated,
    })
}

/// Resolve a stable id first, then a unique exact name.
pub async fn resolve(transport: &Transport, selector: &str) -> Result<IntegrationPolicySummary> {
    Ok(resolve_item(transport, selector).await?.summary)
}

/// Resolve a selector and retain the checked one-object response for later
/// read-only operations.
pub(crate) async fn resolve_item(
    transport: &Transport,
    selector: &str,
) -> Result<ResolvedIntegrationPolicy> {
    match integration_policies::get(transport, selector).await {
        Ok(policy) => return checked_read(selector, policy.item, None),
        Err(error) if error.kind == ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    let matches: Vec<IntegrationPolicySummary> = collect(transport)
        .await?
        .iter()
        .filter(|item| item.get("name").and_then(Value::as_str) == Some(selector))
        .map(summary_from_item)
        .collect::<Result<_>>()?;
    match matches.as_slice() {
        [] => Err(Error::new(
            ErrorKind::NotFound,
            format!("no integration policy with id or name '{selector}'"),
        )),
        [one] => {
            let policy = integration_policies::get(transport, &one.id).await?;
            checked_read(&one.id, policy.item, Some(one))
        }
        many => Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policy '{selector}' is ambiguous: {}",
                many.iter()
                    .map(|policy| policy.id.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        )),
    }
}

/// Bind a one-object response to its route id and, when it came from a list
/// selection, to that row's safe summary. Do not include raw values in errors:
/// simplified items can contain user configuration.
fn checked_read(
    requested_id: &str,
    item: Map<String, Value>,
    selected: Option<&IntegrationPolicySummary>,
) -> Result<ResolvedIntegrationPolicy> {
    let summary = summary_from_item(&item)?;
    if summary.id != requested_id {
        return Err(http(
            "decoding integration policy selector read: response id did not match the selector",
        ));
    }
    if selected.is_some_and(|selected| !same_summary(&summary, selected)) {
        return Err(http(
            "decoding integration policy selector read: fetched item did not match the selected list summary",
        ));
    }
    Ok(ResolvedIntegrationPolicy { summary, item })
}

/// Fleet can return parent ids in a different order between its list and
/// single-item routes. Sort for comparison without removing duplicates, so a
/// malformed repeated parent remains visible to later validation.
fn same_summary(fetched: &IntegrationPolicySummary, selected: &IntegrationPolicySummary) -> bool {
    fetched.id == selected.id
        && fetched.name == selected.name
        && fetched.namespace == selected.namespace
        && fetched.description == selected.description
        && fetched.package == selected.package
        && sorted_parent_ids(&fetched.policy_ids) == sorted_parent_ids(&selected.policy_ids)
}

fn sorted_parent_ids(ids: &[String]) -> Vec<&str> {
    let mut sorted = ids.iter().map(String::as_str).collect::<Vec<_>>();
    sorted.sort_unstable();
    sorted
}

/// Return a safe integration-policy view. Parent reads are both the attachment
/// race check and the sole source of affected-agent counts.
pub async fn get_op(transport: &Transport, selector: &str) -> Result<IntegrationPolicyDetail> {
    let resolved = resolve_item(transport, selector).await?;
    let mut blocked_by = live_blocked_by(&resolved.item, &resolved.summary.id, transport.space())?;
    validate_safe_detail_shape(&resolved.item, transport.space())?;
    let parents = read_parents(&resolved.summary.id, &resolved.item)?;
    let parents = read_parent_snapshots(transport, &resolved.summary.id, &parents).await?;
    for parent in parents.values() {
        if parent.platform_owned {
            blocked_by.insert(format!("parent:{}.platform_owned", parent.id));
        }
        if parent.protected {
            blocked_by.insert(format!("parent:{}.is_protected", parent.id));
        }
    }
    if parents
        .values()
        .map(|parent| parent.namespace.as_str())
        .collect::<BTreeSet<_>>()
        .len()
        != 1
    {
        blocked_by.insert("namespace".into());
    }
    if parents
        .values()
        .any(|parent| parent.namespace != resolved.summary.namespace)
    {
        blocked_by.insert("namespace".into());
    }
    Ok(IntegrationPolicyDetail {
        id: resolved.summary.id,
        name: resolved.summary.name,
        namespace: resolved.summary.namespace,
        description: resolved.summary.description,
        policy_ids: parents.keys().cloned().collect(),
        package: resolved.summary.package,
        affected_agents: parents.values().map(|parent| parent.agents).sum(),
        blocked_by: blocked_by.into_iter().collect(),
    })
}

/// Validate every live shape that a safe detail can reason about without
/// erasing its direct portability blockers. The projection keeps package-owned
/// configuration intact while replacing only values that a detail reports in
/// `blocked_by`, so `normalize` remains the single structural validator.
fn validate_safe_detail_shape(item: &Map<String, Value>, active_space: &str) -> Result<()> {
    let mut projected = item.clone();
    projected.insert("enabled".into(), Value::Bool(true));
    for field in [
        "is_managed",
        "supports_agentless",
        "supports_cloud_connector",
    ] {
        projected.insert(field.into(), Value::Bool(false));
    }
    for field in ["output_id", "cloud_connector_id", "cloud_connector_name"] {
        projected.insert(field.into(), Value::Null);
    }
    projected.insert("secret_references".into(), Value::Array(Vec::new()));
    projected.insert("spaceIds".into(), Value::Null);
    normalize(&projected, active_space).map(|_| ())
}

/// Export selected integrations or every custom integration. A selector is
/// resolved once and deduplicated by its stable id before any parent, package,
/// or metadata reads.
pub async fn export(
    transport: &Transport,
    selectors: &[String],
    all_custom: bool,
    format: ContentFormat,
) -> Result<ExportOutcome> {
    if selectors.is_empty() && !all_custom {
        return Err(Error::new(
            ErrorKind::Error,
            "integration-policy export needs selectors or --all-custom",
        ));
    }
    if !selectors.is_empty() && all_custom {
        return Err(Error::new(
            ErrorKind::Error,
            "--all-custom cannot be combined with selectors",
        ));
    }

    let mut rows = BTreeMap::new();
    if all_custom {
        for item in collect(transport).await? {
            let summary = summary_from_item(&item)?;
            if optional_bool(&item, "is_managed", &summary.id)? == Some(true) {
                continue;
            }
            let live = integration_policies::get(transport, &summary.id).await?;
            let resolved = checked_read(&summary.id, live.item, Some(&summary))?;
            if optional_bool(&resolved.item, "is_managed", &summary.id)? == Some(true) {
                continue;
            }
            rows.insert(summary.id.clone(), resolved);
        }
    } else {
        for selector in selectors {
            let resolved = resolve_item(transport, selector).await?;
            rows.entry(resolved.summary.id.clone()).or_insert(resolved);
        }
    }

    let mut specs = Vec::new();
    for (id, resolved) in rows {
        let parent_ids = read_parents(&id, &resolved.item)?;
        let parents = read_parent_snapshots(transport, &id, &parent_ids).await?;
        if all_custom && parents.values().any(|parent| parent.platform_owned) {
            continue;
        }
        specs.push(effective_spec(transport, &id, &resolved.item, &parents).await?);
    }
    specs.sort_by(|left, right| left.id.cmp(&right.id));
    Ok(ExportOutcome {
        body: content_codec::encode_sequence(&specs, format)?,
        exported: specs.len() as u64,
        missing: Vec::new(),
    })
}

fn read_parents(id: &str, item: &Map<String, Value>) -> Result<Vec<String>> {
    let policy_ids = item
        .get("policy_ids")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            http(format!(
                "decoding integration policy '{id}': policy_ids must be an array"
            ))
        })?;
    if policy_ids.is_empty() {
        return Err(http(format!(
            "decoding integration policy '{id}': policy_ids must not be empty"
        )));
    }
    let mut ids = Vec::with_capacity(policy_ids.len());
    for parent in policy_ids {
        let parent = parent
            .as_str()
            .filter(|value| !value.trim().is_empty())
            .ok_or_else(|| {
                http(format!(
                    "decoding integration policy '{id}': policy_ids must contain non-empty strings"
                ))
            })?;
        ids.push(parent.to_owned());
    }
    ids.sort();
    if ids.windows(2).any(|pair| pair[0] == pair[1]) {
        return Err(http(format!(
            "decoding integration policy '{id}': duplicate policy_ids"
        )));
    }
    Ok(ids)
}

async fn read_parent_snapshots(
    transport: &Transport,
    integration_id: &str,
    parent_ids: &[String],
) -> Result<BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>> {
    let mut parents = BTreeMap::new();
    for parent_id in parent_ids {
        let parent = agent_policy_ops::read_parent_snapshot(transport, parent_id).await?;
        if !parent
            .attached_integrations
            .binary_search_by(|attached| attached.as_str().cmp(integration_id))
            .is_ok()
        {
            return Err(http(format!(
                "decoding integration policy '{integration_id}': parent '{parent_id}' is missing its attachment"
            )));
        }
        parents.insert(parent_id.clone(), parent);
    }
    Ok(parents)
}

async fn effective_spec(
    transport: &Transport,
    id: &str,
    item: &Map<String, Value>,
    parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) -> Result<IntegrationPolicySpec> {
    for parent in parents.values() {
        if parent.platform_owned {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parent {} is platform-owned",
                parent.id
            ));
        }
        if parent.protected {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parent {} is_protected",
                parent.id
            ));
        }
    }
    let dependency =
        read_dependencies(transport, &package_coordinate(item, "integration policy")?).await?;
    let mut spec = normalize(item, transport.space())?;
    if let Some(namespace) = &spec.namespace {
        if parents
            .values()
            .any(|parent| &parent.namespace != namespace)
        {
            return unsupported(format!(
                "integration policy '{id}' is not portable: namespace does not match every parent"
            ));
        }
    } else {
        let namespaces: BTreeSet<&str> = parents
            .values()
            .map(|parent| parent.namespace.as_str())
            .collect();
        if namespaces.len() != 1 {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parents have different namespaces"
            ));
        }
        spec.namespace = namespaces.into_iter().next().map(str::to_owned);
    }
    // A package policy can only have been compiled from the exact installed
    // coordinate. Treat a divergent or absent state as a loud conflict.
    match dependency.state {
        PackageDependencyState::Installed { ref version } if version == &spec.package.version => {}
        PackageDependencyState::Installed { .. } => {
            return Err(Error::new(
                ErrorKind::Conflict,
                format!(
                    "integration policy '{id}' package {} has a different installed version",
                    dependency.name
                ),
            ));
        }
        PackageDependencyState::NotInstalled => {
            return Err(Error::new(
                ErrorKind::Conflict,
                format!(
                    "integration policy '{id}' package {} is not installed",
                    dependency.name
                ),
            ));
        }
    }
    let metadata = integration_policies::package_metadata(
        transport,
        &spec.package.name,
        &spec.package.version,
    )
    .await?;
    let paths = configured_secret_paths(&spec, &metadata.item)?;
    if !paths.is_empty() {
        return unsupported(format!(
            "integration policy '{id}' is not portable: {}",
            paths
                .into_iter()
                .map(|path| format!("{id}:{path}"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    Ok(spec)
}

async fn read_dependencies(
    transport: &Transport,
    package: &IntegrationPackageSpec,
) -> Result<PackageDependencySnapshot> {
    let status = agent_policies::package_status(transport, &package.name).await?;
    let state = match (status.status.as_str(), status.installed_version) {
        ("installed", Some(version)) if !version.trim().is_empty() => {
            PackageDependencyState::Installed { version }
        }
        ("not_installed", None) => PackageDependencyState::NotInstalled,
        _ => {
            return Err(http(format!(
                "decoding package dependency '{}': invalid status/version state",
                package.name
            )));
        }
    };
    Ok(PackageDependencySnapshot {
        name: status.name,
        state,
    })
}

fn configured_secret_paths(
    spec: &IntegrationPolicySpec,
    metadata: &Map<String, Value>,
) -> Result<Vec<String>> {
    let (secrets, known) = secret_schema(metadata)?;
    let mut paths = BTreeSet::new();
    configured_vars(
        spec.vars.as_ref(),
        &known.package_vars,
        &secrets.package_vars,
        &spec.id,
        "vars",
        &mut paths,
    )?;
    for (input_key, input) in &spec.inputs {
        let input = input.as_object().ok_or_else(|| {
            http(format!(
                "decoding integration policy '{}': inputs.{input_key} must be an object",
                spec.id
            ))
        })?;
        let known_vars = known.input_vars.get(input_key).ok_or_else(|| {
            Error::new(
                ErrorKind::Unsupported,
                format!(
                    "integration policy '{}': {}:inputs.{input_key} has no matching package definition",
                    spec.id, spec.id
                ),
            )
        })?;
        let secret_vars = secrets
            .input_vars
            .get(input_key)
            .cloned()
            .unwrap_or_default();
        configured_vars(
            input.get("vars").map(expect_object).transpose()?,
            known_vars,
            &secret_vars,
            &spec.id,
            &format!("inputs.{input_key}.vars"),
            &mut paths,
        )?;
        if let Some(streams) = input.get("streams") {
            let streams = streams.as_object().ok_or_else(|| {
                http(format!(
                    "decoding integration policy '{}': inputs.{input_key}.streams must be an object",
                    spec.id
                ))
            })?;
            for (dataset, stream) in streams {
                let stream = stream.as_object().ok_or_else(|| {
                    http(format!(
                        "decoding integration policy '{}': inputs.{input_key}.streams.{dataset} must be an object",
                        spec.id
                    ))
                })?;
                let key = (input_key.clone(), dataset.clone());
                let known_vars = known.stream_vars.get(&key).ok_or_else(|| {
                    Error::new(
                        ErrorKind::Unsupported,
                        format!(
                            "integration policy '{}': {}:inputs.{input_key}.streams.{dataset} has no matching package definition",
                            spec.id, spec.id
                        ),
                    )
                })?;
                let secret_vars = secrets.stream_vars.get(&key).cloned().unwrap_or_default();
                configured_vars(
                    stream.get("vars").map(expect_object).transpose()?,
                    known_vars,
                    &secret_vars,
                    &spec.id,
                    &format!("inputs.{input_key}.streams.{dataset}.vars"),
                    &mut paths,
                )?;
            }
        }
    }
    Ok(paths.into_iter().collect())
}

fn expect_object(value: &Value) -> Result<&Map<String, Value>> {
    value
        .as_object()
        .ok_or_else(|| http("decoding integration policy: configured vars must be an object"))
}

fn configured_vars(
    configured: Option<&Map<String, Value>>,
    known: &BTreeSet<String>,
    secret: &BTreeSet<String>,
    policy_id: &str,
    prefix: &str,
    paths: &mut BTreeSet<String>,
) -> Result<()> {
    let Some(configured) = configured else {
        return Ok(());
    };
    for name in configured.keys() {
        if !known.contains(name) {
            return Err(Error::new(
                ErrorKind::Unsupported,
                format!(
                    "integration policy '{policy_id}' is not portable: {policy_id}:{prefix}.{name} has no matching package definition"
                ),
            ));
        }
        if secret.contains(name) {
            paths.insert(format!("{prefix}.{name}"));
        }
    }
    Ok(())
}

fn secret_schema(metadata: &Map<String, Value>) -> Result<(SecretSchema, KnownSchema)> {
    let package_name = metadata_name(metadata, "name", "package metadata")?;
    let package_vars = parse_var_definitions(metadata.get("vars"), "package metadata vars")?;
    let modern_datasets = parse_modern_data_streams(metadata.get("data_streams"))?;

    let mut secrets = SecretSchema {
        package_vars: package_vars.secrets.clone(),
        ..SecretSchema::default()
    };
    let mut known = KnownSchema {
        package_vars: package_vars.known,
        ..KnownSchema::default()
    };
    let mut template_names = BTreeSet::new();
    let mut templates = Vec::new();
    let mut legacy_streams = BTreeMap::new();
    let policy_templates = match metadata.get("policy_templates") {
        None => &[][..],
        Some(Value::Array(value)) => value,
        Some(_) => {
            return Err(http(
                "decoding package metadata: policy_templates must be an array",
            ));
        }
    };

    for template in policy_templates {
        let template = template.as_object().ok_or_else(|| {
            http("decoding package metadata: policy_templates entry must be an object")
        })?;
        let template_name = metadata_name(template, "name", "policy_templates entry")?;
        if !template_names.insert(template_name.clone()) {
            return Err(http(format!(
                "decoding package metadata: duplicate template name '{template_name}'"
            )));
        }
        let datasets = resolve_template_datasets(
            template.get("data_streams"),
            &modern_datasets,
            &package_name,
            &template_name,
        )?;
        let inputs = match template.get("inputs") {
            None => &[][..],
            Some(Value::Array(value)) => value,
            Some(_) => {
                return Err(http(
                    "decoding package metadata: policy_templates inputs must be an array",
                ));
            }
        };
        let mut template_inputs = BTreeMap::new();
        for input in inputs {
            let input = input.as_object().ok_or_else(|| {
                http("decoding package metadata: policy_templates inputs entry must be an object")
            })?;
            let input_type = metadata_name(input, "type", "policy_templates input")?;
            let input_key = format!("{template_name}-{input_type}");
            let input_vars =
                parse_var_definitions(input.get("vars"), "package metadata input vars")?;
            if template_inputs
                .insert(input_type.clone(), input_key.clone())
                .is_some()
                || known
                    .input_vars
                    .insert(input_key.clone(), input_vars.known)
                    .is_some()
            {
                return Err(http(format!(
                    "decoding package metadata: duplicate input key '{input_key}'"
                )));
            }
            if !input_vars.secrets.is_empty() {
                secrets
                    .input_vars
                    .insert(input_key.clone(), input_vars.secrets);
            }

            let streams = match input.get("streams") {
                None => &[][..],
                Some(Value::Array(value)) => value,
                Some(_) => {
                    return Err(http(
                        "decoding package metadata: input streams must be an array",
                    ));
                }
            };
            for stream in streams {
                let stream = stream.as_object().ok_or_else(|| {
                    http("decoding package metadata: input streams entry must be an object")
                })?;
                let data_stream = stream
                    .get("data_stream")
                    .and_then(Value::as_object)
                    .ok_or_else(|| {
                        http("decoding package metadata: stream data_stream must be an object")
                    })?;
                let dataset = metadata_name(data_stream, "dataset", "stream data_stream")?;
                let definition =
                    parse_var_definitions(stream.get("vars"), "package metadata stream vars")?;
                let key = (input_key.clone(), dataset);
                if legacy_streams.insert(key.clone(), definition).is_some() {
                    return Err(http(format!(
                        "decoding package metadata: duplicate stream key '{}:{}'",
                        key.0, key.1
                    )));
                }
            }
        }
        templates.push(TemplateDefinitions {
            inputs: template_inputs,
            datasets,
        });
    }

    let mut modern_streams = BTreeMap::new();
    for (dataset, streams) in &modern_datasets {
        for (input_type, definition) in streams {
            let candidates = templates
                .iter()
                .filter(|template| template.datasets.contains(dataset))
                .filter_map(|template| template.inputs.get(input_type))
                .cloned()
                .collect::<Vec<_>>();
            let input_key = match candidates.as_slice() {
                [input_key] => input_key.clone(),
                [] => {
                    return Err(http(format!(
                        "decoding package metadata: stream '{dataset}:{input_type}' has no matching template input"
                    )));
                }
                _ => {
                    return Err(http(format!(
                        "decoding package metadata: stream '{dataset}:{input_type}' has multiple matching template inputs"
                    )));
                }
            };
            let key = (input_key, dataset.clone());
            if modern_streams
                .insert(key.clone(), definition.clone())
                .is_some()
            {
                return Err(http(format!(
                    "decoding package metadata: duplicate stream key '{}:{}'",
                    key.0, key.1
                )));
            }
        }
    }

    for (key, definition) in legacy_streams {
        match modern_streams.get(&key) {
            Some(modern) if modern != &definition => {
                return Err(http(format!(
                    "decoding package metadata: conflicting modern and legacy stream definition '{}:{}'",
                    key.0, key.1
                )));
            }
            Some(_) => {}
            None => {
                modern_streams.insert(key, definition);
            }
        }
    }
    for (key, definition) in modern_streams {
        if !definition.secrets.is_empty() {
            secrets.stream_vars.insert(key.clone(), definition.secrets);
        }
        known.stream_vars.insert(key, definition.known);
    }
    Ok((secrets, known))
}

fn parse_modern_data_streams(
    value: Option<&Value>,
) -> Result<BTreeMap<String, BTreeMap<String, VariableDefinitions>>> {
    let data_streams = match value {
        None => &[][..],
        Some(Value::Array(value)) => value,
        Some(_) => {
            return Err(http(
                "decoding package metadata: data_streams must be an array",
            ));
        }
    };
    let mut datasets = BTreeMap::new();
    for data_stream in data_streams {
        let data_stream = data_stream.as_object().ok_or_else(|| {
            http("decoding package metadata: data_streams entry must be an object")
        })?;
        let dataset = metadata_name(data_stream, "dataset", "data_streams entry")?;
        let streams = match data_stream.get("streams") {
            None => &[][..],
            Some(Value::Array(value)) => value,
            Some(_) => {
                return Err(http(
                    "decoding package metadata: data_streams streams must be an array",
                ));
            }
        };
        let mut stream_definitions = BTreeMap::new();
        for stream in streams {
            let stream = stream.as_object().ok_or_else(|| {
                http("decoding package metadata: data_streams streams entry must be an object")
            })?;
            let input = metadata_name(stream, "input", "data_streams stream")?;
            let definition =
                parse_var_definitions(stream.get("vars"), "package metadata stream vars")?;
            if stream_definitions
                .insert(input.clone(), definition)
                .is_some()
            {
                return Err(http(format!(
                    "decoding package metadata: duplicate stream input '{input}' for dataset '{dataset}'"
                )));
            }
        }
        if datasets
            .insert(dataset.clone(), stream_definitions)
            .is_some()
        {
            return Err(http(format!(
                "decoding package metadata: duplicate data stream dataset '{dataset}'"
            )));
        }
    }
    Ok(datasets)
}

fn resolve_template_datasets(
    value: Option<&Value>,
    datasets: &BTreeMap<String, BTreeMap<String, VariableDefinitions>>,
    package_name: &str,
    template_name: &str,
) -> Result<BTreeSet<String>> {
    let Some(value) = value else {
        return Ok(datasets.keys().cloned().collect());
    };
    let selectors = value
        .as_array()
        .ok_or_else(|| http("decoding package metadata: template data_streams must be an array"))?;
    let mut selected = BTreeSet::new();
    let mut seen = BTreeSet::new();
    for selector in selectors {
        let selector = selector
            .as_str()
            .filter(|selector| !selector.trim().is_empty())
            .ok_or_else(|| {
                http("decoding package metadata: template data_streams selector must be a non-empty string")
            })?;
        if !seen.insert(selector) {
            return Err(http(format!(
                "decoding package metadata: duplicate data_streams selector '{selector}' in template '{template_name}'"
            )));
        }
        let short_name = format!("{package_name}.{selector}");
        let candidates = datasets
            .keys()
            .filter(|dataset| dataset.as_str() == selector || dataset.as_str() == short_name)
            .collect::<Vec<_>>();
        match candidates.as_slice() {
            [dataset] => {
                if !selected.insert((**dataset).clone()) {
                    return Err(http(format!(
                        "decoding package metadata: duplicate data_streams dataset '{}' in template '{template_name}'",
                        dataset
                    )));
                }
            }
            [] => {
                return Err(http(format!(
                    "decoding package metadata: data_streams selector '{selector}' in template '{template_name}' does not match a dataset"
                )));
            }
            _ => {
                return Err(http(format!(
                    "decoding package metadata: data_streams selector '{selector}' in template '{template_name}' matches multiple datasets"
                )));
            }
        }
    }
    Ok(selected)
}

fn parse_var_definitions(value: Option<&Value>, context: &str) -> Result<VariableDefinitions> {
    let values = match value {
        None => return Ok(VariableDefinitions::default()),
        Some(Value::Array(values)) => values,
        Some(_) => return Err(http(format!("decoding {context}: vars must be an array"))),
    };
    let mut definitions = VariableDefinitions::default();
    for value in values {
        let definition = value
            .as_object()
            .ok_or_else(|| http(format!("decoding {context}: variable must be an object")))?;
        let name = metadata_name(definition, "name", context)?;
        if !definitions.known.insert(name.clone()) {
            return Err(http(format!(
                "decoding {context}: duplicate variable name '{name}'"
            )));
        }
        match definition.get("secret") {
            None => {}
            Some(Value::Bool(true)) => {
                definitions.secrets.insert(name);
            }
            Some(Value::Bool(false)) => {}
            Some(_) => {
                return Err(http(format!(
                    "decoding {context}: secret must be a boolean"
                )));
            }
        }
    }
    Ok(definitions)
}

fn metadata_name(object: &Map<String, Value>, field: &str, context: &str) -> Result<String> {
    object
        .get(field)
        .and_then(Value::as_str)
        .filter(|value| !value.trim().is_empty())
        .map(str::to_owned)
        .ok_or_else(|| {
            http(format!(
                "decoding package metadata: {context} {field} must be a non-empty string"
            ))
        })
}

fn live_blocked_by(
    item: &Map<String, Value>,
    id: &str,
    active_space: &str,
) -> Result<BTreeSet<String>> {
    let mut reasons = BTreeSet::new();
    match item.get("enabled") {
        Some(Value::Bool(true)) => {}
        Some(Value::Bool(false)) => {
            reasons.insert("enabled".into());
        }
        _ => {
            return Err(http(format!(
                "decoding integration policy '{id}': enabled must be true or false"
            )));
        }
    }
    for field in [
        "is_managed",
        "supports_agentless",
        "supports_cloud_connector",
    ] {
        if optional_bool(item, field, id)? == Some(true) {
            reasons.insert(field.to_owned());
        }
    }
    for field in ["output_id", "cloud_connector_id", "cloud_connector_name"] {
        match item.get(field) {
            None | Some(Value::Null) | Some(Value::Bool(false)) => {}
            Some(Value::String(_)) => {
                reasons.insert(field.to_owned());
            }
            Some(_) => {
                return Err(http(format!(
                    "decoding integration policy '{id}': {field} must be a string or null"
                )));
            }
        }
    }
    match item.get("secret_references") {
        None | Some(Value::Null) => {}
        Some(Value::Array(values)) if values.is_empty() => {}
        Some(Value::Array(_)) => {
            reasons.insert("secret_references".into());
        }
        Some(_) => {
            return Err(http(format!(
                "decoding integration policy '{id}': secret_references must be an array or null"
            )));
        }
    }
    let active = if active_space.is_empty() {
        "default"
    } else {
        active_space
    };
    match item.get("spaceIds") {
        None | Some(Value::Null) => {}
        Some(Value::Array(spaces)) => {
            for space in spaces {
                let space = space.as_str().filter(|value| !value.is_empty()).ok_or_else(|| {
                    http(format!("decoding integration policy '{id}': spaceIds must contain non-empty strings"))
                })?;
                if space != active {
                    reasons.insert("spaceIds".into());
                }
            }
        }
        Some(_) => {
            return Err(http(format!(
                "decoding integration policy '{id}': spaceIds must be an array or null"
            )));
        }
    }
    Ok(reasons)
}

const PORTABLE_OPTIONAL: [&str; 6] = [
    "description",
    "namespace",
    "vars",
    "var_group_selections",
    "condition",
    "additional_datastreams_permissions",
];

const REMOVED_FIELDS: [&str; 19] = [
    "agents",
    "cloud_connector_id",
    "cloud_connector_name",
    "created_at",
    "created_by",
    "elasticsearch",
    "enabled",
    "is_managed",
    "output_id",
    "package_agent_version_condition",
    "policy_id",
    "revision",
    "secret_references",
    "spaceIds",
    "supports_agentless",
    "supports_cloud_connector",
    "updated_at",
    "updated_by",
    "version",
];

/// Build a fresh portable policy from a simplified live Fleet response.
pub fn normalize(item: &Map<String, Value>, active_space: &str) -> Result<IntegrationPolicySpec> {
    let id = required_string(item, "id", "integration policy")?;
    portability_check(item, &id, active_space)?;
    reject_unknown_top_level(item, &id)?;

    let mut portable = Map::new();
    for field in ["id", "name"] {
        if let Some(value) = item.get(field) {
            portable.insert(field.to_owned(), value.clone());
        }
    }
    portable.insert(
        "policy_ids".to_owned(),
        Value::Array(
            read_parents(&id, item)?
                .into_iter()
                .map(Value::String)
                .collect(),
        ),
    );
    portable.insert("package".to_owned(), normalize_package(item, &id)?);
    portable.insert("inputs".to_owned(), normalize_inputs(item, &id)?);
    for field in PORTABLE_OPTIONAL {
        if let Some(value) = item.get(field)
            && !value.is_null()
        {
            portable.insert(field.to_owned(), value.clone());
        }
    }
    IntegrationPolicySpec::try_from(Value::Object(portable)).map_err(|error| {
        http(format!(
            "decoding integration policy '{id}': {}",
            error.message
        ))
    })
}

fn normalize_package(item: &Map<String, Value>, id: &str) -> Result<Value> {
    let package = item
        .get("package")
        .and_then(Value::as_object)
        .ok_or_else(|| {
            http(format!(
                "decoding integration policy '{id}': package must be an object"
            ))
        })?;
    for (field, expected) in [("title", "a string")] {
        if let Some(value) = package.get(field)
            && !value.is_null()
            && !value.is_string()
        {
            return Err(http(format!(
                "decoding integration policy '{id}': package.{field} must be {expected} or null"
            )));
        }
    }
    for field in ["requires_root", "fips_compatible"] {
        if let Some(value) = package.get(field)
            && !value.is_null()
            && !value.is_boolean()
        {
            return Err(http(format!(
                "decoding integration policy '{id}': package.{field} must be a boolean or null"
            )));
        }
    }
    let mut portable = Map::new();
    for field in ["name", "version"] {
        if let Some(value) = package.get(field) {
            portable.insert(field.to_owned(), value.clone());
        }
    }
    let known: BTreeSet<&str> = [
        "name",
        "version",
        "title",
        "requires_root",
        "fips_compatible",
    ]
    .into_iter()
    .collect();
    if let Some(field) = package
        .keys()
        .map(String::as_str)
        .filter(|field| !known.contains(field))
        .min()
    {
        return Err(Error::new(
            ErrorKind::Unsupported,
            format!("integration policy '{id}' carries unknown package field '{field}'"),
        ));
    }
    Ok(Value::Object(portable))
}

fn normalize_inputs(item: &Map<String, Value>, id: &str) -> Result<Value> {
    let inputs = item
        .get("inputs")
        .and_then(Value::as_object)
        .ok_or_else(|| {
            http(format!(
                "decoding integration policy '{id}': inputs must be an object"
            ))
        })?;
    let mut normalized = Map::new();
    for (input_id, input) in inputs {
        normalized.insert(
            input_id.clone(),
            normalize_package_map(input, "compiled_input")?,
        );
    }
    Ok(Value::Object(normalized))
}

/// Keep package-defined input and stream maps open while rebuilding them
/// without Fleet-generated ids or compiled content.
fn normalize_package_map(value: &Value, compiled_field: &str) -> Result<Value> {
    let object = value
        .as_object()
        .ok_or_else(|| http("decoding integration policy: input must be an object"))?;
    let mut normalized = Map::new();
    for (field, value) in object {
        if field == "id" {
            if !value.is_string() {
                return Err(http(
                    "decoding integration policy: generated id must be a string",
                ));
            }
            continue;
        }
        if field == compiled_field {
            if !value.is_object() {
                return Err(http(format!(
                    "decoding integration policy: {compiled_field} must be an object"
                )));
            }
            continue;
        }
        if field == "streams" {
            let streams = value.as_object().ok_or_else(|| {
                http("decoding integration policy: input streams must be an object")
            })?;
            let mut normalized_streams = Map::new();
            for (stream_id, stream) in streams {
                normalized_streams.insert(
                    stream_id.clone(),
                    normalize_package_map(stream, "compiled_stream")?,
                );
            }
            normalized.insert(field.clone(), Value::Object(normalized_streams));
        } else {
            normalized.insert(field.clone(), value.clone());
        }
    }
    Ok(Value::Object(normalized))
}

fn portability_check(item: &Map<String, Value>, id: &str, active_space: &str) -> Result<()> {
    let mut reasons = BTreeSet::new();
    required_true(item, "enabled", id)?;
    if let Some(value) = item.get("elasticsearch")
        && !value.is_object()
    {
        return Err(http(format!(
            "decoding integration policy '{id}': elasticsearch must be an object"
        )));
    }
    if let Some(value) = item.get("package_agent_version_condition")
        && !value.is_null()
        && !value.is_string()
    {
        return Err(http(format!(
            "decoding integration policy '{id}': package_agent_version_condition must be a string or null"
        )));
    }
    for field in [
        "is_managed",
        "supports_agentless",
        "supports_cloud_connector",
    ] {
        if let Some(true) = optional_bool(item, field, id)? {
            reasons.insert(field);
        }
    }
    for field in ["output_id", "cloud_connector_id", "cloud_connector_name"] {
        match item.get(field) {
            None | Some(Value::Null) | Some(Value::Bool(false)) => {}
            Some(Value::String(_)) => {
                reasons.insert(field);
            }
            Some(_) => {
                return Err(http(format!(
                    "decoding integration policy '{id}': {field} must be a string or null"
                )));
            }
        }
    }
    match item.get("secret_references") {
        None | Some(Value::Null) => {}
        Some(Value::Array(references)) if references.is_empty() => {}
        Some(Value::Array(_)) => {
            reasons.insert("secret_references");
        }
        Some(_) => {
            return Err(http(format!(
                "decoding integration policy '{id}': secret_references must be an array or null"
            )));
        }
    }
    let active = if active_space.is_empty() {
        "default"
    } else {
        active_space
    };
    match item.get("spaceIds") {
        None | Some(Value::Null) => {}
        Some(Value::Array(spaces)) => {
            for space in spaces {
                let space = space.as_str().filter(|space| !space.is_empty()).ok_or_else(|| {
                    http(format!(
                        "decoding integration policy '{id}': spaceIds must contain non-empty strings"
                    ))
                })?;
                if space != active {
                    reasons.insert("spaceIds");
                }
            }
        }
        Some(_) => {
            return Err(http(format!(
                "decoding integration policy '{id}': spaceIds must be an array or null"
            )));
        }
    }
    if let Some(policy_id) = item.get("policy_id").filter(|value| !value.is_null()) {
        let policy_id = policy_id
            .as_str()
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                http(format!(
                    "decoding integration policy '{id}': policy_id must be a non-empty string"
                ))
            })?;
        let policy_ids = item
            .get("policy_ids")
            .and_then(Value::as_array)
            .ok_or_else(|| {
                http(format!(
                    "decoding integration policy '{id}': policy_ids must be an array"
                ))
            })?;
        if policy_ids.first().and_then(Value::as_str) != Some(policy_id) {
            return Err(http(format!(
                "decoding integration policy '{id}': policy_id must equal policy_ids[0]"
            )));
        }
    }
    if reasons.is_empty() {
        Ok(())
    } else {
        unsupported(format!(
            "integration policy '{id}' is not portable: {}",
            reasons.into_iter().collect::<Vec<_>>().join(", ")
        ))
    }
}

fn required_true(item: &Map<String, Value>, field: &str, id: &str) -> Result<()> {
    match item.get(field) {
        Some(Value::Bool(true)) => Ok(()),
        Some(Value::Bool(false)) => unsupported(format!(
            "integration policy '{id}' is not portable: {field}"
        )),
        _ => Err(http(format!(
            "decoding integration policy '{id}': {field} must be true"
        ))),
    }
}

fn optional_bool(item: &Map<String, Value>, field: &str, id: &str) -> Result<Option<bool>> {
    match item.get(field) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Bool(value)) => Ok(Some(*value)),
        Some(_) => Err(http(format!(
            "decoding integration policy '{id}': {field} must be a boolean or null"
        ))),
    }
}

fn reject_unknown_top_level(item: &Map<String, Value>, id: &str) -> Result<()> {
    let known: BTreeSet<&str> = ["id", "name", "policy_ids", "package", "inputs"]
        .into_iter()
        .chain(PORTABLE_OPTIONAL)
        .chain(REMOVED_FIELDS)
        .collect();
    if let Some(field) = item
        .keys()
        .map(String::as_str)
        .filter(|field| !known.contains(field))
        .min()
    {
        return unsupported(format!(
            "integration policy '{id}' carries unknown field '{field}'"
        ));
    }
    Ok(())
}

fn summary_from_item(item: &Map<String, Value>) -> Result<IntegrationPolicySummary> {
    let id = required_string(item, "id", "integration policy")?;
    let name = required_string(item, "name", "integration policy")?;
    let namespace = required_string(item, "namespace", "integration policy")?;
    let description = match item.get("description") {
        None | Some(Value::Null) => None,
        Some(Value::String(value)) => Some(value.clone()),
        Some(_) => {
            return Err(http(
                "decoding integration policy: description must be a string or null",
            ));
        }
    };
    let policy_ids = item
        .get("policy_ids")
        .and_then(Value::as_array)
        .ok_or_else(|| http("decoding integration policy: policy_ids must be an array"))?
        .iter()
        .map(|value| {
            value
                .as_str()
                .filter(|value| !value.is_empty())
                .map(str::to_owned)
                .ok_or_else(|| {
                    http("decoding integration policy: policy_ids must contain non-empty strings")
                })
        })
        .collect::<Result<Vec<_>>>()?;
    let package = package_coordinate(item, "integration policy")?;
    Ok(IntegrationPolicySummary {
        id,
        name,
        namespace,
        description,
        policy_ids,
        package,
    })
}

fn package_coordinate(item: &Map<String, Value>, context: &str) -> Result<IntegrationPackageSpec> {
    let package = item
        .get("package")
        .and_then(Value::as_object)
        .ok_or_else(|| http(format!("decoding {context}: package must be an object")))?;
    Ok(IntegrationPackageSpec {
        name: package_required_string(package, "name", context)?,
        version: package_required_string(package, "version", context)?,
    })
}

fn package_required_string(
    package: &Map<String, Value>,
    field: &str,
    context: &str,
) -> Result<String> {
    package
        .get(field)
        .and_then(Value::as_str)
        .filter(|value| !value.trim().is_empty())
        .map(str::to_owned)
        .ok_or_else(|| {
            http(format!(
                "decoding {context}: package.{field} must be a non-empty string"
            ))
        })
}

fn required_string(item: &Map<String, Value>, field: &str, context: &str) -> Result<String> {
    item.get(field)
        .and_then(Value::as_str)
        .filter(|value| !value.trim().is_empty())
        .map(str::to_owned)
        .ok_or_else(|| {
            http(format!(
                "decoding {context}: {field} must be a non-empty string"
            ))
        })
}

/// Read, validate, and retain an integration-policy artifact before context
/// or credential construction. The returned value has no public raw fields.
pub fn prepare_import(path: &Path) -> Result<IntegrationPolicyImportArtifact> {
    let canonical = validate(path)?;
    if canonical.is_empty() {
        return Err(Error::new(
            ErrorKind::Error,
            "integration-policy import needs at least one integration policy",
        ));
    }
    validate_requested_package_versions(&canonical)?;
    Ok(IntegrationPolicyImportArtifact {
        source: path.to_path_buf(),
        canonical,
    })
}

/// Plan a retained integration-policy import without reopening its source or
/// sending a write. Apply uses only the returned plan.
pub async fn plan_prepared_import(
    transport: &Transport,
    artifact: IntegrationPolicyImportArtifact,
    overwrite: bool,
    skip_existing: bool,
) -> Result<IntegrationPolicyImportPlan> {
    let IntegrationPolicyImportArtifact { source, canonical } = artifact;
    if overwrite && skip_existing {
        return Err(Error::new(
            ErrorKind::Error,
            "--overwrite and --skip-existing cannot be used together",
        ));
    }

    // Read only the requested ids. A conflicting or skipped existing policy is
    // deliberately kept raw: normalize can refuse an unsupported object, but
    // that object will not be written on those paths.
    let mut existing = BTreeMap::new();
    let mut conflicts = Vec::new();
    for spec in &canonical {
        match integration_policies::get(transport, &spec.id).await {
            Ok(policy) => {
                let returned_id = required_string(&policy.item, "id", "integration policy get")?;
                if returned_id != spec.id {
                    return Err(http(
                        "decoding integration policy get: response id did not match the request",
                    ));
                }
                if !overwrite && !skip_existing {
                    conflicts.push(spec.id.clone());
                }
                existing.insert(spec.id.clone(), Some(policy.item));
            }
            Err(error) if error.kind == ErrorKind::NotFound => {
                existing.insert(spec.id.clone(), None);
            }
            Err(error) => return Err(import_remote_error(error, "planning read")),
        }
    }
    if !conflicts.is_empty() {
        return Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policies already exist: {}",
                conflicts.join(", ")
            ),
        ));
    }

    // This phase comes before every parent, package-status, and metadata read.
    // A package-coordinate replacement is a different Fleet operation, never
    // a package-policy import update.
    for spec in &canonical {
        if skip_existing && matches!(existing.get(&spec.id), Some(Some(_))) {
            continue;
        }
        let Some(Some(item)) = existing.get(&spec.id) else {
            continue;
        };
        let current = package_coordinate(item, "integration policy")
            .map_err(|error| import_remote_error(error, "planning read"))?;
        if current != spec.package {
            return unsupported(format!(
                "integration policy '{}' cannot change package {}@{} to {}@{}",
                spec.id, current.name, current.version, spec.package.name, spec.package.version
            ));
        }
    }

    // Every artifact name stays relevant even if its id is skipped. A foreign
    // claimant is always a conflict, and this read deliberately happens before
    // any skipped object's raw response would be normalized.
    let names: BTreeSet<String> = canonical.iter().map(|spec| spec.name.clone()).collect();
    let name_owners = relevant_name_owners(transport, &names)
        .await
        .map_err(|error| import_remote_error(error, "planning names read"))?;
    let mut name_conflicts = Vec::new();
    for spec in &canonical {
        let owners = name_owners
            .get(&spec.name)
            .expect("requested name has an ownership entry");
        for owner in owners.iter().filter(|owner| owner.as_str() != spec.id) {
            name_conflicts.push(format!("{} ({owner})", spec.name));
        }
    }
    if !name_conflicts.is_empty() {
        return Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policy names already exist: {}",
                name_conflicts.join(", ")
            ),
        ));
    }

    let mut skipped = Vec::new();
    let pending: Vec<IntegrationPolicySpec> = canonical
        .iter()
        .filter_map(|spec| match existing.get(&spec.id) {
            Some(Some(item)) if skip_existing => {
                skipped.push(json!({"id": spec.id, "reason": "exists"}));
                None
            }
            _ => Some(spec.clone()),
        })
        .collect();

    let mut targets = Vec::with_capacity(pending.len());
    let mut shared_parents = BTreeMap::new();
    for spec in pending {
        let raw = existing
            .get(&spec.id)
            .expect("every canonical id was fetched")
            .clone();
        let current_parent_ids = raw
            .as_ref()
            .map(|item| {
                read_parents(&spec.id, item)
                    .map_err(|error| import_remote_error(error, "planning read"))
            })
            .transpose()?;
        let parents = read_import_parent_snapshots(
            transport,
            &spec.id,
            current_parent_ids.as_deref().unwrap_or_default(),
            &spec.policy_ids,
        )
        .await
        .map_err(|error| import_remote_error(error, "planning parent read"))?;
        for (parent_id, parent) in &parents {
            match shared_parents.entry(parent_id.clone()) {
                std::collections::btree_map::Entry::Vacant(entry) => {
                    entry.insert(parent.clone());
                }
                std::collections::btree_map::Entry::Occupied(entry) if entry.get() != parent => {
                    return Err(Error::new(
                        ErrorKind::Conflict,
                        format!(
                            "agent policy '{parent_id}' changed while planning integration import"
                        ),
                    ));
                }
                std::collections::btree_map::Entry::Occupied(_) => {}
            }
        }
        let effective = effective_import_spec(&spec, &parents)?;
        let current = raw
            .map(|item| {
                let normalized = normalize(&item, transport.space())
                    .map_err(|error| import_remote_error(error, "planning read"))?;
                if normalized.id != spec.id {
                    return Err(http(
                        "decoding integration policy: response id did not match the request",
                    ));
                }
                Ok(IntegrationPolicyCurrentSnapshot {
                    item,
                    spec: normalized,
                    parent_ids: current_parent_ids.expect("raw policy has parents"),
                })
            })
            .transpose()?;
        targets.push(IntegrationPolicyImportTarget {
            effective,
            current,
            parents,
            replacement_body: None,
        });
    }
    if targets
        .iter()
        .any(|target| !target_name_owners_match(target, &name_owners))
    {
        return Err(Error::new(
            ErrorKind::Conflict,
            "integration policy name ownership changed while planning",
        ));
    }

    let mut package_coordinates = BTreeMap::new();
    for target in &targets {
        package_coordinates
            .entry(target.effective.package.name.clone())
            .or_insert_with(|| target.effective.package.clone());
    }
    let mut package_groups = BTreeMap::new();
    for (name, package) in package_coordinates {
        let state = read_dependencies(transport, &package)
            .await
            .map_err(|error| import_remote_error(error, "planning package read"))?;
        match &state.state {
            PackageDependencyState::Installed { version } if version == &package.version => {}
            PackageDependencyState::Installed { .. } => {
                return Err(Error::new(
                    ErrorKind::Conflict,
                    format!("integration package {name} has a different installed version"),
                ));
            }
            PackageDependencyState::NotInstalled => {
                if targets
                    .iter()
                    .any(|target| target.effective.package.name == name && target.current.is_some())
                {
                    return Err(Error::new(
                        ErrorKind::Conflict,
                        format!("integration package {name} is not installed"),
                    ));
                }
            }
        }
        let metadata =
            integration_policies::package_metadata(transport, &package.name, &package.version)
                .await
                .map_err(|error| import_remote_error(error, "planning package metadata read"))?
                .item;
        validate_package_metadata_snapshot(&metadata, &package)
            .map_err(|error| import_remote_error(error, "planning package metadata read"))?;
        package_groups.insert(
            name,
            IntegrationPackageGroup {
                package,
                state: state.clone(),
                state_snapshot: state,
                metadata_snapshot: metadata.clone(),
                metadata,
            },
        );
    }

    for target in &targets {
        let package = package_groups
            .get(&target.effective.package.name)
            .expect("every effective package has a group");
        validate_effective_input_materialization(&target.effective, &package.metadata)?;
    }

    let mut secret_paths = BTreeSet::new();
    for target in &targets {
        let package = package_groups
            .get(&target.effective.package.name)
            .expect("every effective package has a group");
        if let Some(current) = &target.current {
            for path in configured_secret_paths(&current.spec, &package.metadata)? {
                secret_paths.insert(format!("{}:{path}", current.spec.id));
            }
        }
        for path in configured_secret_paths(&target.effective, &package.metadata)? {
            secret_paths.insert(format!("{}:{path}", target.effective.id));
        }
    }
    if !secret_paths.is_empty() {
        return unsupported(format!(
            "integration policy import contains configured secrets: {}",
            secret_paths.into_iter().collect::<Vec<_>>().join(", ")
        ));
    }

    for target in &mut targets {
        if let Some(current) = &target.current
            && current.spec != target.effective
        {
            target.replacement_body = Some(replace_wire_body(&target.effective)?);
        }
    }
    let package_installs = planned_package_installs(&package_groups);
    let preview = import_preview(&source, &targets, &package_installs);
    let plan = IntegrationPolicyImportPlan {
        preview,
        skipped_snapshot: skipped.clone(),
        skipped,
        package_installs,
        total: canonical.len(),
        source,
        host: transport.kibana_url().to_owned(),
        space: transport.space().to_owned(),
        canonical,
        name_owners_snapshot: name_owners.clone(),
        name_owners,
        parent_snapshots: shared_parents,
        existing_snapshot: existing.clone(),
        targets,
        package_groups,
        overwrite,
        skip_existing,
    };
    validate_import_plan(&plan)?;
    Ok(plan)
}

/// Plan a canonical integration-policy import without sending a write. This
/// convenience wrapper reads the source once, then delegates to the retained
/// artifact planner.
pub async fn plan_import(
    transport: &Transport,
    path: &Path,
    overwrite: bool,
    skip_existing: bool,
) -> Result<IntegrationPolicyImportPlan> {
    let artifact = prepare_import(path)?;
    plan_prepared_import(transport, artifact, overwrite, skip_existing).await
}

fn validate_requested_package_versions(specs: &[IntegrationPolicySpec]) -> Result<()> {
    let mut versions = BTreeMap::new();
    for spec in specs {
        match versions.entry(spec.package.name.as_str()) {
            std::collections::btree_map::Entry::Vacant(entry) => {
                entry.insert(spec.package.version.as_str());
            }
            std::collections::btree_map::Entry::Occupied(entry)
                if entry.get() != &spec.package.version.as_str() =>
            {
                return Err(Error::new(
                    ErrorKind::Conflict,
                    format!(
                        "integration package '{}' is requested at more than one version",
                        spec.package.name
                    ),
                ));
            }
            std::collections::btree_map::Entry::Occupied(_) => {}
        }
    }
    Ok(())
}

async fn relevant_name_owners(
    transport: &Transport,
    names: &BTreeSet<String>,
) -> Result<BTreeMap<String, BTreeSet<String>>> {
    let mut owners = names
        .iter()
        .map(|name| (name.clone(), BTreeSet::new()))
        .collect::<BTreeMap<_, _>>();
    if names.is_empty() {
        return Ok(owners);
    }
    for item in collect(transport).await? {
        let Some(name) = item.get("name").and_then(Value::as_str) else {
            continue;
        };
        let Some(owners) = owners.get_mut(name) else {
            continue;
        };
        owners.insert(required_string(&item, "id", "integration policies list")?);
    }
    Ok(owners)
}

fn target_name_owners_match(
    target: &IntegrationPolicyImportTarget,
    owners: &BTreeMap<String, BTreeSet<String>>,
) -> bool {
    let Some(actual) = owners.get(&target.effective.name) else {
        return false;
    };
    let expected = match &target.current {
        None => BTreeSet::new(),
        Some(current) if current.spec.name == target.effective.name => {
            BTreeSet::from([target.effective.id.clone()])
        }
        Some(_) => BTreeSet::new(),
    };
    actual == &expected
}

async fn read_import_parent_snapshots(
    transport: &Transport,
    integration_id: &str,
    current_parent_ids: &[String],
    desired_parent_ids: &[String],
) -> Result<BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>> {
    let parent_ids = current_parent_ids
        .iter()
        .chain(desired_parent_ids)
        .cloned()
        .collect::<BTreeSet<_>>();
    let mut parents = BTreeMap::new();
    for parent_id in parent_ids {
        let parent = agent_policy_ops::read_parent_snapshot(transport, &parent_id).await?;
        if current_parent_ids.binary_search(&parent_id).is_ok()
            && parent
                .attached_integrations
                .binary_search_by(|attached| attached.as_str().cmp(integration_id))
                .is_err()
        {
            return Err(http(format!(
                "decoding integration policy '{integration_id}': parent '{parent_id}' is missing its attachment"
            )));
        }
        parents.insert(parent_id, parent);
    }
    Ok(parents)
}

fn effective_import_spec(
    canonical: &IntegrationPolicySpec,
    parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) -> Result<IntegrationPolicySpec> {
    canonical.validate()?;
    for parent in parents.values() {
        if parent.platform_owned {
            return unsupported(format!(
                "integration policy '{}' is not portable: parent {} is platform-owned",
                canonical.id, parent.id
            ));
        }
        if parent.protected {
            return unsupported(format!(
                "integration policy '{}' is not portable: parent {} is_protected",
                canonical.id, parent.id
            ));
        }
    }
    let selected = canonical
        .policy_ids
        .iter()
        .map(|id| {
            parents.get(id).ok_or_else(|| {
                Error::new(
                    ErrorKind::Error,
                    format!(
                        "integration policy '{}' has no parent snapshot for '{id}'",
                        canonical.id
                    ),
                )
            })
        })
        .collect::<Result<Vec<_>>>()?;
    let mut effective = canonical.clone();
    if let Some(namespace) = &effective.namespace {
        if selected.iter().any(|parent| &parent.namespace != namespace) {
            return unsupported(format!(
                "integration policy '{}' is not portable: namespace does not match every parent",
                canonical.id
            ));
        }
    } else {
        let namespaces = selected
            .iter()
            .map(|parent| parent.namespace.as_str())
            .collect::<BTreeSet<_>>();
        if namespaces.len() != 1 {
            return Err(Error::new(
                ErrorKind::Conflict,
                format!(
                    "integration policy '{}' is not portable: parents have different namespaces",
                    canonical.id
                ),
            ));
        }
        effective.namespace = namespaces.into_iter().next().map(str::to_owned);
    }
    Ok(effective)
}

fn validate_package_metadata_snapshot(
    metadata: &Map<String, Value>,
    package: &IntegrationPackageSpec,
) -> Result<()> {
    let name = metadata_name(metadata, "name", "package metadata")?;
    let version = metadata_name(metadata, "version", "package metadata")?;
    if name != package.name || version != package.version {
        return Err(http(format!(
            "decoding package metadata: expected {}@{}, got {name}@{version}",
            package.name, package.version
        )));
    }
    secret_schema(metadata).map(|_| ())
}

fn validate_effective_input_materialization(
    spec: &IntegrationPolicySpec,
    metadata: &Map<String, Value>,
) -> Result<()> {
    let (_, known) = secret_schema(metadata)?;
    if spec.inputs.is_empty() && !known.input_vars.is_empty() {
        return unsupported(format!(
            "integration policy '{}' has an empty inputs map but package {}@{} declares inputs",
            spec.id, spec.package.name, spec.package.version
        ));
    }
    Ok(())
}

fn replace_wire_body(spec: &IntegrationPolicySpec) -> Result<Value> {
    spec.validate()?;
    let mut body = serde_json::to_value(spec)
        .map_err(|error| {
            Error::new(
                ErrorKind::Error,
                format!("encoding integration policy: {error}"),
            )
        })?
        .as_object()
        .cloned()
        .expect("integration policy specs serialize to objects");
    body.remove("id");
    Ok(Value::Object(body))
}

fn planned_package_installs(groups: &BTreeMap<String, IntegrationPackageGroup>) -> Vec<String> {
    groups
        .values()
        .filter_map(|group| match group.state.state {
            PackageDependencyState::NotInstalled => {
                Some(format!("{}@{}", group.package.name, group.package.version))
            }
            PackageDependencyState::Installed { .. } => None,
        })
        .collect()
}

fn import_preview(
    path: &Path,
    targets: &[IntegrationPolicyImportTarget],
    package_installs: &[String],
) -> MutationPlan {
    let mut details = targets
        .iter()
        .map(|target| {
            let parents = target
                .parents
                .values()
                .map(|parent| format!("{} ({})", parent.id, parent.name))
                .collect::<Vec<_>>()
                .join(", ");
            let agents = target
                .parents
                .values()
                .map(|parent| parent.agents)
                .sum::<u64>();
            let action = match &target.current {
                None => "create".to_owned(),
                Some(current) if current.spec == target.effective => "unchanged".to_owned(),
                Some(current) if current.spec.name == target.effective.name => "replace".to_owned(),
                Some(current) => format!(
                    "replace  {} -> {}",
                    current.spec.name, target.effective.name
                ),
            };
            format!(
                "{}  {action}  {}  parents {parents}  agents {agents}",
                target.effective.id, target.effective.name
            )
        })
        .collect::<Vec<_>>();
    details.extend(
        package_installs
            .iter()
            .map(|package| format!("package install  {package}")),
    );
    details.push(IMPORT_RACE_WARNING.to_owned());
    MutationPlan {
        preview_action: format!(
            "Import {} integration policy(ies) from {}",
            targets.len(),
            path.display()
        ),
        preview_details: details,
        targets: targets
            .iter()
            .map(|target| target.effective.id.clone())
            .collect(),
    }
}

/// Decode one JSON or YAML artifact without constructing transport or config.
pub fn validate(path: &Path) -> Result<Vec<IntegrationPolicySpec>> {
    let body = std::fs::read_to_string(path).map_err(|error| {
        Error::new(
            ErrorKind::Error,
            format!("reading {}: {error}", path.display()),
        )
    })?;
    let mut specs = content_codec::decode_sequence::<IntegrationPolicySpec>(
        &body,
        ContentFormat::from_path(path),
        "integration policy",
    )?;
    duplicate_error(&specs, |spec| &spec.id, "ids")?;
    duplicate_error(&specs, |spec| &spec.name, "names")?;
    specs.sort_by(|left, right| left.id.cmp(&right.id));
    Ok(specs)
}

fn duplicate_error<'a, F>(specs: &'a [IntegrationPolicySpec], key: F, noun: &str) -> Result<()>
where
    F: Fn(&'a IntegrationPolicySpec) -> &'a String,
{
    let mut seen = BTreeSet::new();
    let mut duplicates = BTreeSet::new();
    for spec in specs {
        let value = key(spec);
        if !seen.insert(value.as_str()) {
            duplicates.insert(value.as_str());
        }
    }
    if duplicates.is_empty() {
        Ok(())
    } else {
        Err(Error::new(
            ErrorKind::Error,
            format!(
                "duplicate integration policy {noun}: {}",
                duplicates.into_iter().collect::<Vec<_>>().join(", ")
            ),
        ))
    }
}

/// Apply a previously validated import plan. Rows are independent except for
/// their exact package group and shared parent-attachment snapshots.
pub async fn apply_import(
    transport: &Transport,
    plan: &IntegrationPolicyImportPlan,
) -> Result<IntegrationPolicyImportReport> {
    validate_import_plan(plan)?;
    if plan.host != transport.kibana_url() || plan.space != transport.space() {
        return Err(Error::new(
            ErrorKind::Conflict,
            "integration import target changed since preview",
        ));
    }
    let mut succeeded = Vec::new();
    let mut unchanged = Vec::new();
    let mut failed = Vec::new();
    let mut expected_groups = plan.package_groups.clone();
    let mut expected_parents = plan.parent_snapshots.clone();
    let mut blocked_packages = BTreeMap::<String, String>::new();
    let mut affected_parents = BTreeMap::<String, u64>::new();
    let mut observed_installs = BTreeSet::new();

    for target in &plan.targets {
        let package_name = &target.effective.package.name;
        if let Some(error) = blocked_packages.get(package_name) {
            failed.push(import_failed_row(
                &target.effective.id,
                false,
                format!("package dependency is unavailable: {error}"),
            ));
            continue;
        }

        let action = match recheck_import_object(transport, target).await {
            Ok(action) => action,
            Err(error) => {
                failed.push(import_failed_row(
                    &target.effective.id,
                    false,
                    error.message,
                ));
                continue;
            }
        };
        if let Err(error) = recheck_import_name_owner(transport, target, &plan.name_owners).await {
            failed.push(import_failed_row(
                &target.effective.id,
                false,
                error.message,
            ));
            continue;
        }
        if let Err(error) = recheck_import_parents(transport, target, &expected_parents).await {
            failed.push(import_failed_row(
                &target.effective.id,
                false,
                error.message,
            ));
            continue;
        }

        let group = expected_groups
            .get_mut(package_name)
            .expect("validated target package group");
        let actual_state = match read_dependencies(transport, &target.effective.package).await {
            Ok(state) if state == group.state => state,
            Ok(_) => {
                let message = "package changed since preview".to_owned();
                blocked_packages.insert(package_name.clone(), message.clone());
                failed.push(import_failed_row(&target.effective.id, false, message));
                continue;
            }
            Err(error) => {
                let message = import_remote_error(error, "apply package read").message;
                blocked_packages.insert(package_name.clone(), message.clone());
                failed.push(import_failed_row(&target.effective.id, false, message));
                continue;
            }
        };
        debug_assert_eq!(actual_state, group.state);

        if action == ImportAction::Unchanged {
            unchanged.push(json!({"id": target.effective.id}));
            continue;
        }

        let (label, applied, route_error) = match action {
            ImportAction::Create => {
                match integration_policies::create(transport, &target.effective).await {
                    Ok(_) => ("created", true, None),
                    Err(error) => (
                        "created",
                        false,
                        Some(import_remote_error(error, "create request").message),
                    ),
                }
            }
            ImportAction::Replace => {
                let _body = target
                    .replacement_body
                    .as_ref()
                    .expect("validated replacement body");
                match integration_policies::update(
                    transport,
                    &target.effective.id,
                    &target.effective,
                )
                .await
                {
                    Ok(_) => ("replaced", true, None),
                    Err(error) => (
                        "replaced",
                        false,
                        Some(import_remote_error(error, "update request").message),
                    ),
                }
            }
            ImportAction::Unchanged => unreachable!("unchanged rows continue above"),
        };

        if applied {
            record_affected_parents(&mut affected_parents, target);
            advance_parent_snapshots(&mut expected_parents, target);
        }

        // A missing package is a shared dependency. Fleet's create path can
        // install it even when the policy write fails, so observation is
        // mandatory after every create attempt, not only decoded success.
        let mut observed_after_create = None;
        let mut package_observation_error = None;
        if action == ImportAction::Create
            && matches!(group.state.state, PackageDependencyState::NotInstalled)
        {
            match read_dependencies(transport, &target.effective.package).await {
                Ok(after) => {
                    if is_exact_installed(&after, &target.effective.package) {
                        group.state = after.clone();
                        observed_installs.insert(format!(
                            "{}@{}",
                            target.effective.package.name, target.effective.package.version
                        ));
                    } else if !matches!(after.state, PackageDependencyState::NotInstalled) {
                        let message =
                            "package installed a different version after create".to_owned();
                        blocked_packages.insert(package_name.clone(), message.clone());
                        package_observation_error = Some(message);
                    }
                    observed_after_create = Some(after);
                }
                Err(error) => {
                    let message = import_remote_error(error, "post-create package read").message;
                    blocked_packages.insert(package_name.clone(), message.clone());
                    package_observation_error = Some(message);
                }
            }
        }

        let mut errors = route_error.into_iter().collect::<Vec<_>>();
        if applied {
            if let Err(error) = verify_import_stored(transport, &target.effective).await {
                errors.push(error.message);
            }
            let package_result = match observed_after_create.as_ref() {
                Some(after) => verify_exact_installed(after, &target.effective.package),
                None => match read_dependencies(transport, &target.effective.package).await {
                    Ok(after) => verify_exact_installed(&after, &target.effective.package),
                    Err(error) => Err(import_remote_error(error, "package verification").message),
                },
            };
            if let Err(message) = package_result {
                blocked_packages
                    .entry(package_name.clone())
                    .or_insert_with(|| message.clone());
                errors.push(message);
            }
        }
        if let Some(error) = package_observation_error
            && !errors.contains(&error)
        {
            errors.push(error);
        }

        if errors.is_empty() {
            succeeded.push(json!({"id": target.effective.id, "action": label}));
        } else {
            failed.push(import_failed_row(
                &target.effective.id,
                applied,
                errors.join("; "),
            ));
        }
    }

    Ok(IntegrationPolicyImportReport {
        applied: true,
        succeeded,
        unchanged,
        skipped: plan.skipped.clone(),
        failed,
        total: plan.total,
        affected_agents: affected_parents.values().sum(),
        package_installs: observed_installs.into_iter().collect(),
    })
}

async fn recheck_import_object(
    transport: &Transport,
    target: &IntegrationPolicyImportTarget,
) -> Result<ImportAction> {
    match &target.current {
        None => match integration_policies::get(transport, &target.effective.id).await {
            Err(error) if error.kind == ErrorKind::NotFound => Ok(ImportAction::Create),
            Ok(_) => Err(Error::new(
                ErrorKind::Conflict,
                "integration policy appeared since preview",
            )),
            Err(error) => Err(import_remote_error(error, "apply integration-policy read")),
        },
        Some(expected) => match integration_policies::get(transport, &target.effective.id).await {
            Ok(actual) if actual.item == expected.item => {
                if expected.spec == target.effective {
                    Ok(ImportAction::Unchanged)
                } else {
                    Ok(ImportAction::Replace)
                }
            }
            Ok(_) => Err(Error::new(
                ErrorKind::Conflict,
                "integration policy changed since preview",
            )),
            Err(error) if error.kind == ErrorKind::NotFound => Err(Error::new(
                ErrorKind::Conflict,
                "integration policy disappeared since preview",
            )),
            Err(error) => Err(import_remote_error(error, "apply integration-policy read")),
        },
    }
}

async fn recheck_import_name_owner(
    transport: &Transport,
    target: &IntegrationPolicyImportTarget,
    expected_owners: &BTreeMap<String, BTreeSet<String>>,
) -> Result<()> {
    let names = BTreeSet::from([target.effective.name.clone()]);
    let owners = relevant_name_owners(transport, &names)
        .await
        .map_err(|error| import_remote_error(error, "apply name read"))?;
    if owners.get(&target.effective.name) == expected_owners.get(&target.effective.name) {
        Ok(())
    } else {
        Err(Error::new(
            ErrorKind::Conflict,
            "integration policy name ownership changed since preview",
        ))
    }
}

async fn recheck_import_parents(
    transport: &Transport,
    target: &IntegrationPolicyImportTarget,
    expected_parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) -> Result<()> {
    for parent_id in target.parents.keys() {
        let expected = expected_parents.get(parent_id).ok_or_else(|| {
            Error::new(
                ErrorKind::Error,
                "integration import lost a shared parent snapshot",
            )
        })?;
        let actual = agent_policy_ops::read_parent_snapshot(transport, parent_id)
            .await
            .map_err(|error| import_remote_error(error, "apply parent read"))?;
        if actual != *expected {
            return Err(Error::new(
                ErrorKind::Conflict,
                "integration policy parent changed since preview",
            ));
        }
    }
    Ok(())
}

fn record_affected_parents(
    affected: &mut BTreeMap<String, u64>,
    target: &IntegrationPolicyImportTarget,
) {
    for parent in target.parents.values() {
        affected.entry(parent.id.clone()).or_insert(parent.agents);
    }
}

fn advance_parent_snapshots(
    parents: &mut BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    target: &IntegrationPolicyImportTarget,
) {
    let desired = target
        .effective
        .policy_ids
        .iter()
        .map(String::as_str)
        .collect::<BTreeSet<_>>();
    for parent_id in target.parents.keys() {
        let parent = parents
            .get_mut(parent_id)
            .expect("validated shared parent snapshot");
        if desired.contains(parent_id.as_str()) {
            if parent
                .attached_integrations
                .binary_search_by(|attached| attached.as_str().cmp(&target.effective.id))
                .is_err()
            {
                parent
                    .attached_integrations
                    .push(target.effective.id.clone());
                parent.attached_integrations.sort();
            }
        } else {
            parent
                .attached_integrations
                .retain(|attached| attached != &target.effective.id);
        }
    }
}

async fn verify_import_stored(
    transport: &Transport,
    desired: &IntegrationPolicySpec,
) -> Result<()> {
    let stored = integration_policies::get(transport, &desired.id)
        .await
        .map_err(|error| import_remote_error(error, "stored-policy read"))?;
    let stored = normalize(&stored.item, transport.space())
        .map_err(|error| import_remote_error(error, "stored-policy read"))?;
    if stored == *desired {
        Ok(())
    } else {
        Err(Error::new(
            ErrorKind::Http,
            "server stored a different integration-policy spec",
        ))
    }
}

fn is_exact_installed(
    snapshot: &PackageDependencySnapshot,
    package: &IntegrationPackageSpec,
) -> bool {
    snapshot.name == package.name
        && matches!(
            &snapshot.state,
            PackageDependencyState::Installed { version } if version == &package.version
        )
}

fn verify_exact_installed(
    snapshot: &PackageDependencySnapshot,
    package: &IntegrationPackageSpec,
) -> std::result::Result<(), String> {
    if is_exact_installed(snapshot, package) {
        return Ok(());
    }
    match &snapshot.state {
        PackageDependencyState::Installed { .. } => Err(format!(
            "package {} installed a different version",
            package.name
        )),
        PackageDependencyState::NotInstalled => {
            Err(format!("package {} is not installed", package.name))
        }
    }
}

fn import_remote_error(error: Error, context: &str) -> Error {
    let message = format!("integration-policy import {context} failed");
    match error.http_status {
        Some(status) => Error::with_status(error.kind, status, message),
        None => Error::new(error.kind, message),
    }
}

fn import_failed_row(id: &str, applied: bool, error: impl Into<String>) -> Value {
    json!({"id": id, "applied": applied, "error": error.into()})
}

fn validate_import_plan(plan: &IntegrationPolicyImportPlan) -> Result<()> {
    let invalid = |message: &str| {
        Err(Error::new(
            ErrorKind::Error,
            format!("invalid integration-policy import plan: {message}"),
        ))
    };
    if plan.overwrite && plan.skip_existing {
        return invalid("overwrite and skip-existing cannot both be set");
    }
    if plan.host.trim().is_empty() {
        return invalid("planned Kibana host is empty");
    }
    if plan.canonical.is_empty() || plan.total != plan.canonical.len() {
        return invalid("total does not equal canonical integration policies");
    }
    let mut canonical_ids = BTreeMap::new();
    let mut canonical_names = BTreeSet::new();
    let mut previous: Option<&str> = None;
    for spec in &plan.canonical {
        if spec.validate().is_err() {
            return invalid("canonical integration policy is invalid");
        }
        if previous.is_some_and(|previous| previous >= spec.id.as_str()) {
            return invalid("canonical integration policies must be unique and sorted by id");
        }
        if !canonical_names.insert(spec.name.as_str()) {
            return invalid("canonical integration-policy names must be unique");
        }
        previous = Some(&spec.id);
        canonical_ids.insert(spec.id.as_str(), spec);
    }
    if validate_requested_package_versions(&plan.canonical).is_err() {
        return invalid("canonical package requests are inconsistent");
    }
    let canonical_id_set = canonical_ids.keys().copied().collect::<BTreeSet<_>>();
    if plan
        .existing_snapshot
        .keys()
        .map(String::as_str)
        .collect::<BTreeSet<_>>()
        != canonical_id_set
    {
        return invalid("existence snapshots do not match canonical integration policies");
    }
    for (id, existing) in &plan.existing_snapshot {
        if let Some(item) = existing
            && required_string(item, "id", "existing integration policy")
                .ok()
                .as_deref()
                != Some(id.as_str())
        {
            return invalid("existence snapshot has an unexpected id");
        }
    }
    if plan.name_owners != plan.name_owners_snapshot {
        return invalid("name ownership snapshots do not match");
    }
    if plan
        .name_owners
        .keys()
        .map(String::as_str)
        .collect::<BTreeSet<_>>()
        != canonical_names
    {
        return invalid("name ownership snapshots do not match canonical names");
    }
    for spec in &plan.canonical {
        let Some(owners) = plan.name_owners.get(&spec.name) else {
            return invalid("canonical name has no ownership snapshot");
        };
        if owners
            .iter()
            .any(|owner| owner.trim().is_empty() || owner != &spec.id)
        {
            return invalid("name ownership snapshot has a foreign or malformed owner");
        }
    }

    let mut target_ids = BTreeSet::new();
    let mut expected_bodies = BTreeMap::new();
    let mut expected_group_names = BTreeSet::new();
    let mut shared_parents = BTreeMap::new();
    let mut previous_target: Option<&str> = None;
    for target in &plan.targets {
        if target.effective.validate().is_err() {
            return invalid("effective integration policy is invalid");
        }
        if previous_target.is_some_and(|previous| previous >= target.effective.id.as_str()) {
            return invalid("pending integration policies must be unique and sorted by id");
        }
        previous_target = Some(&target.effective.id);
        let Some(canonical) = canonical_ids.get(target.effective.id.as_str()) else {
            return invalid("pending policy is not in the canonical artifact");
        };
        if !target_ids.insert(target.effective.id.as_str()) {
            return invalid("pending integration policies must be unique and sorted by id");
        }
        let exact_current = match (
            &target.current,
            plan.existing_snapshot.get(&target.effective.id),
        ) {
            (None, Some(None)) => true,
            (Some(current), Some(Some(item))) => current.item == *item,
            _ => false,
        };
        if !exact_current {
            return invalid("target does not match its plan-time existence snapshot");
        }
        let current_parent_ids = match &target.current {
            None => Vec::new(),
            Some(current) => {
                if current.spec.validate().is_err()
                    || current.spec.id != target.effective.id
                    || normalize(&current.item, &plan.space).ok().as_ref() != Some(&current.spec)
                {
                    return invalid("current integration snapshot does not normalize canonically");
                }
                let parent_ids = match read_parents(&target.effective.id, &current.item) {
                    Ok(parent_ids) if parent_ids == current.parent_ids => parent_ids,
                    _ => {
                        return invalid(
                            "current integration parent snapshot does not match its item",
                        );
                    }
                };
                if package_coordinate(&current.item, "integration policy").ok()
                    != Some(target.effective.package.clone())
                {
                    return invalid("current and desired package coordinates differ");
                }
                parent_ids
            }
        };
        if target.current.is_some() && !plan.overwrite {
            return invalid("existing integration target requires overwrite");
        }
        if !target_name_owners_match(target, &plan.name_owners) {
            return invalid("name ownership snapshot does not match target state");
        }
        let expected_parent_ids = current_parent_ids
            .iter()
            .chain(&target.effective.policy_ids)
            .cloned()
            .collect::<BTreeSet<_>>();
        if target.parents.keys().cloned().collect::<BTreeSet<_>>() != expected_parent_ids {
            return invalid("parent snapshots do not match current and desired parents");
        }
        for (parent_id, parent) in &target.parents {
            if !valid_parent_snapshot(parent_id, parent)
                || parent.platform_owned
                || parent.protected
            {
                return invalid("parent snapshot is unsafe or malformed");
            }
            if current_parent_ids.binary_search(parent_id).is_ok()
                && parent
                    .attached_integrations
                    .binary_search_by(|attached| attached.as_str().cmp(&target.effective.id))
                    .is_err()
            {
                return invalid("current parent snapshot is missing its integration attachment");
            }
            match shared_parents.entry(parent_id.as_str()) {
                std::collections::btree_map::Entry::Vacant(entry) => {
                    entry.insert(parent);
                }
                std::collections::btree_map::Entry::Occupied(entry) if *entry.get() != parent => {
                    return invalid("shared parent snapshots disagree");
                }
                std::collections::btree_map::Entry::Occupied(_) => {}
            }
        }
        if effective_import_spec(canonical, &target.parents)
            .ok()
            .as_ref()
            != Some(&target.effective)
        {
            return invalid("effective integration policy does not match canonical parents");
        }
        if let Some(current) = &target.current {
            if current.spec != target.effective {
                if !plan.overwrite {
                    return invalid("replacement plan requires overwrite");
                }
                let body = match replace_wire_body(&target.effective) {
                    Ok(body) => body,
                    Err(_) => return invalid("replacement body cannot be encoded"),
                };
                if target.replacement_body.as_ref() != Some(&body) {
                    return invalid("replacement body does not match its effective policy");
                }
                expected_bodies.insert(target.effective.id.as_str(), body);
            } else if target.replacement_body.is_some() {
                return invalid("unchanged integration policy carries a replacement body");
            }
        } else if target.replacement_body.is_some() {
            return invalid("planned create carries a replacement body");
        }
        expected_group_names.insert(target.effective.package.name.as_str());
    }

    if plan
        .package_groups
        .keys()
        .map(String::as_str)
        .collect::<BTreeSet<_>>()
        != expected_group_names
    {
        return invalid("package groups do not match pending integration policies");
    }
    let expected_parent_snapshots: BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot> =
        shared_parents
            .iter()
            .map(|(id, parent)| ((*id).to_owned(), (*parent).clone()))
            .collect();
    if plan.parent_snapshots != expected_parent_snapshots {
        return invalid("shared parent snapshots do not match pending integrations");
    }
    for (name, group) in &plan.package_groups {
        if group.package.name != *name
            || group.package.name.trim().is_empty()
            || group.package.version.trim().is_empty()
            || group.state != group.state_snapshot
            || group.metadata != group.metadata_snapshot
            || group.state.name != group.package.name
            || !valid_package_state(&group.state)
            || validate_package_metadata_snapshot(&group.metadata, &group.package).is_err()
        {
            return invalid("package group snapshot is malformed or tampered");
        }
        if !is_exact_installed(&group.state, &group.package)
            && !matches!(group.state.state, PackageDependencyState::NotInstalled)
        {
            return invalid("package group does not hold an exact dependency state");
        }
        if matches!(group.state.state, PackageDependencyState::NotInstalled)
            && plan
                .targets
                .iter()
                .any(|target| target.effective.package.name == *name && target.current.is_some())
        {
            return invalid("existing integration cannot depend on an absent package");
        }
    }
    for target in &plan.targets {
        let Some(group) = plan.package_groups.get(&target.effective.package.name) else {
            return invalid("target has no package group");
        };
        if group.package != target.effective.package {
            return invalid("package group coordinate does not match its target");
        }
        validate_effective_input_materialization(&target.effective, &group.metadata)?;
        match configured_secret_paths(&target.effective, &group.metadata) {
            Ok(paths) if paths.is_empty() => {}
            _ => return invalid("effective integration policy has unsafe configured variables"),
        }
        if let Some(current) = &target.current {
            match configured_secret_paths(&current.spec, &group.metadata) {
                Ok(paths) if paths.is_empty() => {}
                _ => {
                    return invalid("current integration policy has unsafe configured variables");
                }
            }
        }
    }
    if expected_bodies.len()
        != plan
            .targets
            .iter()
            .filter(|target| target.replacement_body.is_some())
            .count()
    {
        return invalid("replacement body set does not match changed integration policies");
    }

    let expected_skipped_ids = plan
        .canonical
        .iter()
        .filter(|spec| {
            plan.skip_existing && matches!(plan.existing_snapshot.get(&spec.id), Some(Some(_)))
        })
        .map(|spec| spec.id.as_str())
        .collect::<BTreeSet<_>>();
    let expected_target_ids = canonical_id_set
        .iter()
        .copied()
        .filter(|id| !expected_skipped_ids.contains(id))
        .collect::<BTreeSet<_>>();
    if target_ids != expected_target_ids {
        return invalid("pending integration policies do not match plan-time existence snapshots");
    }
    let expected_skipped = plan
        .canonical
        .iter()
        .filter(|spec| expected_skipped_ids.contains(spec.id.as_str()))
        .map(|spec| json!({"id": spec.id, "reason": "exists"}))
        .collect::<Vec<_>>();
    if plan.skipped != plan.skipped_snapshot {
        return invalid("skipped rows do not match their snapshot");
    }
    if (!plan.skip_existing && !plan.skipped.is_empty()) || plan.skipped != expected_skipped {
        return invalid("skipped rows do not match the canonical artifact");
    }
    let expected_installs = planned_package_installs(&plan.package_groups);
    if plan.package_installs != expected_installs {
        return invalid("package install preview does not match package groups");
    }
    let expected_preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);
    if plan.preview != expected_preview {
        return invalid("preview does not match the canonical plan");
    }
    Ok(())
}

fn valid_parent_snapshot(id: &str, parent: &agent_policy_ops::AgentPolicyParentSnapshot) -> bool {
    parent.id == id
        && !parent.id.trim().is_empty()
        && !parent.name.trim().is_empty()
        && !parent.namespace.trim().is_empty()
        && parent
            .attached_integrations
            .windows(2)
            .all(|ids| ids[0] < ids[1])
}

fn valid_package_state(snapshot: &PackageDependencySnapshot) -> bool {
    if snapshot.name.trim().is_empty() {
        return false;
    }
    match &snapshot.state {
        PackageDependencyState::Installed { version } => !version.trim().is_empty(),
        PackageDependencyState::NotInstalled => true,
    }
}

/// Plan safe, stable-id integration-policy deletion without issuing a
/// mutation. Each selected object is retained exactly so `apply_delete` can
/// reject a Fleet change before it reaches the single-id delete route.
pub async fn plan_delete(
    transport: &Transport,
    selectors: &[String],
) -> Result<IntegrationPolicyDeletePlan> {
    if selectors.is_empty() {
        return Err(Error::new(
            ErrorKind::Error,
            "integration-policy delete needs at least one selector",
        ));
    }
    if selectors.iter().any(|selector| selector.trim().is_empty()) {
        return Err(Error::new(
            ErrorKind::Error,
            "integration-policy delete selectors must not be empty",
        ));
    }

    let mut resolved = BTreeMap::new();
    for selector in selectors {
        let resolved_policy = resolve_delete_item(transport, selector).await?;
        let id = required_string(
            &resolved_policy.item,
            "id",
            "integration policy delete planning read",
        )?;
        if id != resolved_policy.summary.id {
            return Err(http(
                "decoding integration policy delete planning read: response id did not match its summary",
            ));
        }
        resolved.entry(id).or_insert(resolved_policy);
    }

    let mut targets = Vec::with_capacity(resolved.len());
    let mut issues = Vec::new();
    for (id, resolved_policy) in resolved {
        match plan_delete_target(transport, &id, resolved_policy.item).await {
            Ok(target) => targets.push(target),
            Err(error) => issues.push(error),
        }
    }
    if !issues.is_empty() {
        return collapse_delete_planning_issues(issues);
    }

    let parent_snapshots = shared_delete_parents(&targets).map_err(|_| {
        Error::new(
            ErrorKind::Conflict,
            "agent policy changed while planning integration deletion",
        )
    })?;
    let plan = IntegrationPolicyDeletePlan {
        preview: delete_preview(&targets),
        total: targets.len(),
        host_snapshot: transport.kibana_url().to_owned(),
        host: transport.kibana_url().to_owned(),
        space_snapshot: transport.space().to_owned(),
        space: transport.space().to_owned(),
        parent_snapshots_snapshot: parent_snapshots.clone(),
        parent_snapshots,
        targets,
    };
    validate_delete_plan(&plan)?;
    Ok(plan)
}

/// Delete planning must bind an id selector to the id Fleet returned for that
/// id route. The general resolver keeps its historical public behavior for
/// list, get, and export; a mutation cannot accept a mismatched one-object
/// response as a different target.
async fn resolve_delete_item(
    transport: &Transport,
    selector: &str,
) -> Result<ResolvedIntegrationPolicy> {
    match integration_policies::get(transport, selector).await {
        Ok(policy) => {
            let summary = summary_from_item(&policy.item)?;
            if summary.id != selector {
                return Err(http(
                    "decoding integration policy delete planning read: response id did not match the selector",
                ));
            }
            return Ok(ResolvedIntegrationPolicy {
                summary,
                item: policy.item,
            });
        }
        Err(error) if error.kind == ErrorKind::NotFound => {}
        Err(error) => return Err(delete_remote_error(error, "planning integration read")),
    }
    let matches = collect(transport)
        .await
        .map_err(|error| delete_remote_error(error, "planning integration list read"))?
        .iter()
        .filter(|item| item.get("name").and_then(Value::as_str) == Some(selector))
        .map(summary_from_item)
        .collect::<Result<Vec<_>>>()?;
    match matches.as_slice() {
        [] => Err(Error::new(
            ErrorKind::NotFound,
            format!("no integration policy with id or name '{selector}'"),
        )),
        [summary] => {
            let policy = integration_policies::get(transport, &summary.id)
                .await
                .map_err(|error| delete_remote_error(error, "planning name read"))?;
            let returned_id = required_string(
                &policy.item,
                "id",
                "integration policy delete planning read",
            )?;
            if returned_id != summary.id {
                return Err(http(
                    "decoding integration policy delete planning read: name resolution returned an unexpected id",
                ));
            }
            Ok(ResolvedIntegrationPolicy {
                summary: summary.clone(),
                item: policy.item,
            })
        }
        many => Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policy '{selector}' is ambiguous: {}",
                many.iter()
                    .map(|policy| policy.id.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        )),
    }
}

async fn plan_delete_target(
    transport: &Transport,
    id: &str,
    item: Map<String, Value>,
) -> Result<IntegrationPolicyDeleteTarget> {
    if required_string(&item, "id", "integration policy delete planning read")? != id {
        return Err(http(
            "decoding integration policy delete planning read: response id did not match the request",
        ));
    }
    let spec = normalize(&item, transport.space())?;
    if spec.id != id {
        return Err(http(
            "decoding integration policy delete planning read: normalized id did not match the request",
        ));
    }
    let parent_ids = read_parents(id, &item)?;
    let parents = read_parent_snapshots(transport, id, &parent_ids)
        .await
        .map_err(|error| delete_remote_error(error, "planning parent read"))?;
    validate_delete_parent_safety(id, &spec, &parents)?;

    let package = package_coordinate(&item, "integration policy delete planning read")?;
    if package != spec.package {
        return Err(http(
            "decoding integration policy delete planning read: package did not normalize canonically",
        ));
    }
    let dependency = read_dependencies(transport, &package)
        .await
        .map_err(|error| delete_remote_error(error, "planning package read"))?;
    ensure_delete_dependency(id, &dependency, &package)?;
    let metadata =
        integration_policies::package_metadata(transport, &package.name, &package.version)
            .await
            .map_err(|error| delete_remote_error(error, "planning package metadata read"))?
            .item;
    validate_package_metadata_snapshot(&metadata, &package)?;
    let secret_paths = configured_secret_paths(&spec, &metadata)?;
    if !secret_paths.is_empty() {
        return unsupported(format!(
            "integration policy '{id}' is not portable: {}",
            secret_paths
                .into_iter()
                .map(|path| format!("{id}:{path}"))
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    Ok(IntegrationPolicyDeleteTarget {
        id: id.to_owned(),
        name: spec.name.clone(),
        item_snapshot: item.clone(),
        item,
        spec_snapshot: spec.clone(),
        spec,
        parents,
        package,
        dependency_snapshot: dependency.clone(),
        dependency,
        metadata_snapshot: metadata.clone(),
        metadata,
    })
}

fn collapse_delete_planning_issues(mut issues: Vec<Error>) -> Result<IntegrationPolicyDeletePlan> {
    if issues.len() == 1 {
        return Err(issues.remove(0));
    }
    if issues.iter().all(|error| error.kind == ErrorKind::Conflict) {
        return Err(Error::new(
            ErrorKind::Conflict,
            issues
                .into_iter()
                .map(|error| error.message)
                .collect::<Vec<_>>()
                .join("; "),
        ));
    }
    Err(issues.remove(0))
}

fn validate_delete_parent_safety(
    id: &str,
    spec: &IntegrationPolicySpec,
    parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) -> Result<()> {
    if parents.len() != spec.policy_ids.len()
        || parents
            .keys()
            .map(String::as_str)
            .ne(spec.policy_ids.iter().map(String::as_str))
    {
        return Err(http(format!(
            "decoding integration policy '{id}': parent snapshots do not match policy_ids"
        )));
    }
    for parent in parents.values() {
        if parent.platform_owned {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parent {} is platform-owned",
                parent.id
            ));
        }
        if parent.protected {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parent {} is_protected",
                parent.id
            ));
        }
        if parent
            .attached_integrations
            .binary_search_by(|attached| attached.as_str().cmp(id))
            .is_err()
        {
            return Err(http(format!(
                "decoding integration policy '{id}': parent '{}' is missing its attachment",
                parent.id
            )));
        }
    }
    let namespaces = parents
        .values()
        .map(|parent| parent.namespace.as_str())
        .collect::<BTreeSet<_>>();
    match &spec.namespace {
        Some(namespace)
            if parents
                .values()
                .all(|parent| &parent.namespace == namespace) => {}
        Some(_) => {
            return unsupported(format!(
                "integration policy '{id}' is not portable: namespace does not match every parent"
            ));
        }
        None if namespaces.len() == 1 => {}
        None => {
            return unsupported(format!(
                "integration policy '{id}' is not portable: parents have different namespaces"
            ));
        }
    }
    Ok(())
}

fn ensure_delete_dependency(
    id: &str,
    dependency: &PackageDependencySnapshot,
    package: &IntegrationPackageSpec,
) -> Result<()> {
    match &dependency.state {
        PackageDependencyState::Installed { version }
            if dependency.name == package.name && version == &package.version =>
        {
            Ok(())
        }
        PackageDependencyState::Installed { .. } => Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policy '{id}' package {} has a different installed version",
                package.name
            ),
        )),
        PackageDependencyState::NotInstalled => Err(Error::new(
            ErrorKind::Conflict,
            format!(
                "integration policy '{id}' package {} is not installed",
                package.name
            ),
        )),
    }
}

fn shared_delete_parents(
    targets: &[IntegrationPolicyDeleteTarget],
) -> Result<BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>> {
    let mut shared = BTreeMap::new();
    for target in targets {
        for (id, parent) in &target.parents {
            match shared.entry(id.clone()) {
                std::collections::btree_map::Entry::Vacant(entry) => {
                    entry.insert(parent.clone());
                }
                std::collections::btree_map::Entry::Occupied(entry) if entry.get() != parent => {
                    return Err(Error::new(
                        ErrorKind::Conflict,
                        format!("agent policy '{id}' changed while planning integration deletion"),
                    ));
                }
                std::collections::btree_map::Entry::Occupied(_) => {}
            }
        }
    }
    Ok(shared)
}

fn delete_preview(targets: &[IntegrationPolicyDeleteTarget]) -> MutationPlan {
    let mut affected = BTreeMap::new();
    let mut preview_details = Vec::with_capacity(targets.len() + 2);
    for target in targets {
        let parents = target
            .parents
            .values()
            .map(|parent| {
                affected.entry(parent.id.clone()).or_insert(parent.agents);
                format!("{} ({}) agents {}", parent.id, parent.name, parent.agents)
            })
            .collect::<Vec<_>>();
        let agents = target
            .parents
            .values()
            .map(|parent| parent.agents)
            .sum::<u64>();
        preview_details.push(format!(
            "{}  {}  parents {}  agents {agents}",
            target.id,
            target.name,
            parents.join(", ")
        ));
    }
    preview_details.push(format!(
        "affected agents {}",
        affected.values().sum::<u64>()
    ));
    preview_details.push(DELETE_RACE_WARNING.to_owned());
    MutationPlan {
        preview_action: format!("Delete {} integration policy(ies)", targets.len()),
        preview_details,
        targets: targets.iter().map(|target| target.id.clone()).collect(),
    }
}

/// Recheck the exact planning snapshots, then delete each independent target.
/// An acknowledged wrong-id response is deliberately not treated as a clean
/// deletion, and never advances shared parent expectations.
pub async fn apply_delete(
    transport: &Transport,
    plan: &IntegrationPolicyDeletePlan,
) -> Result<IntegrationPolicyDeleteReport> {
    validate_delete_plan(plan)?;
    if plan.host != transport.kibana_url() || plan.space != transport.space() {
        return Err(Error::new(
            ErrorKind::Conflict,
            "integration delete target changed since preview",
        ));
    }

    let mut expected_parents = plan.parent_snapshots.clone();
    let mut affected = BTreeMap::new();
    let mut deleted = Vec::new();
    let mut failed = Vec::new();

    for target in &plan.targets {
        match integration_policies::get(transport, &target.id).await {
            Ok(actual) if actual.item == target.item => {}
            Ok(_) => {
                failed.push(delete_failed_row(
                    &target.id,
                    false,
                    "integration policy changed since preview",
                ));
                continue;
            }
            Err(error) if error.kind == ErrorKind::NotFound => {
                failed.push(delete_failed_row(
                    &target.id,
                    false,
                    "integration policy disappeared since preview",
                ));
                continue;
            }
            Err(error) => {
                failed.push(delete_failed_row(
                    &target.id,
                    false,
                    delete_remote_error(error, "apply integration-policy read").message,
                ));
                continue;
            }
        }

        if let Err(error) = recheck_delete_parents(transport, target, &expected_parents).await {
            failed.push(delete_failed_row(&target.id, false, error.message));
            continue;
        }
        match read_dependencies(transport, &target.package).await {
            Ok(actual) if actual == target.dependency => {}
            Ok(_) => {
                failed.push(delete_failed_row(
                    &target.id,
                    false,
                    "integration policy package changed since preview",
                ));
                continue;
            }
            Err(error) => {
                failed.push(delete_failed_row(
                    &target.id,
                    false,
                    delete_remote_error(error, "apply package read").message,
                ));
                continue;
            }
        }
        if let Err(error) = recheck_delete_metadata(transport, target).await {
            failed.push(delete_failed_row(&target.id, false, error.message));
            continue;
        }

        match integration_policies::delete(transport, &target.id).await {
            Ok(()) => {
                record_delete_affected_parents(&mut affected, target, &expected_parents);
                advance_delete_parent_snapshots(&mut expected_parents, target);
                deleted.push(json!({"id": target.id}));
            }
            Err(error) => {
                let applied = error
                    .http_status
                    .is_some_and(|status| (200..300).contains(&status));
                let message = if applied {
                    "integration-policy delete response did not confirm the requested id"
                } else {
                    "integration-policy delete request failed"
                };
                failed.push(delete_failed_row(&target.id, applied, message));
            }
        }
    }

    Ok(IntegrationPolicyDeleteReport {
        applied: true,
        deleted,
        failed,
        total: plan.total,
        affected_agents: affected.values().sum(),
    })
}

async fn recheck_delete_parents(
    transport: &Transport,
    target: &IntegrationPolicyDeleteTarget,
    expected_parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) -> Result<()> {
    for parent_id in target.parents.keys() {
        let expected = expected_parents.get(parent_id).ok_or_else(|| {
            Error::new(
                ErrorKind::Error,
                "integration delete lost a shared parent snapshot",
            )
        })?;
        match agent_policy_ops::read_parent_snapshot(transport, parent_id).await {
            Ok(actual) if actual == *expected => {}
            Ok(_) => {
                return Err(Error::new(
                    ErrorKind::Conflict,
                    "integration policy parent changed since preview",
                ));
            }
            Err(error) if error.kind == ErrorKind::NotFound => {
                return Err(Error::new(
                    ErrorKind::NotFound,
                    "integration policy parent disappeared since preview",
                ));
            }
            Err(error) => return Err(delete_remote_error(error, "apply parent read")),
        }
    }
    Ok(())
}

async fn recheck_delete_metadata(
    transport: &Transport,
    target: &IntegrationPolicyDeleteTarget,
) -> Result<()> {
    let metadata = integration_policies::package_metadata(
        transport,
        &target.package.name,
        &target.package.version,
    )
    .await
    .map_err(|error| delete_remote_error(error, "apply package metadata read"))?
    .item;
    validate_package_metadata_snapshot(&metadata, &target.package)
        .map_err(|error| delete_remote_error(error, "apply package metadata read"))?;
    if metadata != target.metadata {
        return Err(Error::new(
            ErrorKind::Conflict,
            "integration policy package metadata changed since preview",
        ));
    }
    Ok(())
}

fn record_delete_affected_parents(
    affected: &mut BTreeMap<String, u64>,
    target: &IntegrationPolicyDeleteTarget,
    expected_parents: &BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
) {
    for parent_id in target.parents.keys() {
        let parent = expected_parents
            .get(parent_id)
            .expect("validated delete target parent exists in shared snapshots");
        affected.entry(parent.id.clone()).or_insert(parent.agents);
    }
}

fn advance_delete_parent_snapshots(
    parents: &mut BTreeMap<String, agent_policy_ops::AgentPolicyParentSnapshot>,
    target: &IntegrationPolicyDeleteTarget,
) {
    for parent_id in target.parents.keys() {
        let parent = parents
            .get_mut(parent_id)
            .expect("validated delete target parent exists in shared snapshots");
        parent
            .attached_integrations
            .retain(|attached| attached != &target.id);
    }
}

fn delete_failed_row(id: &str, applied: bool, error: impl Into<String>) -> Value {
    json!({"id": id, "applied": applied, "error": error.into()})
}

fn delete_remote_error(error: Error, context: &str) -> Error {
    let message = format!("integration-policy delete {context} failed");
    match error.http_status {
        Some(status) => Error::with_status(error.kind, status, message),
        None => Error::new(error.kind, message),
    }
}

fn validate_delete_plan(plan: &IntegrationPolicyDeletePlan) -> Result<()> {
    let invalid = || Error::new(ErrorKind::Error, "invalid integration-policy delete plan");
    if plan.targets.is_empty()
        || plan.total != plan.targets.len()
        || plan.host.trim().is_empty()
        || plan.host != plan.host_snapshot
        || plan.space != plan.space_snapshot
    {
        return Err(invalid());
    }

    let mut previous: Option<&str> = None;
    let mut shared = BTreeMap::new();
    for target in &plan.targets {
        if target.id.trim().is_empty()
            || target.name.trim().is_empty()
            || previous.is_some_and(|previous| previous >= target.id.as_str())
            || target.item != target.item_snapshot
            || target.spec.validate().is_err()
            || target.spec != target.spec_snapshot
            || target.id != target.spec.id
            || target.name != target.spec.name
            || required_string(&target.item, "id", "integration policy delete plan")
                .ok()
                .as_deref()
                != Some(target.id.as_str())
            || normalize(&target.item, &plan.space).ok().as_ref() != Some(&target.spec)
            || package_coordinate(&target.item, "integration policy delete plan")
                .ok()
                .as_ref()
                != Some(&target.package)
            || target.package != target.spec.package
            || target.dependency != target.dependency_snapshot
            || !valid_package_state(&target.dependency)
            || target.dependency.name != target.package.name
            || !is_exact_installed(&target.dependency, &target.package)
            || target.metadata != target.metadata_snapshot
            || validate_package_metadata_snapshot(&target.metadata, &target.package).is_err()
            || !matches!(configured_secret_paths(&target.spec, &target.metadata), Ok(paths) if paths.is_empty())
        {
            return Err(invalid());
        }

        let parent_ids = match read_parents(&target.id, &target.item) {
            Ok(ids) => ids,
            Err(_) => return Err(invalid()),
        };
        if parent_ids.iter().collect::<BTreeSet<_>>()
            != target.parents.keys().collect::<BTreeSet<_>>()
            || validate_delete_parent_safety(&target.id, &target.spec, &target.parents).is_err()
        {
            return Err(invalid());
        }
        for (parent_id, parent) in &target.parents {
            if !valid_parent_snapshot(parent_id, parent)
                || parent.platform_owned
                || parent.protected
                || parent
                    .attached_integrations
                    .binary_search_by(|attached| attached.as_str().cmp(&target.id))
                    .is_err()
            {
                return Err(invalid());
            }
            match shared.entry(parent_id.as_str()) {
                std::collections::btree_map::Entry::Vacant(entry) => {
                    entry.insert(parent);
                }
                std::collections::btree_map::Entry::Occupied(entry) if *entry.get() != parent => {
                    return Err(invalid());
                }
                std::collections::btree_map::Entry::Occupied(_) => {}
            }
        }
        previous = Some(&target.id);
    }
    if plan.parent_snapshots != plan.parent_snapshots_snapshot
        || shared_delete_parents(&plan.targets).ok().as_ref() != Some(&plan.parent_snapshots)
    {
        return Err(invalid());
    }
    if plan.preview != delete_preview(&plan.targets) {
        return Err(invalid());
    }
    Ok(())
}

fn http(message: impl Into<String>) -> Error {
    Error::new(ErrorKind::Http, message)
}

fn unsupported<T>(message: impl Into<String>) -> Result<T> {
    Err(Error::new(ErrorKind::Unsupported, message))
}

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

    fn valid_plan() -> IntegrationPolicyImportPlan {
        let effective = IntegrationPolicySpec::try_from(json!({
            "id": "fresh",
            "name": "Fresh integration",
            "namespace": "default",
            "policy_ids": ["parent-1"],
            "package": {"name": "system", "version": "2.0.0"},
            "inputs": {}
        }))
        .expect("valid test policy");
        let parent = agent_policy_ops::AgentPolicyParentSnapshot {
            id: "parent-1".into(),
            name: "Parent 1".into(),
            namespace: "default".into(),
            agents: 0,
            attached_integrations: Vec::new(),
            platform_owned: false,
            protected: false,
        };
        let targets = vec![IntegrationPolicyImportTarget {
            effective: effective.clone(),
            current: None,
            parents: BTreeMap::from([(parent.id.clone(), parent)]),
            replacement_body: None,
        }];
        let parent_snapshots = targets[0].parents.clone();
        let state = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::NotInstalled,
        };
        let metadata = json!({
            "name": "system",
            "version": "2.0.0",
            "vars": [],
            "policy_templates": []
        })
        .as_object()
        .expect("metadata object")
        .clone();
        let package_groups = BTreeMap::from([(
            "system".into(),
            IntegrationPackageGroup {
                package: effective.package.clone(),
                state: state.clone(),
                state_snapshot: state,
                metadata_snapshot: metadata.clone(),
                metadata,
            },
        )]);
        let package_installs = vec!["system@2.0.0".into()];
        let source = PathBuf::from("fresh.json");
        let preview = import_preview(&source, &targets, &package_installs);
        IntegrationPolicyImportPlan {
            preview,
            skipped: Vec::new(),
            package_installs,
            total: 1,
            source,
            host: "https://fleet.example.invalid".into(),
            space: "default".into(),
            canonical: vec![effective.clone()],
            name_owners: BTreeMap::from([(effective.name.clone(), BTreeSet::new())]),
            name_owners_snapshot: BTreeMap::from([(effective.name.clone(), BTreeSet::new())]),
            parent_snapshots,
            skipped_snapshot: Vec::new(),
            existing_snapshot: BTreeMap::from([("fresh".into(), None)]),
            targets,
            package_groups,
            overwrite: false,
            skip_existing: false,
        }
    }

    fn existing_plan_without_overwrite() -> IntegrationPolicyImportPlan {
        let mut plan = valid_plan();
        let existing = {
            let target = plan.targets.first_mut().expect("fresh target");
            let mut item = serde_json::to_value(&target.effective)
                .expect("serialize current item")
                .as_object()
                .expect("current item object")
                .clone();
            item.insert("enabled".into(), Value::Bool(true));
            target.current = Some(IntegrationPolicyCurrentSnapshot {
                item: item.clone(),
                spec: target.effective.clone(),
                parent_ids: target.effective.policy_ids.clone(),
            });
            target
                .parents
                .get_mut("parent-1")
                .expect("parent")
                .attached_integrations
                .push(target.effective.id.clone());
            item
        };
        plan.existing_snapshot
            .insert("fresh".into(), Some(existing));

        let state = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "2.0.0".into(),
            },
        };
        let group = plan
            .package_groups
            .get_mut("system")
            .expect("package group");
        group.state = state.clone();
        group.state_snapshot = state;
        plan.package_installs.clear();
        plan.name_owners
            .get_mut("Fresh integration")
            .expect("name owner snapshot")
            .insert("fresh".into());
        plan.name_owners_snapshot = plan.name_owners.clone();
        plan.parent_snapshots = plan.targets[0].parents.clone();
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);
        plan
    }

    fn valid_skip_existing_plan() -> IntegrationPolicyImportPlan {
        let mut plan = existing_plan_without_overwrite();
        plan.skip_existing = true;
        plan.targets.clear();
        plan.parent_snapshots.clear();
        plan.package_groups.clear();
        plan.skipped = vec![json!({"id": "fresh", "reason": "exists"})];
        plan.skipped_snapshot = plan.skipped.clone();
        plan.package_installs.clear();
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);
        plan
    }

    fn valid_replace_plan() -> IntegrationPolicyImportPlan {
        let mut plan = existing_plan_without_overwrite();
        plan.overwrite = true;
        let desired = {
            let target = plan.targets.first_mut().expect("existing target");
            let mut desired = target.effective.clone();
            desired.description = Some("changed".into());
            target.effective = desired.clone();
            target.replacement_body = Some(replace_wire_body(&desired).expect("replace body"));
            desired
        };
        plan.canonical = vec![desired];
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);
        plan
    }

    #[test]
    fn replacement_body_omits_response_only_enabled_without_changing_input_enabled() {
        let spec = IntegrationPolicySpec::try_from(json!({
            "id": "replacement",
            "name": "Replacement integration",
            "namespace": "default",
            "policy_ids": ["parent-1"],
            "package": {"name": "system", "version": "2.0.0"},
            "inputs": {"system-log": {"enabled": true}}
        }))
        .expect("valid replacement spec");

        let body = replace_wire_body(&spec).expect("replacement wire body");
        let object = body.as_object().expect("replacement wire object");

        assert!(object.get("id").is_none());
        assert!(object.get("enabled").is_none());
        assert_eq!(object["inputs"]["system-log"]["enabled"], true);
    }

    fn valid_expanded_inputs_plan() -> IntegrationPolicyImportPlan {
        let mut plan = valid_plan();
        let inputs = json!({"system-system": {}})
            .as_object()
            .expect("inputs object")
            .clone();
        plan.canonical[0].inputs = inputs.clone();
        plan.targets[0].effective.inputs = inputs;
        let metadata = json!({
            "name": "system",
            "version": "2.0.0",
            "vars": [],
            "policy_templates": [{
                "name": "system",
                "inputs": [{"type": "system"}]
            }]
        })
        .as_object()
        .expect("metadata object")
        .clone();
        let group = plan
            .package_groups
            .get_mut("system")
            .expect("package group");
        group.metadata = metadata.clone();
        group.metadata_snapshot = metadata;
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);
        plan
    }

    #[test]
    fn import_plan_rejects_a_private_create_name_owner_tamper() {
        let mut plan = valid_plan();
        plan.name_owners
            .get_mut("Fresh integration")
            .expect("name owner snapshot")
            .insert("fresh".into());

        assert!(validate_import_plan(&plan).is_err());
    }

    #[test]
    fn import_plan_rejects_a_coherent_empty_effective_inputs_tamper() {
        let mut plan = valid_expanded_inputs_plan();
        assert!(validate_import_plan(&plan).is_ok());

        plan.canonical[0].inputs.clear();
        plan.targets[0].effective.inputs.clear();
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);

        let error = validate_import_plan(&plan)
            .expect_err("an empty effective map must not reach import requests");
        assert_eq!(error.kind, ErrorKind::Unsupported);
        assert_eq!(
            error.message,
            "integration policy 'fresh' has an empty inputs map but package system@2.0.0 declares inputs"
        );
    }

    #[test]
    fn import_plan_rejects_an_existing_target_without_overwrite() {
        let plan = existing_plan_without_overwrite();

        assert!(validate_import_plan(&plan).is_err());
    }

    #[test]
    fn import_plan_rejects_private_snapshot_body_group_and_order_tampering() {
        let replace = valid_replace_plan();
        assert!(validate_import_plan(&replace).is_ok());

        let mut tampered_body = replace.clone();
        tampered_body.targets[0].replacement_body = Some(json!({"tampered": true}));
        assert!(validate_import_plan(&tampered_body).is_err());

        let mut tampered_current = replace.clone();
        tampered_current.targets[0]
            .current
            .as_mut()
            .expect("current snapshot")
            .item
            .insert("enabled".into(), Value::Bool(false));
        assert!(validate_import_plan(&tampered_current).is_err());

        let mut tampered_group = valid_plan();
        tampered_group
            .package_groups
            .get_mut("system")
            .expect("package group")
            .metadata
            .insert("version".into(), Value::String("9.9.9".into()));
        assert!(validate_import_plan(&tampered_group).is_err());

        let mut tampered_order = valid_plan();
        tampered_order
            .targets
            .push(tampered_order.targets[0].clone());
        assert!(validate_import_plan(&tampered_order).is_err());

        let mut tampered_group_key = valid_plan();
        let group = tampered_group_key
            .package_groups
            .remove("system")
            .expect("package group");
        tampered_group_key
            .package_groups
            .insert("other".into(), group);
        assert!(validate_import_plan(&tampered_group_key).is_err());

        let mut tampered_state = valid_plan();
        tampered_state
            .package_groups
            .get_mut("system")
            .expect("package group")
            .state = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "2.0.0".into(),
            },
        };
        assert!(validate_import_plan(&tampered_state).is_err());

        let mut tampered_coordinate = valid_replace_plan();
        tampered_coordinate.canonical[0].package.version = "3.0.0".into();
        tampered_coordinate.targets[0].effective.package.version = "3.0.0".into();
        tampered_coordinate.targets[0].replacement_body = Some(
            replace_wire_body(&tampered_coordinate.targets[0].effective).expect("replace body"),
        );
        let group = tampered_coordinate
            .package_groups
            .get_mut("system")
            .expect("package group");
        group.package.version = "3.0.0".into();
        group.state = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "3.0.0".into(),
            },
        };
        group.state_snapshot = group.state.clone();
        group.metadata.insert("version".into(), json!("3.0.0"));
        group.metadata_snapshot = group.metadata.clone();
        tampered_coordinate.preview = import_preview(
            &tampered_coordinate.source,
            &tampered_coordinate.targets,
            &tampered_coordinate.package_installs,
        );
        assert!(validate_import_plan(&tampered_coordinate).is_err());
    }

    #[test]
    fn import_plan_rejects_a_private_parent_snapshot_tamper_even_with_preview_rebuilt() {
        let mut plan = valid_plan();
        plan.targets[0]
            .parents
            .get_mut("parent-1")
            .expect("parent snapshot")
            .agents = 42;
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);

        assert!(validate_import_plan(&plan).is_err());
    }

    #[test]
    fn import_plan_rejects_target_removal_rebuilt_as_a_skipped_row() {
        let mut plan = valid_plan();
        plan.skip_existing = true;
        plan.targets.clear();
        plan.parent_snapshots.clear();
        plan.package_groups.clear();
        plan.skipped = vec![json!({"id": "fresh", "reason": "exists"})];
        plan.skipped_snapshot = plan.skipped.clone();
        plan.package_installs.clear();
        plan.preview = import_preview(&plan.source, &plan.targets, &plan.package_installs);

        assert!(validate_import_plan(&plan).is_err());
    }

    #[test]
    fn import_plan_accepts_a_coherent_skip_existing_snapshot() {
        assert!(validate_import_plan(&valid_skip_existing_plan()).is_ok());
    }

    #[test]
    fn import_plan_rejects_existence_snapshot_key_and_target_mismatches() {
        let mut missing_current = valid_replace_plan();
        missing_current
            .existing_snapshot
            .insert("fresh".into(), None);
        assert!(validate_import_plan(&missing_current).is_err());

        let mut changed_current = valid_replace_plan();
        changed_current
            .existing_snapshot
            .get_mut("fresh")
            .expect("existing snapshot")
            .as_mut()
            .expect("existing item")
            .insert("description".into(), json!("tampered"));
        assert!(validate_import_plan(&changed_current).is_err());

        let mut extra_snapshot = valid_plan();
        extra_snapshot
            .existing_snapshot
            .insert("other".into(), None);
        assert!(validate_import_plan(&extra_snapshot).is_err());
    }

    #[test]
    fn import_plan_rejects_public_field_tampering_against_private_snapshots() {
        let plan = valid_plan();

        let mut total = plan.clone();
        total.total = 2;
        assert!(validate_import_plan(&total).is_err());

        let mut preview = plan.clone();
        preview.preview.preview_action = "tampered".into();
        assert!(validate_import_plan(&preview).is_err());

        let mut skipped = plan.clone();
        skipped.skipped = vec![json!({"id": "fresh", "reason": "exists"})];
        assert!(validate_import_plan(&skipped).is_err());

        let mut installs = plan;
        installs.package_installs.clear();
        assert!(validate_import_plan(&installs).is_err());
    }
}

#[cfg(test)]
mod delete_plan_tests {
    use super::*;
    use elasticctl_core::{Profile, Transport};
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn verified_server() -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/status"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "version": {"number": "9.5.1", "build_flavor": "traditional"}
            })))
            .mount(&server)
            .await;
        server
    }

    fn transport_for(server: &MockServer) -> Transport {
        Transport::new(&Profile {
            kibana_url: server.uri(),
            es_url: None,
            api_key: Some("essu_test".into()),
            username: None,
            password: None,
            space: "default".into(),
            verify: true,
            timeout_secs: 5,
        })
        .expect("transport")
    }

    fn valid_plan() -> IntegrationPolicyDeletePlan {
        let spec = IntegrationPolicySpec::try_from(json!({
            "id": "delete-1",
            "name": "Delete integration",
            "namespace": "default",
            "policy_ids": ["parent-1"],
            "package": {"name": "system", "version": "2.0.0"},
            "inputs": {}
        }))
        .expect("valid integration policy");
        let mut item = serde_json::to_value(&spec)
            .expect("serialize integration policy")
            .as_object()
            .expect("integration policy is an object")
            .clone();
        item.insert("enabled".into(), Value::Bool(true));
        let parent = agent_policy_ops::AgentPolicyParentSnapshot {
            id: "parent-1".into(),
            name: "Parent 1".into(),
            namespace: "default".into(),
            agents: 4,
            attached_integrations: vec!["delete-1".into()],
            platform_owned: false,
            protected: false,
        };
        let parents = BTreeMap::from([(parent.id.clone(), parent)]);
        let dependency = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "2.0.0".into(),
            },
        };
        let metadata = json!({
            "name": "system",
            "version": "2.0.0",
            "vars": [],
            "policy_templates": []
        })
        .as_object()
        .expect("metadata object")
        .clone();
        let target = IntegrationPolicyDeleteTarget {
            id: spec.id.clone(),
            name: spec.name.clone(),
            item_snapshot: item.clone(),
            item,
            spec_snapshot: spec.clone(),
            spec,
            parents: parents.clone(),
            package: IntegrationPackageSpec {
                name: "system".into(),
                version: "2.0.0".into(),
            },
            dependency_snapshot: dependency.clone(),
            dependency,
            metadata_snapshot: metadata.clone(),
            metadata,
        };
        let targets = vec![target];
        let parent_snapshots = parents;
        IntegrationPolicyDeletePlan {
            preview: delete_preview(&targets),
            total: targets.len(),
            host: "https://fleet.example.invalid".into(),
            host_snapshot: "https://fleet.example.invalid".into(),
            space: "default".into(),
            space_snapshot: "default".into(),
            parent_snapshots_snapshot: parent_snapshots.clone(),
            parent_snapshots,
            targets,
        }
    }

    #[test]
    fn delete_plan_accepts_a_coherent_private_snapshot() {
        assert!(validate_delete_plan(&valid_plan()).is_ok());
    }

    #[test]
    fn delete_plan_rejects_empty_total_order_and_preview_tampering() {
        let plan = valid_plan();

        let mut empty = plan.clone();
        empty.targets.clear();
        empty.total = 0;
        empty.parent_snapshots.clear();
        empty.parent_snapshots_snapshot.clear();
        empty.preview = delete_preview(&empty.targets);
        assert!(validate_delete_plan(&empty).is_err());

        let mut total = plan.clone();
        total.total = 2;
        assert!(validate_delete_plan(&total).is_err());

        let mut duplicate = plan.clone();
        duplicate.targets.push(duplicate.targets[0].clone());
        duplicate.total = 2;
        duplicate.preview = delete_preview(&duplicate.targets);
        assert!(validate_delete_plan(&duplicate).is_err());

        let mut preview = plan;
        preview.preview.preview_action = "tampered".into();
        assert!(validate_delete_plan(&preview).is_err());

        let mut host = valid_plan();
        host.host = "https://other.example.invalid".into();
        assert!(validate_delete_plan(&host).is_err());

        let mut space = valid_plan();
        space.space = "other".into();
        assert!(validate_delete_plan(&space).is_err());
    }

    #[test]
    fn delete_plan_rejects_raw_spec_parent_package_and_metadata_tampering() {
        let plan = valid_plan();

        let mut raw_and_spec = plan.clone();
        raw_and_spec.targets[0]
            .item
            .insert("description".into(), json!("tampered"));
        raw_and_spec.targets[0].spec.description = Some("tampered".into());
        raw_and_spec.preview = delete_preview(&raw_and_spec.targets);
        assert!(validate_delete_plan(&raw_and_spec).is_err());

        let mut parent = plan.clone();
        parent.targets[0]
            .parents
            .get_mut("parent-1")
            .expect("parent")
            .agents = 99;
        parent.preview = delete_preview(&parent.targets);
        assert!(validate_delete_plan(&parent).is_err());

        let mut parent_snapshot = plan.clone();
        parent_snapshot
            .parent_snapshots
            .get_mut("parent-1")
            .expect("parent")
            .agents = 99;
        assert!(validate_delete_plan(&parent_snapshot).is_err());

        let mut dependency = plan.clone();
        dependency.targets[0].dependency = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "1.0.0".into(),
            },
        };
        assert!(validate_delete_plan(&dependency).is_err());

        let mut metadata = plan;
        metadata.targets[0]
            .metadata
            .insert("version".into(), json!("9.9.9"));
        assert!(validate_delete_plan(&metadata).is_err());
    }

    #[tokio::test]
    async fn delete_apply_rereads_metadata_after_coherent_secret_tampering() {
        let server = verified_server().await;
        let transport = transport_for(&server);
        let spec = IntegrationPolicySpec::try_from(json!({
            "id": "delete-1",
            "name": "Delete integration",
            "namespace": "default",
            "policy_ids": ["parent-1"],
            "package": {"name": "system", "version": "2.0.0"},
            "vars": {"package_secret": "live-plaintext-value-must-not-leak"},
            "inputs": {}
        }))
        .expect("valid integration policy");
        let mut item = serde_json::to_value(&spec)
            .expect("serialize integration policy")
            .as_object()
            .expect("integration policy is an object")
            .clone();
        item.insert("enabled".into(), Value::Bool(true));
        let parent = agent_policy_ops::AgentPolicyParentSnapshot {
            id: "parent-1".into(),
            name: "Parent 1".into(),
            namespace: "default".into(),
            agents: 4,
            attached_integrations: vec![spec.id.clone()],
            platform_owned: false,
            protected: false,
        };
        let parents = BTreeMap::from([(parent.id.clone(), parent)]);
        let dependency = PackageDependencySnapshot {
            name: "system".into(),
            state: PackageDependencyState::Installed {
                version: "2.0.0".into(),
            },
        };
        let original_metadata = json!({
            "name": "system",
            "version": "2.0.0",
            "vars": [{"name": "package_secret", "secret": true}],
            "policy_templates": []
        })
        .as_object()
        .expect("metadata object")
        .clone();
        let mut target = IntegrationPolicyDeleteTarget {
            id: spec.id.clone(),
            name: spec.name.clone(),
            item_snapshot: item.clone(),
            item,
            spec_snapshot: spec.clone(),
            spec,
            parents: parents.clone(),
            package: IntegrationPackageSpec {
                name: "system".into(),
                version: "2.0.0".into(),
            },
            dependency_snapshot: dependency.clone(),
            dependency,
            metadata_snapshot: original_metadata.clone(),
            metadata: original_metadata.clone(),
        };
        let mut plan = IntegrationPolicyDeletePlan {
            preview: delete_preview(std::slice::from_ref(&target)),
            total: 1,
            host: server.uri(),
            host_snapshot: server.uri(),
            space: "default".into(),
            space_snapshot: "default".into(),
            parent_snapshots_snapshot: parents.clone(),
            parent_snapshots: parents,
            targets: vec![target.clone()],
        };
        assert!(validate_delete_plan(&plan).is_err());

        let forged_metadata = json!({
            "name": "system",
            "version": "2.0.0",
            "vars": [{"name": "package_secret", "secret": false}],
            "policy_templates": []
        })
        .as_object()
        .expect("metadata object")
        .clone();
        target.metadata = forged_metadata.clone();
        target.metadata_snapshot = forged_metadata;
        target.item_snapshot = target.item.clone();
        target.spec_snapshot = target.spec.clone();
        plan.targets = vec![target];
        plan.parent_snapshots = shared_delete_parents(&plan.targets).expect("shared parents");
        plan.parent_snapshots_snapshot = plan.parent_snapshots.clone();
        plan.preview = delete_preview(&plan.targets);
        assert!(validate_delete_plan(&plan).is_ok());

        let item = plan.targets[0].item.clone();
        Mock::given(method("GET"))
            .and(path("/api/fleet/package_policies/delete-1"))
            .and(query_param("format", "simplified"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"item": item})))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/api/fleet/agent_policies/parent-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "item": parent_item_for_delete_test("parent-1", "delete-1")
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/api/fleet/epm/packages/system"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "item": {
                    "name": "system",
                    "status": "installed",
                    "installationInfo": {"version": "2.0.0"}
                }
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/api/fleet/epm/packages/system/2.0.0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "item": original_metadata
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("DELETE"))
            .and(path("/api/fleet/package_policies/delete-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"id": "delete-1"})))
            .expect(0)
            .mount(&server)
            .await;

        let report = apply_delete(&transport, &plan)
            .await
            .expect("metadata race is a row failure");
        assert!(report.deleted.is_empty());
        assert_eq!(
            report.failed,
            vec![json!({
                "id": "delete-1",
                "applied": false,
                "error": "integration policy package metadata changed since preview"
            })]
        );
        let requests = server.received_requests().await.expect("recorded requests");
        assert_eq!(
            requests
                .iter()
                .filter(|request| request.url.path() == "/api/fleet/epm/packages/system/2.0.0")
                .count(),
            1
        );
        assert!(requests.iter().all(|request| request.method != "DELETE"));
        assert!(
            !report.failed[0]["error"]
                .as_str()
                .expect("error string")
                .contains("live-plaintext-value-must-not-leak")
        );
    }

    fn parent_item_for_delete_test(id: &str, attached: &str) -> Value {
        json!({
            "id": id,
            "name": "Parent 1",
            "namespace": "default",
            "agents": 4,
            "package_policies": [attached],
        })
    }
}