distributed_cli 4.0.0

The `distributed` CLI for Distributed applications: contracts check/accept, scaffold projects, describe manifests, compile clients, and render schema artifacts. Also a library so other CLIs (e.g. hops) can mount its commands.
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
//! Dialect-aware migration inventory and immutable-history checks.
//!
//! The inventory is deliberately a small, explicit data model. It owns the
//! logical migration order and the source paths/checksums for each supported
//! dialect; SQLx remains the runtime owner of applying those bytes. The
//! history checker reads the comparison inventory and its SQL bytes from one
//! explicit Git revision, so changing a local checksum cannot hide a baseline
//! edit.

use super::diagnostic::is_secret_like;
use super::{
    ArtifactIdentity, ContractArtifactKind, ContractCheckResult, ContractDiagnostic,
    ContractDiagnosticCode, ContractError,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};

/// The current migration inventory wire format.
pub const MIGRATION_INVENTORY_SCHEMA_VERSION: u32 = 1;
/// Repository-relative location of the inventory.
pub const MIGRATION_INVENTORY_PATH: &str = "migrations/inventory.json";
/// Maximum accepted inventory size.
pub const MAX_MIGRATION_INVENTORY_BYTES: usize = 1024 * 1024;
/// Maximum accepted SQL source size for one migration.
pub const MAX_MIGRATION_SQL_BYTES: usize = 4 * 1024 * 1024;
/// Maximum number of migrations in one inventory.
pub const MAX_MIGRATIONS: usize = 256;
/// Maximum nesting depth of JSON objects and arrays in an inventory.
pub const MAX_MIGRATION_JSON_DEPTH: usize = 24;
/// Maximum number of entries traversed beneath one dialect directory tree.
pub const MAX_MIGRATION_TOTAL_ENTRIES: usize = MAX_MIGRATIONS * 4;
/// Maximum number of direct entries beneath `migrations`.
pub const MAX_MIGRATION_TOP_LEVEL_ENTRIES: usize = 64;
/// The stable owner and scope used by migration diagnostics.
pub const MIGRATION_OWNER: &str = "distributed/migrations";
pub const MIGRATION_SCOPE: &str = "repository/migrations";

const DIALECT_DIRECTORY_LIMIT: usize = 4_096;
const REDACTED_MIGRATION_PATH: &str = "<redacted-migration-path>";

/// A SQL dialect with an explicit migration directory.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum MigrationDialect {
    /// SQLite migrations.
    Sqlite,
    /// PostgreSQL migrations.
    Postgres,
}

impl MigrationDialect {
    /// All dialects required by the repository contract.
    pub const ALL: [Self; 2] = [Self::Sqlite, Self::Postgres];

    /// Stable inventory spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Sqlite => "sqlite",
            Self::Postgres => "postgres",
        }
    }

    fn directory(self) -> &'static str {
        match self {
            Self::Sqlite => "migrations/sqlite",
            Self::Postgres => "migrations/postgres",
        }
    }
}

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

/// One dialect-specific SQL file declaration.
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MigrationFile {
    /// Repository-relative path to the SQL file.
    pub path: String,
    /// Lowercase SHA-256 digest of the exact file bytes.
    pub sha256: String,
}

/// One logical migration and its required dialect implementations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MigrationEntry {
    /// Consecutive logical migration version, starting at one.
    pub version: u64,
    /// Human-readable SQLx migration description.
    pub description: String,
    /// SQLite source declaration.
    pub sqlite: MigrationFile,
    /// PostgreSQL source declaration.
    pub postgres: MigrationFile,
}

impl MigrationEntry {
    /// Return the declaration for one supported dialect.
    pub fn file(&self, dialect: MigrationDialect) -> &MigrationFile {
        match dialect {
            MigrationDialect::Sqlite => &self.sqlite,
            MigrationDialect::Postgres => &self.postgres,
        }
    }
}

/// The single source of migration registration and history identity.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MigrationInventory {
    /// Inventory wire-format version.
    pub schema_version: u32,
    /// Migrations in their runtime application order.
    pub migrations: Vec<MigrationEntry>,
}

impl MigrationInventory {
    /// Parse and structurally validate inventory JSON without filesystem I/O.
    pub fn from_json_str(input: &str) -> Result<Self, ContractError> {
        if input.len() > MAX_MIGRATION_INVENTORY_BYTES {
            return Err(inventory_error(format!(
                "migration inventory is {} bytes; maximum supported size is {MAX_MIGRATION_INVENTORY_BYTES}",
                input.len()
            )));
        }
        validate_json_nesting(input)?;
        let value: Value = serde_json::from_str(input)
            .map_err(|error| inventory_error(format!("parse migration inventory JSON: {error}")))?;
        validate_json_value(&value, 1)?;
        let inventory: Self = serde_json::from_value(value)
            .map_err(|error| inventory_error(format!("parse migration inventory JSON: {error}")))?;
        inventory.validate_structure()?;
        Ok(inventory)
    }

    /// Alias for [`Self::from_json_str`].
    pub fn parse(input: &str) -> Result<Self, ContractError> {
        Self::from_json_str(input)
    }

