varve 0.37.0

The PulseEngine toolchain layer manager — pinned, signed, dated toolchain bundles
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
//! `varve inspect` (REQ-INSPECT-001) — what is actually in a layer.
//!
//! Nothing reported a layer's payload names, versions, kinds or platforms.
//! `varve list` prints layer ids; `varve sbom` collapses every non-tool kind to
//! a CycloneDX `library` and is blind to composition. In the ten-persona audit
//! the build engineer chose an export adapter by running all four and reading
//! which one errored, and the newcomer learned the tool set by typo-ing a name
//! into `varve which` so the error would list the alternatives.
//!
//! Three things this command is careful about:
//!
//! * **DISPATCHED vs HELD** (clause 3). Only a `tool` is dispatched by name.
//!   Every other kind is HELD: stored, verified, handed to an export adapter,
//!   and not on your PATH. `varve which` reported a held `wit` payload as "not
//!   part of layer", which is FALSE — the layer holds it.
//! * **The composition** (clause 4). A composed layer's payloads are part of
//!   what the pin delivers, so they are part of the answer. `sbom` being
//!   composition-blind is a known limitation and this must not repeat it.
//! * **No network** (clause 5). The store already holds the answer. The layer
//!   is re-verified against its realm's trust root first — reporting the
//!   contents of a layer varve cannot vouch for would look authoritative and
//!   be worthless.

use anyhow::Context;
use varve_core::Store;

/// The documentation-specific half of a row.
struct DocsRow {
    format: String,
    entry: Option<String>,
    title: Option<String>,
    /// The payload this documents, by name.
    documents: Option<String>,
}

/// One payload, as reported.
struct Row {
    name: String,
    version: Option<String>,
    /// The kind as written in the SIGNED annotation, so an unknown kind is
    /// reported verbatim rather than dropped or guessed (`sbom` labels such an
    /// entry rather than losing it; so does this).
    kind: String,
    known_kind: bool,
    /// The entry's signed platform, or `any` where it carries none — an
    /// unstamped platform means any-platform, as it does everywhere else.
    platform: String,
    digest: String,
    /// `dispatched` | `held` | `unknown` (the kind annotation is one this
    /// varve does not recognise, so whether it dispatches is not knowable).
    dispatch: &'static str,
    /// For a `docs` payload: what it IS, where a reader starts, and the label
    /// a human chooses by — all from SIGNED annotations
    /// (REQ-LAYERDOCS-001). `None` for every other kind.
    docs: Option<DocsRow>,
    /// Which mechanism vouched for this payload's UPSTREAM bytes
    /// (REQ-INGEST-001 clause 5). `unrecorded` where the layer predates the
    /// requirement — absence of a claim is not a claim, and restating a
    /// hundred existing payloads as either verified or unverified would be
    /// inventing one. An unknown mechanism is reported verbatim, like `kind`.
    ingest_proof: String,
    /// The identity credited with vouching, where one is recorded — the fact
    /// a consumer might filter on ("refuse anything not signed under
    /// pulseengine/"), which is why it is its own field and not prose.
    proof_signer: Option<String>,
    /// Are these bytes on disk here? `install` lays down only the host
    /// platform's entries, so another platform's entry is present in the
    /// signed manifest and absent from the store — which is correct, and worth
    /// saying rather than leaving as a mystery.
    present: bool,
    layer: String,
    realm: String,
}

const DISPATCHED: &str = "dispatched";
const HELD: &str = "held";
const UNKNOWN: &str = "unknown";

