varve-core 0.41.0

Layer manifests, resolution, the core store, and verification wiring for varve
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
//! The core — the local content-addressed store (REQ-COEXIST-001, DD-006).
//!
//! ```text
//! <root>/core/sha256-<hex>/          # one layer, keyed by its manifest digest
//!   layer.json                       # the layer manifest, kept for verify/archive
//!   bin/<tool>                       # the tools — dispatched by name
//!   payloads/<name>/<version>        # everything else — held by name AND version
//! ```
//!
//! The split is REQ-STORE-002. A tool is dispatched by name (`varve which`,
//! `varve run`, the argv[0] shims), so a name must resolve to exactly one
//! binary and `bin/<name>` is right. A crate, a WIT package, an SDK or a wasm
//! component is not dispatched at all, and a dependency graph ordinarily holds
//! several versions of one name — laying those down by name alone made the
//! second entry silently overwrite the first's bytes.
//!
//! Keyed by manifest digest, so layers coexist by construction: installing
//! August cannot disturb July, and selecting either costs no download.
//! The store is written at lay-down time and read-only ever after — nothing
//! in resolution or listing mutates it (REQ-SCOPE-001's read-only half).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use sha2::{Digest, Sha256};

use crate::layer::LayerId;
use crate::manifest::ManifestEntry;

/// The directory holding non-dispatchable payloads, keyed by name AND version.
pub const PAYLOAD_DIR: &str = "payloads";

/// One payload to lay down. What it *is* decides where it lands: a dispatchable
/// payload is placed by name, everything else by name and version.
#[derive(Debug, Clone, Copy)]
pub struct Payload<'a> {
    pub name: &'a str,
    /// The version from the signed manifest. Absent only for pre-kind layers
    /// and for tools, which are not keyed by version.
    pub version: Option<&'a str>,
    /// Dispatched by name — see `PayloadKind::is_dispatchable`.
    pub dispatchable: bool,
    /// What this payload BUILDS FOR, when that differs from what runs it
    /// (REQ-SDKTARGET-001 clause 1). `platform` says which machine executes
    /// these bytes; `target` says which machine the artefacts they produce
    /// will run on. For a compiler you invoke they are the same question and
    /// this is `None`; for a cross-toolchain they are different, and the PAIR
    /// is what identifies the payload.
    pub target: Option<&'a str>,
    pub bytes: &'a [u8],
}

impl<'a> Payload<'a> {
    /// A dispatchable tool binary: `bin/<name>`, the original layout.
    pub fn tool(name: &'a str, bytes: &'a [u8]) -> Self {
        Payload {
            name,
            version: None,
            dispatchable: true,
            target: None,
            bytes,
        }
    }

    /// A payload that builds for a target other than the machine running it:
    /// `payloads/<name>/<version>/<target>`.
    pub fn targeted(name: &'a str, version: &'a str, target: &'a str, bytes: &'a [u8]) -> Self {
        Payload {
            name,
            version: Some(version),
            dispatchable: false,
            target: Some(target),
            bytes,
        }
    }
}

/// Is this manifest entry dispatched by name (REQ-STORE-002 clause 1)?
///
/// An entry with no kind annotation is a `tool` (pre-kind layers), so it is.
/// An entry whose kind THIS build does not recognise is not: varve cannot
/// dispatch what it cannot classify, and placing an unknown kind by name alone
/// is exactly the overwrite this requirement exists to prevent — a newer
/// varve's versioned kind must not collapse onto one path here.
pub fn entry_is_dispatchable(entry: &ManifestEntry) -> bool {
    matches!(entry.kind(), Ok(kind) if kind.is_dispatchable())
}

/// The version a manifest entry declares, if any.
pub fn entry_version(entry: &ManifestEntry) -> Option<&str> {
    entry
        .annotations
        .get("eu.pulseengine.tool.version")
        .map(String::as_str)
}

/// Refuse a name or version that is not a single, safe path component. These
/// strings come out of a signed manifest, but "signed" means "attributable",
/// not "benign": a realm root signing `../../evil` must not be able to place
/// bytes outside the layer it is laying down.
fn safe_component(what: &'static str, value: &str) -> Result<(), StoreError> {
    let bad = |why: &str| {
        Err(StoreError::UnsafeComponent {
            what,
            value: value.to_string(),
            why: why.to_string(),
        })
    };
    if value.is_empty() {
        return bad("empty");
    }
    if value == "." || value == ".." {
        return bad("a relative path element");
    }
    if let Some(c) = value
        .chars()
        .find(|c| matches!(c, '/' | '\\' | '\0') || c.is_control())
    {
        return bad(&format!("contains {c:?}"));
    }
    Ok(())
}

/// Where a payload lives inside a layer root, relative to it (clause 2).
///
/// Dispatchable → `bin/<name>`, unchanged and byte-compatible with every layer
/// installed before this requirement. Non-dispatchable with a version →
/// `payloads/<name>/<version>`, so `serde@1.0.200` and `serde@1.0.210` are two
/// files, not one file written twice. A non-dispatchable payload with NO
/// version keeps the legacy `bin/<name>` place — that is what a pre-kind layer
/// looks like on disk, and the collision guard in `lay_down` still refuses to
/// let two of them land on one path.
pub fn payload_rel_path(
    dispatchable: bool,
    name: &str,
    version: Option<&str>,
    target: Option<&str>,
) -> Result<PathBuf, StoreError> {
    safe_component("payload name", name)?;
    match (dispatchable, version) {
        (false, Some(version)) => {
            safe_component("payload version", version)?;
            let at = PathBuf::from(PAYLOAD_DIR).join(name).join(version);
            // The target is the LAST component, so a payload that declares
            // none keeps the exact path it had before this dimension existed
            // (clause 4) and a layer installed by an older varve is still
            // found where it was put.
            match target {
                Some(target) => {
                    safe_component("payload target", target)?;
                    Ok(at.join(target))
                }
                None => Ok(at),
            }
        }
        _ => Ok(PathBuf::from("bin").join(name)),
    }
}

/// The minimal slice of a layer manifest the store needs: the annotations
/// carrying the layer identity. Everything else is preserved verbatim in
/// `layer.json` for later verification and archiving.
#[derive(Debug, Clone, Deserialize)]
struct ManifestEnvelope {
    #[serde(default)]
    annotations: BTreeMap<String, String>,
}

