cursor-setup-system 0.0.60

Install, update, back up, restore and remove complete Cursor CLI configurations. Built by NDDev.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
//! Reading and checking an `ai-stp-bundle/1` before anything is written.
//!
//! The order of checks is the contract's, and it matters. The raw bytes are
//! hashed *before* the archive is parsed, so a corrupted artifact is refused by
//! a cheap comparison rather than by whatever a parser makes of it. Only then is
//! the canonical shape read, the manifest parsed, and each file matched against
//! the record that declares it.
//!
//! Nothing here writes. A bundle that passes every check is still only a bundle
//! that may be planned; materializing it happens later, under the lock, through
//! the same kernel every other effect uses.
//!
//! # Three identities, three checks
//!
//! - `artifact_digest` — plain SHA-256 of the exact ZIP bytes.
//! - `bundle_digest` — the manifest's own identity, in the `ai-stp:bundle:v1`
//!   domain, over the canonical manifest *without* its own digest field.
//! - each file's `digest` — SHA-256 of that file's bytes.
//!
//! They are deliberately not derivable from one another. A provider that
//! computed one from another would be checking its own arithmetic instead of the
//! sender's claim.

use std::collections::{BTreeMap, BTreeSet};

use serde::Deserialize;
use crate::setup_core::digest;

use crate::provider_v3::error::{Error, Result};
use crate::provider_v3::info::ProjectionProfile;
use crate::provider_v3::reason::WireReason;
use crate::provider_v3::zip;

/// The digest domain for a bundle manifest.
pub const BUNDLE_DOMAIN: &str = "ai-stp:bundle:v1";

/// The original format tag, kept byte-identical during the v2 rollout.
pub const BUNDLE_FORMAT: &str = "ai-stp-bundle/2";

/// The adaptation-bound format.
#[cfg(test)]
const RETIRED_BUNDLE_FORMAT_V1: &str = "ai-stp-bundle/1";

/// The protocol version a bundle manifest declares.
///
/// This is **not** the provider protocol. A bundle is `ai-stp-bundle/1` and says
/// `protocol_version: 1`; the provider speaking about it is protocol v3. Two
/// numbers, two contracts, one field name each — comparing a manifest against
/// the provider's version rejects every well-formed bundle, and does it with a
/// message that sounds right.
pub const BUNDLE_PROTOCOL_VERSION: u32 = 1;

/// The manifest member, always first.
pub const MANIFEST_MEMBER: &str = "bundle.json";

/// The prefix under which managed files live.
pub const FILES_PREFIX: &str = "files/";

/// The members the format requires, in the order it requires them.
pub const REQUIRED_MEMBERS: &[&str] = &[
    "bundle.json",
    "setup-passport.json",
    "composition-report.json",
    "conversion-report.json",
];

/// The only file modes a bundle may carry.
const ALLOWED_MODES: &[u32] = &[0o644, 0o755];

/// The contract's own limits, which no bundle may raise.
///
/// A manifest *reports* its limits; it does not set them. Taking the bundle's
/// word would let a hostile one declare a ceiling of its own choosing and then
/// sit comfortably under it. The effective limit is the smaller of what the
/// contract fixes and what the bundle claims.
pub const CONTRACT_MAX_FILES: u64 = 2000;
/// The largest single file the contract admits: 4 MiB.
pub const CONTRACT_MAX_FILE_BYTES: u64 = 4 * 1024 * 1024;
/// The largest archive the contract admits: 64 MiB.
pub const CONTRACT_MAX_BUNDLE_BYTES: u64 = 64 * 1024 * 1024;

/// Path segments and names that mean credentials, refused by name.
///
/// Opening a file to decide whether it holds a secret is the very act this rule
/// exists to prevent, so the decision is made from the name alone.
const SECRET_MARKERS: &[&str] = &[
    "credentials",
    ".credentials.json",
    "auth.json",
    ".netrc",
    "id_rsa",
    "id_ed25519",
    ".pem",
    ".p12",
    "secrets",
];

/// What a manifest record says a file *is*.
///
/// A bundle declares this rather than leaving it to the container, and that is
/// deliberate: a ZIP has no portable hard-link member, so a hostile bundle could
/// carry one as an ordinary file. The declared kind is refused on its own terms,
/// and a provider must not reinterpret it as a regular file merely because the
/// archive format cannot express the difference.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FileKind {
    /// An ordinary file, the only kind that is materialized.
    #[default]
    File,
    /// A symbolic link.
    Symlink,
    /// A hard link.
    Hardlink,
    /// A device, socket or pipe.
    Special,
    /// A kind this build does not know.
    #[serde(other)]
    Unknown,
}

/// What a compiler says it turned each component into.
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
pub struct ConversionReport {
    /// Whether every component was converted.
    #[serde(default)]
    pub complete: bool,
    /// One entry per component.
    #[serde(default)]
    pub entries: Vec<ConversionEntry>,
}

/// One component, and the kind the compiler assigned it.
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
pub struct ConversionEntry {
    /// The component's stable identity.
    #[serde(default)]
    pub stable_id: String,
    /// The component kind. Checked against what a provider declares.
    #[serde(default)]
    pub component_type: String,
    /// Where it was written, relative to the target.
    #[serde(default)]
    pub native_surface: String,
}

/// One record in the bundle's file manifest.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct BundleFile {
    /// The normalized relative path this file takes in the target.
    pub path: String,
    /// SHA-256 of the file's bytes.
    pub digest: String,
    /// The exact byte length.
    pub byte_length: u64,
    /// The Unix mode, one of 0o644 or 0o755.
    pub mode: u32,
    /// Which surface owns it.
    #[serde(default)]
    pub owner: String,
    /// What this record says the file is. Absent means an ordinary file.
    #[serde(default)]
    pub kind: FileKind,
}

/// The limits a manifest reports.
///
/// Reported, not set. See [`Manifest::effective_max_files`] and its siblings.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
pub struct Limits {
    /// The file count this bundle reports.
    #[serde(default)]
    pub max_files: Option<u64>,
    /// The per-file byte count this bundle reports.
    #[serde(default)]
    pub max_file_bytes: Option<u64>,
    /// The archive byte count this bundle reports.
    #[serde(default)]
    pub max_bundle_bytes: Option<u64>,
}

/// The exact provider profile selected by the v2 compiler.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ProjectionProfileBinding {
    /// Stable profile identifier.
    pub profile_id: String,
    /// Content-derived identity of the provider declaration.
    pub profile_digest: String,
    /// Resolved bundle target scope.
    pub target_scope: String,
}

/// One immutable projection artifact named by a component adaptation.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ProjectionArtifactBinding {
    /// Domain-separated digest from the component passport.
    pub digest: String,
    /// Exact projection archive byte length.
    pub size_bytes: u64,
}

