riffdb-application 0.1.0

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

use riffdb_types::{
    AdapterConformanceManifestHash, ApplicationLockHash, ApplicationManifestHash,
    ApplicationRoleHash, ContractBundleHash, ContractLineage, ContractVersion,
    GeneratedArtifactHash, MAX_ADAPTER_PROBE_ITEMS, MigrationBundleHash,
    hash_adapter_conformance_manifest,
};
use serde::{Deserialize, Serialize};

use crate::{
    ApplicationInstallationPlan, InstallationArtifact, InstallationArtifactKind,
    InstallationContract, InstallationDriver, InstallationFeature, InstallationSymbol,
    RoleOperation, RoleOperationKind,
};

/// Canonical schema for adapter-owned conformance manifests.
pub const ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V1: &str = "riffdb.adapter-conformance-manifest/v1";
/// Current schema requiring an explicit disposition for every closed alpha feature.
pub const ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V2: &str = "riffdb.adapter-conformance-manifest/v2";
/// Maximum canonical manifest size.
pub const MAX_ADAPTER_CONFORMANCE_MANIFEST_BYTES: usize = 1_048_576;
/// Maximum feature claims in one manifest.
pub const MAX_ADAPTER_FEATURE_CLAIMS: usize = 32;
/// Maximum exact artifacts in one manifest.
pub const MAX_ADAPTER_ARTIFACTS: usize = 256;
/// Maximum exact roles in one manifest.
pub const MAX_ADAPTER_ROLES: usize = 128;
/// Maximum driver/runtime requirements in one manifest.
pub const MAX_ADAPTER_DRIVERS: usize = 16;
/// Maximum supported platforms per driver requirement.
pub const MAX_ADAPTER_PLATFORMS: usize = 16;
/// Maximum conformance probes in one manifest.
pub const MAX_ADAPTER_CONFORMANCE_PROBES: usize = 256;
/// Maximum evolution cases in one manifest.
pub const MAX_ADAPTER_EVOLUTIONS: usize = 32;

/// Stable, value-free adapter manifest failure class.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AdapterConformanceErrorKind {
    /// A fixed byte or collection ceiling was exceeded.
    LimitExceeded,
    /// JSON or a closed registry value was invalid.
    InvalidEncoding,
    /// The manifest schema is well formed but unsupported by this release.
    UnsupportedVersion,
    /// Valid bytes were not the one canonical encoding.
    NonCanonical,
    /// A required shape or disposition was inconsistent.
    InvalidShape,
    /// A symbolic or exact identity was duplicated.
    Duplicate,
    /// Manifest and application-plan identities disagree.
    IdentityMismatch,
    /// A required closed product feature is unavailable.
    UnsupportedFeature,
    /// A required first-party driver identity is unavailable.
    UnsupportedDriver,
}

/// Bounded adapter manifest error without paths, values, or engine prose.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AdapterConformanceError {
    kind: AdapterConformanceErrorKind,
}

impl AdapterConformanceError {
    const fn new(kind: AdapterConformanceErrorKind) -> Self {
        Self { kind }
    }

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

impl fmt::Display for AdapterConformanceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self.kind {
            AdapterConformanceErrorKind::LimitExceeded => {
                "adapter conformance manifest exceeds a fixed limit"
            }
            AdapterConformanceErrorKind::InvalidEncoding => {
                "adapter conformance manifest encoding is invalid"
            }
            AdapterConformanceErrorKind::UnsupportedVersion => {
                "adapter conformance manifest version is unsupported"
            }
            AdapterConformanceErrorKind::NonCanonical => {
                "adapter conformance manifest encoding is not canonical"
            }
            AdapterConformanceErrorKind::InvalidShape => {
                "adapter conformance manifest shape is invalid"
            }
            AdapterConformanceErrorKind::Duplicate => {
                "adapter conformance manifest contains a duplicate identity"
            }
            AdapterConformanceErrorKind::IdentityMismatch => {
                "adapter conformance manifest identity does not match the application plan"
            }
            AdapterConformanceErrorKind::UnsupportedFeature => {
                "adapter requires an unavailable RiffDB feature"
            }
            AdapterConformanceErrorKind::UnsupportedDriver => {
                "adapter requires an unavailable driver or platform"
            }
        })
    }
}

impl Error for AdapterConformanceError {}

/// Explicit support posture for one closed RiffDB feature.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum AdapterFeatureDisposition {
    /// Installation must stop when the feature is unavailable.
    Required,
    /// The adapter does not require or emulate this feature.
    Optional,
    /// The feature is used with a declared bounded limitation.
    Degraded,
    /// The feature is knowingly unavailable and is not emulated.
    Unavailable,
}