/// One layer present in the core.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstalledLayer {
    /// `sha256:<hex>` of the manifest bytes — the store key.
    pub digest: String,
    /// The layer identity from the manifest annotations.
    pub layer: LayerId,
    /// The channel annotation (`qualified` / `rolling`), verbatim.
    pub channel: String,
    /// Root directory of this layer in the core.
    pub root: PathBuf,
    /// The platform this layer was INSTALLED FOR, where the install recorded
    /// one (`varve install --platform`, or the host at install time).
    ///
    /// `verify` must filter by this and not by the host it happens to be run
    /// on. Installing a Linux toolchain from a Mac is legitimate — building or
    /// inspecting one — and before this, `verify` resolved the HOST, found the
    /// darwin entry, hashed the linux bytes that were actually laid down, and
    /// reported "its bytes were altered" about bytes nobody had touched
    /// (varve#189). A trust tool that cries wolf teaches people to ignore it.
    ///
    /// `None` for layers installed before this was recorded; callers fall back
    /// to the host, which is what they did for all of them.
    ///
    /// This file is LOCAL state and is not signed, which is safe in one
    /// direction only: a tampered value can name a platform whose payloads
    /// were never laid down (`MissingTool`), or one the layer has no entries
    /// for (`NothingToVerify`), or one whose digests do not match what is on
    /// disk (`ToolDigestMismatch`). Every outcome is a refusal. It cannot
    /// cause a verification to pass that would otherwise fail.
    pub platform: Option<String>,
}

/// The core store rooted at a directory (defaults to `~/.varve` in the CLI;
/// injectable here so tests and future tools own their roots).
#[derive(Debug, Clone)]
pub struct Store {
    root: PathBuf,
}

/// Store failures. Note what is *absent*: there is no variant for "fell back
/// to another layer" — the API cannot express fallback.
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    #[error("io error at {path}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("{path}: layer.json is not a valid layer manifest: {reason}")]
    BadManifest { path: String, reason: String },
    #[error("{what} {value:?} is not a usable path component ({why}) — refusing to lay it down")]
    UnsafeComponent {
        what: &'static str,
        value: String,
        why: String,
    },
    #[error(
        "two payloads of this layer both claim {path} ('{first}' and '{second}') — refusing to \
         lay one down over the other. A layer may hold several versions of one name, but each \
         must be a distinct payload; two entries with one identity would mean the wrong bytes \
         land under the right name."
    )]
    Collision {
        path: String,
        first: String,
        second: String,
    },
}

impl Store {
    pub fn at(root: impl Into<PathBuf>) -> Self {
        Store { root: root.into() }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Lay a layer down in the core from its manifest bytes and tool
    /// binaries. Returns the manifest digest (`sha256:<hex>`) — the store key.
    ///
    /// The dispatchable-only convenience over [`Store::lay_down_payloads`],
    /// which is the single writer.
    pub fn lay_down(
        &self,
        manifest_bytes: &[u8],
        tools: &[(&str, &[u8])],
    ) -> Result<String, StoreError> {
        let payloads: Vec<Payload<'_>> = tools
            .iter()
            .map(|(name, bytes)| Payload::tool(name, bytes))
            .collect();
        self.lay_down_payloads(manifest_bytes, &payloads)
    }

    /// Lay a layer down in the core from its manifest bytes and its payloads.
    /// Returns the manifest digest (`sha256:<hex>`) — the store key.
    ///
    /// This is the write path shared by the installer and by tests; nothing
    /// else writes to the core. Two payloads that would land on ONE path are
    /// refused (`StoreError::Collision`) rather than written in turn: relaxing
    /// the deposit-time identity check without this would turn a clean error
    /// into silent data loss — the second entry's bytes under the first's name,
    /// with verification then failing on the *other* entry and nothing
    /// explaining why (REQ-STORE-002).
    pub fn lay_down_payloads(
        &self,
        manifest_bytes: &[u8],
        payloads: &[Payload<'_>],
    ) -> Result<String, StoreError> {
        let digest = manifest_digest(manifest_bytes);
        let entry = self.core_dir().join(digest.replace(':', "-"));
        let io = |path: &Path, source: std::io::Error| StoreError::Io {
            path: path.display().to_string(),
            source,
        };

        // Resolve every destination BEFORE writing anything: an unusable name
        // or a collision must leave the core untouched, not half-written.
        let mut placed: BTreeMap<PathBuf, String> = BTreeMap::new();
        let mut plan: Vec<(PathBuf, &Payload<'_>)> = Vec::new();
        for payload in payloads {
            let rel = payload_rel_path(
                payload.dispatchable,
                payload.name,
                payload.version,
                payload.target,
            )?;
            let who = match (payload.version, payload.target) {
                (Some(v), Some(t)) => format!("{}@{v} for {t}", payload.name),
                (Some(v), None) => format!("{}@{v}", payload.name),
                (None, _) => payload.name.to_string(),
            };
            if let Some(first) = placed.get(&rel) {
                return Err(StoreError::Collision {
                    path: rel.display().to_string(),
                    first: first.clone(),
                    second: who,
                });
            }
            placed.insert(rel.clone(), who);
            plan.push((rel, payload));
        }

        let bin = entry.join("bin");
        std::fs::create_dir_all(&bin).map_err(|e| io(&bin, e))?;
        let manifest_path = entry.join("layer.json");
        std::fs::write(&manifest_path, manifest_bytes).map_err(|e| io(&manifest_path, e))?;
        for (rel, payload) in plan {
            let path = entry.join(rel);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
            }
            std::fs::write(&path, payload.bytes).map_err(|e| io(&path, e))?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                // Only what is dispatched gets the execute bit. A `.crate`
                // tarball or a WIT package is data varve hands to another tool.
                let mode = if payload.dispatchable { 0o755 } else { 0o644 };
                std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
                    .map_err(|e| io(&path, e))?;
            }
        }
        Ok(digest)
    }

    /// Every layer present in the core, in stable (digest) order.
    pub fn list(&self) -> Result<Vec<InstalledLayer>, StoreError> {
        let core = self.core_dir();
        if !core.exists() {
            return Ok(Vec::new());
        }
        let mut names: Vec<String> = std::fs::read_dir(&core)
            .map_err(|e| StoreError::Io {
                path: core.display().to_string(),
                source: e,
            })?
            .filter_map(|e| e.ok())
            .filter(|e| e.path().is_dir())
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n.starts_with("sha256-"))
            .collect();
        names.sort();
        names
            .into_iter()
            .map(|name| self.read_entry(&name.replacen('-', ":", 1)))
            .collect()
    }

