riffdb-types 0.1.0

First-party RiffDB runtime crate (riffdb-types)
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
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;

use crate::{
    AdapterConformanceManifestHash, ApplicationExportManifestHash, ApplicationExportReceiptHash,
    ApplicationInstallationPlanHash, ApplicationLockHash, ApplicationManifestHash,
    ApplicationPortabilityManifestHash, ApplicationRoleHash, ApplicationSourceHash, CapabilityId,
    ContractBundleHash, ContractLineage, ContractVersion, DatabaseAlias, Environment,
    GeneratedArtifactHash, MigrationBundleHash, hash_application_installation_plan,
};
use serde::{Deserialize, Serialize};

/// Canonical schema version for exact application installation plans.
pub const APPLICATION_INSTALLATION_PLAN_SCHEMA_V1: &str = "riffdb.application-installation-plan/v1";
/// Canonical schema version for plans carrying exact reimport authority.
pub const APPLICATION_INSTALLATION_PLAN_SCHEMA_V2: &str = "riffdb.application-installation-plan/v2";
/// Canonical schema version for plans carrying secret-output authority atoms.
pub const APPLICATION_INSTALLATION_PLAN_SCHEMA_V3: &str = "riffdb.application-installation-plan/v3";
/// Maximum canonical bytes in one installation plan.
pub const MAX_INSTALLATION_PLAN_BYTES: usize = 4 * 1_024 * 1_024;
/// Maximum exact artifacts in one plan.
pub const MAX_INSTALLATION_ARTIFACTS: usize = 256;
/// Maximum symbolic application roles in one plan.
pub const MAX_INSTALLATION_ROLES: usize = 128;
/// Maximum credential destinations in one plan.
pub const MAX_CREDENTIAL_DESTINATIONS: usize = 256;
/// Maximum bounded seed batches in one plan.
pub const MAX_INSTALLATION_SEEDS: usize = 256;
/// Maximum ordinary commands represented by one seed batch.
pub const MAX_SEED_BATCH_ITEMS: u64 = 1_000_000;
/// Maximum symbolic operations in one application role.
pub const MAX_ROLE_OPERATIONS: usize = 1_024;
/// Maximum symbolic secret-output atoms in one application role.
pub const MAX_ROLE_SECRET_OUTPUTS: usize = 1_024;
/// Maximum total authority atoms in one application role.
pub const MAX_ROLE_AUTHORITY_ATOMS: usize = 2_048;
/// Maximum bytes in one installation-local symbolic name.
pub const MAX_INSTALLATION_SYMBOL_BYTES: usize = 256;

/// A bounded, non-secret symbol retained in plans and diagnostics.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct InstallationSymbol(String);

impl InstallationSymbol {
    /// Validates one exact source-like symbol without normalization.
    pub fn new(value: impl Into<String>) -> Result<Self, InstallationPlanError> {
        let value = value.into();
        if value.is_empty() || value.len() > MAX_INSTALLATION_SYMBOL_BYTES {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::LimitExceeded,
            ));
        }
        if let Some(index) = value.bytes().enumerate().find_map(|(index, byte)| {
            (!(byte == b'_'
                || byte == b'-'
                || byte == b'.'
                || byte.is_ascii_alphabetic()
                || index > 0 && byte.is_ascii_digit()))
            .then_some(index)
        }) {
            let _ = index;
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidIdentifier,
            ));
        }
        Ok(Self(value))
    }

    /// Borrows the exact symbol.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for InstallationSymbol {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("InstallationSymbol")
            .field(&self.0)
            .finish()
    }
}

/// Exact selected database, environment, and application lineage.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstallationTarget {
    database: DatabaseAlias,
    environment: Environment,
    lineage: ContractLineage,
}

impl InstallationTarget {
    /// Creates an exact installation authority target.
    #[must_use]
    pub const fn new(
        database: DatabaseAlias,
        environment: Environment,
        lineage: ContractLineage,
    ) -> Self {
        Self {
            database,
            environment,
            lineage,
        }
    }

    /// Selected canonical database alias.
    #[must_use]
    pub const fn database(&self) -> &DatabaseAlias {
        &self.database
    }

    /// Selected exact deployment environment.
    #[must_use]
    pub const fn environment(&self) -> &Environment {
        &self.environment
    }

    /// Selected application lineage.
    #[must_use]
    pub const fn lineage(&self) -> &ContractLineage {
        &self.lineage
    }
}

/// Candidate contract identity pinned by the exact lock.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct InstallationContract {
    version: ContractVersion,
    bundle_hash: ContractBundleHash,
}

impl InstallationContract {
    /// Binds one exact candidate version and bundle.
    #[must_use]
    pub const fn new(version: ContractVersion, bundle_hash: ContractBundleHash) -> Self {
        Self {
            version,
            bundle_hash,
        }
    }

    /// Exact candidate version.
    #[must_use]
    pub const fn version(self) -> ContractVersion {
        self.version
    }

    /// Exact candidate bundle hash.
    #[must_use]
    pub const fn bundle_hash(self) -> ContractBundleHash {
        self.bundle_hash
    }
}

/// Closed compiler-owned artifact class.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum InstallationArtifactKind {
    /// Canonical application manifest.
    Manifest,
    /// Canonical contract bundle.
    ContractBundle,
    /// Named-query module.
    QueryModule,
    /// Reactive module.
    ReactiveModule,
    /// Compiled migration bundle.
    MigrationBundle,
    /// Rust generated bindings.
    Rust,
    /// TypeScript generated bindings.
    TypeScript,
    /// Go generated bindings.
    Go,
    /// Python generated bindings.
    Python,
    /// Generated MCP catalog.
    Mcp,
    /// Bounded seed input.
    SeedInput,
    /// Adapter conformance manifest.
    AdapterManifest,
}

impl InstallationArtifactKind {
    #[doc(hidden)]
    pub const fn tag(self) -> &'static str {
        match self {
            Self::Manifest => "manifest",
            Self::ContractBundle => "contract_bundle",
            Self::QueryModule => "query_module",
            Self::ReactiveModule => "reactive_module",
            Self::MigrationBundle => "migration_bundle",
            Self::Rust => "rust",
            Self::TypeScript => "typescript",
            Self::Go => "go",
            Self::Python => "python",
            Self::Mcp => "mcp",
            Self::SeedInput => "seed_input",
            Self::AdapterManifest => "adapter_manifest",
        }
    }

    #[doc(hidden)]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "manifest" => Self::Manifest,
            "contract_bundle" => Self::ContractBundle,
            "query_module" => Self::QueryModule,
            "reactive_module" => Self::ReactiveModule,
            "migration_bundle" => Self::MigrationBundle,
            "rust" => Self::Rust,
            "typescript" => Self::TypeScript,
            "go" => Self::Go,
            "python" => Self::Python,
            "mcp" => Self::Mcp,
            "seed_input" => Self::SeedInput,
            "adapter_manifest" => Self::AdapterManifest,
            _ => return None,
        })
    }
}

/// One exact compiler-produced artifact without a host filesystem path.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct InstallationArtifact {
    kind: InstallationArtifactKind,
    name: InstallationSymbol,
    content_hash: GeneratedArtifactHash,
}

impl InstallationArtifact {
    /// Creates one name-addressed exact artifact reference.
    #[must_use]
    pub const fn new(
        kind: InstallationArtifactKind,
        name: InstallationSymbol,
        content_hash: GeneratedArtifactHash,
    ) -> Self {
        Self {
            kind,
            name,
            content_hash,
        }
    }

    /// Closed artifact kind.
    #[must_use]
    pub const fn kind(&self) -> InstallationArtifactKind {
        self.kind
    }

    /// Symbolic artifact name, never a host path.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }

    /// Exact generated content identity.
    #[must_use]
    pub const fn content_hash(&self) -> GeneratedArtifactHash {
        self.content_hash
    }
}

/// Closed symbolic operation category used only to compute authority diffs.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum RoleOperationKind {
    /// Named query.
    Query,
    /// Compiled command.
    Command,
    /// Durable event stream.
    EventStream,
    /// Live named-query watch.
    QueryWatch,
    /// Contextual agent subscription.
    AgentSubscription,
}