/// One component version's exact adaptation atom in a v2 bundle.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ComponentAdaptationBinding {
    /// Stable component identity.
    pub stable_id: String,
    /// Exact component version.
    pub version: String,
    /// Exact component-version passport digest.
    pub passport_digest: String,
    /// Content-derived adaptation identity.
    pub adaptation_id: String,
    /// Exact immutable projection artifact.
    pub projection_artifact: ProjectionArtifactBinding,
    /// Provider-native component vocabulary member.
    pub provider_component_kind: String,
    /// Projection vocabulary member selected by the adaptation.
    pub projection_kind: String,
    /// Sorted exact paths the adaptation artifact declares.
    #[serde(default)]
    pub member_paths: Vec<String>,
}

/// The `bundle.json` a compiler writes into the archive.
///
/// This is *not* the compiler's own result object. `cli-harness-bundle.schema.json`
/// describes the latter — a `CompiledBundle` with `compiled`, `refusals`, and a
/// flat `max_files` — and reading it as though it described the archive member
/// costs a day: every field name is plausible and every one is wrong.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct Manifest {
    /// Schema of this manifest.
    pub schema_version: u32,
    /// Always `ai-stp-bundle/1`.
    pub bundle_format: String,
    /// The *bundle* protocol, which is 1. Not the provider protocol.
    pub protocol_version: u32,
    /// The harness this bundle configures.
    pub harness_id: String,
    /// The resolved non-global scope. Absent means `global`.
    #[serde(default)]
    pub target_scope: Option<String>,
    /// Exact profile binding required by bundle v2.
    #[serde(default)]
    pub projection_profile: Option<ProjectionProfileBinding>,
    /// Sorted component adaptation bindings required by bundle v2.
    #[serde(default)]
    pub component_adaptations: Vec<ComponentAdaptationBinding>,
    /// What compiled it.
    #[serde(default)]
    pub builder_version: String,
    /// The manifest's own identity, over itself without this field.
    pub bundle_digest: String,
    /// The digest of the compiler's input.
    #[serde(default)]
    pub input_digest: String,
    /// What the compiler turned each component into.
    ///
    /// This is the only place a component's *kind* is stated: the manifest does
    /// not carry kinds and the setup passport carries references without them.
    /// A provider that never reads this cannot tell that it has been handed a
    /// kind it does not implement -- and a hostile bundle declaring one is
    /// exactly the case the consumer's corpus drives.
    #[serde(default)]
    pub conversion_report: ConversionReport,
    /// Every path this bundle is allowed to write.
    #[serde(default)]
    pub managed_paths: Vec<String>,
    /// The file manifest.
    #[serde(default)]
    pub files: Vec<BundleFile>,
    /// The limits this bundle reports.
    #[serde(default)]
    pub limits: Limits,
}

impl Manifest {
    /// The effective file-count limit: the contract's, never raised.
    #[must_use]
    pub fn effective_max_files(&self) -> u64 {
        self.limits
            .max_files
            .map_or(CONTRACT_MAX_FILES, |c| c.min(CONTRACT_MAX_FILES))
    }

    /// The effective per-file limit: the contract's, never raised.
    #[must_use]
    pub fn effective_max_file_bytes(&self) -> u64 {
        self.limits
            .max_file_bytes
            .map_or(CONTRACT_MAX_FILE_BYTES, |c| c.min(CONTRACT_MAX_FILE_BYTES))
    }

    /// The effective archive limit: the contract's, never raised.
    #[must_use]
    pub fn effective_max_bundle_bytes(&self) -> u64 {
        self.limits
            .max_bundle_bytes
            .map_or(CONTRACT_MAX_BUNDLE_BYTES, |c| {
                c.min(CONTRACT_MAX_BUNDLE_BYTES)
            })
    }
}

/// A bundle that passed every check, with its files ready to materialize.
#[derive(Debug, Clone)]
pub struct Bundle {
    /// The manifest as read.
    pub manifest: Manifest,
    /// What the setup passport says the setup is.
    pub passport: SetupPassport,
    /// Each declared file's bytes and mode, by target-relative path.
    pub files: BTreeMap<String, (Vec<u8>, u32)>,
}

/// The two things the setup passport states that a provider must record.
///
/// `setup-passport.json` is a required member and was required and then
/// discarded, so a target configured from a bundle recorded no setup identity
/// and no setup version at all -- both are provenance fields the contract names,
/// and both were null for every bundle install.
///
/// Only what the passport *states* is copied. Its own digest is not computed
/// here: the passport does not carry one and the contract does not define how
/// it is taken, so a value produced here would be this program's opinion rather
/// than the passport's identity, and that is worse than the null the field is
/// allowed to hold. Everything else the passport carries -- tags, permissions,
/// component version references, evidence links -- belongs to the consumer.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
pub struct SetupPassport {
    /// The setup's stable identity.
    #[serde(default)]
    pub stable_id: String,
    /// The setup version this bundle was built from.
    #[serde(default)]
    pub version: String,
}

/// What the caller claimed about the bytes it sent.
#[derive(Debug, Clone, Copy)]
pub struct Claim<'a> {
    /// The format tag from argv.
    pub bundle_format: &'a str,
    /// The logical manifest digest from argv.
    pub bundle_digest: &'a str,
    /// The raw artifact digest from argv.
    pub artifact_digest: &'a str,
    /// The exact byte count from argv.
    pub bundle_size: u64,
    /// The harness this provider configures.
    pub harness_id: &'a str,
}