    /// Look up a layer by manifest digest (`sha256:<hex>`).
    /// The varve root this store lives under: itself, or the parent of a realm
    /// partition (`<root>/realms/<fingerprint>`).
    pub fn varve_root(&self) -> std::path::PathBuf {
        let root = self.root();
        if root
            .parent()
            .and_then(|p| p.file_name())
            .is_some_and(|n| n == "realms")
        {
            root.parent()
                .and_then(|p| p.parent())
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| root.to_path_buf())
        } else {
            root.to_path_buf()
        }
    }

    /// Every partition under this varve root: the top-level core first, then
    /// each realm partition in a stable order, paired with the realm
    /// fingerprint that names it (`None` for the top-level core, which is not
    /// realm-scoped).
    ///
    /// `find_anywhere` had this enumeration inline and private, so a caller
    /// that needed to WALK the store rather than look one digest up had no way
    /// to do it — which is how `verify --all` came to check only the pinned
    /// realm's partition while its `--help` promised every installed layer
    /// (REQ-VERIFYALL-001, varve#84).
    pub fn partitions(&self) -> Vec<(Option<String>, Store)> {
        let root = self.varve_root();
        let mut out: Vec<(Option<String>, Store)> = vec![(None, Store::at(&root))];
        if let Ok(rd) = std::fs::read_dir(root.join("realms")) {
            let mut parts: Vec<std::path::PathBuf> =
                rd.filter_map(|e| e.ok()).map(|e| e.path()).collect();
            parts.sort();
            for p in parts {
                let fp = p.file_name().map(|n| n.to_string_lossy().into_owned());
                out.push((fp, Store::at(p)));
            }
        }
        out
    }

    /// Find a layer by digest in ANY partition under this varve root — the
    /// top-level core or any realm's. A digest is content-addressed, so where
    /// it happens to live does not change what it is; a cross-realm composition
    /// include is installed under the INCLUDED realm's fingerprint, not the
    /// including project's, and looking only in one partition reported it as
    /// missing while `list` showed it installed (REQ-STORE-001).
    ///
    /// Locating a layer is not accepting it: the caller still verifies it
    /// against the trust root of the realm that vouches for it.
    pub fn find_anywhere(
        &self,
        digest: &str,
    ) -> Result<Option<(Store, InstalledLayer)>, StoreError> {
        if let Some(entry) = self.get(digest)? {
            return Ok(Some((self.clone(), entry)));
        }
        let root = self.varve_root();
        // The top-level core, then every realm partition, in a stable order.
        let mut candidates = vec![Store::at(&root)];
        if let Ok(rd) = std::fs::read_dir(root.join("realms")) {
            let mut parts: Vec<std::path::PathBuf> =
                rd.filter_map(|e| e.ok()).map(|e| e.path()).collect();
            parts.sort();
            candidates.extend(parts.into_iter().map(Store::at));
        }
        for candidate in candidates {
            if candidate.root() == self.root() {
                continue;
            }
            if let Some(entry) = candidate.get(digest)? {
                return Ok(Some((candidate, entry)));
            }
        }
        Ok(None)
    }

    pub fn get(&self, digest: &str) -> Result<Option<InstalledLayer>, StoreError> {
        let entry = self.core_dir().join(digest.replace(':', "-"));
        if !entry.join("layer.json").is_file() {
            return Ok(None);
        }
        self.read_entry(digest).map(Some)
    }

    /// Path of one tool's binary within an installed layer, if present.
    /// Dispatch is by name, so this takes a bare name — see `entry_path` for
    /// payloads that are held rather than dispatched.
    pub fn tool_path(&self, layer: &InstalledLayer, tool: &str) -> Option<PathBuf> {
        let path = layer.root.join("bin").join(tool);
        path.is_file().then_some(path)
    }

    /// Path of the bytes one MANIFEST ENTRY refers to within an installed
    /// layer, if present. This is the read side of `lay_down_payloads`, and
    /// every consumer of a layer's bytes (`verify`, `archive`, the export
    /// adapters) goes through it so the two cannot drift.
    ///
    /// Backward compatibility: a layer installed BEFORE REQ-STORE-002 holds its
    /// crates at `bin/<name>`, so a versioned payload that is not at its
    /// versioned path falls back there. Such a layer can hold only one version
    /// per name — the old deposit check made sure of it — so the fallback is
    /// unambiguous.
    pub fn entry_path(&self, layer: &InstalledLayer, entry: &ManifestEntry) -> Option<PathBuf> {
        let name = entry.annotations.get("eu.pulseengine.tool")?;
        let dispatchable = entry_is_dispatchable(entry);
        let rel = payload_rel_path(
            dispatchable,
            name,
            entry_version(entry),
            crate::platform::entry_target(entry),
        )
        .ok()?;
        let path = layer.root.join(rel);
        if path.is_file() {
            return Some(path);
        }
        (!dispatchable)
            .then(|| layer.root.join("bin").join(name))
            .filter(|legacy| legacy.is_file())
    }

    fn core_dir(&self) -> PathBuf {
        self.root.join("core")
    }

    fn read_entry(&self, digest: &str) -> Result<InstalledLayer, StoreError> {
        let root = self.core_dir().join(digest.replace(':', "-"));
        let manifest_path = root.join("layer.json");
        let bad = |reason: String| StoreError::BadManifest {
            path: manifest_path.display().to_string(),
            reason,
        };
        let bytes = std::fs::read(&manifest_path).map_err(|source| StoreError::Io {
            path: manifest_path.display().to_string(),
            source,
        })?;
        let envelope: ManifestEnvelope =
            serde_json::from_slice(&bytes).map_err(|e| bad(e.to_string()))?;
        let layer_str = envelope
            .annotations
            .get("eu.pulseengine.varve.layer")
            .ok_or_else(|| bad("missing eu.pulseengine.varve.layer annotation".into()))?;
        let layer: LayerId = layer_str
            .parse()
            .map_err(|e: crate::layer::LayerIdError| bad(e.to_string()))?;
        let channel = envelope
            .annotations
            .get("eu.pulseengine.varve.channel")
            .cloned()
            .unwrap_or_default();
        let platform = std::fs::read_to_string(root.join(INSTALL_FILE))
            .ok()
            .and_then(|t| serde_json::from_str::<InstallRecord>(&t).ok())
            .map(|r| r.platform);
        Ok(InstalledLayer {
            digest: digest.to_string(),
            layer,
            channel,
            root,
            platform,
        })
    }
}

