varve-core 0.44.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
//! Reading and exporting the documentation a layer carries (REQ-LAYERDOCS-001).
//!
//! The payload is the archive exactly as its producer published it — never
//! unpacked into the store. That is not a preference about tidiness: the
//! stored bytes have to stay identical to what the signature covers, or
//! `varve verify` cannot re-derive the digest. An unpacked store would trade
//! re-verification for disk, which is the wrong way round for a tool whose
//! whole claim is that it can still prove what it holds.
//!
//! So there are two ways to get at a document, and they answer different
//! questions:
//!
//! - [`read_one`] pulls ONE file out of the archive in place. Nothing is
//!   written and nothing is duplicated; this is what the viewer uses, and it
//!   is the reason the viewer does not need an export first.
//! - [`export`] materialises a copy on disk, for handing to someone or
//!   publishing as a CI artifact. It costs space only when asked for.
//!
//! **The known cost, stated rather than discovered.** A `.tar.gz` is
//! sequential: [`read_one`] decompresses the whole archive to reach one
//! member. That is free for the 1.2 MB traceability bundle and wrong for a
//! few-hundred-megabyte rustdoc. The fix is a random-access container (zip's
//! central directory lets one entry be read without touching the rest), and it
//! belongs with rustdoc rather than here — an unused dependency in a
//! verification binary is its own cost. A caller serving many files from one
//! large payload should read the members once and keep them, not call
//! [`read_one`] in a loop.

use crate::layerspec::DocsFormat;
use crate::sdkexport::{Member, MemberBody, SdkExportError, read_members};
use std::path::Path;

/// One documentation payload, as the exporter and the viewer see it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocsPayload {
    /// The handle a command takes.
    pub name: String,
    pub version: String,
    /// What it IS, from the signed annotation — never guessed from `bytes`.
    pub format: DocsFormat,
    /// Where a reader starts, for a tree format.
    pub entry: Option<String>,
    /// The human label shown when choosing.
    pub title: Option<String>,
    /// The payload this documents, by name (clause 2).
    pub documents: Option<String>,
    /// The archive (or the single file), exactly as signed.
    pub bytes: Vec<u8>,
}

impl DocsPayload {
    /// A docs payload, read from the annotations its layer SIGNED.
    ///
    /// The one reader of those annotations on the consumer side. `export-docs`
    /// and `varve-serve` each used to build this by hand, with their own format
    /// parser, so a field added to one would reach one reader and not the
    /// other — exactly the shape that shipped `documents` half-read would have.
    pub fn from_signed(
        annotations: &std::collections::BTreeMap<String, String>,
        bytes: Vec<u8>,
    ) -> Result<DocsPayload, DocsExportError> {
        let get = |k: &str| annotations.get(k).cloned();
        let name = get("eu.pulseengine.tool").unwrap_or_else(|| "(unnamed)".into());
        let format = match annotations.get(crate::deposit::ANN_DOCS_FORMAT) {
            None => {
                return Err(DocsExportError::Unreadable {
                    name,
                    detail: format!(
                        "it carries no {} annotation — it was deposited without the gate that \
                         requires one, so there is no way to tell how to open it",
                        crate::deposit::ANN_DOCS_FORMAT
                    ),
                });
            }
            Some(raw) => DocsFormat::parse(raw).ok_or_else(|| DocsExportError::Unreadable {
                name: name.clone(),
                detail: format!(
                    "it declares the documentation format {raw:?}, which this build does not \
                     know. The document is carried and verified; a newer varve may open it"
                ),
            })?,
        };
        Ok(DocsPayload {
            version: get("eu.pulseengine.tool.version").unwrap_or_default(),
            format,
            entry: get(crate::deposit::ANN_DOCS_ENTRY),
            title: get(crate::deposit::ANN_DOCS_TITLE),
            documents: get(crate::deposit::ANN_DOCS_DOCUMENTS),
            name,
            bytes,
        })
    }
}