impl AdapterFeatureDisposition {
    const fn tag(self) -> &'static str {
        match self {
            Self::Required => "required",
            Self::Optional => "optional",
            Self::Degraded => "degraded",
            Self::Unavailable => "unavailable",
        }
    }

    fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "required" => Self::Required,
            "optional" => Self::Optional,
            "degraded" => Self::Degraded,
            "unavailable" => Self::Unavailable,
            _ => return None,
        })
    }
}

/// Closed reason attached only to degraded or unavailable claims.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum AdapterLimitation {
    /// The product feature is not implemented in this exact release.
    ProductUnavailable,
    /// The exact released driver platform matrix is narrower than requested.
    PlatformLimited,
    /// The supported operation exists with a documented bounded performance limit.
    PerformanceLimited,
}

impl AdapterLimitation {
    const fn tag(self) -> &'static str {
        match self {
            Self::ProductUnavailable => "product_unavailable",
            Self::PlatformLimited => "platform_limited",
            Self::PerformanceLimited => "performance_limited",
        }
    }

    fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "product_unavailable" => Self::ProductUnavailable,
            "platform_limited" => Self::PlatformLimited,
            "performance_limited" => Self::PerformanceLimited,
            _ => return None,
        })
    }
}

/// One explicit feature claim. There is no fallback or emulation field.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct AdapterFeatureClaim {
    feature: InstallationFeature,
    disposition: AdapterFeatureDisposition,
    limitation: Option<AdapterLimitation>,
}

impl AdapterFeatureClaim {
    /// Validates one closed support claim.
    pub fn new(
        feature: InstallationFeature,
        disposition: AdapterFeatureDisposition,
        limitation: Option<AdapterLimitation>,
    ) -> Result<Self, AdapterConformanceError> {
        if matches!(
            disposition,
            AdapterFeatureDisposition::Degraded | AdapterFeatureDisposition::Unavailable
        ) != limitation.is_some()
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::InvalidShape,
            ));
        }
        Ok(Self {
            feature,
            disposition,
            limitation,
        })
    }

    /// Required claim with no silent fallback.
    #[must_use]
    pub const fn required(feature: InstallationFeature) -> Self {
        Self {
            feature,
            disposition: AdapterFeatureDisposition::Required,
            limitation: None,
        }
    }

    /// Explicit unavailable claim with a closed reason.
    #[must_use]
    pub const fn unavailable(feature: InstallationFeature, limitation: AdapterLimitation) -> Self {
        Self {
            feature,
            disposition: AdapterFeatureDisposition::Unavailable,
            limitation: Some(limitation),
        }
    }

    /// Closed feature identity.
    #[must_use]
    pub const fn feature(self) -> InstallationFeature {
        self.feature
    }

    /// Explicit support disposition.
    #[must_use]
    pub const fn disposition(self) -> AdapterFeatureDisposition {
        self.disposition
    }

    /// Closed limitation for degraded or unavailable support.
    #[must_use]
    pub const fn limitation(self) -> Option<AdapterLimitation> {
        self.limitation
    }
}

/// Closed platform triples supported by the alpha driver matrix.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum AdapterPlatform {
    /// GNU Linux on x86-64.
    LinuxX86_64Gnu,
    /// musl Linux on x86-64.
    LinuxX86_64Musl,
    /// GNU Linux on AArch64.
    LinuxAarch64Gnu,
    /// macOS on x86-64.
    MacosX86_64,
    /// macOS on Apple silicon.
    MacosAarch64,
    /// Windows on x86-64.
    WindowsX86_64,
}

impl AdapterPlatform {
    const fn tag(self) -> &'static str {
        match self {
            Self::LinuxX86_64Gnu => "linux-x86_64-gnu",
            Self::LinuxX86_64Musl => "linux-x86_64-musl",
            Self::LinuxAarch64Gnu => "linux-aarch64-gnu",
            Self::MacosX86_64 => "macos-x86_64",
            Self::MacosAarch64 => "macos-aarch64",
            Self::WindowsX86_64 => "windows-x86_64",
        }
    }

    fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "linux-x86_64-gnu" => Self::LinuxX86_64Gnu,
            "linux-x86_64-musl" => Self::LinuxX86_64Musl,
            "linux-aarch64-gnu" => Self::LinuxAarch64Gnu,
            "macos-x86_64" => Self::MacosX86_64,
            "macos-aarch64" => Self::MacosAarch64,
            "windows-x86_64" => Self::WindowsX86_64,
            _ => return None,
        })
    }
}

/// One exact first-party driver/runtime/platform claim.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct AdapterDriverRequirement {
    driver: InstallationDriver,
    runtime_version: InstallationSymbol,
    platforms: Vec<AdapterPlatform>,
    conformance_hash: GeneratedArtifactHash,
}