impl RoleOperationKind {
    #[doc(hidden)]
    pub const fn tag(self) -> &'static str {
        match self {
            Self::Query => "query",
            Self::Command => "command",
            Self::EventStream => "event_stream",
            Self::QueryWatch => "query_watch",
            Self::AgentSubscription => "agent_subscription",
        }
    }

    #[doc(hidden)]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "query" => Self::Query,
            "command" => Self::Command,
            "event_stream" => Self::EventStream,
            "query_watch" => Self::QueryWatch,
            "agent_subscription" => Self::AgentSubscription,
            _ => return None,
        })
    }
}

/// One symbolic application operation in an authority diff.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct RoleOperation {
    kind: RoleOperationKind,
    name: InstallationSymbol,
}

/// One symbolic secret output granted to one exact named query.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct QuerySecretOutput {
    query: InstallationSymbol,
    entity: InstallationSymbol,
    field: InstallationSymbol,
}

impl QuerySecretOutput {
    /// Creates a value-free secret-output authority atom.
    #[must_use]
    pub const fn new(
        query: InstallationSymbol,
        entity: InstallationSymbol,
        field: InstallationSymbol,
    ) -> Self {
        Self {
            query,
            entity,
            field,
        }
    }

    /// Exact named-query symbol.
    #[must_use]
    pub const fn query(&self) -> &InstallationSymbol {
        &self.query
    }

    /// Exact entity symbol.
    #[must_use]
    pub const fn entity(&self) -> &InstallationSymbol {
        &self.entity
    }

    /// Exact secret field symbol.
    #[must_use]
    pub const fn field(&self) -> &InstallationSymbol {
        &self.field
    }
}

/// Closed symbolic vocabulary used by installation authority diffs.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum RoleAuthorityAtom {
    /// One invocable application operation.
    Operation(RoleOperation),
    /// One exact secret output of one exact named query.
    QuerySecretOutput(QuerySecretOutput),
}

/// Independently canonical bounded authority for one application role.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoleAuthoritySet {
    operations: Vec<RoleOperation>,
    secret_outputs: Vec<QuerySecretOutput>,
}

impl RoleAuthoritySet {
    /// Validates and canonicalizes one complete symbolic authority set.
    pub fn new(
        mut operations: Vec<RoleOperation>,
        mut secret_outputs: Vec<QuerySecretOutput>,
    ) -> Result<Self, InstallationPlanError> {
        sort_unique(&mut operations)?;
        sort_unique(&mut secret_outputs)?;
        if operations.len() > MAX_ROLE_OPERATIONS
            || secret_outputs.len() > MAX_ROLE_SECRET_OUTPUTS
            || operations.len() + secret_outputs.len() > MAX_ROLE_AUTHORITY_ATOMS
        {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::LimitExceeded,
            ));
        }
        Ok(Self {
            operations,
            secret_outputs,
        })
    }

    /// Canonical operation atoms.
    #[must_use]
    pub fn operations(&self) -> &[RoleOperation] {
        &self.operations
    }

    /// Canonical named-query secret-output atoms.
    #[must_use]
    pub fn secret_outputs(&self) -> &[QuerySecretOutput] {
        &self.secret_outputs
    }

    /// Complete canonical closed authority vocabulary.
    #[must_use]
    pub fn atoms(&self) -> Vec<RoleAuthorityAtom> {
        self.operations
            .iter()
            .cloned()
            .map(RoleAuthorityAtom::Operation)
            .chain(
                self.secret_outputs
                    .iter()
                    .cloned()
                    .map(RoleAuthorityAtom::QuerySecretOutput),
            )
            .collect()
    }

    const fn is_empty(&self) -> bool {
        self.operations.is_empty() && self.secret_outputs.is_empty()
    }
}

impl RoleOperation {
    /// Creates one symbolic operation.
    #[must_use]
    pub const fn new(kind: RoleOperationKind, name: InstallationSymbol) -> Self {
        Self { kind, name }
    }

    /// Operation category.
    #[must_use]
    pub const fn kind(&self) -> RoleOperationKind {
        self.kind
    }

    /// Exact operation symbol.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }
}

/// Exact approval for only the additions in one existing role.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoleWideningApproval {
    expected_previous_role: ApplicationRoleHash,
    additions: Vec<RoleAuthorityAtom>,
}

impl RoleWideningApproval {
    /// Creates an approval whose exact additions are checked during compilation.
    pub fn new(
        expected_previous_role: ApplicationRoleHash,
        mut additions: Vec<RoleOperation>,
    ) -> Result<Self, InstallationPlanError> {
        sort_unique(&mut additions)?;
        if additions.is_empty() || additions.len() > MAX_ROLE_OPERATIONS {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidApproval,
            ));
        }
        Ok(Self {
            expected_previous_role,
            additions: additions
                .into_iter()
                .map(RoleAuthorityAtom::Operation)
                .collect(),
        })
    }

    /// Creates an exact, already-canonical approval over the closed authority vocabulary.
    pub fn new_authority(
        expected_previous_role: ApplicationRoleHash,
        additions: Vec<RoleAuthorityAtom>,
    ) -> Result<Self, InstallationPlanError> {
        let operation_count = additions
            .iter()
            .filter(|atom| matches!(atom, RoleAuthorityAtom::Operation(_)))
            .count();
        let secret_output_count = additions.len() - operation_count;
        if additions.is_empty()
            || operation_count > MAX_ROLE_OPERATIONS
            || secret_output_count > MAX_ROLE_SECRET_OUTPUTS
            || additions.len() > MAX_ROLE_AUTHORITY_ATOMS
            || additions.windows(2).any(|pair| pair[0] >= pair[1])
        {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidApproval,
            ));
        }
        Ok(Self {
            expected_previous_role,
            additions,
        })
    }

    /// Exact predecessor role identity being widened.
    #[must_use]
    pub const fn expected_previous_role(&self) -> ApplicationRoleHash {
        self.expected_previous_role
    }

    /// Exact symbolic additions approved by the operator.
    #[must_use]
    pub fn additions(&self) -> &[RoleAuthorityAtom] {
        &self.additions
    }
}

/// One desired exact role plus enough predecessor state to compute its authority diff.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstallationRole {
    name: InstallationSymbol,
    role_hash: ApplicationRoleHash,
    previous_role_hash: Option<ApplicationRoleHash>,
    desired_authority: RoleAuthoritySet,
    previous_authority: RoleAuthoritySet,
    widening_approval: Option<RoleWideningApproval>,
}

impl InstallationRole {
    /// Creates one exact initial or successor role.
    pub fn new(
        name: InstallationSymbol,
        role_hash: ApplicationRoleHash,
        previous_role_hash: Option<ApplicationRoleHash>,
        desired_operations: Vec<RoleOperation>,
        previous_operations: Vec<RoleOperation>,
        widening_approval: Option<RoleWideningApproval>,
    ) -> Result<Self, InstallationPlanError> {
        Self::new_with_authority(
            name,
            role_hash,
            previous_role_hash,
            RoleAuthoritySet::new(desired_operations, vec![])?,
            RoleAuthoritySet::new(previous_operations, vec![])?,
            widening_approval,
        )
    }