#[derive(Debug, thiserror::Error)]
pub enum DocsExportError {
    #[error("{name}: {source}")]
    Archive {
        name: String,
        #[source]
        source: SdkExportError,
    },
    #[error("cannot write {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    /// Asked for a document the layer does not carry. Names what IS carried,
    /// because the next thing the caller needs is the right handle.
    #[error(
        "this layer carries no documentation named {asked:?}. It carries: {carried}. \
         `varve inspect` lists every payload."
    )]
    NoSuchDocument { asked: String, carried: String },
    /// More than one document and no way to tell which was meant.
    #[error(
        "this layer carries {n} documents and none was named: {carried}. Name one — \
         a selector is only optional where there is nothing to choose between."
    )]
    Ambiguous { n: usize, carried: String },
    /// Asked for the documentation of a payload nothing documents.
    #[error(
        "nothing in this layer documents {asked:?}. Documented: {documented}. \
         `varve inspect` shows what each document documents."
    )]
    NothingDocuments { asked: String, documented: String },
    /// Several documents of the one payload.
    #[error("{n} documents in this layer document {asked:?}: {carried}. Name one with --select.")]
    AmbiguousFor {
        asked: String,
        n: usize,
        carried: String,
    },
    /// A docs payload whose signed annotations cannot be read as a document.
    #[error("docs payload {name:?} cannot be opened: {detail}")]
    Unreadable { name: String, detail: String },
}

/// What an export did. Reported rather than assumed: "wrote 0 files" and
/// "wrote 341 files" look the same on disk unless someone says.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DocsExportReport {
    pub files: usize,
    pub dirs: usize,
    /// The path a reader should open, absolute, once the export has happened.
    pub entry_path: Option<String>,
}

/// Choose one payload by name, or the only one if there is exactly one.
///
/// The no-selector case is deliberate ergonomics, borrowed from
/// `criticalup doc`: a reader has already said which layer they want by
/// pinning it, and making them name the document again is asking twice. But
/// it holds ONLY where there is nothing to choose between — guessing among
/// several would open the wrong document silently, which is worse than asking.
pub fn select<'a>(
    payloads: &'a [DocsPayload],
    asked: Option<&str>,
) -> Result<&'a DocsPayload, DocsExportError> {
    let carried = || {
        let mut names: Vec<&str> = payloads.iter().map(|p| p.name.as_str()).collect();
        names.sort_unstable();
        if names.is_empty() {
            "nothing".to_string()
        } else {
            names.join(", ")
        }
    };
    match asked {
        Some(name) => payloads.iter().find(|p| p.name == name).ok_or_else(|| {
            DocsExportError::NoSuchDocument {
                asked: name.to_string(),
                carried: carried(),
            }
        }),
        None => match payloads {
            [only] => Ok(only),
            many => Err(DocsExportError::Ambiguous {
                n: many.len(),
                carried: carried(),
            }),
        },
    }
}

/// Choose the document of a payload: the one whose signed `documents` names it.
///
/// Matched on what a document SAYS it documents, never on its own name — a
/// document called `varve-core` is not thereby the documentation of the
/// `varve-core` crate, and guessing so would open the wrong thing and report
/// success.
pub fn select_for<'a>(
    payloads: &'a [DocsPayload],
    asked: &str,
) -> Result<&'a DocsPayload, DocsExportError> {
    let hits: Vec<&DocsPayload> = payloads
        .iter()
        .filter(|p| p.documents.as_deref() == Some(asked))
        .collect();
    match hits.as_slice() {
        [only] => Ok(only),
        [] => {
            let mut documented: Vec<&str> = payloads
                .iter()
                .filter_map(|p| p.documents.as_deref())
                .collect();
            documented.sort_unstable();
            documented.dedup();
            Err(DocsExportError::NothingDocuments {
                asked: asked.to_string(),
                documented: if documented.is_empty() {
                    "nothing — no document in this layer names a payload".to_string()
                } else {
                    documented.join(", ")
                },
            })
        }
        many => {
            let mut names: Vec<&str> = many.iter().map(|p| p.name.as_str()).collect();
            names.sort_unstable();
            Err(DocsExportError::AmbiguousFor {
                asked: asked.to_string(),
                n: many.len(),
                carried: names.join(", "),
            })
        }
    }
}

/// Read ONE file out of a tree payload, without writing anything.
///
/// `None` means the archive opened and did not contain that path — a fact the
/// caller reports as a 404, distinct from the archive failing to open, which
/// is an error. Conflating the two would turn "this page does not exist" and
/// "this payload is corrupt" into the same message.
pub fn read_one(payload: &DocsPayload, path: &str) -> Result<Option<Vec<u8>>, DocsExportError> {
    if !payload.format.is_tree() {
        // A single-file document has exactly one thing to read, and asking it
        // for an inner path is a category error rather than a miss.
        return Ok(None);
    }
    let want = path.trim_start_matches('/');
    let members = members_of(payload)?;
    Ok(members.into_iter().find_map(|m| match m.body {
        MemberBody::File { bytes, .. } if rel_path(&m.path, want) => Some(bytes),
        _ => None,
    }))
}