    /// Read and fully validate an inventory at its conventional repository path.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, ContractError> {
        let path = path.as_ref();
        let repository_root = inferred_repository_root(path);
        let canonical_root = canonical_repository_root(&repository_root)?;
        let relative = relative_path(&repository_root, path)?;
        reject_symlink_components(&canonical_root, &relative, "migration inventory")?;
        let bytes = read_bounded_file(path, MAX_MIGRATION_INVENTORY_BYTES, "migration inventory")?;
        let input = std::str::from_utf8(&bytes)
            .map_err(|_| inventory_error("migration inventory is not UTF-8".to_string()))?;
        let inventory = Self::from_json_str(input)?;
        inventory.validate_paths(&canonical_root)?;
        Ok(inventory)
    }

    /// Load and validate `migrations/inventory.json` beneath a repository root.
    pub fn from_repository_root(root: impl AsRef<Path>) -> Result<Self, ContractError> {
        Self::from_path(root.as_ref().join(MIGRATION_INVENTORY_PATH))
    }

    /// Serialize the validated inventory without changing its runtime order.
    pub fn canonical_bytes(&self) -> Result<Vec<u8>, ContractError> {
        self.validate_structure()?;
        serde_json::to_vec(self)
            .map_err(|error| inventory_error(format!("serialize migration inventory: {error}")))
    }

    /// Validate all declared files, checksums, dialect directories, and extras.
    pub fn validate_paths(&self, root: impl AsRef<Path>) -> Result<(), ContractError> {
        self.validate_structure()?;
        let root = canonical_repository_root(root.as_ref())?;
        let declared = self
            .migrations
            .iter()
            .flat_map(|migration| {
                MigrationDialect::ALL
                    .into_iter()
                    .map(move |dialect| (dialect, migration.file(dialect).path.clone()))
            })
            .collect::<BTreeSet<_>>();

        for migration in &self.migrations {
            for dialect in MigrationDialect::ALL {
                let declaration = migration.file(dialect);
                let display_path = declared_path_display(&declaration.path);
                let bytes = read_migration_file(&root, declaration, dialect)?;
                let observed = sha256_hex(&bytes);
                if observed != declaration.sha256 {
                    return Err(inventory_error(format!(
                        "{} migration `{}` checksum mismatch: expected {}, observed {}",
                        dialect, display_path, declaration.sha256, observed
                    )));
                }
                if std::str::from_utf8(&bytes).is_err() {
                    return Err(inventory_error(format!(
                        "{} migration `{display_path}` is not UTF-8 SQL",
                        dialect
                    )));
                }
            }
        }

        for dialect in MigrationDialect::ALL {
            let actual = collect_sql_files(&root, dialect)?;
            let declared_for_dialect = declared
                .iter()
                .filter(|(declared_dialect, _)| *declared_dialect == dialect)
                .cloned()
                .collect::<BTreeSet<_>>();
            if let Some(path) = actual.difference(&declared_for_dialect).next() {
                let display_path = declared_path_display(&path.1);
                return Err(inventory_error(format!(
                    "extra {} migration file `{}` is not registered",
                    dialect, display_path
                )));
            }
        }
        validate_no_extra_dialect_directories(&root)?;
        Ok(())
    }

    /// Collect a read-only current-tree result with stable diagnostics.
    pub fn check(&self, root: impl AsRef<Path>) -> ContractCheckResult {
        let mut result = ContractCheckResult::default();
        let identity = match self.canonical_bytes() {
            Ok(identity) => identity,
            Err(error) => {
                result.push(diagnostic_for_error(&error));
                return result;
            }
        };
        result.catalog_identity = Some(super::artifact::canonical_digest(&identity));
        result.artifacts.insert(
            "migration-inventory".to_string(),
            ArtifactIdentity::from_canonical_bytes(
                ContractArtifactKind::MigrationInventory,
                &identity,
            ),
        );
        if let Err(error) = self.validate_paths(root) {
            result.push(diagnostic_for_error(&error));
        }
        result
    }

    /// Compare this current inventory against inventory and SQL bytes at a Git revision.
    pub fn check_history(
        &self,
        root: impl AsRef<Path>,
        base_revision: &str,
    ) -> MigrationHistoryCheck {
        let root = root.as_ref();
        let mut result = MigrationHistoryCheck {
            baseline: BaselineAvailability::Unavailable {
                revision: base_revision.to_string(),
                reason: "comparison has not started".to_string(),
            },
            diagnostics: BTreeSet::new(),
        };

        if let Err(error) = self.validate_paths(root) {
            result.push(diagnostic_for_error(&error));
        }

        let Ok(root) = canonical_repository_root(root) else {
            result.baseline = BaselineAvailability::Unavailable {
                revision: base_revision.to_string(),
                reason: "repository root is unavailable".to_string(),
            };
            result.push(unavailable_diagnostic(
                base_revision,
                "repository root is unavailable",
                false,
            ));
            return result;
        };
        if !valid_revision(base_revision) || !git_revision_exists(&root, base_revision) {
            result.baseline = BaselineAvailability::Unavailable {
                revision: base_revision.to_string(),
                reason: "explicit Git revision is unavailable".to_string(),
            };
            result.push(unavailable_diagnostic(
                base_revision,
                "immutable migration history evidence is unavailable for the explicit base revision",
                false,
            ));
            return result;
        }

        let baseline_bytes = match git_file(&root, base_revision, MIGRATION_INVENTORY_PATH) {
            Ok(bytes) => bytes,
            Err(reason) => {
                result.baseline = BaselineAvailability::Unavailable {
                    revision: base_revision.to_string(),
                    reason,
                };
                result.push(unavailable_diagnostic(
                    base_revision,
                    "the explicit Git revision has no readable migration inventory",
                    true,
                ));
                return result;
            }
        };
        let baseline_input = match std::str::from_utf8(&baseline_bytes) {
            Ok(input) => input,
            Err(_) => {
                result.baseline = BaselineAvailability::Unavailable {
                    revision: base_revision.to_string(),
                    reason: "baseline migration inventory is not UTF-8".to_string(),
                };
                result.push(unavailable_diagnostic(
                    base_revision,
                    "the explicit Git revision contains a non-UTF-8 migration inventory",
                    true,
                ));
                return result;
            }
        };
        let baseline = match Self::from_json_str(baseline_input) {
            Ok(inventory) => inventory,
            Err(error) => {
                result.baseline = BaselineAvailability::Unavailable {
                    revision: base_revision.to_string(),
                    reason: "baseline migration inventory is structurally invalid".to_string(),
                };
                result.push(
                    ContractDiagnostic::new(
                        ContractDiagnosticCode::MigrationHistory,
                        Some(ContractArtifactKind::MigrationInventory),
                        Some(MIGRATION_SCOPE),
                        MIGRATION_OWNER,
                        [MIGRATION_INVENTORY_PATH],
                        std::iter::empty::<&str>(),
                        None::<&str>,
                        Some(base_revision),
                        Some(error.message()),
                        Some("restore the baseline inventory and add a new migration"),
                        Some(true),
                        "restore the baseline inventory and add a new migration",
                    )
                    .with_detail("baseline migration inventory is structurally invalid"),
                );
                return result;
            }
        };

        result.baseline = BaselineAvailability::Available {
            revision: base_revision.to_string(),
        };
        let baseline_files = match load_baseline_files(&root, base_revision, &baseline) {
            Ok(files) => files,
            Err(reason) => {
                result.baseline = BaselineAvailability::Unavailable {
                    revision: base_revision.to_string(),
                    reason,
                };
                result.push(unavailable_diagnostic(
                    base_revision,
                    "the explicit Git revision has incomplete migration SQL evidence",
                    true,
                ));
                return result;
            }
        };
        compare_history(
            self,
            &baseline,
            &baseline_files,
            &root,
            base_revision,
            &mut result,
        );
        result
    }

    /// Alias emphasizing that the baseline comparison is read-only.
    pub fn compare_history(
        &self,
        root: impl AsRef<Path>,
        base_revision: &str,
    ) -> MigrationHistoryCheck {
        self.check_history(root, base_revision)
    }

    fn validate_structure(&self) -> Result<(), ContractError> {
        if self.schema_version != MIGRATION_INVENTORY_SCHEMA_VERSION {
            return Err(inventory_error(format!(
                "unsupported migration inventory schema version {}; expected {}",
                self.schema_version, MIGRATION_INVENTORY_SCHEMA_VERSION
            )));
        }
        if self.migrations.is_empty() || self.migrations.len() > MAX_MIGRATIONS {
            return Err(inventory_error(format!(
                "migration inventory must contain 1..={MAX_MIGRATIONS} migrations"
            )));
        }

        let mut paths = BTreeMap::<String, (u64, MigrationDialect)>::new();
        for (index, migration) in self.migrations.iter().enumerate() {
            let expected_version = (index + 1) as u64;
            if migration.version != expected_version {
                return Err(inventory_error(format!(
                    "migration versions must be ordered and consecutive: expected {expected_version}, observed {}",
                    migration.version
                )));
            }
            if migration.version > i64::MAX as u64 {
                return Err(inventory_error(format!(
                    "migration version {} exceeds SQLx's signed version range",
                    migration.version
                )));
            }
            validate_description(&migration.description, migration.version)?;
            for dialect in MigrationDialect::ALL {
                let file = migration.file(dialect);
                validate_migration_path(&file.path, dialect)?;
                validate_checksum(&file.sha256, &file.path)?;
                if let Some((previous_version, previous_dialect)) = paths.get(&file.path) {
                    return Err(inventory_error(format!(
                        "{} migration path `{}` is declared more than once ({} version {}, {} version {})",
                        dialect,
                        declared_path_display(&file.path),
                        previous_dialect,
                        previous_version,
                        dialect,
                        migration.version
                    )));
                }
                paths.insert(file.path.clone(), (migration.version, dialect));
            }
        }
        Ok(())
    }
}