    /// Creates one exact initial or successor role over the complete closed authority vocabulary.
    pub fn new_with_authority(
        name: InstallationSymbol,
        role_hash: ApplicationRoleHash,
        previous_role_hash: Option<ApplicationRoleHash>,
        desired_authority: RoleAuthoritySet,
        previous_authority: RoleAuthoritySet,
        widening_approval: Option<RoleWideningApproval>,
    ) -> Result<Self, InstallationPlanError> {
        if desired_authority.is_empty()
            || (previous_role_hash.is_none() && !previous_authority.is_empty())
        {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidShape,
            ));
        }
        let desired_atoms = desired_authority.atoms();
        let previous_atoms = previous_authority.atoms();
        let additions = desired_atoms
            .iter()
            .filter(|atom| previous_atoms.binary_search(atom).is_err())
            .cloned()
            .collect::<Vec<_>>();
        match (
            previous_role_hash,
            additions.is_empty(),
            widening_approval.as_ref(),
        ) {
            (None, _, None) | (Some(_), true, None) => {}
            (Some(previous), false, Some(approval))
                if approval.expected_previous_role == previous
                    && approval.additions == additions => {}
            (Some(_), false, None) => {
                return Err(InstallationPlanError::new(
                    InstallationPlanErrorKind::ApprovalRequired,
                ));
            }
            _ => {
                return Err(InstallationPlanError::new(
                    InstallationPlanErrorKind::InvalidApproval,
                ));
            }
        }
        Ok(Self {
            name,
            role_hash,
            previous_role_hash,
            desired_authority,
            previous_authority,
            widening_approval,
        })
    }

    /// Symbolic role name.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }

    /// Exact desired role identity.
    #[must_use]
    pub const fn role_hash(&self) -> ApplicationRoleHash {
        self.role_hash
    }

    /// Exact predecessor identity, when reconciling an existing role.
    #[must_use]
    pub const fn previous_role_hash(&self) -> Option<ApplicationRoleHash> {
        self.previous_role_hash
    }

    /// Desired symbolic operation surface.
    #[must_use]
    pub fn desired_operations(&self) -> &[RoleOperation] {
        self.desired_authority.operations()
    }

    /// Existing symbolic operation surface used to compute the diff.
    #[must_use]
    pub fn previous_operations(&self) -> &[RoleOperation] {
        self.previous_authority.operations()
    }

    /// Desired named-query secret-output authority.
    #[must_use]
    pub fn desired_secret_outputs(&self) -> &[QuerySecretOutput] {
        self.desired_authority.secret_outputs()
    }

    /// Previously observed named-query secret-output authority.
    #[must_use]
    pub fn previous_secret_outputs(&self) -> &[QuerySecretOutput] {
        self.previous_authority.secret_outputs()
    }

    /// Complete desired authority set.
    #[must_use]
    pub const fn desired_authority(&self) -> &RoleAuthoritySet {
        &self.desired_authority
    }

    /// Complete predecessor authority set.
    #[must_use]
    pub const fn previous_authority(&self) -> &RoleAuthoritySet {
        &self.previous_authority
    }

    /// Exact role-widening approval, present only when additions exist.
    #[must_use]
    pub const fn widening_approval(&self) -> Option<&RoleWideningApproval> {
        self.widening_approval.as_ref()
    }
}

/// One credential destination with exact no-overwrite semantics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CredentialDestination {
    name: InstallationSymbol,
    role: InstallationSymbol,
    expected_current: Option<CapabilityId>,
    successor: CapabilityId,
}

impl CredentialDestination {
    /// Creates one empty-slot install or exact-predecessor replacement.
    pub fn new(
        name: InstallationSymbol,
        role: InstallationSymbol,
        expected_current: Option<CapabilityId>,
        successor: CapabilityId,
    ) -> Result<Self, InstallationPlanError> {
        if expected_current == Some(successor) {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::CredentialConflict,
            ));
        }
        Ok(Self {
            name,
            role,
            expected_current,
            successor,
        })
    }

    /// Symbolic destination name; this is never a host path.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }

    /// Symbolic role whose credential is installed.
    #[must_use]
    pub const fn role(&self) -> &InstallationSymbol {
        &self.role
    }

    /// Exact current capability that may be replaced, or `None` for must-be-empty.
    #[must_use]
    pub const fn expected_current(&self) -> Option<CapabilityId> {
        self.expected_current
    }

    /// Caller-stable successor capability identity; credential bytes are never retained.
    #[must_use]
    pub const fn successor(&self) -> CapabilityId {
        self.successor
    }
}

/// Only backup posture admitted for an installation-driven migration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MigrationBackupPolicy {
    /// Create and verify the operation-owned backup before staging.
    RequiredVerified,
}

/// Only downtime posture admitted by the current offline migration engine.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MigrationDowntimeClass {
    /// Reject application work for the complete migration operation.
    OfflineExclusive,
}

/// Exact, explicitly confirmed migration gate.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InstallationMigration {
    parent_version: ContractVersion,
    parent_bundle_hash: ContractBundleHash,
    successor_version: ContractVersion,
    successor_bundle_hash: ContractBundleHash,
    migration_hash: MigrationBundleHash,
    confirmation: MigrationBundleHash,
    backup_policy: MigrationBackupPolicy,
    downtime: MigrationDowntimeClass,
}

impl InstallationMigration {
    /// Creates the only safe migration shape admitted by an installation plan.
    pub fn new(
        parent_version: ContractVersion,
        parent_bundle_hash: ContractBundleHash,
        successor_version: ContractVersion,
        successor_bundle_hash: ContractBundleHash,
        migration_hash: MigrationBundleHash,
        confirmation: MigrationBundleHash,
    ) -> Result<Self, InstallationPlanError> {
        if parent_version >= successor_version || migration_hash != confirmation {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::UnsafeMigration,
            ));
        }
        Ok(Self {
            parent_version,
            parent_bundle_hash,
            successor_version,
            successor_bundle_hash,
            migration_hash,
            confirmation,
            backup_policy: MigrationBackupPolicy::RequiredVerified,
            downtime: MigrationDowntimeClass::OfflineExclusive,
        })
    }

    /// Exact predecessor version.
    #[must_use]
    pub const fn parent_version(self) -> ContractVersion {
        self.parent_version
    }

    /// Exact predecessor bundle.
    #[must_use]
    pub const fn parent_bundle_hash(self) -> ContractBundleHash {
        self.parent_bundle_hash
    }

    /// Exact successor version.
    #[must_use]
    pub const fn successor_version(self) -> ContractVersion {
        self.successor_version
    }

    /// Exact successor bundle.
    #[must_use]
    pub const fn successor_bundle_hash(self) -> ContractBundleHash {
        self.successor_bundle_hash
    }

    /// Exact compiled migration identity.
    #[must_use]
    pub const fn migration_hash(self) -> MigrationBundleHash {
        self.migration_hash
    }

    /// Exact caller confirmation; always equal to the migration hash.
    #[must_use]
    pub const fn confirmation(self) -> MigrationBundleHash {
        self.confirmation
    }

    /// Required backup policy.
    #[must_use]
    pub const fn backup_policy(self) -> MigrationBackupPolicy {
        self.backup_policy
    }

    /// Required downtime class.
    #[must_use]
    pub const fn downtime(self) -> MigrationDowntimeClass {
        self.downtime
    }
}

/// Exact completed portability export selected for an empty-destination reimport.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InstallationReimport {
    export_manifest_hash: ApplicationExportManifestHash,
    export_receipt_hash: ApplicationExportReceiptHash,
    portability_manifest_hash: ApplicationPortabilityManifestHash,
}

impl InstallationReimport {
    /// Binds the source receipt and compiler-closed portability mapping exactly.
    #[must_use]
    pub const fn new(
        export_manifest_hash: ApplicationExportManifestHash,
        export_receipt_hash: ApplicationExportReceiptHash,
        portability_manifest_hash: ApplicationPortabilityManifestHash,
    ) -> Self {
        Self {
            export_manifest_hash,
            export_receipt_hash,
            portability_manifest_hash,
        }
    }

    /// Exact completed export manifest identity.
    #[must_use]
    pub const fn export_manifest_hash(self) -> ApplicationExportManifestHash {
        self.export_manifest_hash
    }

    /// Exact completed portability-intent export receipt identity.
    #[must_use]
    pub const fn export_receipt_hash(self) -> ApplicationExportReceiptHash {
        self.export_receipt_hash
    }

    /// Exact compiler-closed portability manifest identity.
    #[must_use]
    pub const fn portability_manifest_hash(self) -> ApplicationPortabilityManifestHash {
        self.portability_manifest_hash
    }
}

/// First-class stable driver targets that must prove the installed identity.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum InstallationDriver {
    /// First-party Rust client.
    Rust,
    /// First-party TypeScript client.
    TypeScript,
    /// First-party Go client.
    Go,
    /// First-party Python client.
    Python,
}