impl Bundle {
    /// Check exact bytes against an exact claim.
    ///
    /// # Errors
    ///
    /// Refuses with the contract's reason for the first check that fails. Every
    /// refusal happens before anything is written, because nothing here writes.
    pub fn read(bytes: &[u8], claim: Claim<'_>) -> Result<Self> {
        if claim.bundle_format != BUNDLE_FORMAT {
            return Err(Error::refuse(
                WireReason::UnsupportedBundleFormat,
                format!("{:?} is not a supported bundle format", claim.bundle_format),
            ));
        }
        // The raw bytes are checked before the parser sees them: a corrupted
        // artifact should be refused by a comparison, not by whatever a parser
        // makes of it.
        let actual_length = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
        if actual_length != claim.bundle_size {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                format!(
                    "the artifact is {actual_length} bytes, not {}",
                    claim.bundle_size
                ),
            ));
        }
        if digest::of_bytes(bytes) != claim.artifact_digest {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                "the artifact bytes do not hash to the digest that named them",
            ));
        }

        let members = zip::read(bytes)?;
        let manifest_bytes = require_members(&members)?;
        let manifest = parse_manifest(manifest_bytes)?;

        if manifest.bundle_format != claim.bundle_format {
            return Err(Error::refuse(
                WireReason::UnsupportedBundleFormat,
                format!("the manifest declares {:?}", manifest.bundle_format),
            ));
        }
        if manifest.protocol_version != BUNDLE_PROTOCOL_VERSION {
            return Err(Error::refuse(
                WireReason::UnsupportedProtocolVersion,
                format!(
                    "the manifest declares bundle protocol {}, and this reader speaks {BUNDLE_PROTOCOL_VERSION}",
                    manifest.protocol_version
                ),
            ));
        }
        if manifest.harness_id != claim.harness_id {
            return Err(Error::refuse(
                WireReason::ProjectionProfileMismatch,
                format!(
                    "the bundle is for harness {:?}, and this provider configures {:?}",
                    manifest.harness_id, claim.harness_id
                ),
            ));
        }
        check_adaptation_bindings(&manifest)?;
        let files = check_files(&manifest, &members, actual_length)?;

        // The manifest's own identity is checked after the files, so a bundle
        // with a concrete defect reports that defect rather than an unstated
        // field. The artifact digest -- the one that proves these are the bytes
        // the caller sent -- was already checked before the parser ran.
        check_manifest_digest(manifest_bytes, &manifest.bundle_digest)?;
        if manifest.bundle_digest != claim.bundle_digest {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                "the manifest's identity is not the one the caller named",
            ));
        }

        // The passport is required to be the second member and was, until now,
        // required and then discarded. What it states about the setup is the
        // only source for two provenance fields, and a malformed one is not a
        // reason to refuse a bundle whose files and digests all hold — so it is
        // read leniently and its absence of content reads as no content.
        let passport = members
            .get(1)
            .and_then(|member| serde_json::from_slice::<SetupPassport>(&member.data).ok())
            .unwrap_or_default();

        Ok(Self {
            manifest,
            passport,
            files,
        })
    }

    /// Bind a v2 manifest to the exact profile selected for this operation.
    ///
    /// V1 has no such fields and remains unchanged during the ordered rollout.
    ///
    /// # Errors
    ///
    /// Refuses a missing, mismatched or out-of-vocabulary v2 binding.
    pub fn require_projection_profile(&self, expected: &ProjectionProfile) -> Result<()> {
        let Some(binding) = self.manifest.projection_profile.as_ref() else {
            return Err(Error::refuse(
                WireReason::AdaptationBindingMissing,
                "bundle v2 has no projection_profile",
            ));
        };
        let expected_scope = expected.target_scope.as_deref().unwrap_or("global");
        if binding.profile_id != expected.profile_id
            || binding.profile_digest != expected.digest
            || binding.target_scope != expected_scope
        {
            return Err(Error::refuse(
                WireReason::ProjectionProfileMismatch,
                "bundle v2 was compiled for a different provider projection profile",
            ));
        }
        for adaptation in &self.manifest.component_adaptations {
            if !expected
                .component_kinds
                .contains(&adaptation.provider_component_kind)
                || !expected
                    .projection_kinds
                    .contains(&adaptation.projection_kind)
            {
                return Err(Error::refuse(
                    WireReason::AdaptationBindingMismatch,
                    format!(
                        "adaptation for {:?} names a kind outside the selected profile",
                        adaptation.stable_id
                    ),
                ));
            }
        }
        Ok(())
    }
}