/// What the install recorded about itself, beside the layer it laid down.
pub const INSTALL_FILE: &str = "installed.json";

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct InstallRecord {
    platform: String,
}

/// Record the platform a layer was laid down FOR.
///
/// Written by `install` after the lay-down, so `verify` filters by the
/// decision the install made rather than re-deriving one from the host it is
/// run on — the shape that has cost this codebase repeatedly.
pub fn record_install_platform(root: &Path, platform: &str) -> Result<(), StoreError> {
    let path = root.join(INSTALL_FILE);
    let body = serde_json::to_vec_pretty(&InstallRecord {
        platform: platform.to_string(),
    })
    .map_err(|e| StoreError::Io {
        path: path.display().to_string(),
        source: std::io::Error::other(e),
    })?;
    std::fs::write(&path, body).map_err(|source| StoreError::Io {
        path: path.display().to_string(),
        source,
    })
}

/// Compute the store key for manifest bytes: `sha256:<hex>`.
impl Store {
    /// Every tool name the layer's SIGNED manifest carries, whatever this host
    /// laid down. Used to tell "the pin asks for something that was never in
    /// this layer" apart from "the install is incomplete" — the two need
    /// opposite advice, and conflating them produced an error whose stated fix
    /// could not work.
    pub fn manifest_tool_names(&self, layer: &InstalledLayer) -> Result<Vec<String>, StoreError> {
        let payload = std::fs::read(layer.root.join("layer.json")).map_err(|e| StoreError::Io {
            path: layer.root.join("layer.json").display().to_string(),
            source: e,
        })?;
        let json: serde_json::Value = match serde_json::from_slice(&payload) {
            Ok(j) => j,
            Err(_) => return Ok(Vec::new()),
        };
        Ok(json["manifests"]
            .as_array()
            .map(|es| {
                es.iter()
                    .filter_map(|e| e["annotations"]["eu.pulseengine.tool"].as_str())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default())
    }
}

pub fn manifest_digest(bytes: &[u8]) -> String {
    format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
}

/// Buffer size for [`digest_file`]. Large enough that syscall overhead is
/// negligible against a GB-scale payload, small enough that the memory a
/// digest costs is a constant rather than the size of the thing being checked.
pub const DIGEST_BUFFER: usize = 1 << 16;

/// The digest of a file, computed from a stream in bounded memory
/// (REQ-VERIFYSTREAM-001 clause 1).
///
/// `manifest_digest(&std::fs::read(path)?)` gives the same answer, and it is
/// what verify used to do — which made checking a 2 GB SDK a 2 GB heap
/// allocation per payload, one at a time, reported from real use as ~9 seconds
/// with nothing printed (varve#141). The answer does not change; only what it
/// costs to reach it.
///
/// No hand-rolled cursor, deliberately. `io::copy` drives the loop and decides
/// when it ends, so there is no `pos += n` for a mutant to turn into a loop
/// that never advances — the shape that killed a CI job outright in v0.35.0.
pub fn digest_file(path: &Path) -> std::io::Result<String> {
    Ok(digest_file_timed(path)?.0)
}

/// Where the time went while digesting one file (REQ-VERIFYSTREAM-001 clause 2).
///
/// Attributed rather than guessed. varve#141 reported ~9 s to verify a layer
/// with a 2 GB SDK, and the arithmetic said the hash could not account for it:
/// a claim like that is only settled by measuring the stages separately.
///
/// There is no `decompress` field because verify does not decompress. A payload
/// is hashed exactly as its producer signed it — that is what makes the digest
/// re-derivable — so an archive's compression costs verify nothing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StageTiming {
    /// Time inside the reader: the syscall and whatever the kernel did to serve
    /// it, which on a cold cache is the disk.
    pub read: std::time::Duration,
    /// Time inside SHA-256.
    pub hash: std::time::Duration,
    /// Bytes read, which is the file's size — reported so a rate can be
    /// computed from the same run that produced the times.
    pub bytes: u64,
}

impl StageTiming {
    /// Sum, for attributing a whole layer from its payloads.
    pub fn add(&mut self, other: StageTiming) {
        self.read += other.read;
        self.hash += other.hash;
        self.bytes += other.bytes;
    }
}

/// [`digest_file`], with the read and hash time attributed separately.
///
/// The timing rides ON the real digest path rather than living in a benchmark:
/// a number measured by a copy of the code is a number about the copy. The
/// clocks are read per buffer, which at a 64 KiB buffer is two `Instant::now()`
/// calls per 64 KiB — under a millisecond per gigabyte, and measured against
/// the untimed path in the tests below.
pub fn digest_file_timed(path: &Path) -> std::io::Result<(String, StageTiming)> {
    let file = std::fs::File::open(path)?;
    let mut reader = TimedReader {
        inner: std::io::BufReader::with_capacity(DIGEST_BUFFER, file),
        timing: StageTiming::default(),
    };
    let mut hasher = Sha256::new();
    let mut writer = HashWriter {
        hasher: &mut hasher,
        hash: std::time::Duration::ZERO,
    };
    std::io::copy(&mut reader, &mut writer)?;
    let hash = writer.hash;
    let mut timing = reader.timing;
    timing.hash = hash;
    Ok((format!("sha256:{}", hex::encode(hasher.finalize())), timing))
}

/// Times the reads without changing what is read.
///
/// A wrapper rather than a hand-written loop, for the reason `io::copy` is used
/// at all: a loop here would need its own termination condition, and a mutant
/// that removes it hangs the job instead of failing a test.
struct TimedReader<R> {
    inner: R,
    timing: StageTiming,
}

impl<R: std::io::Read> std::io::Read for TimedReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let t = std::time::Instant::now();
        let n = self.inner.read(buf)?;
        self.timing.read += t.elapsed();
        self.timing.bytes += n as u64;
        Ok(n)
    }
}