/// The result of comparing an inventory with an explicit Git baseline.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MigrationHistoryCheck {
    /// Whether the explicit revision was available and readable.
    pub baseline: BaselineAvailability,
    /// Deterministically ordered history and current-tree diagnostics.
    pub diagnostics: BTreeSet<ContractDiagnostic>,
}

impl MigrationHistoryCheck {
    /// True only when baseline evidence exists and no diagnostic was emitted.
    pub fn is_verified(&self) -> bool {
        self.baseline.is_available() && self.diagnostics.is_empty()
    }

    /// Alias for [`Self::is_verified`]. Unavailable evidence is never success.
    pub fn is_ok(&self) -> bool {
        self.is_verified()
    }

    /// Whether the explicit comparison baseline could not be read.
    pub fn is_unavailable(&self) -> bool {
        !self.baseline.is_available()
    }

    /// Add one deterministic diagnostic.
    pub fn push(&mut self, diagnostic: ContractDiagnostic) {
        self.diagnostics.insert(diagnostic);
    }

    /// Human output shared with aggregate contract checks.
    pub fn human(&self) -> String {
        self.diagnostics
            .iter()
            .map(ContractDiagnostic::human)
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// JSON output shared with aggregate contract checks.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        let mut result = ContractCheckResult::default();
        for diagnostic in &self.diagnostics {
            result.push(diagnostic.clone());
        }
        result.to_json()
    }
}

/// Typed fact describing whether the comparison revision was available.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BaselineAvailability {
    /// Inventory and all declared SQL bytes were read from this revision.
    Available { revision: String },
    /// Comparison evidence was unavailable; this is not a successful check.
    Unavailable { revision: String, reason: String },
}

impl BaselineAvailability {
    /// Whether baseline inventory and SQL evidence was available.
    pub fn is_available(&self) -> bool {
        matches!(self, Self::Available { .. })
    }

    /// The requested revision, regardless of availability.
    pub fn revision(&self) -> &str {
        match self {
            Self::Available { revision } | Self::Unavailable { revision, .. } => revision,
        }
    }

    /// Unavailability explanation, if any.
    pub fn reason(&self) -> Option<&str> {
        match self {
            Self::Available { .. } => None,
            Self::Unavailable { reason, .. } => Some(reason),
        }
    }
}