/// Materialise a document on disk.
///
/// A tree becomes a directory; a single-file format becomes one file named
/// `<name>-<version>.<ext>`. Returns where a reader should start, so the
/// caller can print a path rather than leave someone to find it.
///
/// Member paths are validated by `sdkexport::safe_member_path` — the SAME
/// rule the SDK exporter applies, not a second copy of it. One member is
/// enough to escape an export directory, and a tree has thousands.
pub fn export(payload: &DocsPayload, out: &Path) -> Result<DocsExportReport, DocsExportError> {
    let io = |path: &Path, source: std::io::Error| DocsExportError::Io {
        path: path.display().to_string(),
        source,
    };
    std::fs::create_dir_all(out).map_err(|e| io(out, e))?;
    let mut report = DocsExportReport::default();

    if !payload.format.is_tree() {
        let ext = payload
            .format
            .file_extension()
            .expect("a non-tree format names an extension");
        let file = out.join(format!("{}-{}.{ext}", payload.name, payload.version));
        std::fs::write(&file, &payload.bytes).map_err(|e| io(&file, e))?;
        report.files = 1;
        report.entry_path = Some(file.display().to_string());
        return Ok(report);
    }

    for m in members_of(payload)? {
        // `tar -C dir .` writes the root itself first; as a directory it is
        // the export directory, which already exists.
        if matches!(m.body, MemberBody::Dir) && crate::sdkexport::names_archive_root(&m.path) {
            continue;
        }
        let rel = crate::sdkexport::safe_member_path(&m.path).map_err(|source| {
            DocsExportError::Archive {
                name: payload.name.clone(),
                source,
            }
        })?;
        let dest = out.join(&rel);
        match m.body {
            MemberBody::Dir => {
                std::fs::create_dir_all(&dest).map_err(|e| io(&dest, e))?;
                report.dirs += 1;
            }
            MemberBody::File { bytes, .. } => {
                if let Some(parent) = dest.parent() {
                    std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
                }
                std::fs::write(&dest, &bytes).map_err(|e| io(&dest, e))?;
                report.files += 1;
            }
            // A document is read, never executed, so a symlink inside one buys
            // nothing and can point anywhere. Skipped rather than followed.
            MemberBody::Symlink { .. } => {}
        }
    }
    report.entry_path = payload
        .entry
        .as_deref()
        .map(|e| out.join(e).display().to_string());
    Ok(report)
}

/// Every member of a tree payload, wrapped with the payload's name so a
/// failure says which document could not be opened.
pub fn members_of(payload: &DocsPayload) -> Result<Vec<Member>, DocsExportError> {
    read_members(&payload.bytes).map_err(|source| DocsExportError::Archive {
        name: payload.name.clone(),
        source,
    })
}