pub fn run(store: &Store, layer: Option<&str>, json: bool) -> anyhow::Result<()> {
    let target = crate::export_target(store, layer)?;
    let layers = crate::composition_for_export(&target)?;
    let host = varve_core::host_platform();
    let mut rows = Vec::new();

    for l in &layers {
        let payload = std::fs::read(l.entry.root.join("layer.json")).with_context(|| {
            format!(
                "cannot read the signed manifest of layer {} — the store entry is incomplete",
                l.entry.layer
            )
        })?;
        let manifest = varve_core::LayerManifest::parse(&payload)?;
        for e in &manifest.entries {
            let parsed = e.kind();
            let kind = match &parsed {
                Ok(k) => k.as_str().to_string(),
                Err(varve_core::UnknownKind(raw)) => raw.clone(),
            };
            // A `layer` entry is a composition EDGE, not a payload: its digest
            // is another layer's signed manifest, and there is nothing to lay
            // down. It is reported in the `composition` block instead, where
            // its realm and digest belong.
            if parsed == Ok(varve_core::PayloadKind::Layer) {
                continue;
            }
            let name = e
                .annotations
                .get("eu.pulseengine.tool")
                .cloned()
                // An entry with no name annotation is malformed rather than
                // secret; say so instead of hiding the row.
                .unwrap_or_else(|| "(unnamed entry)".to_string());
            rows.push(Row {
                version: e.annotations.get("eu.pulseengine.tool.version").cloned(),
                kind,
                known_kind: parsed.is_ok(),
                platform: e
                    .annotations
                    .get(varve_core::platform::ANN_PLATFORM)
                    .cloned()
                    .unwrap_or_else(|| "any".to_string()),
                digest: e.digest.clone(),
                dispatch: match parsed {
                    Ok(k) if k.is_dispatchable() => DISPATCHED,
                    Ok(_) => HELD,
                    Err(_) => UNKNOWN,
                },
                ingest_proof: match e.ingest_proof() {
                    Ok(p) => varve_core::IngestProof::label(p).to_string(),
                    Err(varve_core::UnknownProof(raw)) => raw,
                },
                proof_signer: e.annotations.get(varve_core::ANN_PROOF_SIGNER).cloned(),
                docs: e
                    .annotations
                    .get(varve_core::deposit::ANN_DOCS_FORMAT)
                    .map(|format| DocsRow {
                        format: format.clone(),
                        entry: e
                            .annotations
                            .get(varve_core::deposit::ANN_DOCS_ENTRY)
                            .cloned(),
                        title: e
                            .annotations
                            .get(varve_core::deposit::ANN_DOCS_TITLE)
                            .cloned(),
                        documents: e
                            .annotations
                            .get(varve_core::deposit::ANN_DOCS_DOCUMENTS)
                            .cloned(),
                    }),
                present: store_of(l).entry_path(&l.entry, e).is_some(),
                layer: l.entry.layer.to_string(),
                realm: l.realm.clone(),
                name,
            });
        }
    }
    // Stable order, so two runs — and two machines — agree.
    rows.sort_by(|a, b| {
        (&a.layer, &a.kind, &a.name, &a.version, &a.platform).cmp(&(
            &b.layer,
            &b.kind,
            &b.name,
            &b.version,
            &b.platform,
        ))
    });

    if json {
        print_json(&target, &layers, &rows, &host);
    } else {
        print_text(&target, &layers, &rows, &host);
    }
    Ok(())
}

/// The store partition a composed layer lives in — a cross-realm include lives
/// under the INCLUDED realm's fingerprint, not the including project's.
fn store_of(l: &crate::ComposedLayer) -> &Store {
    &l.store
}

/// The machine-readable report.
///
/// The shape is a compatibility promise, so it is stated here rather than left
/// to whatever `serde` happened to derive:
///
/// ```text
/// {
///   "command": "inspect",
///   "layer", "channel", "realm", "manifest_digest",   the layer the pin
///                                             resolved to, and the realm that
///                                             vouched for it (a layer id is
///                                             unique only within a realm)
///   "host_platform",                          what `present` was decided against
///   "composition": [ {"layer","manifest_digest","realm","root"} ],
///   "payloads":    [ {"name","version","kind","known_kind","platform",
///                     "dispatch","ingest_proof","proof_signer","digest",
///                     "present","layer","realm"} ],
///   "summary": {"payloads","dispatched","held","layers",
///               "unverified","unrecorded"}
/// }
/// ```
///
/// `version` is null where the entry carries none. `platform` is the string
/// `"any"` where the entry is unstamped, never null — an unstamped platform is
/// a positive fact (it runs anywhere), not a missing one. `dispatch` is one of
/// `dispatched` | `held` | `unknown`. `composition` always has at least one
/// element, the root, flagged `"root": true`.
fn print_json(
    target: &crate::ExportTarget,
    layers: &[crate::ComposedLayer],
    rows: &[Row],
    host: &str,
) {
    let composition: Vec<_> = layers
        .iter()
        .map(|l| {
            serde_json::json!({
                "layer": l.entry.layer.to_string(),
                "manifest_digest": l.entry.digest,
                "realm": l.realm,
                "root": l.entry.digest == target.entry.digest,
            })
        })
        .collect();
    let payloads: Vec<_> = rows
        .iter()
        .map(|r| {
            serde_json::json!({
                "name": r.name,
                "version": r.version,
                "kind": r.kind,
                "known_kind": r.known_kind,
                "platform": r.platform,
                "dispatch": r.dispatch,
                "ingest_proof": r.ingest_proof,
                "proof_signer": r.proof_signer,
                "digest": r.digest,
                "present": r.present,
                "layer": r.layer,
                "realm": r.realm,
                // The text form prints a documentation block; a machine
                // reading --format json must be able to see the same facts, or
                // the two outputs disagree about what the layer contains.
                "docs_format": r.docs.as_ref().map(|d| &d.format),
                "docs_entry": r.docs.as_ref().and_then(|d| d.entry.as_ref()),
                "docs_title": r.docs.as_ref().and_then(|d| d.title.as_ref()),
                "docs_documents": r.docs.as_ref().and_then(|d| d.documents.as_ref()),
            })
        })
        .collect();
    let doc = serde_json::json!({
        "command": "inspect",
        "layer": target.entry.layer.to_string(),
        "channel": target.entry.channel,
        // A layer id is YYYY.MM.P and is only unique WITHIN a realm; a
        // consumer diffing two inspect reports needs to know which realm each
        // came from. It was in `composition[]` and absent from the top level.
        "realm": layers
            .iter()
            .find(|l| l.entry.digest == target.entry.digest)
            .map(|l| l.realm.clone()),
        "manifest_digest": target.entry.digest,
        "host_platform": host,
        "composition": composition,
        "payloads": payloads,
        "summary": {
            "payloads": rows.len(),
            "dispatched": rows.iter().filter(|r| r.dispatch == DISPATCHED).count(),
            "held": rows.iter().filter(|r| r.dispatch == HELD).count(),
            "layers": layers.len(),
            // Surfaced in the SUMMARY, not only per payload, so a CI gate can
            // assert "nothing in this layer went unverified" without walking
            // the list. `unrecorded` is counted separately from `unverified`:
            // a layer minted before REQ-INGEST-001 made no claim either way,
            // and collapsing the two would invent one.
            "unverified": rows.iter().filter(|r| r.ingest_proof == "unverified").count(),
            "unrecorded": rows.iter().filter(|r| r.ingest_proof == "unrecorded").count(),
        },
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&doc).expect("the inspect report serialises")
    );
}