/// Compare a repository's conventional inventory against an explicit Git revision.
pub fn check_migration_history(
    root: impl AsRef<Path>,
    base_revision: &str,
) -> MigrationHistoryCheck {
    let root = root.as_ref();
    match MigrationInventory::from_repository_root(root) {
        Ok(inventory) => inventory.check_history(root, base_revision),
        Err(error) => {
            let mut result = MigrationHistoryCheck {
                baseline: BaselineAvailability::Unavailable {
                    revision: base_revision.to_string(),
                    reason: "current migration inventory is invalid".to_string(),
                },
                diagnostics: BTreeSet::new(),
            };
            result.push(diagnostic_for_error(&error));
            result
        }
    }
}

/// Validate a repository's conventional inventory and SQL files.
pub fn check_migration_inventory(root: impl AsRef<Path>) -> ContractCheckResult {
    match MigrationInventory::from_repository_root(root.as_ref()) {
        Ok(inventory) => inventory.check(root),
        Err(error) => {
            let mut result = ContractCheckResult::default();
            result.push(diagnostic_for_error(&error));
            result
        }
    }
}

fn compare_history(
    current: &MigrationInventory,
    baseline: &MigrationInventory,
    baseline_files: &BTreeMap<(u64, MigrationDialect), Vec<u8>>,
    root: &Path,
    base_revision: &str,
    result: &mut MigrationHistoryCheck,
) {
    let current_by_version = current
        .migrations
        .iter()
        .map(|migration| (migration.version, migration))
        .collect::<BTreeMap<_, _>>();
    let current_last = current
        .migrations
        .last()
        .map_or(0, |migration| migration.version);
    let baseline_last = baseline
        .migrations
        .last()
        .map_or(0, |migration| migration.version);
    let next_version = current_last.max(baseline_last).saturating_add(1);

    let baseline_versions = baseline
        .migrations
        .iter()
        .map(|migration| migration.version)
        .collect::<Vec<_>>();
    let current_baseline_versions = current
        .migrations
        .iter()
        .filter(|migration| baseline_versions.contains(&migration.version))
        .map(|migration| migration.version)
        .collect::<Vec<_>>();
    if current_baseline_versions != baseline_versions {
        result.push(history_diagnostic(
            base_revision,
            next_version,
            baseline
                .migrations
                .iter()
                .flat_map(|migration| {
                    MigrationDialect::ALL.map(|dialect| migration.file(dialect).path.clone())
                })
                .collect::<Vec<_>>(),
            Some(&format!("versions={baseline_versions:?}")),
            Some(&format!("versions={current_baseline_versions:?}")),
            "baseline migration order or numbering changed",
        ));
    }

    for baseline_migration in &baseline.migrations {
        let Some(current_migration) = current_by_version.get(&baseline_migration.version) else {
            result.push(history_diagnostic(
                base_revision,
                next_version,
                MigrationDialect::ALL.map(|dialect| baseline_migration.file(dialect).path.clone()),
                Some(&format!(
                    "version {} is present",
                    baseline_migration.version
                )),
                Some("missing"),
                &format!(
                    "baseline migration {} was deleted; restore it and add migration {}",
                    baseline_migration.version, next_version
                ),
            ));
            continue;
        };

        if current_migration.description != baseline_migration.description {
            result.push(history_diagnostic(
                base_revision,
                next_version,
                MigrationDialect::ALL.map(|dialect| current_migration.file(dialect).path.clone()),
                Some(&baseline_migration.description),
                Some(&current_migration.description),
                &format!(
                    "baseline migration {} description changed; restore it and add migration {}",
                    baseline_migration.version, next_version
                ),
            ));
        }

        for dialect in MigrationDialect::ALL {
            let baseline_file = baseline_migration.file(dialect);
            let current_file = current_migration.file(dialect);
            if baseline_file.path != current_file.path {
                let expected_path = declared_path_display(&baseline_file.path);
                let observed_path = declared_path_display(&current_file.path);
                result.push(history_diagnostic(
                    base_revision,
                    next_version,
                    [baseline_file.path.clone(), current_file.path.clone()],
                    Some(&expected_path),
                    Some(&observed_path),
                    &format!(
                        "baseline migration {} {} path changed; restore it and add migration {}",
                        baseline_migration.version, dialect, next_version
                    ),
                ));
            }
            if baseline_file.sha256 != current_file.sha256 {
                result.push(history_diagnostic(
                    base_revision,
                    next_version,
                    [baseline_file.path.clone(), current_file.path.clone()],
                    Some(&baseline_file.sha256),
                    Some(&current_file.sha256),
                    &format!(
                        "baseline migration {} {} checksum changed; restore it and add migration {}",
                        baseline_migration.version, dialect, next_version
                    ),
                ));
            }
            let Some(baseline_bytes) = baseline_files.get(&(baseline_migration.version, dialect))
            else {
                continue;
            };
            let Ok(current_bytes) = read_migration_file(root, current_file, dialect) else {
                continue;
            };
            if baseline_bytes != &current_bytes {
                let baseline_hash = sha256_hex(baseline_bytes);
                let current_hash = sha256_hex(&current_bytes);
                result.push(history_diagnostic(
                    base_revision,
                    next_version,
                    [baseline_file.path.clone(), current_file.path.clone()],
                    Some(&baseline_hash),
                    Some(&current_hash),
                    &format!(
                        "baseline migration {} {} SQL bytes changed; restore it and add migration {}",
                        baseline_migration.version, dialect, next_version
                    ),
                ));
            }
        }
    }
}