impl InstallationDriver {
    #[doc(hidden)]
    pub const fn tag(self) -> &'static str {
        match self {
            Self::Rust => "rust",
            Self::TypeScript => "typescript",
            Self::Go => "go",
            Self::Python => "python",
        }
    }

    #[doc(hidden)]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "rust" => Self::Rust,
            "typescript" => Self::TypeScript,
            "go" => Self::Go,
            "python" => Self::Python,
            _ => return None,
        })
    }
}

/// Closed alpha application feature catalog consumed by installation planning.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum InstallationFeature {
    /// Authenticated remote TLS transport.
    RemoteTls,
    /// Compiler-visible bounded bulk commands.
    BulkCommands,
    /// Bounded operational RiffQL.
    OperationalQueries,
    /// Fenced workflow concurrency.
    WorkflowConcurrency,
    /// Principal-aware row policies.
    RowPolicies,
    /// Programmatic exact installation campaigns.
    InstallationCampaigns,
    /// Public export and compatibility lifecycle.
    DataLifecycle,
    /// Exact reviewed secret outputs from named RiffQL queries.
    QuerySecretOutputs,
}

impl InstallationFeature {
    /// Complete closed alpha feature catalog in canonical order.
    pub const ALL: [Self; 8] = [
        Self::RemoteTls,
        Self::BulkCommands,
        Self::OperationalQueries,
        Self::WorkflowConcurrency,
        Self::RowPolicies,
        Self::InstallationCampaigns,
        Self::DataLifecycle,
        Self::QuerySecretOutputs,
    ];

    /// Adapter-owned alpha features in canonical conformance order.
    pub const ADAPTER_CONFORMANCE: [Self; 7] = [
        Self::RemoteTls,
        Self::BulkCommands,
        Self::OperationalQueries,
        Self::WorkflowConcurrency,
        Self::RowPolicies,
        Self::InstallationCampaigns,
        Self::DataLifecycle,
    ];

    #[doc(hidden)]
    pub const fn tag(self) -> &'static str {
        match self {
            Self::RemoteTls => "remote_tls",
            Self::BulkCommands => "bulk_commands",
            Self::OperationalQueries => "operational_queries",
            Self::WorkflowConcurrency => "workflow_concurrency",
            Self::RowPolicies => "row_policies",
            Self::InstallationCampaigns => "installation_campaigns",
            Self::DataLifecycle => "data_lifecycle",
            Self::QuerySecretOutputs => "query_secret_outputs",
        }
    }

    #[doc(hidden)]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "remote_tls" => Self::RemoteTls,
            "bulk_commands" => Self::BulkCommands,
            "operational_queries" => Self::OperationalQueries,
            "workflow_concurrency" => Self::WorkflowConcurrency,
            "row_policies" => Self::RowPolicies,
            "installation_campaigns" => Self::InstallationCampaigns,
            "data_lifecycle" => Self::DataLifecycle,
            "query_secret_outputs" => Self::QuerySecretOutputs,
            _ => return None,
        })
    }
}

/// One bounded seed batch whose items remain ordinary compiled commands.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct InstallationSeed {
    name: InstallationSymbol,
    content_hash: GeneratedArtifactHash,
    item_count: u64,
}

/// Bounded terminal counters for one ordinary-command seed batch.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct InstalledSeedEvidence {
    name: InstallationSymbol,
    content_hash: GeneratedArtifactHash,
    succeeded: u64,
    replayed: u64,
}

impl InstalledSeedEvidence {
    /// Creates exact seed completion evidence without retaining item values.
    #[must_use]
    pub const fn new(
        name: InstallationSymbol,
        content_hash: GeneratedArtifactHash,
        succeeded: u64,
        replayed: u64,
    ) -> Self {
        Self {
            name,
            content_hash,
            succeeded,
            replayed,
        }
    }

    /// Symbolic seed name.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }

    /// Exact seed artifact identity.
    #[must_use]
    pub const fn content_hash(&self) -> GeneratedArtifactHash {
        self.content_hash
    }

    /// Newly completed command items.
    #[must_use]
    pub const fn succeeded(&self) -> u64 {
        self.succeeded
    }

    /// Previously completed command items recovered by idempotency.
    #[must_use]
    pub const fn replayed(&self) -> u64 {
        self.replayed
    }
}

impl InstallationSeed {
    /// Binds one seed artifact and its exact nonzero item count.
    pub fn new(
        name: InstallationSymbol,
        content_hash: GeneratedArtifactHash,
        item_count: u64,
    ) -> Result<Self, InstallationPlanError> {
        if item_count == 0 || item_count > MAX_SEED_BATCH_ITEMS {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::LimitExceeded,
            ));
        }
        Ok(Self {
            name,
            content_hash,
            item_count,
        })
    }

    /// Symbolic seed name.
    #[must_use]
    pub const fn name(&self) -> &InstallationSymbol {
        &self.name
    }

    /// Exact content identity without exposing seed values.
    #[must_use]
    pub const fn content_hash(&self) -> GeneratedArtifactHash {
        self.content_hash
    }

    /// Number of individually idempotent ordinary command items.
    #[must_use]
    pub const fn item_count(&self) -> u64 {
        self.item_count
    }
}

/// Complete local input to deterministic installation-plan compilation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApplicationInstallationPlanInput {
    /// Symbolic application name.
    pub application: InstallationSymbol,
    /// Exact author-source identity.
    pub source_hash: ApplicationSourceHash,
    /// Exact compiler-owned lock identity.
    pub lock_hash: ApplicationLockHash,
    /// Exact application-manifest identity.
    pub manifest_hash: ApplicationManifestHash,
    /// Exact installation authority target.
    pub target: InstallationTarget,
    /// Exact candidate contract.
    pub contract: InstallationContract,
    /// Complete exact generated artifact set.
    pub artifacts: Vec<InstallationArtifact>,
    /// Optional explicit offline migration gate.
    pub migration: Option<InstallationMigration>,
    /// Exact symbolic desired roles and predecessor authority observations.
    pub roles: Vec<InstallationRole>,
    /// Optional exact completed portability export reconstituted before credentials exist.
    pub reimport: Option<InstallationReimport>,
    /// Exact empty-or-predecessor-bound credential destinations.
    pub credential_destinations: Vec<CredentialDestination>,
    /// Public drivers that must prove the installed identity.
    pub drivers: Vec<InstallationDriver>,
    /// Bounded ordinary-command seed batches.
    pub seeds: Vec<InstallationSeed>,
    /// Closed features required by the application.
    pub required_features: Vec<InstallationFeature>,
    /// Optional exact adapter conformance manifest identity.
    pub adapter_manifest_hash: Option<AdapterConformanceManifestHash>,
}

/// One immutable content-addressed installation plan.
#[derive(Clone, Eq, PartialEq)]
pub struct ApplicationInstallationPlan {
    schema: ApplicationInstallationPlanSchema,
    input: ApplicationInstallationPlanInput,
    identity: ApplicationInstallationPlanHash,
    canonical_bytes: Vec<u8>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ApplicationInstallationPlanSchema {
    V1,
    V2,
    V3,
}

impl ApplicationInstallationPlanSchema {
    fn for_input(input: &ApplicationInstallationPlanInput) -> Self {
        if has_secret_output_authority(input) {
            Self::V3
        } else if input.reimport.is_some() {
            Self::V2
        } else {
            Self::V1
        }
    }

    const fn name(self) -> &'static str {
        match self {
            Self::V1 => APPLICATION_INSTALLATION_PLAN_SCHEMA_V1,
            Self::V2 => APPLICATION_INSTALLATION_PLAN_SCHEMA_V2,
            Self::V3 => APPLICATION_INSTALLATION_PLAN_SCHEMA_V3,
        }
    }
}