/// Does this member path denote `want`, allowing for a single wrapper
/// directory and a leading `./`?
///
/// Mirrors `layerspec::docs_entry_present`'s rule for one path rather than a
/// whole listing. Kept exact for the same reason: a tail match would let
/// `eu-ai-act/index.html` answer a request for `index.html`, and varve's own
/// traceability bundle carries two such namesakes.
fn rel_path(member: &str, want: &str) -> bool {
    let m = member.trim_start_matches("./");
    m == want
}

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

    fn payload(name: &str, format: DocsFormat) -> DocsPayload {
        DocsPayload {
            name: name.into(),
            version: "0.1.0".into(),
            format,
            entry: Some("index.html".into()),
            title: None,
            documents: None,
            bytes: Vec::new(),
        }
    }

    fn documenting(name: &str, documents: &str) -> DocsPayload {
        DocsPayload {
            documents: Some(documents.into()),
            ..payload(name, DocsFormat::Rustdoc)
        }
    }

    /// `--for varve-core` answers with the document that SAYS it documents
    /// varve-core — not with one that happens to be named like it.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_reader_can_ask_for_the_documentation_of_a_payload() {
        let docs = vec![
            payload("varve-core", DocsFormat::Html),
            documenting("varve-core-api", "varve-core"),
            documenting("varve-api", "varve"),
        ];
        assert_eq!(
            select_for(&docs, "varve-core").expect("selects").name,
            "varve-core-api"
        );
        assert_eq!(
            select_for(&docs, "varve").expect("selects").name,
            "varve-api"
        );
    }

    /// Nothing documents it: say what IS documented, so the next command is
    /// not a guess.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn asking_for_an_undocumented_payload_names_what_is_documented() {
        let docs = vec![
            payload("handbook", DocsFormat::Pdf),
            documenting("varve-core-api", "varve-core"),
        ];
        let e = select_for(&docs, "serde").expect_err("must refuse");
        assert!(
            matches!(e, DocsExportError::NothingDocuments { .. }),
            "{e:?}"
        );
        let msg = e.to_string();
        assert!(msg.contains("serde"), "{msg}");
        assert!(msg.contains("varve-core"), "{msg}");
        assert!(
            !msg.contains("handbook"),
            "a document of nothing is not an answer: {msg}"
        );
    }

    /// Two documents of one payload — say a rustdoc and a guide — must ask.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn two_documents_of_one_payload_refuse_rather_than_guess() {
        let docs = vec![
            documenting("varve-core-api", "varve-core"),
            documenting("varve-core-guide", "varve-core"),
        ];
        let e = select_for(&docs, "varve-core").expect_err("must refuse");
        assert!(
            matches!(e, DocsExportError::AmbiguousFor { n: 2, .. }),
            "{e:?}"
        );
        assert!(e.to_string().contains("varve-core-api"), "{e}");
        assert!(e.to_string().contains("varve-core-guide"), "{e}");
    }

    /// The consumer reads every docs field from the SIGNED annotations in one
    /// place. It used to be read twice — by `export-docs` and by `varve-serve`
    /// — each with its own format parser, so a field added to one reader and
    /// not the other would ship half-read.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_payload_is_read_from_its_signed_annotations() {
        let mut ann = std::collections::BTreeMap::new();
        ann.insert(
            "eu.pulseengine.tool".to_string(),
            "varve-core-api".to_string(),
        );
        ann.insert(
            "eu.pulseengine.tool.version".to_string(),
            "0.36.0".to_string(),
        );
        ann.insert(
            crate::deposit::ANN_DOCS_FORMAT.to_string(),
            "rustdoc".to_string(),
        );
        ann.insert(
            crate::deposit::ANN_DOCS_ENTRY.to_string(),
            "varve_core/index.html".to_string(),
        );
        ann.insert(
            crate::deposit::ANN_DOCS_TITLE.to_string(),
            "API".to_string(),
        );
        ann.insert(
            crate::deposit::ANN_DOCS_DOCUMENTS.to_string(),
            "varve-core".to_string(),
        );
        let p = DocsPayload::from_signed(&ann, b"bytes".to_vec()).expect("reads");
        assert_eq!(p.name, "varve-core-api");
        assert_eq!(p.version, "0.36.0");
        assert_eq!(p.format, DocsFormat::Rustdoc);
        assert_eq!(p.entry.as_deref(), Some("varve_core/index.html"));
        assert_eq!(p.title.as_deref(), Some("API"));
        assert_eq!(p.documents.as_deref(), Some("varve-core"));
        assert_eq!(p.bytes, b"bytes");

        ann.insert(
            crate::deposit::ANN_DOCS_FORMAT.to_string(),
            "epub".to_string(),
        );
        let e = DocsPayload::from_signed(&ann, Vec::new()).expect_err("unknown format");
        assert!(e.to_string().contains("epub"), "{e}");
        ann.remove(crate::deposit::ANN_DOCS_FORMAT);
        let e = DocsPayload::from_signed(&ann, Vec::new()).expect_err("no format");
        assert!(e.to_string().contains("varve-core-api"), "{e}");
    }

    /// One document and no selector is the common case, and asking the reader
    /// to name what they already pinned is asking twice.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_single_document_needs_no_selector() {
        let one = vec![payload("traceability", DocsFormat::Html)];
        assert_eq!(select(&one, None).expect("selects").name, "traceability");
    }

    /// Several documents and no selector must ASK, not guess. Opening the
    /// wrong document silently is worse than a question.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn several_documents_and_no_selector_refuses_rather_than_guessing() {
        let many = vec![
            payload("traceability", DocsFormat::Html),
            payload("handbook", DocsFormat::Pdf),
        ];
        let e = select(&many, None).expect_err("must refuse");
        assert!(
            matches!(e, DocsExportError::Ambiguous { n: 2, .. }),
            "{e:?}"
        );
        // The message has to carry the handles, or the reader's next step is a
        // guess as well.
        assert!(e.to_string().contains("handbook"), "{e}");
        assert!(e.to_string().contains("traceability"), "{e}");
    }

    /// A wrong name names what IS there — the reader's next action needs the
    /// right handle, and "not found" alone does not supply it.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn an_unknown_name_reports_what_the_layer_does_carry() {
        let one = vec![payload("traceability", DocsFormat::Html)];
        let e = select(&one, Some("handbok")).expect_err("must refuse");
        assert!(e.to_string().contains("traceability"), "{e}");
    }

    /// A namesake in a subdirectory does not answer a request for the root
    /// file. The traceability bundle carries `eu-ai-act/index.html`, so a tail
    /// match would serve the wrong page and report success.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_subdirectory_namesake_is_not_the_root_file() {
        assert!(rel_path("./index.html", "index.html"));
        assert!(!rel_path("./eu-ai-act/index.html", "index.html"));
        assert!(rel_path("./eu-ai-act/index.html", "eu-ai-act/index.html"));
    }

    /// Export writes what the archive holds, and reports where to start.
    /// Built from a real tar.gz rather than a hand-made member list, so the
    /// decompression path is exercised too.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_tree_document_exports_and_names_its_starting_page() {
        use std::io::Write;
        let mut tar_bytes = Vec::new();
        {
            let mut b = tar::Builder::new(&mut tar_bytes);
            // An explicit directory member, so `report.dirs` counts something
            // real. Without one the counter was never incremented and its
            // mutants survived — a fixture that cannot reach a branch is why
            // the branch looked tested.
            {
                let mut d = tar::Header::new_gnu();
                d.set_size(0);
                d.set_mode(0o755);
                d.set_entry_type(tar::EntryType::Directory);
                d.set_cksum();
                b.append_data(&mut d, "./sub/", std::io::empty())
                    .expect("append dir");
            }
            // The ROOT itself, first, as `tar -C dir .` writes it. It names
            // the export directory and must neither refuse the export nor
            // count as a directory written.
            {
                let mut d = tar::Header::new_gnu();
                d.set_size(0);
                d.set_mode(0o755);
                d.set_entry_type(tar::EntryType::Directory);
                d.set_cksum();
                b.append_data(&mut d, "./", std::io::empty())
                    .expect("append root");
            }
            for (path, body) in [
                ("./index.html", "<h1>root</h1>"),
                ("./eu-ai-act/index.html", "<h1>not the root</h1>"),
            ] {
                let mut h = tar::Header::new_gnu();
                h.set_size(body.len() as u64);
                h.set_mode(0o644);
                h.set_cksum();
                b.append_data(&mut h, path, body.as_bytes())
                    .expect("append");
            }
            b.finish().expect("finish");
        }
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        gz.write_all(&tar_bytes).expect("compress");
        let bytes = gz.finish().expect("finish gz");

        let doc = DocsPayload {
            name: "traceability".into(),
            version: "0.34.3".into(),
            format: DocsFormat::Html,
            entry: Some("index.html".into()),
            title: None,
            documents: None,
            bytes,
        };

        let dir = std::env::temp_dir().join(format!("varve-docs-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let report = export(&doc, &dir).expect("exports");

        assert_eq!(report.files, 2);
        // `dirs` had no assertion, so `report.dirs += 1` survived mutation to
        // `-=` and `*=`. A count nobody reads is a count nobody can trust.
        assert_eq!(
            report.dirs, 1,
            "the tar carries one directory entry (./sub/), and it must be counted"
        );
        let entry = report.entry_path.expect("names an entry");
        assert!(entry.ends_with("index.html"), "{entry}");
        assert_eq!(
            std::fs::read_to_string(&entry).expect("entry exists on disk"),
            "<h1>root</h1>",
            "the entry must be the ROOT page, not the namesake one directory down"
        );

        // And the no-copy read path agrees with what was written.
        let served = read_one(&doc, "index.html")
            .expect("reads")
            .expect("present");
        assert_eq!(served, b"<h1>root</h1>");
        assert_eq!(
            read_one(&doc, "nope.html").expect("reads"),
            None,
            "a missing page is None, not an error"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A single-file document has nothing inside to address, and that is a
    /// different fact from a missing page.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_single_file_document_has_no_inner_paths() {
        let pdf = payload("handbook", DocsFormat::Pdf);
        assert_eq!(read_one(&pdf, "index.html").expect("no error"), None);
    }
}