fn load_baseline_files(
    root: &Path,
    revision: &str,
    inventory: &MigrationInventory,
) -> Result<BTreeMap<(u64, MigrationDialect), Vec<u8>>, String> {
    let mut files = BTreeMap::new();
    for migration in &inventory.migrations {
        for dialect in MigrationDialect::ALL {
            let declaration = migration.file(dialect);
            let display_path = declared_path_display(&declaration.path);
            let bytes = git_file(root, revision, &declaration.path).map_err(|reason| {
                format!(
                    "unable to read baseline {} migration `{}`: {reason}",
                    dialect, display_path
                )
            })?;
            let observed = sha256_hex(&bytes);
            if observed != declaration.sha256 {
                return Err(format!(
                    "baseline {} migration `{}` checksum does not match its inventory",
                    dialect, display_path
                ));
            }
            if bytes.len() > MAX_MIGRATION_SQL_BYTES || std::str::from_utf8(&bytes).is_err() {
                return Err(format!(
                    "baseline {} migration `{}` is not bounded UTF-8 SQL",
                    dialect, display_path
                ));
            }
            files.insert((migration.version, dialect), bytes);
        }
    }
    Ok(files)
}

fn history_diagnostic<I, P>(
    base_revision: &str,
    next_version: u64,
    paths: I,
    expected: Option<&str>,
    observed: Option<&str>,
    detail: &str,
) -> ContractDiagnostic
where
    I: IntoIterator<Item = P>,
    P: AsRef<str>,
{
    let repair = format!(
        "restore the baseline migration from {base_revision} and add migration {next_version}"
    );
    let paths = paths
        .into_iter()
        .map(|path| declared_path_display(path.as_ref()))
        .collect::<Vec<_>>();
    ContractDiagnostic::new(
        ContractDiagnosticCode::MigrationHistory,
        Some(ContractArtifactKind::MigrationInventory),
        Some(MIGRATION_SCOPE),
        MIGRATION_OWNER,
        paths,
        [MIGRATION_INVENTORY_PATH],
        None::<&str>,
        expected,
        observed,
        Some(format!("add migration {next_version}")),
        Some(true),
        repair,
    )
    .with_detail(detail)
}

fn unavailable_diagnostic(
    base_revision: &str,
    detail: &str,
    merge_base_available: bool,
) -> ContractDiagnostic {
    ContractDiagnostic::new(
        ContractDiagnosticCode::MigrationHistory,
        Some(ContractArtifactKind::MigrationInventory),
        Some(MIGRATION_SCOPE),
        MIGRATION_OWNER,
        [MIGRATION_INVENTORY_PATH],
        std::iter::empty::<&str>(),
        None::<&str>,
        Some(base_revision),
        Some("unavailable"),
        Some("history evidence unavailable"),
        Some(merge_base_available),
        "rerun with `distributed contracts check --base <revision>`",
    )
    .with_detail(detail)
}

fn diagnostic_for_error(error: &ContractError) -> ContractDiagnostic {
    ContractDiagnostic::new(
        error.code(),
        Some(ContractArtifactKind::MigrationInventory),
        Some(MIGRATION_SCOPE),
        MIGRATION_OWNER,
        [MIGRATION_INVENTORY_PATH],
        std::iter::empty::<&str>(),
        None::<&str>,
        None,
        None,
        None::<&str>,
        None,
        "inspect migrations/inventory.json and declared SQL files",
    )
    .with_detail(error.message())
}

fn inventory_error(message: String) -> ContractError {
    ContractError::new(ContractDiagnosticCode::MigrationInventory, message)
}

fn validate_json_nesting(input: &str) -> Result<(), ContractError> {
    let mut depth = 0usize;
    let mut escaped = false;
    let mut in_string = false;

    for byte in input.bytes() {
        if in_string {
            if escaped {
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == b'"' {
                in_string = false;
            }
            continue;
        }

        match byte {
            b'"' => in_string = true,
            b'{' | b'[' => {
                depth = depth.saturating_add(1);
                if depth > MAX_MIGRATION_JSON_DEPTH {
                    return Err(inventory_error(
                        "migration inventory exceeds maximum JSON nesting depth".to_string(),
                    ));
                }
            }
            b'}' | b']' => depth = depth.saturating_sub(1),
            _ => {}
        }
    }

    Ok(())
}

fn validate_json_value(value: &Value, depth: usize) -> Result<(), ContractError> {
    if depth > MAX_MIGRATION_JSON_DEPTH {
        return Err(inventory_error(
            "migration inventory exceeds maximum JSON nesting depth".to_string(),
        ));
    }
    match value {
        Value::Object(object) => {
            for (key, child) in object {
                if is_secret_like(key) {
                    return Err(inventory_error(format!(
                        "migration inventory contains a credential-like field `{key}`"
                    )));
                }
                let child_depth = if child.is_object() || child.is_array() {
                    depth + 1
                } else {
                    depth
                };
                validate_json_value(child, child_depth)?;
            }
        }
        Value::Array(array) => {
            if array.len() > MAX_MIGRATIONS * 4 {
                return Err(inventory_error(
                    "migration inventory contains too many JSON array values".to_string(),
                ));
            }
            for child in array {
                let child_depth = if child.is_object() || child.is_array() {
                    depth + 1
                } else {
                    depth
                };
                validate_json_value(child, child_depth)?;
            }
        }
        Value::String(string) => {
            if string.len() > 4 * 1024 {
                return Err(inventory_error(
                    "migration inventory contains an oversized string".to_string(),
                ));
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) => {}
    }
    Ok(())
}

fn validate_description(description: &str, version: u64) -> Result<(), ContractError> {
    if description.is_empty()
        || description.trim() != description
        || description.len() > 4 * 1024
        || description.contains('\0')
        || is_secret_like(description)
    {
        return Err(inventory_error(format!(
            "migration {version} description is empty, sensitive, or not portable"
        )));
    }
    Ok(())
}

fn validate_checksum(checksum: &str, path: &str) -> Result<(), ContractError> {
    if checksum.len() != 64
        || !checksum.bytes().all(|byte| byte.is_ascii_hexdigit())
        || checksum
            .chars()
            .any(|character| character.is_ascii_uppercase())
    {
        return Err(inventory_error(format!(
            "migration `{}` must declare one lowercase 64-character SHA-256 checksum",
            declared_path_display(path)
        )));
    }
    Ok(())
}

fn validate_migration_path(path: &str, dialect: MigrationDialect) -> Result<(), ContractError> {
    let display_path = declared_path_display(path);
    if path.is_empty()
        || path.trim() != path
        || path.len() > 4 * 1024
        || path.contains('\0')
        || path.contains('\\')
        || !path.ends_with(".sql")
    {
        return Err(inventory_error(format!(
            "{} migration path `{display_path}` is not a portable SQL path",
            dialect,
        )));
    }
    let path_value = Path::new(path);
    if path_value.is_absolute()
        || path_value
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
        || !path_value.starts_with(dialect.directory())
    {
        return Err(inventory_error(format!(
            "{} migration path `{display_path}` must remain beneath `{}`",
            dialect,
            dialect.directory()
        )));
    }
    if is_secret_like(path) {
        return Err(inventory_error(format!(
            "{} migration path `{display_path}` contains sensitive material",
            dialect,
        )));
    }
    Ok(())
}

fn declared_path_display(path: &str) -> String {
    let path_value = Path::new(path);
    if is_secret_like(path)
        || path_value.is_absolute()
        || path.contains('\\')
        || path_value
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        REDACTED_MIGRATION_PATH.to_string()
    } else {
        path.to_string()
    }
}

fn canonical_repository_root(root: &Path) -> Result<PathBuf, ContractError> {
    let metadata = fs::symlink_metadata(root)
        .map_err(|error| inventory_error(format!("inspect migration repository root: {error}")))?;
    if metadata.file_type().is_symlink() {
        return Err(ContractError::new(
            ContractDiagnosticCode::CatalogSymlinkEscape,
            "migration repository root must not be a symlink".to_string(),
        ));
    }
    let root = fs::canonicalize(root)
        .map_err(|error| inventory_error(format!("resolve migration repository root: {error}")))?;
    let metadata = fs::metadata(&root)
        .map_err(|error| inventory_error(format!("inspect migration repository root: {error}")))?;
    if !metadata.is_dir() {
        return Err(inventory_error(
            "migration repository root is not a directory".to_string(),
        ));
    }
    Ok(root)
}

fn relative_path(root: &Path, path: &Path) -> Result<PathBuf, ContractError> {
    let current_directory = std::env::current_dir()
        .map_err(|error| inventory_error(format!("resolve current directory: {error}")))?;
    let absolute_root = if root.is_absolute() {
        root.to_path_buf()
    } else {
        current_directory.join(root)
    };
    let absolute_path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        current_directory.join(path)
    };
    absolute_path
        .strip_prefix(&absolute_root)
        .map(Path::to_path_buf)
        .map_err(|_| {
            inventory_error("migration inventory path escaped repository root".to_string())
        })
}