impl AdapterDriverRequirement {
    /// Creates one exact driver requirement; ranges and empty platforms are impossible.
    pub fn new(
        driver: InstallationDriver,
        runtime_version: InstallationSymbol,
        mut platforms: Vec<AdapterPlatform>,
        conformance_hash: GeneratedArtifactHash,
    ) -> Result<Self, AdapterConformanceError> {
        let runtime = runtime_version.as_str();
        if !runtime.bytes().any(|byte| byte.is_ascii_digit())
            || runtime.contains("..")
            || matches!(runtime, "latest" | "current" | "stable" | "any")
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::InvalidShape,
            ));
        }
        platforms.sort();
        if platforms.is_empty()
            || platforms.len() > MAX_ADAPTER_PLATFORMS
            || platforms.windows(2).any(|pair| pair[0] == pair[1])
        {
            return Err(AdapterConformanceError::new(if platforms.is_empty() {
                AdapterConformanceErrorKind::InvalidShape
            } else if platforms.len() > MAX_ADAPTER_PLATFORMS {
                AdapterConformanceErrorKind::LimitExceeded
            } else {
                AdapterConformanceErrorKind::Duplicate
            }));
        }
        Ok(Self {
            driver,
            runtime_version,
            platforms,
            conformance_hash,
        })
    }

    /// First-party transport owner selected by this requirement.
    #[must_use]
    pub const fn driver(&self) -> InstallationDriver {
        self.driver
    }

    /// Exact runtime/toolchain version symbol, never a version range.
    #[must_use]
    pub const fn runtime_version(&self) -> &InstallationSymbol {
        &self.runtime_version
    }

    /// Closed supported platforms.
    #[must_use]
    pub fn platforms(&self) -> &[AdapterPlatform] {
        &self.platforms
    }

    /// Exact golden driver-conformance observation identity.
    #[must_use]
    pub const fn conformance_hash(&self) -> GeneratedArtifactHash {
        self.conformance_hash
    }
}

/// Exact symbolic role required by an adapter.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct AdapterRoleRequirement {
    name: InstallationSymbol,
    role_hash: ApplicationRoleHash,
    operations: Vec<RoleOperation>,
}

impl AdapterRoleRequirement {
    /// Creates one exact, nonempty, name-only role surface.
    pub fn new(
        name: InstallationSymbol,
        role_hash: ApplicationRoleHash,
        mut operations: Vec<RoleOperation>,
    ) -> Result<Self, AdapterConformanceError> {
        operations.sort();
        if operations.is_empty()
            || operations.len() > crate::MAX_ROLE_OPERATIONS
            || operations.windows(2).any(|pair| pair[0] == pair[1])
        {
            return Err(AdapterConformanceError::new(if operations.is_empty() {
                AdapterConformanceErrorKind::InvalidShape
            } else if operations.len() > crate::MAX_ROLE_OPERATIONS {
                AdapterConformanceErrorKind::LimitExceeded
            } else {
                AdapterConformanceErrorKind::Duplicate
            }));
        }
        Ok(Self {
            name,
            role_hash,
            operations,
        })
    }

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

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

    /// Closed named application operations.
    #[must_use]
    pub fn operations(&self) -> &[RoleOperation] {
        &self.operations
    }
}

/// One public operation and bounded golden observation.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct AdapterConformanceProbe {
    name: InstallationSymbol,
    role: InstallationSymbol,
    operation: RoleOperation,
    expected_observation_hash: GeneratedArtifactHash,
    maximum_items: u32,
}

impl AdapterConformanceProbe {
    /// Creates one bounded named-operation probe. It cannot carry code or a method path.
    pub fn new(
        name: InstallationSymbol,
        role: InstallationSymbol,
        operation: RoleOperation,
        expected_observation_hash: GeneratedArtifactHash,
        maximum_items: u32,
    ) -> Result<Self, AdapterConformanceError> {
        if maximum_items == 0 || maximum_items > MAX_ADAPTER_PROBE_ITEMS {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::LimitExceeded,
            ));
        }
        Ok(Self {
            name,
            role,
            operation,
            expected_observation_hash,
            maximum_items,
        })
    }

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

    /// Exact least-authority role used by the probe.
    #[must_use]
    pub const fn role(&self) -> &InstallationSymbol {
        &self.role
    }

    /// Public symbolic operation invoked by the probe.
    #[must_use]
    pub const fn operation(&self) -> &RoleOperation {
        &self.operation
    }

    /// Exact value-free golden observation identity.
    #[must_use]
    pub const fn expected_observation_hash(&self) -> GeneratedArtifactHash {
        self.expected_observation_hash
    }

    /// Maximum number of returned or mutated items accepted by the probe.
    #[must_use]
    pub const fn maximum_items(&self) -> u32 {
        self.maximum_items
    }
}

/// Closed application evolution class. No open version range exists.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum AdapterEvolutionClass {
    /// Install into an empty selected database.
    EmptyInstall,
    /// Upgrade one exact predecessor through ordinary compatible deployment.
    CompatibleUpgrade,
    /// Upgrade one exact predecessor through one exact reviewed migration.
    ExplicitMigration,
}