impl ApplicationInstallationPlan {
    /// Compiles a canonical plan without remote mutation.
    pub fn compile(
        mut input: ApplicationInstallationPlanInput,
    ) -> Result<Self, InstallationPlanError> {
        validate_and_sort(&mut input)?;
        let schema = ApplicationInstallationPlanSchema::for_input(&input);
        let dto = PlanDto::from_input(&input, schema);
        let mut canonical_bytes = serde_json::to_vec(&dto)
            .map_err(|_| InstallationPlanError::new(InstallationPlanErrorKind::InvalidEncoding))?;
        canonical_bytes.push(b'\n');
        if canonical_bytes.len() > MAX_INSTALLATION_PLAN_BYTES {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::LimitExceeded,
            ));
        }
        let identity = hash_application_installation_plan(&canonical_bytes);
        Ok(Self {
            schema,
            input,
            identity,
            canonical_bytes,
        })
    }

    /// Strictly decodes canonical bytes and revalidates every semantic gate.
    pub fn decode_canonical(bytes: &[u8]) -> Result<Self, InstallationPlanError> {
        if bytes.is_empty() || bytes.len() > MAX_INSTALLATION_PLAN_BYTES {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::LimitExceeded,
            ));
        }
        let dto: PlanDto = serde_json::from_slice(bytes)
            .map_err(|_| InstallationPlanError::new(InstallationPlanErrorKind::InvalidEncoding))?;
        let schema = dto.schema()?;
        let plan = Self::compile(dto.into_input(schema)?)?;
        if plan.schema != schema {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidShape,
            ));
        }
        if plan.canonical_bytes != bytes {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::NonCanonical,
            ));
        }
        Ok(plan)
    }

    /// Exact plan identity.
    #[must_use]
    pub const fn identity(&self) -> ApplicationInstallationPlanHash {
        self.identity
    }

    /// Complete validated input retained by the plan.
    #[must_use]
    pub const fn input(&self) -> &ApplicationInstallationPlanInput {
        &self.input
    }

    /// Canonical compatibility bytes.
    #[must_use]
    pub fn canonical_bytes(&self) -> &[u8] {
        &self.canonical_bytes
    }

    /// Canonical installation-plan schema selected by the least-sufficient writer.
    #[must_use]
    pub const fn schema(&self) -> &'static str {
        self.schema.name()
    }

    /// Validates exact public-driver proof for a transport submission.
    pub fn validate_driver_proof(
        &self,
        drivers: &[InstallationDriver],
    ) -> Result<(), InstallationCampaignError> {
        if drivers == self.input.drivers {
            Ok(())
        } else {
            Err(InstallationCampaignError::new(
                InstallationCampaignErrorKind::EvidenceMismatch,
            ))
        }
    }

    /// Validates bounded seed receipts for a transport submission.
    pub fn validate_seed_receipts(
        &self,
        seeds: &[InstalledSeedEvidence],
    ) -> Result<(), InstallationCampaignError> {
        let valid = seeds.len() == self.input.seeds.len()
            && seeds
                .iter()
                .zip(&self.input.seeds)
                .all(|(observed, expected)| {
                    observed.name() == expected.name()
                        && observed.content_hash() == expected.content_hash()
                        && observed.succeeded().checked_add(observed.replayed())
                            == Some(expected.item_count())
                });
        if valid {
            Ok(())
        } else {
            Err(InstallationCampaignError::new(
                InstallationCampaignErrorKind::EvidenceMismatch,
            ))
        }
    }
}

impl fmt::Debug for ApplicationInstallationPlan {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ApplicationInstallationPlan")
            .field("identity", &self.identity)
            .field("application", &self.input.application)
            .field("target", &self.input.target)
            .field("artifacts", &self.input.artifacts.len())
            .field("roles", &self.input.roles.len())
            .field("credentials", &self.input.credential_destinations.len())
            .field("seeds", &self.input.seeds.len())
            .finish_non_exhaustive()
    }
}

/// Closed deterministic plan-compilation failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InstallationPlanErrorKind {
    /// A bounded symbolic identifier is invalid.
    InvalidIdentifier,
    /// One hard input or encoded-size bound was exceeded.
    LimitExceeded,
    /// A supposedly unique symbolic key was duplicated.
    Duplicate,
    /// Exact source, lock, manifest, contract, or artifact identities disagree.
    IdentityMismatch,
    /// An existing role would gain authority without explicit exact approval.
    ApprovalRequired,
    /// A supplied authority approval is stale, broader, or otherwise inexact.
    InvalidApproval,
    /// Migration confirmation, ordering, backup, or downtime semantics are unsafe.
    UnsafeMigration,
    /// A credential replacement is ambiguous or would overwrite its predecessor.
    CredentialConflict,
    /// The decoded version is not supported.
    UnsupportedVersion,
    /// The submitted document is malformed.
    InvalidEncoding,
    /// The submitted document has valid meaning but noncanonical bytes.
    NonCanonical,
    /// The submitted values do not form a closed installation shape.
    InvalidShape,
}

/// Bounded, redaction-safe plan compilation failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InstallationPlanError {
    kind: InstallationPlanErrorKind,
}

impl InstallationPlanError {
    const fn new(kind: InstallationPlanErrorKind) -> Self {
        Self { kind }
    }

    /// Stable error kind.
    #[must_use]
    pub const fn kind(self) -> InstallationPlanErrorKind {
        self.kind
    }

    #[doc(hidden)]
    pub const fn from_kind_for_diff(kind: InstallationPlanErrorKind) -> Self {
        Self::new(kind)
    }
}

impl fmt::Display for InstallationPlanError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self.kind {
            InstallationPlanErrorKind::InvalidIdentifier => {
                "application installation symbol is invalid"
            }
            InstallationPlanErrorKind::LimitExceeded => {
                "application installation input exceeds a hard bound"
            }
            InstallationPlanErrorKind::Duplicate => {
                "application installation input contains a duplicate symbolic key"
            }
            InstallationPlanErrorKind::IdentityMismatch => {
                "application installation exact identities disagree"
            }
            InstallationPlanErrorKind::ApprovalRequired => {
                "application role widening requires explicit exact approval"
            }
            InstallationPlanErrorKind::InvalidApproval => {
                "application role widening approval is stale or inexact"
            }
            InstallationPlanErrorKind::UnsafeMigration => {
                "application migration gate is absent, stale, or unsafe"
            }
            InstallationPlanErrorKind::CredentialConflict => {
                "application credential destination cannot be replaced safely"
            }
            InstallationPlanErrorKind::UnsupportedVersion => {
                "application installation plan version is unsupported"
            }
            InstallationPlanErrorKind::InvalidEncoding => {
                "application installation plan encoding is invalid"
            }
            InstallationPlanErrorKind::NonCanonical => {
                "application installation plan encoding is not canonical"
            }
            InstallationPlanErrorKind::InvalidShape => {
                "application installation plan shape is invalid"
            }
        })
    }
}

impl Error for InstallationPlanError {}

/// Closed campaign state-machine failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InstallationCampaignErrorKind {
    /// Caller supplied another campaign identity for retained state.
    CampaignIdentityMismatch,
    /// Caller reused a campaign identity for another exact plan.
    PlanIdentityMismatch,
    /// A stage was skipped, repeated, or submitted out of order.
    StageOutOfOrder,
    /// Observed stage state differs from the exact plan.
    EvidenceMismatch,
    /// The campaign already sealed its terminal receipt.
    AlreadyTerminal,
    /// A canonical campaign artifact exceeds its hard bound.
    LimitExceeded,
    /// A canonical campaign artifact is malformed.
    InvalidEncoding,
    /// A canonical campaign artifact has a valid shape but inexact bytes.
    NonCanonical,
    /// A canonical campaign artifact version is unsupported.
    UnsupportedVersion,
}

/// Bounded, redaction-safe campaign error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct InstallationCampaignError {
    kind: InstallationCampaignErrorKind,
}

impl InstallationCampaignError {
    /// Constructs one closed error for the application-owned campaign machine.
    #[doc(hidden)]
    #[must_use]
    pub const fn new(kind: InstallationCampaignErrorKind) -> Self {
        Self { kind }
    }

    /// Maps a plan codec failure without exposing its source document.
    #[doc(hidden)]
    #[must_use]
    pub fn from_plan_error(error: InstallationPlanError) -> Self {
        match error.kind() {
            InstallationPlanErrorKind::LimitExceeded => {
                Self::new(InstallationCampaignErrorKind::LimitExceeded)
            }
            InstallationPlanErrorKind::UnsupportedVersion => {
                Self::new(InstallationCampaignErrorKind::UnsupportedVersion)
            }
            InstallationPlanErrorKind::NonCanonical => {
                Self::new(InstallationCampaignErrorKind::NonCanonical)
            }
            _ => Self::new(InstallationCampaignErrorKind::InvalidEncoding),
        }
    }