fn inferred_repository_root(path: &Path) -> PathBuf {
    if path.file_name().and_then(|name| name.to_str()) == Some("inventory.json")
        && path
            .parent()
            .and_then(Path::file_name)
            .and_then(|name| name.to_str())
            == Some("migrations")
    {
        return path
            .parent()
            .and_then(Path::parent)
            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    }
    path.parent()
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}

fn read_migration_file(
    root: &Path,
    declaration: &MigrationFile,
    dialect: MigrationDialect,
) -> Result<Vec<u8>, ContractError> {
    let path = root.join(&declaration.path);
    let display_path = declared_path_display(&declaration.path);
    let mut current = root.to_path_buf();
    let components = Path::new(&declaration.path)
        .components()
        .collect::<Vec<_>>();
    for (index, component) in components.iter().enumerate() {
        let Component::Normal(component) = component else {
            return Err(inventory_error(format!(
                "{} migration path `{}` contains traversal",
                dialect, display_path
            )));
        };
        current.push(component);
        let metadata = fs::symlink_metadata(&current).map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                inventory_error(format!(
                    "missing {} migration file `{}`",
                    dialect, display_path
                ))
            } else {
                inventory_error(format!(
                    "inspect {} migration file `{}`: {error}",
                    dialect, display_path
                ))
            }
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ContractError::new(
                ContractDiagnosticCode::CatalogSymlinkEscape,
                format!(
                    "{} migration file `{}` must not be a symlink",
                    dialect, display_path
                ),
            ));
        }
        if index + 1 != components.len() && !metadata.is_dir() {
            return Err(inventory_error(format!(
                "{} migration path `{}` has a non-directory parent",
                dialect, display_path
            )));
        }
    }
    let metadata = fs::metadata(&path).map_err(|error| {
        inventory_error(format!(
            "inspect {} migration file `{}`: {error}",
            dialect, display_path
        ))
    })?;
    if !metadata.is_file() {
        return Err(
            ContractDiagnosticCode::CatalogSpecialFile.into_error(format!(
                "{} migration file `{}` is not regular",
                dialect, display_path
            )),
        );
    }
    let file = File::open(&path).map_err(|error| {
        inventory_error(format!(
            "open {} migration file `{}`: {error}",
            dialect, display_path
        ))
    })?;
    let opened_metadata = file.metadata().map_err(|error| {
        inventory_error(format!(
            "inspect opened {} migration file `{}`: {error}",
            dialect, display_path
        ))
    })?;
    if !opened_metadata.is_file() {
        return Err(
            ContractDiagnosticCode::CatalogSpecialFile.into_error(format!(
                "opened {} migration file `{}` is not regular",
                dialect, display_path
            )),
        );
    }
    if opened_metadata.len() > MAX_MIGRATION_SQL_BYTES as u64 {
        return Err(inventory_error(format!(
            "{} migration file `{}` exceeds {MAX_MIGRATION_SQL_BYTES} bytes",
            dialect, display_path
        )));
    }
    let mut bytes = Vec::with_capacity(opened_metadata.len() as usize);
    file.take(MAX_MIGRATION_SQL_BYTES as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| {
            inventory_error(format!(
                "read {} migration file `{}`: {error}",
                dialect, display_path
            ))
        })?;
    if bytes.len() > MAX_MIGRATION_SQL_BYTES {
        return Err(inventory_error(format!(
            "{} migration file `{}` exceeds {MAX_MIGRATION_SQL_BYTES} bytes",
            dialect, display_path
        )));
    }
    Ok(bytes)
}