/// Feeds whatever `io::copy` writes straight into a hasher.
///
/// A local adapter rather than enabling a `sha2` feature: a dependency's
/// feature set inside a verification crate is a thing to keep small. Mutating
/// the reported length is caught rather than hidden — `Ok(0)` makes `copy`
/// fail with `WriteZero`, and a short count makes it re-send bytes already
/// hashed, so the digest disagrees with `manifest_digest` at every size the
/// differential test checks.
struct HashWriter<'a> {
    hasher: &'a mut Sha256,
    hash: std::time::Duration,
}

impl std::io::Write for HashWriter<'_> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let t = std::time::Instant::now();
        self.hasher.update(buf);
        self.hash += t.elapsed();
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

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

    /// The streaming digest must be BYTE-FOR-BYTE the digest of the whole
    /// file. Asserted against `manifest_digest` rather than against a
    /// hard-coded hash, so the oracle is the implementation that has always
    /// been trusted, and the new one has to agree with it.
    ///
    /// The sizes are where a chunked reader goes wrong: empty, a single
    /// byte, one short of the buffer, exactly the buffer, one past it, and
    /// several buffers with a ragged tail. A reader that drops a final partial
    /// chunk, or double-counts one at a boundary, is right on most of these
    /// and wrong on exactly one.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn a_streamed_digest_equals_the_whole_file_digest_at_every_boundary() {
        let dir = std::env::temp_dir().join(format!("varve-digest-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let b = DIGEST_BUFFER;
        for len in [0, 1, b - 1, b, b + 1, 3 * b + 7] {
            // Not all zeros: a pattern that changes with position, so a chunk
            // read out of order would hash differently.
            let bytes: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
            let path = dir.join(format!("payload-{len}"));
            std::fs::write(&path, &bytes).expect("write fixture");
            assert_eq!(
                digest_file(&path).expect("streams"),
                manifest_digest(&bytes),
                "streaming and whole-file digests disagree at {len} bytes"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The timed path and the untimed path must agree about the digest, at
    /// every buffer boundary: timing must not be able to change the answer,
    /// and `digest_file` is now implemented BY the timed one.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn timing_does_not_change_the_digest_at_any_boundary() {
        let dir = tempfile::tempdir().expect("tempdir");
        let b = DIGEST_BUFFER;
        for size in [0usize, 1, b - 1, b, b + 1, 3 * b + 7] {
            let path = dir.path().join(format!("f{size}"));
            let bytes: Vec<u8> = (0..size).map(|i| (i % 251) as u8).collect();
            std::fs::write(&path, &bytes).expect("write");
            let (timed, stage) = digest_file_timed(&path).expect("timed digest");
            assert_eq!(timed, manifest_digest(&bytes), "size {size}");
            assert_eq!(digest_file(&path).expect("digest"), timed, "size {size}");
            assert_eq!(stage.bytes, size as u64, "size {size}: bytes read");
        }
    }

    /// Both stages are attributed, and the bytes are the file's. The numbers
    /// this requirement asks to have RECORDED are what a rate is computed
    /// from, so a stage left silently at zero would make the record a lie.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn read_and_hash_are_attributed_separately() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("many-buffers");
        // Enough buffers that neither stage can round to zero on any clock.
        std::fs::write(&path, vec![7u8; DIGEST_BUFFER * 64]).expect("write");
        let (_, stage) = digest_file_timed(&path).expect("timed digest");
        assert_eq!(stage.bytes, (DIGEST_BUFFER * 64) as u64);
        assert!(stage.read > std::time::Duration::ZERO, "read unattributed");
        assert!(stage.hash > std::time::Duration::ZERO, "hash unattributed");
    }

    /// Summing is how a whole layer is attributed from its payloads.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn stage_timings_sum() {
        let mut total = StageTiming::default();
        total.add(StageTiming {
            read: std::time::Duration::from_millis(3),
            hash: std::time::Duration::from_millis(5),
            bytes: 100,
        });
        total.add(StageTiming {
            read: std::time::Duration::from_millis(7),
            hash: std::time::Duration::from_millis(11),
            bytes: 23,
        });
        assert_eq!(total.read, std::time::Duration::from_millis(10));
        assert_eq!(total.hash, std::time::Duration::from_millis(16));
        assert_eq!(total.bytes, 123);
    }

    /// THE CLASS GUARD. The paths that answer "does this installed payload
    /// still match its signed digest" must digest it through `digest_file`,
    /// never through `manifest_digest(&std::fs::read(..))`.
    ///
    /// A blanket "no fs::read" would be wrong — reverify legitimately reads
    /// the small signed envelope and manifest. The precise invariant is that
    /// their production code calls `manifest_digest` NOT AT ALL, so the only
    /// way to hash a payload there is the streaming one.
    ///
    /// Two files, not one, and that is the point: `reverify` is varve's own
    /// verify, `consumer` is the check other repositories call. Fixing only the
    /// first would stream varve's answer while every consumer still allocated a
    /// 2 GB SDK to ask the same question.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn no_payload_check_digests_a_whole_file_read() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        for rel in ["src/reverify.rs", "src/consumer.rs"] {
            let src = std::fs::read_to_string(root.join(rel)).expect("readable");
            let prod = match src.find("#[cfg(test)]") {
                Some(i) => &src[..i],
                None => &src[..],
            };
            assert!(
                !prod.contains("manifest_digest("),
                "{rel} digests with `manifest_digest` in production code. A payload \
                 check must stream through `digest_file`; hashing a whole-file read \
                 allocates the entire payload, which is 2 GB for an SDK (varve#141)."
            );
            // `digest_file_timed` counts: it IS the streaming path, and
            // `digest_file` is a thin wrapper over it. What must not appear is
            // a whole-file read, which the assertion above covers.
            assert!(
                prod.contains("digest_file(") || prod.contains("digest_file_timed("),
                "{rel} no longer streams a payload digest at all — the payload check \
                 has moved or vanished, and this guard would pass vacuously"
            );
        }
    }

    /// A missing file is an error the caller can name, not a digest of
    /// nothing. Hashing an absent file to the empty-string digest would be a
    /// silent pass for any entry whose signed digest happened to be that.
    // rivet: verifies REQ-VERIFYSTREAM-001
    #[test]
    fn a_missing_file_is_an_error_not_the_empty_digest() {
        let missing = std::env::temp_dir().join("varve-digest-definitely-absent-0");
        assert!(digest_file(&missing).is_err());
    }
}