fn canonical_digest(value: &str) -> bool {
    value.len() == 71
        && value.starts_with("sha256:")
        && value[7..]
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn canonical_adaptation_id(value: &str) -> bool {
    value.len() == 75
        && value.starts_with("adaptation_")
        && value[11..]
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// Validate v2's immutable bindings independently of the selected provider profile.
fn check_adaptation_bindings(manifest: &Manifest) -> Result<()> {
    if manifest.bundle_format != BUNDLE_FORMAT {
        return Err(Error::refuse(
            WireReason::UnsupportedBundleFormat,
            format!("the manifest declares {:?}", manifest.bundle_format),
        ));
    }
    let Some(profile) = manifest.projection_profile.as_ref() else {
        return Err(Error::refuse(
            WireReason::AdaptationBindingMissing,
            "bundle v2 has no projection_profile",
        ));
    };
    if manifest.component_adaptations.is_empty() {
        return Err(Error::refuse(
            WireReason::AdaptationBindingMissing,
            "bundle v2 has no component_adaptations",
        ));
    }
    let manifest_scope = manifest.target_scope.as_deref().unwrap_or("global");
    if profile.profile_id.is_empty()
        || !canonical_digest(&profile.profile_digest)
        || profile.target_scope != manifest_scope
    {
        return Err(Error::refuse(
            WireReason::ProjectionProfileMismatch,
            "bundle v2's profile binding is incomplete or names another scope",
        ));
    }

    let mut prior = None;
    let mut owners = BTreeSet::new();
    let mut bound_paths = BTreeSet::new();
    for binding in &manifest.component_adaptations {
        if prior.is_some_and(|value: &str| value >= binding.stable_id.as_str()) {
            return Err(Error::refuse(
                WireReason::AdaptationBindingMismatch,
                "component_adaptations are not strictly sorted by stable_id",
            ));
        }
        prior = Some(binding.stable_id.as_str());
        if binding.stable_id.is_empty()
            || binding.version.is_empty()
            || !canonical_digest(&binding.passport_digest)
            || !canonical_adaptation_id(&binding.adaptation_id)
            || !canonical_digest(&binding.projection_artifact.digest)
            || binding.projection_artifact.size_bytes == 0
            || binding.provider_component_kind.is_empty()
            || binding.projection_kind.is_empty()
            || binding.member_paths.is_empty()
            || !owners.insert(binding.stable_id.as_str())
        {
            return Err(Error::refuse(
                WireReason::AdaptationBindingMismatch,
                format!("adaptation for {:?} is not canonical", binding.stable_id),
            ));
        }
        let mut previous_path = None;
        for path in &binding.member_paths {
            check_path(path)?;
            if previous_path.is_some_and(|value: &str| value >= path.as_str()) {
                return Err(Error::refuse(
                    WireReason::AdaptationBindingMismatch,
                    format!(
                        "member_paths for {:?} are not strictly sorted",
                        binding.stable_id
                    ),
                ));
            }
            previous_path = Some(path.as_str());
            bound_paths.insert((binding.stable_id.as_str(), path.as_str()));
        }
    }
    let file_owners: BTreeSet<&str> = manifest
        .files
        .iter()
        .map(|file| file.owner.as_str())
        .collect();
    if file_owners != owners
        || manifest
            .files
            .iter()
            .any(|file| !bound_paths.contains(&(file.owner.as_str(), file.path.as_str())))
    {
        return Err(Error::refuse(
            WireReason::AdaptationBindingMismatch,
            "bundle files do not close over the declared component adaptations",
        ));
    }
    Ok(())
}

/// Require the four documents, once each, in order, before anything else.
fn require_members(members: &[zip::Member]) -> Result<&[u8]> {
    for (index, required) in REQUIRED_MEMBERS.iter().enumerate() {
        match members.get(index) {
            Some(member) if member.name == *required => {}
            Some(member) => {
                return Err(Error::refuse(
                    WireReason::UnsupportedBundleFormat,
                    format!("member {index} is {:?}, not {required:?}", member.name),
                ));
            }
            None => {
                return Err(Error::refuse(
                    WireReason::UnsupportedBundleFormat,
                    format!("the bundle has no {required:?}"),
                ));
            }
        }
    }
    let mut seen = BTreeSet::new();
    for member in members {
        if !seen.insert(member.name.as_str()) {
            return Err(Error::refuse(
                WireReason::PathDuplicate,
                format!("member {:?} appears twice", member.name),
            ));
        }
    }
    members
        .first()
        .map(|member| member.data.as_slice())
        .ok_or_else(|| Error::refuse(WireReason::UnsupportedBundleFormat, "the bundle is empty"))
}

fn parse_manifest(bytes: &[u8]) -> Result<Manifest> {
    serde_json::from_slice(bytes).map_err(|source| {
        Error::refuse(
            WireReason::UnsupportedBundleFormat,
            format!("{MANIFEST_MEMBER} does not parse: {source}"),
        )
    })
}

/// The manifest's identity is taken over itself minus that identity.
fn check_manifest_digest(bytes: &[u8], declared: &str) -> Result<()> {
    let mut value: serde_json::Value = serde_json::from_slice(bytes).map_err(|source| {
        Error::refuse(
            WireReason::UnsupportedBundleFormat,
            format!("{MANIFEST_MEMBER} does not parse: {source}"),
        )
    })?;
    let Some(object) = value.as_object_mut() else {
        return Err(Error::refuse(
            WireReason::UnsupportedBundleFormat,
            format!("{MANIFEST_MEMBER} is not an object"),
        ));
    };
    // A value cannot be part of the input it identifies.
    object.remove("bundle_digest");
    let computed = digest::of_domain_canonical_json(BUNDLE_DOMAIN, &value)?;
    if computed != declared {
        return Err(Error::refuse(
            WireReason::DigestMismatch,
            "the manifest does not hash to the identity it declares",
        ));
    }
    Ok(())
}

fn check_files(
    manifest: &Manifest,
    members: &[zip::Member],
    artifact_length: u64,
) -> Result<BTreeMap<String, (Vec<u8>, u32)>> {
    let declared = u64::try_from(manifest.files.len()).unwrap_or(u64::MAX);
    let max_files = manifest.effective_max_files();
    if declared > max_files {
        return Err(Error::refuse(
            WireReason::LimitExceeded,
            format!("{declared} files declared against a limit of {max_files}"),
        ));
    }
    let max_bundle = manifest.effective_max_bundle_bytes();
    if artifact_length > max_bundle {
        return Err(Error::refuse(
            WireReason::LimitExceeded,
            format!("the artifact is {artifact_length} bytes against a limit of {max_bundle}"),
        ));
    }

    let present: BTreeMap<&str, &zip::Member> = members
        .iter()
        .filter_map(|member| {
            member
                .name
                .strip_prefix(FILES_PREFIX)
                .map(|rest| (rest, member))
        })
        // A directory member is structure, not content: `files/` itself appears
        // in every bundle and declares nothing.
        .filter(|(rest, _)| !rest.is_empty() && !rest.ends_with('/'))
        .collect();

    let mut files = BTreeMap::new();
    let mut lowercase: BTreeMap<String, String> = BTreeMap::new();
    for record in &manifest.files {
        check_record(record, manifest, &mut lowercase)?;
        let Some(member) = present.get(record.path.as_str()) else {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                format!(
                    "the manifest declares {:?}, which the archive does not carry",
                    record.path
                ),
            ));
        };
        let actual = u64::try_from(member.data.len()).unwrap_or(u64::MAX);
        if actual != record.byte_length {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                format!(
                    "{:?} is {actual} bytes, not {}",
                    record.path, record.byte_length
                ),
            ));
        }
        if digest::of_bytes(&member.data) != record.digest {
            return Err(Error::refuse(
                WireReason::DigestMismatch,
                format!(
                    "{:?} does not hash to the digest that declares it",
                    record.path
                ),
            ));
        }
        if files
            .insert(record.path.clone(), (member.data.clone(), record.mode))
            .is_some()
        {
            return Err(Error::refuse(
                WireReason::PathDuplicate,
                format!("{:?} is declared twice", record.path),
            ));
        }
    }

    // A file the archive carries but the manifest never declared would be
    // installed by nobody's decision.
    for name in present.keys() {
        if !files.contains_key(*name) {
            return Err(Error::refuse(
                WireReason::UnsupportedNativeSurface,
                format!("the archive carries {name:?}, which the manifest does not declare"),
            ));
        }
    }
    Ok(files)
}

/// Check one manifest record's own claims, before its bytes are looked at.
fn check_record(
    record: &BundleFile,
    manifest: &Manifest,
    lowercase: &mut BTreeMap<String, String>,
) -> Result<()> {
    check_path(&record.path)?;
    match record.kind {
        FileKind::File => {}
        FileKind::Symlink | FileKind::Hardlink => {
            return Err(Error::refuse(
                WireReason::LinkNotAllowed,
                format!(
                    "{:?} is declared as a link, which is never materialized",
                    record.path
                ),
            ));
        }
        FileKind::Special | FileKind::Unknown => {
            return Err(Error::refuse(
                WireReason::SpecialFileNotAllowed,
                format!("{:?} is declared as neither a file nor a link", record.path),
            ));
        }
    }
    if !ALLOWED_MODES.contains(&record.mode) {
        return Err(Error::refuse(
            WireReason::UnsupportedNativeSurface,
            format!(
                "{:?} declares mode {:o}, which is not allowed",
                record.path, record.mode
            ),
        ));
    }
    if record.byte_length > manifest.effective_max_file_bytes() {
        return Err(Error::refuse(
            WireReason::LimitExceeded,
            format!("{:?} is larger than the declared file limit", record.path),
        ));
    }
    // Two paths differing only in case are one path on a case-insensitive file
    // system, and the second would silently overwrite the first.
    if let Some(other) = lowercase.insert(record.path.to_lowercase(), record.path.clone())
        && other != record.path
    {
        return Err(Error::refuse(
            WireReason::PathDuplicate,
            format!("{:?} and {other:?} differ only in case", record.path),
        ));
    }
    Ok(())
}

/// Every rule a bundle path must satisfy, checked by shape rather than by trial.
/// The device names the consumer's compiler refuses, and therefore these do too.
///
/// Taken verbatim from `ai-stp`'s `_RESERVED_STEMS` rather than from the vendor
/// page, on purpose. A provider stricter than the compiler refuses bundles the
/// platform has already blessed, and the person sees an install failure for a
/// thing nothing warned them about -- the same asymmetry as a route that is a
/// member of one side's list and not the other's, which cost this estate a
/// release to open a window for.
///
/// The superscript forms are not decoration.
/// `learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file`: *"Windows
/// recognizes the 8-bit ISO/IEC 8859-1 superscript digits ¹, ², and ³ as digits
/// and treats them as valid parts of COM# and LPT# device names, making them
/// reserved in every directory. For example, `echo test > COM¹` fails to create
/// a file."* They were raised with the consumer rather than shipped alone, and
/// arrived on both sides in the same hour.
const RESERVED_STEMS: &[&str] = &[
    "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
    "com9", "com¹", "com²", "com³", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8",
    "lpt9", "lpt¹", "lpt²", "lpt³",
];