fn relative_path_display(root: &Path, path: &Path) -> String {
    let relative = path
        .strip_prefix(root)
        .map(|relative| {
            relative
                .to_string_lossy()
                .replace(std::path::MAIN_SEPARATOR, "/")
        })
        .unwrap_or_else(|_| "<outside-repository>".to_string());
    declared_path_display(&relative)
}

fn collect_sql_files(
    root: &Path,
    dialect: MigrationDialect,
) -> Result<BTreeSet<(MigrationDialect, String)>, ContractError> {
    let directory = root.join(dialect.directory());
    let mut result = BTreeSet::new();
    let mut pending = vec![directory];
    let mut directories = 0;
    let mut entries_seen = 0usize;
    while let Some(directory) = pending.pop() {
        directories += 1;
        if directories > DIALECT_DIRECTORY_LIMIT {
            return Err(inventory_error(format!(
                "{} migration directory tree exceeds {DIALECT_DIRECTORY_LIMIT} directories",
                dialect
            )));
        }
        let directory_metadata = fs::symlink_metadata(&directory).map_err(|error| {
            inventory_error(format!(
                "inspect {} migration directory `{}`: {error}",
                dialect,
                relative_path_display(root, &directory)
            ))
        })?;
        if directory_metadata.file_type().is_symlink() {
            return Err(ContractError::new(
                ContractDiagnosticCode::CatalogSymlinkEscape,
                format!(
                    "{} migration directory `{}` must not be a symlink",
                    dialect,
                    relative_path_display(root, &directory)
                ),
            ));
        }
        if !directory_metadata.is_dir() {
            return Err(inventory_error(format!(
                "{} migration directory `{}` is not a directory",
                dialect,
                relative_path_display(root, &directory)
            )));
        }
        let mut read_entries = fs::read_dir(&directory).map_err(|error| {
            inventory_error(format!(
                "read {} migration directory `{}`: {error}",
                dialect,
                relative_path_display(root, &directory)
            ))
        })?;
        let remaining_entries = MAX_MIGRATION_TOTAL_ENTRIES - entries_seen;
        let mut entries = Vec::with_capacity(remaining_entries);
        loop {
            let Some(entry) = read_entries.next() else {
                break;
            };
            if entries_seen >= MAX_MIGRATION_TOTAL_ENTRIES {
                return Err(inventory_error(format!(
                    "{} migration directory tree exceeds {MAX_MIGRATION_TOTAL_ENTRIES} entries",
                    dialect
                )));
            }
            entries_seen += 1;
            entries.push(entry.map_err(|error| {
                inventory_error(format!("read {dialect} migration directory entry: {error}"))
            })?);
        }
        entries.sort_by_key(|entry| entry.file_name());
        for entry in entries {
            let path = entry.path();
            let metadata = fs::symlink_metadata(&path).map_err(|error| {
                inventory_error(format!(
                    "inspect {dialect} migration directory entry `{}`: {error}",
                    relative_path_display(root, &path)
                ))
            })?;
            if metadata.file_type().is_symlink() {
                return Err(ContractError::new(
                    ContractDiagnosticCode::CatalogSymlinkEscape,
                    format!(
                        "{} migration path `{}` must not be a symlink",
                        dialect,
                        relative_path_display(root, &path)
                    ),
                ));
            }
            if metadata.is_dir() {
                pending.push(path);
                continue;
            }
            if !metadata.is_file() {
                return Err(
                    ContractDiagnosticCode::CatalogSpecialFile.into_error(format!(
                        "{} migration path `{}` is not regular",
                        dialect,
                        relative_path_display(root, &path)
                    )),
                );
            }
            if path.extension().and_then(|extension| extension.to_str()) != Some("sql") {
                continue;
            }
            let relative = path
                .strip_prefix(root)
                .map_err(|_| inventory_error("migration path escaped repository root".to_string()))?
                .to_string_lossy()
                .replace(std::path::MAIN_SEPARATOR, "/");
            result.insert((dialect, relative));
            if result.len() > MAX_MIGRATIONS * 2 {
                return Err(inventory_error(
                    "migration directory contains too many SQL files".to_string(),
                ));
            }
        }
    }
    Ok(result)
}

fn validate_no_extra_dialect_directories(root: &Path) -> Result<(), ContractError> {
    let migrations = root.join("migrations");
    let migrations_metadata = fs::symlink_metadata(&migrations)
        .map_err(|error| inventory_error(format!("inspect migrations directory: {error}")))?;
    if migrations_metadata.file_type().is_symlink() {
        return Err(ContractError::new(
            ContractDiagnosticCode::CatalogSymlinkEscape,
            "migrations directory must not be a symlink".to_string(),
        ));
    }
    if !migrations_metadata.is_dir() {
        return Err(inventory_error(
            "migrations path is not a directory".to_string(),
        ));
    }
    let mut read_entries = fs::read_dir(&migrations)
        .map_err(|error| inventory_error(format!("read migrations directory: {error}")))?;
    let mut entries_seen = 0usize;
    let mut entries = Vec::with_capacity(MAX_MIGRATION_TOP_LEVEL_ENTRIES);
    loop {
        let Some(entry) = read_entries.next() else {
            break;
        };
        if entries_seen >= MAX_MIGRATION_TOP_LEVEL_ENTRIES {
            return Err(inventory_error(format!(
                "migrations directory exceeds {MAX_MIGRATION_TOP_LEVEL_ENTRIES} entries"
            )));
        }
        entries_seen += 1;
        entries.push(
            entry.map_err(|error| inventory_error(format!("read migrations entry: {error}")))?,
        );
    }
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path)
            .map_err(|error| inventory_error(format!("inspect migrations entry: {error}")))?;
        if metadata.file_type().is_symlink() {
            return Err(ContractError::new(
                ContractDiagnosticCode::CatalogSymlinkEscape,
                format!(
                    "migration path `{}` must not be a symlink",
                    relative_path_display(root, &path)
                ),
            ));
        }
        if !metadata.is_dir() {
            continue;
        }
        let name = path
            .file_name()
            .and_then(|value| value.to_str())
            .unwrap_or_default();
        if !matches!(name, "sqlite" | "postgres") {
            return Err(inventory_error(format!(
                "unsupported migration dialect directory `{}`",
                relative_path_display(root, &path)
            )));
        }
    }
    Ok(())
}