    /// Stable campaign failure kind.
    #[must_use]
    pub const fn kind(self) -> InstallationCampaignErrorKind {
        self.kind
    }
}

impl fmt::Display for InstallationCampaignError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self.kind {
            InstallationCampaignErrorKind::CampaignIdentityMismatch => {
                "application installation campaign identity does not match retained state"
            }
            InstallationCampaignErrorKind::PlanIdentityMismatch => {
                "application installation campaign identity is bound to another exact plan"
            }
            InstallationCampaignErrorKind::StageOutOfOrder => {
                "application installation stage is not the exact next stage"
            }
            InstallationCampaignErrorKind::EvidenceMismatch => {
                "application installation stage evidence differs from the exact plan"
            }
            InstallationCampaignErrorKind::AlreadyTerminal => {
                "application installation campaign already has a terminal receipt"
            }
            InstallationCampaignErrorKind::LimitExceeded => {
                "application installation campaign artifact exceeds a hard bound"
            }
            InstallationCampaignErrorKind::InvalidEncoding => {
                "application installation campaign artifact encoding is invalid"
            }
            InstallationCampaignErrorKind::NonCanonical => {
                "application installation campaign artifact encoding is not canonical"
            }
            InstallationCampaignErrorKind::UnsupportedVersion => {
                "application installation campaign artifact version is unsupported"
            }
        })
    }
}

impl Error for InstallationCampaignError {}

fn validate_and_sort(
    input: &mut ApplicationInstallationPlanInput,
) -> Result<(), InstallationPlanError> {
    if input.artifacts.is_empty()
        || input.artifacts.len() > MAX_INSTALLATION_ARTIFACTS
        || input.roles.is_empty()
        || input.roles.len() > MAX_INSTALLATION_ROLES
        || input.credential_destinations.len() > MAX_CREDENTIAL_DESTINATIONS
        || input.seeds.len() > MAX_INSTALLATION_SEEDS
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::LimitExceeded,
        ));
    }
    input.artifacts.sort();
    if input
        .artifacts
        .windows(2)
        .any(|pair| (pair[0].kind, &pair[0].name) == (pair[1].kind, &pair[1].name))
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::Duplicate,
        ));
    }
    if !input
        .artifacts
        .iter()
        .any(|artifact| artifact.kind == InstallationArtifactKind::Manifest)
        || !input
            .artifacts
            .iter()
            .any(|artifact| artifact.kind == InstallationArtifactKind::ContractBundle)
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::InvalidShape,
        ));
    }
    input
        .roles
        .sort_by(|left, right| left.name.cmp(&right.name));
    ensure_unique_by(input.roles.iter().map(|role| &role.name))?;
    input
        .credential_destinations
        .sort_by(|left, right| left.name.cmp(&right.name));
    ensure_unique_by(
        input
            .credential_destinations
            .iter()
            .map(|destination| &destination.name),
    )?;
    for destination in &input.credential_destinations {
        let role = input
            .roles
            .binary_search_by(|role| role.name.cmp(&destination.role))
            .ok()
            .map(|index| &input.roles[index])
            .ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::IdentityMismatch)
            })?;
        if role.previous_role_hash().is_some() != destination.expected_current().is_some() {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::CredentialConflict,
            ));
        }
    }
    input.seeds.sort();
    ensure_unique_by(input.seeds.iter().map(|seed| &seed.name))?;
    sort_unique(&mut input.drivers)?;
    let has_secret_outputs = has_secret_output_authority(input);
    if has_secret_outputs
        && !input
            .required_features
            .contains(&InstallationFeature::QuerySecretOutputs)
    {
        input
            .required_features
            .push(InstallationFeature::QuerySecretOutputs);
    } else if !has_secret_outputs
        && input
            .required_features
            .contains(&InstallationFeature::QuerySecretOutputs)
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::InvalidShape,
        ));
    }
    sort_unique(&mut input.required_features)?;
    if input.drivers.is_empty()
        || !input
            .required_features
            .contains(&InstallationFeature::InstallationCampaigns)
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::InvalidShape,
        ));
    }
    if let Some(migration) = input.migration
        && (migration.successor_version != input.contract.version
            || migration.successor_bundle_hash != input.contract.bundle_hash
            || migration.migration_hash != migration.confirmation
            || !input
                .artifacts
                .iter()
                .any(|artifact| artifact.kind == InstallationArtifactKind::MigrationBundle))
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::IdentityMismatch,
        ));
    }
    let adapter_artifact = input
        .artifacts
        .iter()
        .find(|artifact| artifact.kind == InstallationArtifactKind::AdapterManifest);
    if input.adapter_manifest_hash.is_some() != adapter_artifact.is_some()
        || input.adapter_manifest_hash.is_some_and(|manifest_hash| {
            adapter_artifact
                .is_none_or(|artifact| artifact.content_hash.as_bytes() != manifest_hash.as_bytes())
        })
    {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::IdentityMismatch,
        ));
    }
    Ok(())
}

fn has_secret_output_authority(input: &ApplicationInstallationPlanInput) -> bool {
    input.roles.iter().any(|role| {
        !role.desired_secret_outputs().is_empty() || !role.previous_secret_outputs().is_empty()
    })
}

fn sort_unique<T: Ord>(values: &mut [T]) -> Result<(), InstallationPlanError> {
    values.sort();
    if values.windows(2).any(|pair| pair[0] == pair[1]) {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::Duplicate,
        ));
    }
    Ok(())
}