impl AdapterEvolutionClass {
    const fn tag(self) -> &'static str {
        match self {
            Self::EmptyInstall => "empty_install",
            Self::CompatibleUpgrade => "compatible_upgrade",
            Self::ExplicitMigration => "explicit_migration",
        }
    }

    fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "empty_install" => Self::EmptyInstall,
            "compatible_upgrade" => Self::CompatibleUpgrade,
            "explicit_migration" => Self::ExplicitMigration,
            _ => return None,
        })
    }
}

/// One exact install/upgrade case and its golden observation identity.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct AdapterEvolutionRequirement {
    class: AdapterEvolutionClass,
    predecessor: Option<InstallationContract>,
    successor: InstallationContract,
    migration_hash: Option<MigrationBundleHash>,
    expected_observation_hash: GeneratedArtifactHash,
}

impl AdapterEvolutionRequirement {
    /// Creates a closed exact evolution case.
    pub fn new(
        class: AdapterEvolutionClass,
        predecessor: Option<InstallationContract>,
        successor: InstallationContract,
        migration_hash: Option<MigrationBundleHash>,
        expected_observation_hash: GeneratedArtifactHash,
    ) -> Result<Self, AdapterConformanceError> {
        let shape_valid = match class {
            AdapterEvolutionClass::EmptyInstall => {
                predecessor.is_none() && migration_hash.is_none()
            }
            AdapterEvolutionClass::CompatibleUpgrade => {
                predecessor.is_some_and(|value| {
                    value.version() < successor.version()
                        || (value.version() == successor.version()
                            && value.bundle_hash() == successor.bundle_hash())
                }) && migration_hash.is_none()
            }
            AdapterEvolutionClass::ExplicitMigration => {
                predecessor.is_some_and(|value| value.version() < successor.version())
                    && migration_hash.is_some()
            }
        };
        if !shape_valid {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::InvalidShape,
            ));
        }
        Ok(Self {
            class,
            predecessor,
            successor,
            migration_hash,
            expected_observation_hash,
        })
    }

    /// Exact successor contract installed by this case.
    #[must_use]
    pub const fn successor(&self) -> InstallationContract {
        self.successor
    }

    /// Closed evolution class.
    #[must_use]
    pub const fn class(&self) -> AdapterEvolutionClass {
        self.class
    }

    /// Exact predecessor, absent only for empty installation.
    #[must_use]
    pub const fn predecessor(&self) -> Option<InstallationContract> {
        self.predecessor
    }

    /// Exact migration identity for migration-required evolution.
    #[must_use]
    pub const fn migration_hash(&self) -> Option<MigrationBundleHash> {
        self.migration_hash
    }

    /// Exact golden evolution observation identity.
    #[must_use]
    pub const fn expected_observation_hash(&self) -> GeneratedArtifactHash {
        self.expected_observation_hash
    }
}

/// Complete bounded adapter-owned input.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AdapterConformanceManifestInput {
    /// Stable symbolic adapter name.
    pub adapter: InstallationSymbol,
    /// Exact adapter version; ranges are not representable.
    pub adapter_version: InstallationSymbol,
    /// Exact generated application manifest identity.
    pub application_manifest_hash: ApplicationManifestHash,
    /// Exact compiler-owned application lock identity.
    pub application_lock_hash: ApplicationLockHash,
    /// Exact application lineage.
    pub contract_lineage: ContractLineage,
    /// Closed feature claims, including explicit unavailable/degraded states.
    pub feature_claims: Vec<AdapterFeatureClaim>,
    /// Exact required generated artifacts.
    pub artifacts: Vec<InstallationArtifact>,
    /// Exact least-authority symbolic roles.
    pub roles: Vec<AdapterRoleRequirement>,
    /// Exact first-party driver/runtime/platform claims.
    pub drivers: Vec<AdapterDriverRequirement>,
    /// Bounded public named-operation probes and golden observations.
    pub conformance: Vec<AdapterConformanceProbe>,
    /// Exact empty-install and evolution cases.
    pub evolution: Vec<AdapterEvolutionRequirement>,
}

/// One immutable content-addressed adapter conformance manifest.
#[derive(Clone, Eq, PartialEq)]
pub struct AdapterConformanceManifest {
    schema: &'static str,
    input: AdapterConformanceManifestInput,
    identity: AdapterConformanceManifestHash,
    canonical_bytes: Vec<u8>,
}

impl AdapterConformanceManifest {
    /// Compiles one canonical manifest without filesystem, server, or application execution.
    pub fn compile(
        input: AdapterConformanceManifestInput,
    ) -> Result<Self, AdapterConformanceError> {
        Self::compile_version(ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V1, input, false)
    }

    /// Compiles the current manifest format with an exhaustive feature disposition catalog.
    pub fn compile_v2(
        input: AdapterConformanceManifestInput,
    ) -> Result<Self, AdapterConformanceError> {
        Self::compile_version(ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V2, input, true)
    }