/// Characters Windows reserves inside a name, beyond the separators.
///
/// The full reserved set on that page is `< > : " / \ | ? *`. `/` is the
/// separator this format uses and `\` is already refused as a path shape, so
/// these six and the colon are what remains for a segment.
const RESERVED_IN_A_NAME: &[char] = &['<', '>', '"', '|', '?', '*'];

/// Whether one path segment is a name Windows will not give to a file.
///
/// The test is the *stem* -- everything before the first period, lowercased --
/// because the vendor is explicit that `NUL.txt` and `NUL.tar.gz` are both
/// equivalent to `NUL`, and because a substring test would cost `console.md`,
/// `connect.json`, `auxiliary.md`, `nullable`, `com10.txt`, `prnt.md` and
/// `a.con`, every one of them a name somebody will legitimately want.
fn names_a_device(segment: &str) -> Option<&'static str> {
    let stem = segment.split_once('.').map_or(segment, |(head, _)| head);
    let folded = stem.to_lowercase();
    RESERVED_STEMS.iter().copied().find(|name| folded == *name)
}

/// Everything one path segment must not be, on any system that will read it.
///
/// Split out of `check_path` because that function grew past what one screen
/// holds, not because the rules divide -- a segment is refused for what it is,
/// and the caller is refused for what the whole path is.
fn check_segment(path: &str, segment: &str) -> Result<()> {
    if segment.is_empty() || segment == "." {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!("{path:?} has an empty or bare-dot segment"),
        ));
    }
    if segment == ".." {
        return Err(Error::refuse(
            WireReason::PathEscapesTarget,
            format!("{path:?} climbs out of the target"),
        ));
    }
    if segment.len() > 255 {
        return Err(Error::refuse(
            WireReason::LimitExceeded,
            format!("{path:?} has a segment longer than 255 bytes"),
        ));
    }
    // **A limit Windows keeps that this does not, recorded rather than enforced
    // alone.** Microsoft's naming page and `MoveFileExW` both say it: a path is
    // limited to `MAX_PATH`, 260 characters, unless it is prefixed `\\?\` or the
    // machine opted out -- which needs Windows 10 1607 and a registry key or a
    // manifest. A bundle path may be 1024 bytes here, so one of 300 characters
    // installs on two systems out of three, which is the thing the rules just
    // below exist to prevent, one limit further out.
    //
    // Not refused, for the reason the reserved-name list gives: a provider
    // stricter than the compiler refuses bundles the platform has already
    // blessed. And a bound here could not be exact anyway -- `MAX_PATH` counts
    // the target root, which validation does not know, so any number chosen
    // here would be a guess at somebody's home directory. Raised with the
    // consumer, whose compiler is where it would have to be agreed.
    //
    // Measured for what this estate ships: the deepest relative path in any
    // setup is 85 bytes. `catalog.rs` does the same arithmetic for the
    // directory it materialises; this is that care one layer out, where the
    // path is the consumer's rather than ours.
    // One digest is one installability. A bundle whose paths cannot be
    // written on Windows is a bundle that installs on two systems out of
    // three, and nothing in its digest says which two -- so it is refused
    // here rather than discovered there.
    if let Some(device) = names_a_device(segment) {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!(
                "{path:?} has the segment {segment:?}, which names the reserved device \
                 {device} on Windows -- with or without an extension, and in any case"
            ),
        ));
    }
    if let Some(bad) = segment.chars().find(|c| RESERVED_IN_A_NAME.contains(c)) {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!(
                "{path:?} has the segment {segment:?}, which carries {bad:?}, one of the \
                 characters Windows reserves inside a name"
            ),
        ));
    }
    if segment.contains(':') {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!(
                "{path:?} has the segment {segment:?}, which carries a colon; on Windows \
                 that opens an alternate data stream rather than naming a file, wherever \
                 in the segment it appears"
            ),
        ));
    }
    if segment.ends_with(' ') || segment.ends_with('.') {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!(
                "{path:?} has the segment {segment:?}, which ends in a space or a period; \
                 Windows does not give a file or directory such a name"
            ),
        ));
    }
    Ok(())
}