fn ensure_unique_by<'a, T: Ord + 'a>(
    values: impl Iterator<Item = &'a T>,
) -> Result<(), InstallationPlanError> {
    let mut seen = BTreeSet::new();
    if values.into_iter().any(|value| !seen.insert(value)) {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::Duplicate,
        ));
    }
    Ok(())
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct PlanDto {
    schema: String,
    application: String,
    source_hash: String,
    lock_hash: String,
    manifest_hash: String,
    target: TargetDto,
    contract: ContractDto,
    artifacts: Vec<ArtifactDto>,
    migration: Option<MigrationDto>,
    roles: Vec<RoleDto>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    reimport: Option<ReimportDto>,
    credential_destinations: Vec<CredentialDto>,
    drivers: Vec<String>,
    seeds: Vec<SeedDto>,
    required_features: Vec<String>,
    adapter_manifest_hash: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TargetDto {
    database: String,
    environment: String,
    lineage: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ContractDto {
    version: u64,
    bundle_hash: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ArtifactDto {
    kind: String,
    name: String,
    content_hash: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct OperationDto {
    kind: String,
    name: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ApprovalDto {
    expected_previous_role: String,
    additions: Vec<AuthorityAtomDto>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RoleDto {
    name: String,
    role_hash: String,
    previous_role_hash: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    desired_operations: Option<Vec<OperationDto>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    previous_operations: Option<Vec<OperationDto>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    desired_authority: Option<Vec<AuthorityAtomDto>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    previous_authority: Option<Vec<AuthorityAtomDto>>,
    widening_approval: Option<ApprovalDto>,
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum AuthorityAtomDto {
    Operation(OperationDto),
    QuerySecretOutput(SecretOutputDto),
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SecretOutputDto {
    query: String,
    entity: String,
    field: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CredentialDto {
    name: String,
    role: String,
    expected_current: Option<String>,
    successor: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct MigrationDto {
    parent_version: u64,
    parent_bundle_hash: String,
    successor_version: u64,
    successor_bundle_hash: String,
    migration_hash: String,
    confirmation: String,
    backup_policy: String,
    downtime: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ReimportDto {
    export_manifest_hash: String,
    export_receipt_hash: String,
    portability_manifest_hash: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SeedDto {
    name: String,
    content_hash: String,
    item_count: u64,
}

impl PlanDto {
    fn from_input(
        input: &ApplicationInstallationPlanInput,
        schema: ApplicationInstallationPlanSchema,
    ) -> Self {
        Self {
            schema: schema.name().to_owned(),
            application: input.application.as_str().to_owned(),
            source_hash: hex32(input.source_hash.as_bytes()),
            lock_hash: hex32(input.lock_hash.as_bytes()),
            manifest_hash: hex32(input.manifest_hash.as_bytes()),
            target: TargetDto {
                database: input.target.database.as_str().to_owned(),
                environment: input.target.environment.as_str().to_owned(),
                lineage: input.target.lineage.as_str().to_owned(),
            },
            contract: ContractDto {
                version: input.contract.version.get(),
                bundle_hash: hex32(input.contract.bundle_hash.as_bytes()),
            },
            artifacts: input
                .artifacts
                .iter()
                .map(|artifact| ArtifactDto {
                    kind: artifact.kind.tag().to_owned(),
                    name: artifact.name.as_str().to_owned(),
                    content_hash: hex32(artifact.content_hash.as_bytes()),
                })
                .collect(),
            migration: input.migration.map(|migration| MigrationDto {
                parent_version: migration.parent_version.get(),
                parent_bundle_hash: hex32(migration.parent_bundle_hash.as_bytes()),
                successor_version: migration.successor_version.get(),
                successor_bundle_hash: hex32(migration.successor_bundle_hash.as_bytes()),
                migration_hash: hex32(migration.migration_hash.as_bytes()),
                confirmation: hex32(migration.confirmation.as_bytes()),
                backup_policy: "required_verified".to_owned(),
                downtime: "offline_exclusive".to_owned(),
            }),
            roles: input
                .roles
                .iter()
                .map(|role| RoleDto::from_role(role, schema))
                .collect(),
            reimport: input.reimport.map(|reimport| ReimportDto {
                export_manifest_hash: hex32(reimport.export_manifest_hash.as_bytes()),
                export_receipt_hash: hex32(reimport.export_receipt_hash.as_bytes()),
                portability_manifest_hash: hex32(reimport.portability_manifest_hash.as_bytes()),
            }),
            credential_destinations: input
                .credential_destinations
                .iter()
                .map(|destination| CredentialDto {
                    name: destination.name.as_str().to_owned(),
                    role: destination.role.as_str().to_owned(),
                    expected_current: destination
                        .expected_current
                        .map(|value| hex16(value.as_bytes())),
                    successor: hex16(destination.successor.as_bytes()),
                })
                .collect(),
            drivers: input
                .drivers
                .iter()
                .map(|driver| driver.tag().to_owned())
                .collect(),
            seeds: input
                .seeds
                .iter()
                .map(|seed| SeedDto {
                    name: seed.name.as_str().to_owned(),
                    content_hash: hex32(seed.content_hash.as_bytes()),
                    item_count: seed.item_count,
                })
                .collect(),
            required_features: input
                .required_features
                .iter()
                .map(|feature| feature.tag().to_owned())
                .collect(),
            adapter_manifest_hash: input
                .adapter_manifest_hash
                .map(|value| hex32(value.as_bytes())),
        }
    }

    fn schema(&self) -> Result<ApplicationInstallationPlanSchema, InstallationPlanError> {
        match self.schema.as_str() {
            APPLICATION_INSTALLATION_PLAN_SCHEMA_V1 => Ok(ApplicationInstallationPlanSchema::V1),
            APPLICATION_INSTALLATION_PLAN_SCHEMA_V2 => Ok(ApplicationInstallationPlanSchema::V2),
            APPLICATION_INSTALLATION_PLAN_SCHEMA_V3 => Ok(ApplicationInstallationPlanSchema::V3),
            _ => Err(InstallationPlanError::new(
                InstallationPlanErrorKind::UnsupportedVersion,
            )),
        }
    }

    fn into_input(
        self,
        schema: ApplicationInstallationPlanSchema,
    ) -> Result<ApplicationInstallationPlanInput, InstallationPlanError> {
        if matches!(schema, ApplicationInstallationPlanSchema::V1) && self.reimport.is_some()
            || matches!(schema, ApplicationInstallationPlanSchema::V2) && self.reimport.is_none()
        {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidShape,
            ));
        }
        Ok(ApplicationInstallationPlanInput {
            application: InstallationSymbol::new(self.application)?,
            source_hash: ApplicationSourceHash::from_bytes(parse_hex32(&self.source_hash)?),
            lock_hash: ApplicationLockHash::from_bytes(parse_hex32(&self.lock_hash)?),
            manifest_hash: ApplicationManifestHash::from_bytes(parse_hex32(&self.manifest_hash)?),
            target: InstallationTarget::new(
                DatabaseAlias::new(self.target.database).map_err(|_| {
                    InstallationPlanError::new(InstallationPlanErrorKind::InvalidIdentifier)
                })?,
                Environment::new(self.target.environment).map_err(|_| {
                    InstallationPlanError::new(InstallationPlanErrorKind::InvalidIdentifier)
                })?,
                ContractLineage::new(self.target.lineage).map_err(|_| {
                    InstallationPlanError::new(InstallationPlanErrorKind::InvalidIdentifier)
                })?,
            ),
            contract: InstallationContract::new(
                ContractVersion::new(self.contract.version).ok_or_else(|| {
                    InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
                })?,
                ContractBundleHash::from_bytes(parse_hex32(&self.contract.bundle_hash)?),
            ),
            artifacts: self
                .artifacts
                .into_iter()
                .map(ArtifactDto::into_artifact)
                .collect::<Result<Vec<_>, _>>()?,
            migration: self
                .migration
                .map(MigrationDto::into_migration)
                .transpose()?,
            roles: self
                .roles
                .into_iter()
                .map(|role| role.into_role(schema))
                .collect::<Result<Vec<_>, _>>()?,
            reimport: self.reimport.map(ReimportDto::into_reimport).transpose()?,
            credential_destinations: self
                .credential_destinations
                .into_iter()
                .map(CredentialDto::into_destination)
                .collect::<Result<Vec<_>, _>>()?,
            drivers: self
                .drivers
                .into_iter()
                .map(|driver| {
                    InstallationDriver::parse(&driver).ok_or_else(|| {
                        InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
                    })
                })
                .collect::<Result<Vec<_>, _>>()?,
            seeds: self
                .seeds
                .into_iter()
                .map(SeedDto::into_seed)
                .collect::<Result<Vec<_>, _>>()?,
            required_features: self
                .required_features
                .into_iter()
                .map(|feature| {
                    InstallationFeature::parse(&feature).ok_or_else(|| {
                        InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
                    })
                })
                .collect::<Result<Vec<_>, _>>()?,
            adapter_manifest_hash: self
                .adapter_manifest_hash
                .map(|hash| parse_hex32(&hash).map(AdapterConformanceManifestHash::from_bytes))
                .transpose()?,
        })
    }
}

impl ArtifactDto {
    fn into_artifact(self) -> Result<InstallationArtifact, InstallationPlanError> {
        Ok(InstallationArtifact::new(
            InstallationArtifactKind::parse(&self.kind).ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?,
            InstallationSymbol::new(self.name)?,
            GeneratedArtifactHash::from_bytes(parse_hex32(&self.content_hash)?),
        ))
    }
}

impl ReimportDto {
    fn into_reimport(self) -> Result<InstallationReimport, InstallationPlanError> {
        Ok(InstallationReimport::new(
            ApplicationExportManifestHash::from_bytes(parse_hex32(&self.export_manifest_hash)?),
            ApplicationExportReceiptHash::from_bytes(parse_hex32(&self.export_receipt_hash)?),
            ApplicationPortabilityManifestHash::from_bytes(parse_hex32(
                &self.portability_manifest_hash,
            )?),
        ))
    }
}

impl OperationDto {
    fn from_operation(operation: &RoleOperation) -> Self {
        Self {
            kind: operation.kind.tag().to_owned(),
            name: operation.name.as_str().to_owned(),
        }
    }

    fn into_operation(self) -> Result<RoleOperation, InstallationPlanError> {
        Ok(RoleOperation::new(
            RoleOperationKind::parse(&self.kind).ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?,
            InstallationSymbol::new(self.name)?,
        ))
    }
}

impl AuthorityAtomDto {
    fn from_atom(atom: &RoleAuthorityAtom) -> Self {
        match atom {
            RoleAuthorityAtom::Operation(operation) => {
                Self::Operation(OperationDto::from_operation(operation))
            }
            RoleAuthorityAtom::QuerySecretOutput(output) => {
                Self::QuerySecretOutput(SecretOutputDto {
                    query: output.query.as_str().to_owned(),
                    entity: output.entity.as_str().to_owned(),
                    field: output.field.as_str().to_owned(),
                })
            }
        }
    }

    fn into_atom(self) -> Result<RoleAuthorityAtom, InstallationPlanError> {
        Ok(match self {
            Self::Operation(operation) => RoleAuthorityAtom::Operation(operation.into_operation()?),
            Self::QuerySecretOutput(output) => {
                RoleAuthorityAtom::QuerySecretOutput(QuerySecretOutput::new(
                    InstallationSymbol::new(output.query)?,
                    InstallationSymbol::new(output.entity)?,
                    InstallationSymbol::new(output.field)?,
                ))
            }
        })
    }
}

impl RoleDto {
    fn from_role(role: &InstallationRole, schema: ApplicationInstallationPlanSchema) -> Self {
        let uses_authority = schema == ApplicationInstallationPlanSchema::V3;
        Self {
            name: role.name.as_str().to_owned(),
            role_hash: hex32(role.role_hash.as_bytes()),
            previous_role_hash: role.previous_role_hash.map(|hash| hex32(hash.as_bytes())),
            desired_operations: (!uses_authority).then(|| {
                role.desired_operations()
                    .iter()
                    .map(OperationDto::from_operation)
                    .collect()
            }),
            previous_operations: (!uses_authority).then(|| {
                role.previous_operations()
                    .iter()
                    .map(OperationDto::from_operation)
                    .collect()
            }),
            desired_authority: uses_authority.then(|| {
                role.desired_authority()
                    .atoms()
                    .iter()
                    .map(AuthorityAtomDto::from_atom)
                    .collect()
            }),
            previous_authority: uses_authority.then(|| {
                role.previous_authority()
                    .atoms()
                    .iter()
                    .map(AuthorityAtomDto::from_atom)
                    .collect()
            }),
            widening_approval: role.widening_approval.as_ref().map(|approval| ApprovalDto {
                expected_previous_role: hex32(approval.expected_previous_role.as_bytes()),
                additions: approval
                    .additions
                    .iter()
                    .map(AuthorityAtomDto::from_atom)
                    .collect(),
            }),
        }
    }

    fn into_role(
        self,
        schema: ApplicationInstallationPlanSchema,
    ) -> Result<InstallationRole, InstallationPlanError> {
        let uses_authority = schema == ApplicationInstallationPlanSchema::V3;
        let shape_is_exact = if uses_authority {
            self.desired_authority.is_some()
                && self.previous_authority.is_some()
                && self.desired_operations.is_none()
                && self.previous_operations.is_none()
        } else {
            self.desired_authority.is_none()
                && self.previous_authority.is_none()
                && self.desired_operations.is_some()
                && self.previous_operations.is_some()
        };
        if !shape_is_exact {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::InvalidShape,
            ));
        }
        let approval = self
            .widening_approval
            .map(|approval| {
                RoleWideningApproval::new_authority(
                    ApplicationRoleHash::from_bytes(parse_hex32(&approval.expected_previous_role)?),
                    approval
                        .additions
                        .into_iter()
                        .map(AuthorityAtomDto::into_atom)
                        .collect::<Result<Vec<_>, _>>()?,
                )
            })
            .transpose()?;
        let authority = |atoms: Vec<AuthorityAtomDto>| {
            let mut operations = Vec::new();
            let mut secret_outputs = Vec::new();
            for atom in atoms {
                match atom.into_atom()? {
                    RoleAuthorityAtom::Operation(operation) => operations.push(operation),
                    RoleAuthorityAtom::QuerySecretOutput(output) => secret_outputs.push(output),
                }
            }
            RoleAuthoritySet::new(operations, secret_outputs)
        };
        let desired_authority = if uses_authority {
            authority(self.desired_authority.ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?)?
        } else {
            RoleAuthoritySet::new(
                self.desired_operations
                    .ok_or_else(|| {
                        InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
                    })?
                    .into_iter()
                    .map(OperationDto::into_operation)
                    .collect::<Result<Vec<_>, _>>()?,
                vec![],
            )?
        };
        let previous_authority = if uses_authority {
            authority(self.previous_authority.ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?)?
        } else {
            RoleAuthoritySet::new(
                self.previous_operations
                    .ok_or_else(|| {
                        InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
                    })?
                    .into_iter()
                    .map(OperationDto::into_operation)
                    .collect::<Result<Vec<_>, _>>()?,
                vec![],
            )?
        };
        InstallationRole::new_with_authority(
            InstallationSymbol::new(self.name)?,
            ApplicationRoleHash::from_bytes(parse_hex32(&self.role_hash)?),
            self.previous_role_hash
                .map(|hash| parse_hex32(&hash).map(ApplicationRoleHash::from_bytes))
                .transpose()?,
            desired_authority,
            previous_authority,
            approval,
        )
    }
}

impl CredentialDto {
    fn into_destination(self) -> Result<CredentialDestination, InstallationPlanError> {
        CredentialDestination::new(
            InstallationSymbol::new(self.name)?,
            InstallationSymbol::new(self.role)?,
            self.expected_current
                .map(|value| parse_capability_id(&value))
                .transpose()?,
            parse_capability_id(&self.successor)?,
        )
    }
}

impl MigrationDto {
    fn into_migration(self) -> Result<InstallationMigration, InstallationPlanError> {
        if self.backup_policy != "required_verified" || self.downtime != "offline_exclusive" {
            return Err(InstallationPlanError::new(
                InstallationPlanErrorKind::UnsafeMigration,
            ));
        }
        InstallationMigration::new(
            ContractVersion::new(self.parent_version).ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?,
            ContractBundleHash::from_bytes(parse_hex32(&self.parent_bundle_hash)?),
            ContractVersion::new(self.successor_version).ok_or_else(|| {
                InstallationPlanError::new(InstallationPlanErrorKind::InvalidShape)
            })?,
            ContractBundleHash::from_bytes(parse_hex32(&self.successor_bundle_hash)?),
            MigrationBundleHash::from_bytes(parse_hex32(&self.migration_hash)?),
            MigrationBundleHash::from_bytes(parse_hex32(&self.confirmation)?),
        )
    }
}

impl SeedDto {
    fn into_seed(self) -> Result<InstallationSeed, InstallationPlanError> {
        InstallationSeed::new(
            InstallationSymbol::new(self.name)?,
            GeneratedArtifactHash::from_bytes(parse_hex32(&self.content_hash)?),
            self.item_count,
        )
    }
}

#[doc(hidden)]
pub fn hex32(bytes: &[u8; 32]) -> String {
    hex(bytes)
}

#[doc(hidden)]
pub fn hex16(bytes: &[u8; 16]) -> String {
    hex(bytes)
}

fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
        output.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
    }
    output
}

#[doc(hidden)]
pub fn parse_hex32(value: &str) -> Result<[u8; 32], InstallationPlanError> {
    parse_hex(value)
}

#[doc(hidden)]
pub fn parse_hex16(value: &str) -> Result<[u8; 16], InstallationPlanError> {
    parse_hex(value)
}

fn parse_hex<const N: usize>(value: &str) -> Result<[u8; N], InstallationPlanError> {
    if value.len() != N * 2 {
        return Err(InstallationPlanError::new(
            InstallationPlanErrorKind::InvalidEncoding,
        ));
    }
    let mut bytes = [0_u8; N];
    for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
        bytes[index] = (hex_nibble(pair[0])? << 4) | hex_nibble(pair[1])?;
    }
    Ok(bytes)
}

fn hex_nibble(byte: u8) -> Result<u8, InstallationPlanError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        _ => Err(InstallationPlanError::new(
            InstallationPlanErrorKind::InvalidEncoding,
        )),
    }
}

fn parse_capability_id(value: &str) -> Result<CapabilityId, InstallationPlanError> {
    CapabilityId::from_bytes(parse_hex16(value)?)
        .map_err(|_| InstallationPlanError::new(InstallationPlanErrorKind::InvalidEncoding))
}