    fn compile_version(
        schema: &'static str,
        mut input: AdapterConformanceManifestInput,
        exhaustive_features: bool,
    ) -> Result<Self, AdapterConformanceError> {
        validate_and_sort(&mut input, exhaustive_features)?;
        let dto = ManifestDto::from_input(schema, &input);
        let mut canonical_bytes = serde_json::to_vec(&dto).map_err(|_| {
            AdapterConformanceError::new(AdapterConformanceErrorKind::InvalidEncoding)
        })?;
        canonical_bytes.push(b'\n');
        if canonical_bytes.len() > MAX_ADAPTER_CONFORMANCE_MANIFEST_BYTES {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::LimitExceeded,
            ));
        }
        let identity = hash_adapter_conformance_manifest(&canonical_bytes);
        Ok(Self {
            schema,
            input,
            identity,
            canonical_bytes,
        })
    }

    /// Strictly decodes and revalidates one canonical manifest.
    pub fn decode_canonical(bytes: &[u8]) -> Result<Self, AdapterConformanceError> {
        if bytes.is_empty() || bytes.len() > MAX_ADAPTER_CONFORMANCE_MANIFEST_BYTES {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::LimitExceeded,
            ));
        }
        let dto: ManifestDto = serde_json::from_slice(bytes).map_err(|_| {
            AdapterConformanceError::new(AdapterConformanceErrorKind::InvalidEncoding)
        })?;
        let schema = match dto.schema.as_str() {
            ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V1 => ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V1,
            ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V2 => ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V2,
            _ => {
                return Err(AdapterConformanceError::new(
                    AdapterConformanceErrorKind::UnsupportedVersion,
                ));
            }
        };
        let input = dto.into_input()?;
        let manifest = Self::compile_version(
            schema,
            input,
            schema == ADAPTER_CONFORMANCE_MANIFEST_SCHEMA_V2,
        )?;
        if manifest.canonical_bytes != bytes {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::NonCanonical,
            ));
        }
        Ok(manifest)
    }

    /// Content identity recorded in installation plans and receipts.
    #[must_use]
    pub const fn identity(&self) -> AdapterConformanceManifestHash {
        self.identity
    }

    /// Exact accepted compatibility schema.
    #[must_use]
    pub const fn schema(&self) -> &'static str {
        self.schema
    }

    /// Validated manifest contents.
    #[must_use]
    pub const fn input(&self) -> &AdapterConformanceManifestInput {
        &self.input
    }

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

    /// Verifies one installation plan is exactly the adapter-reviewed plan.
    pub fn validate_installation_plan(
        &self,
        plan: &ApplicationInstallationPlan,
    ) -> Result<(), AdapterConformanceError> {
        let planned = plan.input();
        if planned.adapter_manifest_hash != Some(self.identity)
            || planned.manifest_hash != self.input.application_manifest_hash
            || planned.lock_hash != self.input.application_lock_hash
            || planned.target.lineage() != &self.input.contract_lineage
            || self
                .input
                .evolution
                .iter()
                .any(|evolution| evolution.successor != planned.contract)
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::IdentityMismatch,
            ));
        }
        let self_artifact_hash = GeneratedArtifactHash::from_bytes(*self.identity.as_bytes());
        if !planned.artifacts.iter().any(|artifact| {
            artifact.kind() == InstallationArtifactKind::AdapterManifest
                && artifact.name() == &self.input.adapter
                && artifact.content_hash() == self_artifact_hash
        }) || self
            .input
            .artifacts
            .iter()
            .any(|required| planned.artifacts.binary_search(required).is_err())
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::IdentityMismatch,
            ));
        }
        for required in &self.input.roles {
            let Some(role) = planned
                .roles
                .iter()
                .find(|role| role.name() == required.name())
            else {
                return Err(AdapterConformanceError::new(
                    AdapterConformanceErrorKind::IdentityMismatch,
                ));
            };
            if role.role_hash() != required.role_hash
                || role.desired_operations() != required.operations
            {
                return Err(AdapterConformanceError::new(
                    AdapterConformanceErrorKind::IdentityMismatch,
                ));
            }
        }
        if self
            .input
            .drivers
            .iter()
            .any(|required| planned.drivers.binary_search(&required.driver).is_err())
            || self.input.feature_claims.iter().any(|claim| {
                claim.disposition == AdapterFeatureDisposition::Required
                    && planned
                        .required_features
                        .binary_search(&claim.feature)
                        .is_err()
            })
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::IdentityMismatch,
            ));
        }
        Ok(())
    }

    /// Verifies required features and exact driver conformance identities against a closed catalog.
    pub fn validate_catalog(
        &self,
        supported_features: &[InstallationFeature],
        supported_drivers: &[AdapterDriverRequirement],
    ) -> Result<(), AdapterConformanceError> {
        if self.input.feature_claims.iter().any(|claim| {
            claim.disposition == AdapterFeatureDisposition::Required
                && !supported_features.contains(&claim.feature)
        }) {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::UnsupportedFeature,
            ));
        }
        if self
            .input
            .drivers
            .iter()
            .any(|required| !supported_drivers.contains(required))
        {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::UnsupportedDriver,
            ));
        }
        Ok(())
    }
}