fn print_text(
    target: &crate::ExportTarget,
    layers: &[crate::ComposedLayer],
    rows: &[Row],
    host: &str,
) {
    // The realm belongs on this line, not only in the composition block below.
    // Layer ids are YYYY.MM.P, so two realms can publish the same one --
    // "layer 2026.08.26" alone does not say WHICH 2026.08.26, and the realm is
    // what the trust root, the store partition and the pin all hang on.
    // Reported from a real session: a user read this output beside a
    // `realm = "linc"` pin and the word realm appeared nowhere in it.
    let realm = layers
        .iter()
        .find(|l| l.entry.digest == target.entry.digest)
        .map(|l| l.realm.as_str());
    match realm {
        Some(r) => println!(
            "layer {} ({}) realm '{}' {}",
            target.entry.layer, target.entry.channel, r, target.entry.digest
        ),
        None => println!(
            "layer {} ({}) {}",
            target.entry.layer, target.entry.channel, target.entry.digest
        ),
    }
    if layers.len() > 1 {
        println!("composition: {} layers —", layers.len());
        for l in layers {
            println!(
                "  {} {} (verified against realm '{}'){}",
                l.entry.layer,
                l.entry.digest,
                l.realm,
                if l.entry.digest == target.entry.digest {
                    "  [pinned]"
                } else {
                    ""
                }
            );
        }
    }
    if rows.is_empty() {
        println!("\nno payloads — this layer carries no entries beyond its composition");
        return;
    }
    let dispatched = rows.iter().filter(|r| r.dispatch == DISPATCHED).count();
    let held = rows.len() - dispatched;
    println!(
        "\n{} payload(s): {dispatched} DISPATCHED, {held} HELD  (platform {host})\n",
        rows.len()
    );
    // Column widths from the data: a fixed width truncates the one crate name
    // somebody needed to read.
    let w = |f: fn(&Row) -> &str, head: &str| {
        rows.iter()
            .map(|r| f(r).chars().count())
            .chain(std::iter::once(head.chars().count()))
            .max()
            .unwrap_or(1)
    };
    let (wn, wk, wp) = (w(|r| &r.name, "NAME"), w(|r| &r.kind, "KIND"), {
        rows.iter()
            .map(|r| r.platform.chars().count())
            .chain(std::iter::once(8))
            .max()
            .unwrap_or(8)
    });
    let wv = rows
        .iter()
        .map(|r| r.version.as_deref().unwrap_or("-").chars().count())
        .chain(std::iter::once(7))
        .max()
        .unwrap_or(7);
    println!(
        "  {:<12}{:<wk$}  {:<wn$}  {:<wv$}  {:<wp$}  LAYER",
        "", "KIND", "NAME", "VERSION", "PLATFORM"
    );
    for r in rows {
        println!(
            "  {:<12}{:<wk$}  {:<wn$}  {:<wv$}  {:<wp$}  {}{}",
            r.dispatch.to_uppercase(),
            r.kind,
            r.name,
            r.version.as_deref().unwrap_or("-"),
            r.platform,
            r.layer,
            if r.present {
                ""
            } else {
                "  (not laid down here)"
            },
        );
    }
    if held > 0 {
        println!(
            "\nHELD payloads are stored and verified but NOT on your PATH — `varve which` will \
             not find them, by design. Only a `tool` is dispatched by name. See \
             `varve docs inspect`."
        );
    }
    // Documentation, after the table rather than before it: the table is what
    // `inspect` is run for, and the natural next line once someone has seen
    // what a layer holds is where to start reading it (REQ-LAYERDOCS-001).
    //
    // Reported from the SIGNED annotations, so this says what the producer
    // declared rather than what the file name suggests.
    let docs: Vec<(&Row, &DocsRow)> = rows
        .iter()
        .filter_map(|r| r.docs.as_ref().map(|d| (r, d)))
        .collect();
    if !docs.is_empty() {
        println!("\ndocumentation for the versions this layer pins:");
        for (row, d) in &docs {
            let label = d.title.as_deref().unwrap_or(&row.name);
            println!(
                "  {label} {} ({})",
                row.version.as_deref().unwrap_or("-"),
                d.format
            );
            if let Some(entry) = &d.entry {
                println!("    starts at {entry}");
            }
            // Printed as the command that answers it, because "which document
            // is the API of varve-core" is the question this field exists for.
            if let Some(of) = &d.documents {
                println!("    documents {of}    (varve export-docs --for {of})");
            }
        }
        // One document needs no selector; several do. Printing the exact next
        // command beats describing it, and the reader has already said which
        // layer they want by pinning it.
        match docs.as_slice() {
            [(row, _)] => {
                println!("\n  read it, copying nothing:  varve-serve");
                println!(
                    "  or write a copy:           varve export-docs --out ./doc   ({})",
                    row.name
                );
            }
            many => {
                println!(
                    "\n  {} documents, so name one:  varve-serve --select <NAME>",
                    many.len()
                );
                println!(
                    "  or:                        varve export-docs --out ./doc --select <NAME>"
                );
            }
        }
    }
    if rows.iter().any(|r| !r.known_kind) {
        println!(
            "\nAn entry above carries a payload kind this varve does not know. Its bytes still \
             verify against the signed digest — only the adapters that must DO something \
             kind-specific will refuse it. A newer varve may handle it."
        );
    }
}

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

    fn row(name: &str, docs: Option<DocsRow>) -> Row {
        Row {
            name: name.into(),
            version: Some("1.0.0".into()),
            kind: if docs.is_some() {
                "docs".into()
            } else {
                "tool".into()
            },
            known_kind: true,
            platform: "any".into(),
            digest: "sha256:0".into(),
            dispatch: if docs.is_some() { HELD } else { DISPATCHED },
            docs,
            ingest_proof: "cosign-sums".into(),
            proof_signer: None,
            present: true,
            layer: "2026.09.9".into(),
            realm: "t".into(),
        }
    }

    /// `inspect` has two output paths and they must agree about what the layer
    /// contains. The text form grew a documentation block; a gate parsing
    /// `--format json` would otherwise be blind to it, and "the two renderings
    /// of one fact disagree" is the shape that cost three releases this month.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn both_renderings_report_the_same_documents() {
        let rows = [
            row("rivet", None),
            row(
                "handbook",
                Some(DocsRow {
                    format: "pdf".into(),
                    entry: None,
                    title: Some("The handbook".into()),
                    documents: None,
                }),
            ),
        ];

        // What the text form would say it has:
        let in_text: Vec<&str> = rows
            .iter()
            .filter(|r| r.docs.is_some())
            .map(|r| r.name.as_str())
            .collect();
        // What the JSON form would say it has: a payload is a document exactly
        // when it carries a format.
        let in_json: Vec<&str> = rows
            .iter()
            .filter(|r| r.docs.as_ref().map(|d| !d.format.is_empty()) == Some(true))
            .map(|r| r.name.as_str())
            .collect();

        assert_eq!(in_text, in_json, "the two renderings disagree");
        assert_eq!(in_text, vec!["handbook"]);
    }

    /// A document is HELD, never dispatched: it is read, not executed.
    // rivet: verifies REQ-LAYERDOCS-001
    #[test]
    fn a_document_is_never_reported_as_dispatched() {
        let d = row(
            "handbook",
            Some(DocsRow {
                format: "html".into(),
                entry: Some("index.html".into()),
                title: None,
                documents: None,
            }),
        );
        assert_eq!(d.dispatch, HELD);
        assert!(!varve_core::PayloadKind::Docs.is_dispatchable());
    }
}