fn reject_symlink_components(
    root: &Path,
    relative: &Path,
    label: &str,
) -> Result<(), ContractError> {
    let display_path = declared_path_display(&relative.to_string_lossy());
    let mut current = root.to_path_buf();
    for component in relative.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                return Err(inventory_error(format!(
                    "{label} path `{}` contains parent traversal",
                    display_path
                )));
            }
            Component::Normal(part) => current.push(part),
            Component::Prefix(_) | Component::RootDir => {
                return Err(inventory_error(format!(
                    "{label} path `{}` is not relative to the repository root",
                    display_path
                )));
            }
        }
        let metadata = fs::symlink_metadata(&current).map_err(|error| {
            inventory_error(format!("inspect {label} path `{}`: {error}", display_path))
        })?;
        if metadata.file_type().is_symlink() {
            return Err(ContractError::new(
                ContractDiagnosticCode::CatalogSymlinkEscape,
                format!(
                    "{label} path `{}` must not traverse a symlink",
                    display_path
                ),
            ));
        }
    }
    Ok(())
}

fn read_bounded_file(path: &Path, limit: usize, label: &str) -> Result<Vec<u8>, ContractError> {
    let metadata = fs::symlink_metadata(path)
        .map_err(|error| inventory_error(format!("read {label}: {error}")))?;
    if metadata.file_type().is_symlink() {
        return Err(ContractError::new(
            ContractDiagnosticCode::CatalogSymlinkEscape,
            format!("{label} must not be a symlink"),
        ));
    }
    if !metadata.is_file() {
        return Err(ContractDiagnosticCode::CatalogSpecialFile
            .into_error(format!("{label} is not a regular file")));
    }
    if metadata.len() > limit as u64 {
        return Err(inventory_error(format!(
            "{label} is {} bytes; maximum supported size is {limit}",
            metadata.len()
        )));
    }
    let file =
        File::open(path).map_err(|error| inventory_error(format!("read {label}: {error}")))?;
    let opened_size = file
        .metadata()
        .map_err(|error| inventory_error(format!("inspect opened {label}: {error}")))?;
    if !opened_size.is_file() {
        return Err(ContractDiagnosticCode::CatalogSpecialFile
            .into_error(format!("opened {label} is not a regular file")));
    }
    let opened_size = opened_size.len();
    if opened_size > limit as u64 {
        return Err(inventory_error(format!(
            "opened {label} is {opened_size} bytes; maximum supported size is {limit}"
        )));
    }
    let mut bytes = Vec::with_capacity(opened_size as usize);
    file.take(limit as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|error| inventory_error(format!("read {label}: {error}")))?;
    if bytes.len() > limit {
        return Err(inventory_error(format!("{label} exceeds {limit} bytes")));
    }
    Ok(bytes)
}

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

fn valid_revision(revision: &str) -> bool {
    !revision.is_empty()
        && revision.trim() == revision
        && !revision.starts_with('-')
        && !revision.contains(':')
        && !revision.chars().any(char::is_control)
        && !revision.chars().any(char::is_whitespace)
}

fn git_revision_exists(root: &Path, revision: &str) -> bool {
    Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["rev-parse", "--verify", "--quiet", "--end-of-options"])
        .arg(format!("{revision}^{{commit}}"))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_ok_and(|status| status.success())
}

fn git_file(root: &Path, revision: &str, path: &str) -> Result<Vec<u8>, String> {
    let object = format!("{revision}:{path}");
    let limit = if path == MIGRATION_INVENTORY_PATH {
        MAX_MIGRATION_INVENTORY_BYTES
    } else {
        MAX_MIGRATION_SQL_BYTES
    };
    let mut child = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["show", "--no-ext-diff", "--format=", "--end-of-options"])
        .arg(object)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|_| "could not invoke Git for the explicit revision".to_string())?;
    let mut stdout = child.stdout.take().ok_or_else(|| {
        terminate_child(&mut child);
        "Git did not provide a readable baseline stream".to_string()
    })?;
    let mut bytes = Vec::new();
    let mut buffer = [0u8; 8 * 1024];
    loop {
        match stdout.read(&mut buffer) {
            Ok(0) => break,
            Ok(read) => {
                if read > limit.saturating_sub(bytes.len()) {
                    terminate_child(&mut child);
                    return Err(format!("baseline file exceeds {limit} bytes"));
                }
                bytes.extend_from_slice(&buffer[..read]);
            }
            Err(_) => {
                terminate_child(&mut child);
                return Err("could not read the explicit Git baseline file".to_string());
            }
        }
    }
    drop(stdout);
    let status = child
        .wait()
        .map_err(|_| "could not wait for Git baseline file".to_string())?;
    if !status.success() {
        return Err("Git did not provide the requested baseline file".to_string());
    }
    Ok(bytes)
}

fn terminate_child(child: &mut std::process::Child) {
    let _ = child.kill();
    let _ = child.wait();
}

trait DiagnosticCodeError {
    fn into_error(self, message: String) -> ContractError;
}

impl DiagnosticCodeError for ContractDiagnosticCode {
    fn into_error(self, message: String) -> ContractError {
        ContractError::new(self, message)
    }
}