impl fmt::Debug for AdapterConformanceManifest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AdapterConformanceManifest")
            .field("adapter", &self.input.adapter)
            .field("adapter_version", &self.input.adapter_version)
            .field("identity", &self.identity)
            .finish_non_exhaustive()
    }
}

fn validate_and_sort(
    input: &mut AdapterConformanceManifestInput,
    exhaustive_features: bool,
) -> Result<(), AdapterConformanceError> {
    if input.feature_claims.len() > MAX_ADAPTER_FEATURE_CLAIMS
        || input.artifacts.is_empty()
        || input.artifacts.len() > MAX_ADAPTER_ARTIFACTS
        || input.roles.is_empty()
        || input.roles.len() > MAX_ADAPTER_ROLES
        || input.drivers.is_empty()
        || input.drivers.len() > MAX_ADAPTER_DRIVERS
        || input.conformance.is_empty()
        || input.conformance.len() > MAX_ADAPTER_CONFORMANCE_PROBES
        || input.evolution.is_empty()
        || input.evolution.len() > MAX_ADAPTER_EVOLUTIONS
    {
        return Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::LimitExceeded,
        ));
    }
    if exhaustive_features
        && input.feature_claims.len() != InstallationFeature::ADAPTER_CONFORMANCE.len()
    {
        return Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::InvalidShape,
        ));
    }
    input.feature_claims.sort();
    reject_duplicate(
        input
            .feature_claims
            .windows(2)
            .any(|pair| pair[0].feature == pair[1].feature),
    )?;
    if exhaustive_features
        && input
            .feature_claims
            .iter()
            .map(|claim| claim.feature)
            .ne(InstallationFeature::ADAPTER_CONFORMANCE)
    {
        return Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::InvalidShape,
        ));
    }
    if !input.feature_claims.iter().any(|claim| {
        claim.feature == InstallationFeature::InstallationCampaigns
            && claim.disposition == AdapterFeatureDisposition::Required
    }) {
        return Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::InvalidShape,
        ));
    }
    input.artifacts.sort();
    reject_duplicate(
        input
            .artifacts
            .windows(2)
            .any(|pair| (pair[0].kind(), pair[0].name()) == (pair[1].kind(), pair[1].name())),
    )?;
    input.roles.sort();
    reject_duplicate(
        input
            .roles
            .windows(2)
            .any(|pair| pair[0].name == pair[1].name),
    )?;
    input.drivers.sort();
    reject_duplicate(
        input
            .drivers
            .windows(2)
            .any(|pair| pair[0].driver == pair[1].driver),
    )?;
    input.conformance.sort();
    reject_duplicate(
        input
            .conformance
            .windows(2)
            .any(|pair| pair[0].name == pair[1].name),
    )?;
    for probe in &input.conformance {
        let Some(role) = input.roles.iter().find(|role| role.name == probe.role) else {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::IdentityMismatch,
            ));
        };
        if role.operations.binary_search(&probe.operation).is_err() {
            return Err(AdapterConformanceError::new(
                AdapterConformanceErrorKind::IdentityMismatch,
            ));
        }
    }
    input.evolution.sort();
    reject_duplicate(input.evolution.windows(2).any(|pair| pair[0] == pair[1]))?;
    let genesis = input
        .evolution
        .iter()
        .filter(|item| item.class == AdapterEvolutionClass::EmptyInstall)
        .collect::<Vec<_>>();
    if genesis.len() != 1
        || input
            .evolution
            .iter()
            .any(|item| item.successor != genesis[0].successor)
    {
        return Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::InvalidShape,
        ));
    }
    Ok(())
}