#[cfg(test)]
pub(crate) mod fixtures {
    /// A minimal, valid layer manifest for tests.
    pub fn manifest(layer: &str, channel: &str) -> Vec<u8> {
        format!(
            r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "{layer}",
    "eu.pulseengine.varve.channel": "{channel}"
  }},
  "manifests": []
}}"#
        )
        .into_bytes()
    }

    /// A layer from before channel annotations existed. The resolver's channel
    /// guard must exempt it: a pre-channel layer states no channel, so it
    /// contradicts no pin.
    pub fn manifest_without_channel(layer: &str) -> Vec<u8> {
        format!(
            r#"{{
  "schemaVersion": 2,
  "mediaType": "application/vnd.oci.image.index.v1+json",
  "artifactType": "application/vnd.pulseengine.varve.layer.v1+json",
  "annotations": {{
    "eu.pulseengine.varve.layer": "{layer}"
  }},
  "manifests": []
}}"#
        )
        .into_bytes()
    }
}

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

    // rivet: verifies REQ-STORE-001
    #[test]
    fn a_layer_is_found_in_any_partition_under_the_same_root() {
        // A cross-realm composition include lives under the INCLUDED realm's
        // fingerprint, not the including project's. Looking in one partition
        // reported it missing while `list` showed it installed — `verify`,
        // `which` and `run` disagreed with `list`, and the corrective advice
        // failed (REQ-STORE-001).
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let mine = Store::at(root.join("realms").join("aaaa"));
        let theirs = Store::at(root.join("realms").join("bbbb"));
        let digest = theirs
            .lay_down(
                &fixtures::manifest("2026.08.0", "qualified"),
                &[("btool", b"b")],
            )
            .unwrap();

        // My own partition does not have it…
        assert!(mine.get(&digest).unwrap().is_none());
        // …but it is installed under this varve root, and locating it says so.
        let (owner, entry) = mine.find_anywhere(&digest).unwrap().expect("found");
        assert_eq!(entry.digest, digest);
        assert_eq!(owner.root(), theirs.root(), "found in the owning partition");
        // The tool resolves through the partition that actually holds it.
        assert!(owner.tool_path(&entry, "btool").is_some());
    }

    // rivet: verifies REQ-STORE-001
    #[test]
    fn the_varve_root_is_recovered_from_a_realm_partition() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        assert_eq!(
            Store::at(root.join("realms").join("ffff")).varve_root(),
            root.to_path_buf()
        );
        // A non-partition store is its own root.
        assert_eq!(Store::at(root).varve_root(), root.to_path_buf());
    }
}

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

    fn store() -> (tempfile::TempDir, Store) {
        let tmp = tempfile::tempdir().unwrap();
        let store = Store::at(tmp.path().join("varve-root"));
        (tmp, store)
    }

    // rivet: verifies REQ-COEXIST-001
    #[test]
    fn two_layers_coexist_and_are_independently_addressable() {
        let (_tmp, store) = store();
        let july = fixtures::manifest("2026.07.0", "qualified");
        let august = fixtures::manifest("2026.08.0", "qualified");
        let d_july = store.lay_down(&july, &[("synth", b"july-synth")]).unwrap();
        let d_august = store
            .lay_down(&august, &[("synth", b"august-synth")])
            .unwrap();
        assert_ne!(d_july, d_august);

        let listed = store.list().unwrap();
        assert_eq!(listed.len(), 2);

        let july_entry = store.get(&d_july).unwrap().unwrap();
        let august_entry = store.get(&d_august).unwrap().unwrap();
        assert_eq!(july_entry.layer.to_string(), "2026.07.0");
        assert_eq!(august_entry.layer.to_string(), "2026.08.0");

        // The same tool name resolves to different bytes per layer — the
        // wohl-on-July-while-relay-on-August afternoon, on one machine.
        let july_synth = store.tool_path(&july_entry, "synth").unwrap();
        let august_synth = store.tool_path(&august_entry, "synth").unwrap();
        assert_eq!(std::fs::read(july_synth).unwrap(), b"july-synth");
        assert_eq!(std::fs::read(august_synth).unwrap(), b"august-synth");
    }

    // rivet: verifies REQ-COEXIST-001
    #[test]
    fn store_key_is_the_manifest_digest() {
        let (_tmp, store) = store();
        let bytes = fixtures::manifest("2026.07.0", "qualified");
        let digest = store.lay_down(&bytes, &[]).unwrap();
        assert_eq!(digest, manifest_digest(&bytes));
        let entry = store.get(&digest).unwrap().unwrap();
        assert!(
            entry
                .root
                .ends_with(format!("core/{}", digest.replace(':', "-"))),
            "entry rooted at digest-keyed dir, got {}",
            entry.root.display()
        );
        // layer.json preserved verbatim for verify/archive.
        assert_eq!(std::fs::read(entry.root.join("layer.json")).unwrap(), bytes);
    }

    // rivet: verifies REQ-PIN-001
    #[test]
    fn missing_layer_is_none_not_an_invention() {
        let (_tmp, store) = store();
        assert_eq!(
            store
                .get("sha256:0000000000000000000000000000000000000000000000000000000000000000")
                .unwrap(),
            None
        );
        assert_eq!(store.list().unwrap(), vec![]);
    }

    /// A manifest entry as a signed layer carries it.
    fn entry(name: &str, version: Option<&str>, kind: Option<&str>) -> ManifestEntry {
        let mut annotations = BTreeMap::new();
        annotations.insert("eu.pulseengine.tool".to_string(), name.to_string());
        if let Some(v) = version {
            annotations.insert("eu.pulseengine.tool.version".to_string(), v.to_string());
        }
        if let Some(k) = kind {
            annotations.insert(crate::kind::ANN_KIND.to_string(), k.to_string());
        }
        ManifestEntry {
            digest: manifest_digest(name.as_bytes()),
            annotations,
        }
    }

    fn held<'a>(name: &'a str, version: &'a str, bytes: &'a [u8]) -> Payload<'a> {
        Payload {
            name,
            version: Some(version),
            dispatchable: false,
            target: None,
            bytes,
        }
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn two_versions_of_one_name_are_two_files_neither_overwriting_the_other() {
        // Clause 2. `lay_down` wrote every payload to `bin/<name>`, so relaxing
        // the deposit check alone would have made the second serde silently
        // overwrite the first: the WRONG BYTES land under the right name, and
        // verification then fails on the OTHER entry with nothing explaining
        // why. A clean error turned into silent data loss.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let digest = store
            .lay_down_payloads(
                &manifest,
                &[
                    held("serde", "1.0.200", b"serde-200-bytes"),
                    held("serde", "1.0.210", b"serde-210-bytes"),
                ],
            )
            .unwrap();
        let layer = store.get(&digest).unwrap().unwrap();

        // Each version is its OWN file, holding its OWN bytes.
        let two_hundred = layer.root.join("payloads/serde/1.0.200");
        let two_ten = layer.root.join("payloads/serde/1.0.210");
        assert_eq!(std::fs::read(&two_hundred).unwrap(), b"serde-200-bytes");
        assert_eq!(std::fs::read(&two_ten).unwrap(), b"serde-210-bytes");
        // …and nothing landed under the bare name, where one would have won.
        assert!(!layer.root.join("bin/serde").exists());

        // Both are reachable FROM THEIR MANIFEST ENTRIES — the lookup every
        // consumer uses, so `verify`, `archive` and `export-cargo` each see the
        // version they asked for rather than whichever landed last.
        assert_eq!(
            store.entry_path(&layer, &entry("serde", Some("1.0.200"), Some("crate"))),
            Some(two_hundred)
        );
        assert_eq!(
            store.entry_path(&layer, &entry("serde", Some("1.0.210"), Some("crate"))),
            Some(two_ten)
        );
    }

    /// A cross-toolchain is identified by a PAIR: the host that runs it and
    /// the target it builds for. Two SDKs with one name and one version, for
    /// one host, differing only in target, are two different payloads —
    /// `toolchain_gnu_linux-x86_64_arm-zephyr-eabi` and
    /// `..._riscv64-zephyr-elf` are both "the toolchain", for this machine,
    /// and a realm wants both installed at once.
    ///
    /// Before this they landed on one path. The platform dimension could not
    /// separate them because platform describes the machine that RUNS the
    /// bytes, and for a cross-toolchain that is the same machine for every
    /// target — which is the whole reason this requirement exists.
    // rivet: verifies REQ-SDKTARGET-001
    #[test]
    fn two_sdks_differing_only_by_target_are_two_payloads() {
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let arm = Payload::targeted("zephyr-sdk", "1.0.1", "arm-zephyr-eabi", b"arm-bytes");
        let riscv = Payload::targeted("zephyr-sdk", "1.0.1", "riscv64-zephyr-elf", b"riscv-bytes");
        let digest = store
            .lay_down_payloads(&manifest, &[arm, riscv])
            .expect("two targets of one SDK are not a collision");

        let root = store.core_dir().join(digest.replace(':', "-"));
        let arm_path = root
            .join(crate::store::PAYLOAD_DIR)
            .join("zephyr-sdk")
            .join("1.0.1")
            .join("arm-zephyr-eabi");
        let riscv_path = root
            .join(crate::store::PAYLOAD_DIR)
            .join("zephyr-sdk")
            .join("1.0.1")
            .join("riscv64-zephyr-elf");
        assert_eq!(std::fs::read(&arm_path).unwrap(), b"arm-bytes");
        assert_eq!(std::fs::read(&riscv_path).unwrap(), b"riscv-bytes");
    }

    /// …and the guard still holds WITHIN a target: two payloads with the same
    /// name, version and target are still one identity and must be refused.
    /// Adding a dimension must not open a hole in the rule it extends.
    // rivet: verifies REQ-SDKTARGET-001
    #[test]
    fn two_sdks_with_the_same_target_still_collide() {
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let err = store
            .lay_down_payloads(
                &manifest,
                &[
                    Payload::targeted("zephyr-sdk", "1.0.1", "arm-zephyr-eabi", b"first"),
                    Payload::targeted("zephyr-sdk", "1.0.1", "arm-zephyr-eabi", b"second"),
                ],
            )
            .unwrap_err();
        assert!(matches!(&err, StoreError::Collision { .. }), "got: {err}");
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn two_payloads_claiming_one_path_are_refused_before_anything_is_written() {
        // The guard that makes the relaxation safe. deposit refuses two tools
        // under one name, but deposit is not the only producer: install accepts
        // ANY manifest a realm root signed, including one built by other
        // software. If two entries ever reach one path, the store must say so
        // loudly rather than write one over the other.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let err = store
            .lay_down_payloads(
                &manifest,
                &[
                    Payload::tool("synth", b"first-bytes"),
                    Payload::tool("synth", b"second-bytes"),
                ],
            )
            .unwrap_err();
        assert!(
            matches!(&err, StoreError::Collision { path, .. } if path.contains("synth")),
            "got: {err}"
        );
        // And the core is untouched: destinations are resolved before any byte
        // is written, so a colliding layer never half-lands.
        assert!(store.list().unwrap().is_empty(), "nothing may be laid down");

        // The same collision through the versionless legacy placement.
        let err = store
            .lay_down_payloads(
                &manifest,
                &[
                    Payload {
                        name: "wit-pkg",
                        version: None,
                        dispatchable: false,
                        target: None,
                        bytes: b"a",
                    },
                    Payload {
                        name: "wit-pkg",
                        version: None,
                        dispatchable: false,
                        target: None,
                        bytes: b"b",
                    },
                ],
            )
            .unwrap_err();
        assert!(matches!(err, StoreError::Collision { .. }), "got: {err}");
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn a_name_or_version_that_escapes_the_layer_is_refused() {
        // The names now compose a PATH, and they come out of a manifest.
        // "Signed" means attributable, not benign: a realm root must not be
        // able to place bytes outside the layer it is laying down.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        for (name, version) in [
            ("../../escape", Some("1.0.0")),
            ("serde", Some("../../escape")),
            ("a/b", Some("1.0.0")),
            ("..", Some("1.0.0")),
            ("", Some("1.0.0")),
            ("serde", Some("")),
        ] {
            let err = store
                .lay_down_payloads(&manifest, &[held(name, version.unwrap(), b"x")])
                .unwrap_err();
            assert!(
                matches!(err, StoreError::UnsafeComponent { .. }),
                "{name:?}@{version:?} must be refused, got: {err}"
            );
        }
        assert!(store.list().unwrap().is_empty());
        // The escape did not happen by any other route either.
        assert!(!store.root().join("escape").exists());
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn a_layer_installed_before_this_change_still_resolves_its_crate() {
        // Backward compatibility, stated as a test rather than a hope: a layer
        // laid down by an older varve holds its crate at `bin/<name>`, and
        // `verify`/`archive`/`export-cargo` must still find it there. Such a
        // layer can hold only ONE version per name — the old deposit check made
        // sure of it — so the fallback is unambiguous.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let digest = store
            .lay_down(&manifest, &[("legacy-crate", b"old-layout-bytes")])
            .unwrap();
        let layer = store.get(&digest).unwrap().unwrap();
        let path = store
            .entry_path(&layer, &entry("legacy-crate", Some("0.1.0"), Some("crate")))
            .expect("a pre-REQ-STORE-002 layer must keep resolving");
        assert_eq!(std::fs::read(path).unwrap(), b"old-layout-bytes");
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn a_tool_keeps_bin_and_a_held_payload_never_borrows_it() {
        // Dispatch is by name, so `bin/<name>` is not merely retained for
        // compatibility — it is the contract `varve which`, `varve run` and the
        // argv[0] shims resolve through. A held payload must never satisfy a
        // dispatch lookup by landing there.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let digest = store
            .lay_down_payloads(
                &manifest,
                &[
                    Payload::tool("synth", b"synth-binary"),
                    held("serde", "1.0.200", b"serde-crate"),
                ],
            )
            .unwrap();
        let layer = store.get(&digest).unwrap().unwrap();
        assert_eq!(
            std::fs::read(store.tool_path(&layer, "synth").unwrap()).unwrap(),
            b"synth-binary"
        );
        assert_eq!(store.tool_path(&layer, "serde"), None, "not dispatchable");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode =
                |p: std::path::PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode(layer.root.join("bin/synth")), 0o755);
            assert_eq!(
                mode(layer.root.join("payloads/serde/1.0.200")),
                0o644,
                "a .crate tarball is data, not something to execute"
            );
        }
    }

    // rivet: verifies REQ-STORE-002
    #[test]
    fn an_unrecognised_kind_is_held_by_version_never_dispatched_by_name() {
        // A layer deposited by a NEWER varve carries kinds this build has never
        // heard of, and installs and verifies normally (DD-003, kind.rs). If an
        // unknown kind were placed by name alone, two versions of it would
        // overwrite each other — the very loss this requirement forbids, one
        // release later.
        let e = entry("future", Some("2.0.0"), Some("quantum-blob"));
        assert!(!entry_is_dispatchable(&e));
        assert_eq!(
            payload_rel_path(false, "future", Some("2.0.0"), None).unwrap(),
            PathBuf::from("payloads/future/2.0.0")
        );
        // …while an entry with NO kind annotation is a tool, as pre-kind
        // layers require.
        assert!(entry_is_dispatchable(&entry("synth", Some("0.45.0"), None)));
        assert_eq!(
            payload_rel_path(true, "synth", Some("0.45.0"), None).unwrap(),
            PathBuf::from("bin/synth")
        );
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_tree_shaped_payload_is_held_by_name_and_version_like_any_other() {
        // REQ-SDK-001 clause 1, and the correction the clause needed. A tree
        // payload is held as the single archive its producer SIGNED — one blob,
        // one digest, at `payloads/<name>/<version>` exactly like a `.crate` or
        // a `.vsix`. It is not unpacked here, and that is the design rather than
        // a shortfall:
        //
        //   * `verify` and `archive` re-hash ONE file at `entry_path` against
        //     ONE signed digest, so an unpacked store entry would be neither
        //     verifiable nor archivable — the opposite of clause 2;
        //   * relocation can only ever SHORTEN a path, and the store path is
        //     ~90 characters before any content, so an SDK could not be
        //     relocated INTO the store even if it were unpacked there.
        //
        // The tree is materialised where it is used, by `sdkexport`.
        let (_tmp, store) = store();
        let manifest = fixtures::manifest("2026.08.0", "qualified");
        let digest = store
            .lay_down_payloads(
                &manifest,
                &[
                    held("poky-cortexa53", "4.0.15", b"sdk-tarball-4.0.15"),
                    held("poky-cortexa53", "5.0.2", b"sdk-tarball-5.0.2"),
                    held("zephyr-hal", "3.6.0", b"zephyr-module-tarball"),
                ],
            )
            .unwrap();
        let layer = store.get(&digest).unwrap().unwrap();

        // Two SDK versions coexist, neither overwriting the other — a project
        // migrating between Yocto releases holds both.
        for (version, want) in [
            ("4.0.15", &b"sdk-tarball-4.0.15"[..]),
            ("5.0.2", &b"sdk-tarball-5.0.2"[..]),
        ] {
            let path = store
                .entry_path(&layer, &entry("poky-cortexa53", Some(version), Some("sdk")))
                .expect("an sdk resolves from its manifest entry like any held payload");
            assert_eq!(
                path,
                layer
                    .root
                    .join(format!("payloads/poky-cortexa53/{version}"))
            );
            assert_eq!(std::fs::read(&path).unwrap(), want);
        }
        // An SDK is data handed to a compiler, never something varve dispatches.
        assert!(!crate::kind::PayloadKind::Sdk.is_dispatchable());
        assert_eq!(store.tool_path(&layer, "poky-cortexa53"), None);
        assert!(!layer.root.join("bin/poky-cortexa53").exists());
        // The other tree kinds are held the same way — nothing about `sdk` is
        // special in the store, which is what "like any other held payload"
        // means.
        assert!(
            store
                .entry_path(
                    &layer,
                    &entry("zephyr-hal", Some("3.6.0"), Some("zephyr-module"))
                )
                .is_some()
        );
    }

    // rivet: verifies REQ-PIN-001
    #[test]
    fn missing_tool_in_an_installed_layer_is_none() {
        let (_tmp, store) = store();
        let bytes = fixtures::manifest("2026.07.0", "qualified");
        let digest = store.lay_down(&bytes, &[("rivet", b"r")]).unwrap();
        let entry = store.get(&digest).unwrap().unwrap();
        assert!(store.tool_path(&entry, "rivet").is_some());
        assert_eq!(store.tool_path(&entry, "synth"), None);
    }
}