fn check_path(path: &str) -> Result<()> {
    if path.is_empty() {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            "a bundle path is not empty",
        ));
    }
    if path.len() > 1024 {
        return Err(Error::refuse(
            WireReason::LimitExceeded,
            format!("{path:?} is longer than 1024 bytes"),
        ));
    }
    if path.starts_with('/') || path.starts_with('~') || path.starts_with('\\') {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!("{path:?} is not relative"),
        ));
    }
    // A drive letter is absolute on the platform that has drive letters, and a
    // path is checked for what it is rather than for where it is read.
    if path.as_bytes().get(1) == Some(&b':') {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!("{path:?} carries a drive letter"),
        ));
    }
    for segment in path.split('/') {
        check_segment(path, segment)?;
    }

    if path.chars().any(char::is_control) {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!("{path:?} contains a control character"),
        ));
    }
    if path.contains('\\') {
        return Err(Error::refuse(
            WireReason::PathNotRelative,
            format!("{path:?} uses a backslash separator"),
        ));
    }
    let lowered = path.to_lowercase();
    if SECRET_MARKERS.iter().any(|marker| lowered.contains(marker)) {
        return Err(Error::refuse(
            WireReason::SpecialFileNotAllowed,
            format!("{path:?} is named like a credential and is refused by name"),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::panic)]

    use super::*;
    use crate::provider_v3::zip::build::{Entry, write};

    fn document(name: &str) -> Entry {
        Entry {
            name: name.to_owned(),
            data: b"{}".to_vec(),
            mode: 0o644,
        }
    }

    struct Built {
        bytes: Vec<u8>,
        claim_digest: String,
        artifact_digest: String,
        length: u64,
    }

    /// Build a bundle whose three identities are all internally consistent.
    /// A bundle cannot raise its own ceiling, and a bundle may lower it.
    ///
    /// **A constraint with no subjects, until this.** `effective_max_files` and
    /// its two siblings clamp a bundle's declared limits to the contract's, and
    /// the comment above them says why: without it *"a hostile one could declare
    /// a ceiling of its own choosing"*. Three enforcement sites call them. **No
    /// test had ever handed one a bundle that declared more than the contract
    /// allows** -- every fixture in this file declares limits at or below the
    /// contract, so the clamp and the data agreed by accident, which is
    /// indistinguishable from the clamp working.
    ///
    /// That is the shape a peer hit from the other side today: a length bound
    /// whose only data had never approached it, so nothing exercised the
    /// difference between the type that declares the value and the code that
    /// constructs it. Review cannot see it -- the declaration reads correct and
    /// the use reads plausible, and they sit in different files. Only data at
    /// the boundary tells you.
    ///
    /// Both directions, because `min` has two of them: a hostile ceiling is
    /// refused, and a *stricter* bundle is honoured rather than widened back up
    /// to the contract.
    #[test]
    fn a_bundle_may_lower_its_limits_and_may_not_raise_them() {
        let hostile: Manifest = serde_json::from_value(serde_json::json!({
            "schema_version": 1,
            "bundle_format": BUNDLE_FORMAT,
            "protocol_version": BUNDLE_PROTOCOL_VERSION,
            "harness_id": "test",
            "bundle_digest": "sha256:aa",
            "limits": {
                "max_files": 999_999,
                "max_file_bytes": 8_u64 * 1024 * 1024 * 1024,
                "max_bundle_bytes": 8_u64 * 1024 * 1024 * 1024,
            }
        }))
        .unwrap();
        assert_eq!(hostile.effective_max_files(), CONTRACT_MAX_FILES);
        assert_eq!(hostile.effective_max_file_bytes(), CONTRACT_MAX_FILE_BYTES);
        assert_eq!(
            hostile.effective_max_bundle_bytes(),
            CONTRACT_MAX_BUNDLE_BYTES
        );

        let stricter: Manifest = serde_json::from_value(serde_json::json!({
            "schema_version": 1,
            "bundle_format": BUNDLE_FORMAT,
            "protocol_version": BUNDLE_PROTOCOL_VERSION,
            "harness_id": "test",
            "bundle_digest": "sha256:aa",
            "limits": {"max_files": 3, "max_file_bytes": 16, "max_bundle_bytes": 32}
        }))
        .unwrap();
        assert_eq!(stricter.effective_max_files(), 3);
        assert_eq!(stricter.effective_max_file_bytes(), 16);
        assert_eq!(stricter.effective_max_bundle_bytes(), 32);

        // A bundle that declares nothing gets the contract, which is the case
        // every other fixture here exercises and the reason this went unnoticed.
        let silent: Manifest = serde_json::from_value(serde_json::json!({
            "schema_version": 1,
            "bundle_format": BUNDLE_FORMAT,
            "protocol_version": BUNDLE_PROTOCOL_VERSION,
            "harness_id": "test",
            "bundle_digest": "sha256:aa",
        }))
        .unwrap();
        assert_eq!(silent.effective_max_files(), CONTRACT_MAX_FILES);
        assert_eq!(silent.effective_max_file_bytes(), CONTRACT_MAX_FILE_BYTES);
        assert_eq!(
            silent.effective_max_bundle_bytes(),
            CONTRACT_MAX_BUNDLE_BYTES
        );
    }

    fn v2_manifest() -> Manifest {
        serde_json::from_value(serde_json::json!({
            "schema_version": 1,
            "bundle_format": BUNDLE_FORMAT,
            "protocol_version": BUNDLE_PROTOCOL_VERSION,
            "harness_id": "test",
            "bundle_digest": "sha256:aa",
            "projection_profile": {
                "profile_id": "test/native-files/2",
                "profile_digest": "sha256:".to_owned() + &"4".repeat(64),
                "target_scope": "global"
            },
            "component_adaptations": [{
                "stable_id": "component_a",
                "version": "1.0",
                "passport_digest": "sha256:".to_owned() + &"1".repeat(64),
                "adaptation_id": "adaptation_".to_owned() + &"2".repeat(64),
                "projection_artifact": {
                    "digest": "sha256:".to_owned() + &"3".repeat(64),
                    "size_bytes": 128
                },
                "provider_component_kind": "skill",
                "projection_kind": "native_files",
                "member_paths": ["skills/a.md"]
            }],
            "files": [{
                "path": "skills/a.md",
                "digest": "sha256:".to_owned() + &"5".repeat(64),
                "byte_length": 1,
                "mode": 420,
                "owner": "component_a"
            }]
        }))
        .unwrap()
    }

    #[test]
    fn bundle_v2_requires_complete_sorted_adaptation_bindings() {
        let manifest = v2_manifest();
        check_adaptation_bindings(&manifest).unwrap();

        let mut missing = manifest.clone();
        missing.component_adaptations.clear();
        assert_eq!(
            check_adaptation_bindings(&missing).unwrap_err().reason(),
            Some(WireReason::AdaptationBindingMissing)
        );

        let mut unbound = manifest;
        unbound.files[0].owner = "component_b".to_owned();
        assert_eq!(
            check_adaptation_bindings(&unbound).unwrap_err().reason(),
            Some(WireReason::AdaptationBindingMismatch)
        );
    }

    #[test]
    fn bundle_v2_is_bound_to_the_exact_provider_profile() {
        let manifest = v2_manifest();
        let profile = ProjectionProfile::new(
            "test/native-files/2",
            &[crate::provider_v3::ComponentKind::Skill],
            &[crate::provider_v3::ProjectionKind::NativeFiles],
            &["skills"],
            &[BUNDLE_FORMAT],
            CONTRACT_MAX_FILES,
            CONTRACT_MAX_BUNDLE_BYTES,
        )
        .unwrap();
        let bundle = Bundle {
            manifest: manifest.clone(),
            passport: SetupPassport::default(),
            files: BTreeMap::new(),
        };
        assert_eq!(
            bundle
                .require_projection_profile(&profile)
                .unwrap_err()
                .reason(),
            Some(WireReason::ProjectionProfileMismatch),
            "the manifest carries a deliberately different profile digest"
        );
        let mut exact = manifest;
        exact.projection_profile.as_mut().unwrap().profile_digest = profile.digest.clone();
        Bundle {
            manifest: exact,
            passport: SetupPassport::default(),
            files: BTreeMap::new(),
        }
        .require_projection_profile(&profile)
        .unwrap();
    }

    fn build(files: &[(&str, &str, u32)]) -> Built {
        let mut member_paths = files.iter().map(|(path, _, _)| *path).collect::<Vec<_>>();
        member_paths.sort_unstable();
        let records: Vec<serde_json::Value> = files
            .iter()
            .map(|(path, body, mode)| {
                serde_json::json!({
                    "schema_version": 1,
                    "path": path,
                    "digest": digest::of_bytes(body.as_bytes()),
                    "byte_length": body.len(),
                    "mode": mode,
                    "owner": "component_a",
                })
            })
            .collect();
        let mut manifest = serde_json::json!({
            "schema_version": 1,
            "bundle_format": BUNDLE_FORMAT,
            "protocol_version": BUNDLE_PROTOCOL_VERSION,
            "harness_id": "test",
            "builder_version": "0.1.0",
            "input_digest": "sha256:".to_owned() + &"3".repeat(64),
            "projection_profile": {
                "profile_id": "test/native-files/2",
                "profile_digest": "sha256:".to_owned() + &"4".repeat(64),
                "target_scope": "global"
            },
            "component_adaptations": [{
                "stable_id": "component_a",
                "version": "1.0",
                "passport_digest": "sha256:".to_owned() + &"1".repeat(64),
                "adaptation_id": "adaptation_".to_owned() + &"2".repeat(64),
                "projection_artifact": {
                    "digest": "sha256:".to_owned() + &"3".repeat(64),
                    "size_bytes": 128
                },
                "provider_component_kind": "instruction",
                "projection_kind": "native_files",
                "member_paths": member_paths
            }],
            "managed_paths": files.iter().map(|(path, _, _)| *path).collect::<Vec<_>>(),
            "files": records,
            "limits": {
                "max_files": 2000,
                "max_file_bytes": 4 * 1024 * 1024,
                "max_bundle_bytes": 64 * 1024 * 1024,
            },
        });
        let bundle_digest = digest::of_domain_canonical_json(BUNDLE_DOMAIN, &manifest).unwrap();
        manifest["bundle_digest"] = serde_json::json!(bundle_digest);
        let manifest_bytes = crate::setup_core::canonical::to_canonical_bytes(&manifest).unwrap();

        let mut entries = vec![Entry {
            name: MANIFEST_MEMBER.to_owned(),
            data: manifest_bytes,
            mode: 0o644,
        }];
        for name in REQUIRED_MEMBERS.iter().skip(1) {
            entries.push(document(name));
        }
        for (path, body, mode) in files {
            entries.push(Entry {
                name: format!("{FILES_PREFIX}{path}"),
                data: body.as_bytes().to_vec(),
                mode: *mode,
            });
        }
        let bytes = write(&entries);
        let artifact_digest = digest::of_bytes(&bytes);
        let length = bytes.len() as u64;
        Built {
            bytes,
            claim_digest: bundle_digest,
            artifact_digest,
            length,
        }
    }

    /// `build`, with one hand on the manifest before its digest is taken.
    ///
    /// Some refusals are about what a record *says* rather than about the bytes
    /// beside it -- a record declaring itself a link, for instance -- and those
    /// cannot be reached by choosing different files.
    fn build_declaring(
        files: &[(&str, &str, u32)],
        bend: impl Fn(&mut serde_json::Value),
    ) -> Built {
        let plain = build(files);
        let mut manifest: serde_json::Value = serde_json::from_slice(
            &zip::read(&plain.bytes)
                .unwrap()
                .into_iter()
                .find(|member| member.name == MANIFEST_MEMBER)
                .unwrap()
                .data,
        )
        .unwrap();
        bend(&mut manifest);
        // The digest is taken over the manifest without its own digest field,
        // exactly as `build` takes it, or the bundle would fail for the wrong
        // reason and the test would prove nothing.
        manifest["bundle_digest"] = serde_json::Value::Null;
        let mut without = manifest.clone();
        without.as_object_mut().unwrap().remove("bundle_digest");
        let bundle_digest = digest::of_domain_canonical_json(BUNDLE_DOMAIN, &without).unwrap();
        manifest["bundle_digest"] = serde_json::json!(bundle_digest);
        let manifest_bytes = crate::setup_core::canonical::to_canonical_bytes(&manifest).unwrap();

        let mut entries: Vec<Entry> = Vec::new();
        for member in zip::read(&plain.bytes).unwrap() {
            let data = if member.name == MANIFEST_MEMBER {
                manifest_bytes.clone()
            } else {
                member.data
            };
            entries.push(Entry {
                name: member.name,
                data,
                mode: member.mode.unwrap_or(0o644),
            });
        }
        let bytes = write(&entries);
        let artifact_digest = digest::of_bytes(&bytes);
        let length = bytes.len() as u64;
        Built {
            bytes,
            claim_digest: bundle_digest,
            artifact_digest,
            length,
        }
    }

    fn claim(built: &Built) -> Claim<'_> {
        Claim {
            bundle_format: BUNDLE_FORMAT,
            bundle_digest: &built.claim_digest,
            artifact_digest: &built.artifact_digest,
            bundle_size: built.length,
            harness_id: "test",
        }
    }

    #[test]
    fn a_consistent_bundle_is_read_and_carries_its_files() {
        let built = build(&[
            ("AGENTS.md", "# hello\n", 0o644),
            ("skills/a.md", "skill", 0o644),
        ]);
        let bundle = Bundle::read(&built.bytes, claim(&built)).unwrap();
        assert_eq!(bundle.manifest.harness_id, "test");
        assert_eq!(bundle.files.len(), 2);
        assert_eq!(bundle.files["AGENTS.md"].0, b"# hello\n");
        assert_eq!(bundle.files["skills/a.md"].1, 0o644);
    }

    #[test]
    fn an_executable_mode_is_carried_because_some_surfaces_are_executable() {
        let built = build(&[("hooks/run.sh", "#!/bin/sh\n", 0o755)]);
        let bundle = Bundle::read(&built.bytes, claim(&built)).unwrap();
        assert_eq!(bundle.files["hooks/run.sh"].1, 0o755);
    }

    #[test]
    fn the_raw_bytes_are_checked_before_the_parser_ever_runs() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut claim = claim(&built);
        let wrong = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
        claim.artifact_digest = wrong;
        let error = Bundle::read(&built.bytes, claim).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::DigestMismatch));
        assert!(error.detail().contains("do not hash"), "{error}");
    }

    #[test]
    fn a_size_that_disagrees_with_the_bytes_is_refused_first() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut claim = claim(&built);
        claim.bundle_size = built.length + 1;
        assert!(
            Bundle::read(&built.bytes, claim)
                .unwrap_err()
                .detail()
                .contains("bytes, not")
        );
    }

    #[test]
    fn a_bundle_for_another_harness_is_a_profile_mismatch_not_a_generic_refusal() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut claim = claim(&built);
        claim.harness_id = "other";
        let error = Bundle::read(&built.bytes, claim).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::ProjectionProfileMismatch));
    }

    #[test]
    fn a_manifest_identity_the_caller_did_not_name_is_refused() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut claim = claim(&built);
        let other = "sha256:1111111111111111111111111111111111111111111111111111111111111111";
        claim.bundle_digest = other;
        let error = Bundle::read(&built.bytes, claim).unwrap_err();
        assert!(
            error.detail().contains("not the one the caller named"),
            "{error}"
        );
    }

    #[test]
    fn a_file_whose_bytes_do_not_match_its_record_is_refused() {
        let mut built = build(&[("AGENTS.md", "hello", 0o644)]);
        // Corrupt the member payload, then re-stamp the two outer identities so
        // only the inner file digest is wrong.
        let position = built.bytes.windows(5).position(|w| w == b"hello").unwrap();
        built.bytes[position] = b'j';
        // The CRC check fires first, which is itself the right refusal.
        built.artifact_digest = digest::of_bytes(&built.bytes);
        let error = Bundle::read(&built.bytes, claim(&built)).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::DigestMismatch));
    }

    #[test]
    fn every_hostile_path_shape_is_refused_by_its_own_reason() {
        for (path, reason) in [
            ("/etc/passwd", WireReason::PathNotRelative),
            ("~/.ssh/config", WireReason::PathNotRelative),
            ("C:/Windows/system32", WireReason::PathNotRelative),
            ("../outside", WireReason::PathEscapesTarget),
            ("a/../../b", WireReason::PathEscapesTarget),
            ("a//b", WireReason::PathNotRelative),
            ("./a", WireReason::PathNotRelative),
            ("a\\b", WireReason::PathNotRelative),
            ("", WireReason::PathNotRelative),
        ] {
            let error = check_path(path).unwrap_err();
            assert_eq!(error.reason(), Some(reason), "{path:?} gave {error}");
        }
    }

    #[test]
    fn a_path_windows_cannot_write_is_refused_here_rather_than_discovered_there() {
        // One digest is one installability. A bundle whose paths cannot be
        // written on Windows installs on two systems out of three, and nothing
        // in its digest says which two.
        for path in [
            "NUL",
            "nul",
            "CON.txt",
            "nul.tar.gz",
            "com9.md",
            "LPT3",
            "skills/aux/SKILL.md",
            "commands/build./x.md",
            "a ",
            "plugins/a:b/c.md",
            "stream.md:hidden",
            "COM\u{b9}",
            "lpt\u{b3}.txt",
            "a<b.md",
            "a>b.md",
            "a\"b.md",
            "a|b.md",
            "a?b.md",
            "a*b.md",
        ] {
            let error = check_path(path).unwrap_err();
            assert_eq!(
                error.reason(),
                Some(WireReason::PathNotRelative),
                "{path:?} gave {error}"
            );
        }
    }

    #[test]
    fn a_name_that_merely_starts_like_a_device_is_kept() {
        // The stem test rather than a substring test, and this is what it buys.
        // A guard that cost these would be paid every day to prevent something
        // rare -- the consumer chose the same seven, and they are the same
        // seven here so that neither side refuses what the other allows.
        for path in [
            "console.md",
            "commands/connect.json",
            "auxiliary.md",
            "skills/nullable/SKILL.md",
            "com10.txt",
            "prnt.md",
            "a.con",
        ] {
            assert!(check_path(path).is_ok(), "{path:?} was refused");
        }
    }

    #[test]
    fn a_path_named_like_a_credential_is_refused_without_opening_it() {
        // Opening a file to decide whether it is a secret is the act this rule
        // exists to prevent.
        for path in [
            ".credentials.json",
            "auth.json",
            "keys/id_ed25519",
            "certs/server.pem",
        ] {
            let error = check_path(path).unwrap_err();
            assert_eq!(
                error.reason(),
                Some(WireReason::SpecialFileNotAllowed),
                "{path}"
            );
        }
    }

    #[test]
    fn a_control_character_in_a_path_is_refused() {
        assert!(check_path("a\u{1}b").is_err());
    }

    #[test]
    fn an_over_long_path_or_segment_is_refused() {
        // By its reason, not merely by failing. A consumer decides from the
        // reason alone, so a refusal for the wrong one is a wrong answer that
        // an `is_err()` assertion calls correct -- and this test was that
        // assertion until it was read back.
        for path in [&"a".repeat(1025), &format!("dir/{}", "a".repeat(256))] {
            let error = check_path(path).unwrap_err();
            assert_eq!(
                error.reason(),
                Some(WireReason::LimitExceeded),
                "{}",
                error.detail()
            );
        }
    }

    #[test]
    fn two_paths_differing_only_in_case_are_a_duplicate() {
        // On a case-insensitive filesystem -- Windows, and macOS by default --
        // these are one file, so a bundle carrying both installs something
        // different there than it does here. One digest is one installability,
        // and this is that rule at the manifest rather than at the name.
        let built = build(&[("skills/a.md", "one", 0o644), ("skills/A.md", "two", 0o644)]);
        let error = Bundle::read(&built.bytes, claim(&built)).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::PathDuplicate), "{error}");
    }

    #[test]
    fn a_manifest_record_that_is_a_link_is_refused_as_one() {
        // A link is the entry that can point a write somewhere else, which is
        // the whole reason this reader accepts regular files and nothing else.
        let built = build_declaring(&[("AGENTS.md", "x", 0o644)], |manifest| {
            manifest["files"][0]["kind"] = serde_json::json!("symlink");
        });
        let error = Bundle::read(&built.bytes, claim(&built)).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::LinkNotAllowed), "{error}");
    }

    #[test]
    fn an_archive_member_the_manifest_never_declared_is_refused() {
        // Otherwise it would be installed by nobody's decision.
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut entries: Vec<Entry> = Vec::new();
        for member in zip::read(&built.bytes).unwrap() {
            entries.push(Entry {
                name: member.name,
                data: member.data,
                mode: 0o644,
            });
        }
        entries.push(Entry {
            name: format!("{FILES_PREFIX}undeclared.md"),
            data: b"sneaky".to_vec(),
            mode: 0o644,
        });
        let bytes = write(&entries);
        let artifact = digest::of_bytes(&bytes);
        let claim = Claim {
            bundle_format: BUNDLE_FORMAT,
            bundle_digest: &built.claim_digest,
            artifact_digest: &artifact,
            bundle_size: bytes.len() as u64,
            harness_id: "test",
        };
        let error = Bundle::read(&bytes, claim).unwrap_err();
        assert!(error.detail().contains("undeclared.md"), "{error}");
    }

    #[test]
    fn the_four_documents_are_required_in_order() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut members = zip::read(&built.bytes).unwrap();
        members.swap(1, 2);
        let entries: Vec<Entry> = members
            .into_iter()
            .map(|m| Entry {
                name: m.name,
                data: m.data,
                mode: 0o644,
            })
            .collect();
        let bytes = write(&entries);
        let artifact = digest::of_bytes(&bytes);
        let claim = Claim {
            bundle_format: BUNDLE_FORMAT,
            bundle_digest: &built.claim_digest,
            artifact_digest: &artifact,
            bundle_size: bytes.len() as u64,
            harness_id: "test",
        };
        let error = Bundle::read(&bytes, claim).unwrap_err();
        assert!(error.detail().contains("not"), "{error}");
    }

    #[test]
    fn a_format_tag_this_reader_does_not_know_is_refused_before_anything_else() {
        let built = build(&[("AGENTS.md", "x", 0o644)]);
        let mut claim = claim(&built);
        claim.bundle_format = RETIRED_BUNDLE_FORMAT_V1;
        let error = Bundle::read(&built.bytes, claim).unwrap_err();
        assert_eq!(error.reason(), Some(WireReason::UnsupportedBundleFormat));
    }
}