fn reject_duplicate(value: bool) -> Result<(), AdapterConformanceError> {
    if value {
        Err(AdapterConformanceError::new(
            AdapterConformanceErrorKind::Duplicate,
        ))
    } else {
        Ok(())
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ManifestDto {
    schema: String,
    adapter: String,
    adapter_version: String,
    application_manifest_hash: String,
    application_lock_hash: String,
    contract_lineage: String,
    feature_claims: Vec<FeatureClaimDto>,
    artifacts: Vec<ArtifactDto>,
    roles: Vec<RoleDto>,
    drivers: Vec<DriverDto>,
    conformance: Vec<ProbeDto>,
    evolution: Vec<EvolutionDto>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct FeatureClaimDto {
    feature: String,
    disposition: String,
    limitation: Option<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 RoleDto {
    name: String,
    role_hash: String,
    operations: Vec<OperationDto>,
}

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

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct DriverDto {
    driver: String,
    runtime_version: String,
    platforms: Vec<String>,
    conformance_hash: String,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct ProbeDto {
    name: String,
    role: String,
    operation: OperationDto,
    expected_observation_hash: String,
    maximum_items: u32,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EvolutionDto {
    class: String,
    predecessor: Option<ContractDto>,
    successor: ContractDto,
    migration_hash: Option<String>,
    expected_observation_hash: String,
}

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

impl ManifestDto {
    fn from_input(schema: &str, input: &AdapterConformanceManifestInput) -> Self {
        Self {
            schema: schema.to_owned(),
            adapter: input.adapter.as_str().to_owned(),
            adapter_version: input.adapter_version.as_str().to_owned(),
            application_manifest_hash: hex(input.application_manifest_hash.as_bytes()),
            application_lock_hash: hex(input.application_lock_hash.as_bytes()),
            contract_lineage: input.contract_lineage.as_str().to_owned(),
            feature_claims: input
                .feature_claims
                .iter()
                .map(FeatureClaimDto::from_claim)
                .collect(),
            artifacts: input
                .artifacts
                .iter()
                .map(ArtifactDto::from_artifact)
                .collect(),
            roles: input.roles.iter().map(RoleDto::from_role).collect(),
            drivers: input.drivers.iter().map(DriverDto::from_driver).collect(),
            conformance: input.conformance.iter().map(ProbeDto::from_probe).collect(),
            evolution: input
                .evolution
                .iter()
                .map(EvolutionDto::from_evolution)
                .collect(),
        }
    }

    fn into_input(self) -> Result<AdapterConformanceManifestInput, AdapterConformanceError> {
        Ok(AdapterConformanceManifestInput {
            adapter: symbol(self.adapter)?,
            adapter_version: symbol(self.adapter_version)?,
            application_manifest_hash: ApplicationManifestHash::from_bytes(parse_hash(
                &self.application_manifest_hash,
            )?),
            application_lock_hash: ApplicationLockHash::from_bytes(parse_hash(
                &self.application_lock_hash,
            )?),
            contract_lineage: ContractLineage::new(self.contract_lineage)
                .map_err(|_| invalid_encoding())?,
            feature_claims: self
                .feature_claims
                .into_iter()
                .map(FeatureClaimDto::into_claim)
                .collect::<Result<_, _>>()?,
            artifacts: self
                .artifacts
                .into_iter()
                .map(ArtifactDto::into_artifact)
                .collect::<Result<_, _>>()?,
            roles: self
                .roles
                .into_iter()
                .map(RoleDto::into_role)
                .collect::<Result<_, _>>()?,
            drivers: self
                .drivers
                .into_iter()
                .map(DriverDto::into_driver)
                .collect::<Result<_, _>>()?,
            conformance: self
                .conformance
                .into_iter()
                .map(ProbeDto::into_probe)
                .collect::<Result<_, _>>()?,
            evolution: self
                .evolution
                .into_iter()
                .map(EvolutionDto::into_evolution)
                .collect::<Result<_, _>>()?,
        })
    }
}

impl FeatureClaimDto {
    fn from_claim(claim: &AdapterFeatureClaim) -> Self {
        Self {
            feature: claim.feature.tag().to_owned(),
            disposition: claim.disposition.tag().to_owned(),
            limitation: claim.limitation.map(|value| value.tag().to_owned()),
        }
    }

    fn into_claim(self) -> Result<AdapterFeatureClaim, AdapterConformanceError> {
        AdapterFeatureClaim::new(
            InstallationFeature::parse(&self.feature).ok_or_else(invalid_encoding)?,
            AdapterFeatureDisposition::parse(&self.disposition).ok_or_else(invalid_encoding)?,
            self.limitation
                .map(|value| AdapterLimitation::parse(&value).ok_or_else(invalid_encoding))
                .transpose()?,
        )
    }
}

impl ArtifactDto {
    fn from_artifact(value: &InstallationArtifact) -> Self {
        Self {
            kind: value.kind().tag().to_owned(),
            name: value.name().as_str().to_owned(),
            content_hash: hex(value.content_hash().as_bytes()),
        }
    }

    fn into_artifact(self) -> Result<InstallationArtifact, AdapterConformanceError> {
        Ok(InstallationArtifact::new(
            InstallationArtifactKind::parse(&self.kind).ok_or_else(invalid_encoding)?,
            symbol(self.name)?,
            GeneratedArtifactHash::from_bytes(parse_hash(&self.content_hash)?),
        ))
    }
}

impl RoleDto {
    fn from_role(value: &AdapterRoleRequirement) -> Self {
        Self {
            name: value.name.as_str().to_owned(),
            role_hash: hex(value.role_hash.as_bytes()),
            operations: value
                .operations
                .iter()
                .map(OperationDto::from_operation)
                .collect(),
        }
    }

    fn into_role(self) -> Result<AdapterRoleRequirement, AdapterConformanceError> {
        AdapterRoleRequirement::new(
            symbol(self.name)?,
            ApplicationRoleHash::from_bytes(parse_hash(&self.role_hash)?),
            self.operations
                .into_iter()
                .map(OperationDto::into_operation)
                .collect::<Result<_, _>>()?,
        )
    }
}

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

    fn into_operation(self) -> Result<RoleOperation, AdapterConformanceError> {
        Ok(RoleOperation::new(
            RoleOperationKind::parse(&self.kind).ok_or_else(invalid_encoding)?,
            symbol(self.name)?,
        ))
    }
}

impl DriverDto {
    fn from_driver(value: &AdapterDriverRequirement) -> Self {
        Self {
            driver: value.driver.tag().to_owned(),
            runtime_version: value.runtime_version.as_str().to_owned(),
            platforms: value
                .platforms
                .iter()
                .map(|value| value.tag().to_owned())
                .collect(),
            conformance_hash: hex(value.conformance_hash.as_bytes()),
        }
    }

    fn into_driver(self) -> Result<AdapterDriverRequirement, AdapterConformanceError> {
        AdapterDriverRequirement::new(
            InstallationDriver::parse(&self.driver).ok_or_else(invalid_encoding)?,
            symbol(self.runtime_version)?,
            self.platforms
                .into_iter()
                .map(|value| AdapterPlatform::parse(&value).ok_or_else(invalid_encoding))
                .collect::<Result<_, _>>()?,
            GeneratedArtifactHash::from_bytes(parse_hash(&self.conformance_hash)?),
        )
    }
}

impl ProbeDto {
    fn from_probe(value: &AdapterConformanceProbe) -> Self {
        Self {
            name: value.name.as_str().to_owned(),
            role: value.role.as_str().to_owned(),
            operation: OperationDto::from_operation(&value.operation),
            expected_observation_hash: hex(value.expected_observation_hash.as_bytes()),
            maximum_items: value.maximum_items,
        }
    }

    fn into_probe(self) -> Result<AdapterConformanceProbe, AdapterConformanceError> {
        AdapterConformanceProbe::new(
            symbol(self.name)?,
            symbol(self.role)?,
            self.operation.into_operation()?,
            GeneratedArtifactHash::from_bytes(parse_hash(&self.expected_observation_hash)?),
            self.maximum_items,
        )
    }
}

impl EvolutionDto {
    fn from_evolution(value: &AdapterEvolutionRequirement) -> Self {
        Self {
            class: value.class.tag().to_owned(),
            predecessor: value.predecessor.map(ContractDto::from_contract),
            successor: ContractDto::from_contract(value.successor),
            migration_hash: value.migration_hash.map(|value| hex(value.as_bytes())),
            expected_observation_hash: hex(value.expected_observation_hash.as_bytes()),
        }
    }

    fn into_evolution(self) -> Result<AdapterEvolutionRequirement, AdapterConformanceError> {
        AdapterEvolutionRequirement::new(
            AdapterEvolutionClass::parse(&self.class).ok_or_else(invalid_encoding)?,
            self.predecessor
                .map(ContractDto::into_contract)
                .transpose()?,
            self.successor.into_contract()?,
            self.migration_hash
                .map(|value| parse_hash(&value).map(MigrationBundleHash::from_bytes))
                .transpose()?,
            GeneratedArtifactHash::from_bytes(parse_hash(&self.expected_observation_hash)?),
        )
    }
}

impl ContractDto {
    fn from_contract(value: InstallationContract) -> Self {
        Self {
            version: value.version().get(),
            bundle_hash: hex(value.bundle_hash().as_bytes()),
        }
    }

    fn into_contract(self) -> Result<InstallationContract, AdapterConformanceError> {
        Ok(InstallationContract::new(
            ContractVersion::new(self.version).ok_or_else(invalid_encoding)?,
            ContractBundleHash::from_bytes(parse_hash(&self.bundle_hash)?),
        ))
    }
}

fn symbol(value: String) -> Result<InstallationSymbol, AdapterConformanceError> {
    InstallationSymbol::new(value).map_err(|_| invalid_encoding())
}

fn invalid_encoding() -> AdapterConformanceError {
    AdapterConformanceError::new(AdapterConformanceErrorKind::InvalidEncoding)
}

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

fn parse_hash(value: &str) -> Result<[u8; 32], AdapterConformanceError> {
    if value.len() != 64 {
        return Err(invalid_encoding());
    }
    let mut bytes = [0_u8; 32];
    for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
        bytes[index] = (nibble(pair[0]).ok_or_else(invalid_encoding)? << 4)
            | nibble(pair[1]).ok_or_else(invalid_encoding)?;
    }
    Ok(bytes)
}

const fn nibble(value: u8) -> Option<u8> {
    match value {
        b'0'..=b'9' => Some(value - b'0'),
        b'a'..=b'f' => Some(value - b'a' + 10),
        _ => None,
    }
}