verirun-core 0.2.0

Deterministic core for verirun covering RFC 8785 canonical JSON, domain-separated SHA-256 digest framing, DAG validation, and Merkle manifests with std only.
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
//! Manifests, task records, and the Merkle construction
//! (docs/ARCHITECTURE.md sections 3.3 and 9).
//!
//! A manifest is the commitment a run leaves behind: one record per
//! task in the spec, sorted by task id, plus the Merkle root over
//! the task record digests. It is stored as a blob whose bytes are
//! the canonical encoding (section 4) of the value form defined in
//! section 9.1, so the manifest digest is the blob digest of those
//! bytes and a manifest carries no timestamps, host paths, user
//! names, or tool versions.
//!
//! The Merkle construction pairs adjacent digests level by level
//! under the `verirun/v1/node` tag. An odd element at any level is
//! promoted unchanged to the next level, never duplicated. A single
//! leaf is its own root, and zero tasks give the `verirun/v1/empty`
//! digest. This module builds manifests, renders and parses their
//! value form, and recomputes roots from record fields alone, which
//! is the core of the verification algorithm (section 9.3).

use crate::canonical;
use crate::digest::{self, Digest, HasherFactory, TaskStatus};
use crate::error::{CanonicalError, ManifestError};
use crate::value::Value;

/// The value of the manifest `format` field.
///
/// The format tag is the version marker: a future format change
/// mints a new tag and a new domain tag set, and version 1
/// manifests stay verifiable under version 1 rules.
pub const MANIFEST_FORMAT: &str = "verirun-manifest/1";

/// One produced file in a task record.
///
/// The record holds the file's sandbox relative path, the blob
/// digest of its content, its byte length, and whether any
/// execute bit was set on it at collection time. No timestamps,
/// owners, or host paths ever appear (INV-SBX-4).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtifactRecord {
    /// The normalized sandbox relative path.
    pub path: String,
    /// The blob digest of the file content.
    pub digest: Digest,
    /// The byte length of the content.
    pub bytes: u64,
    /// Whether any execute bit was set when the file was collected.
    pub executable: bool,
}

impl ArtifactRecord {
    /// The `verirun/v1/artifact` framing digest of this record.
    #[must_use]
    pub fn framing_digest(&self, factory: &dyn HasherFactory) -> Digest {
        digest::artifact_digest(
            factory,
            &self.path,
            &self.digest,
            self.bytes,
            self.executable,
        )
    }

    /// The value form of section 9.1: an object with `path`,
    /// `sha256`, `bytes`, and `executable` fields.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    #[allow(
        clippy::cast_precision_loss,
        reason = "byte lengths are inside the safe integer domain by physical necessity (section 9.1), and the canonical encoder rejects any value outside it at encode time"
    )]
    pub fn to_value(&self) -> Value {
        Value::Object(vec![
            ("path".to_string(), Value::String(self.path.clone())),
            ("sha256".to_string(), Value::String(self.digest.to_hex())),
            ("bytes".to_string(), Value::Number(self.bytes as f64)),
            ("executable".to_string(), Value::Bool(self.executable)),
        ])
    }

    /// Parses the value form back into a record.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError`] when a field is missing, mistyped,
    /// or holds a digest that is not valid lowercase hex.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
        let pairs = as_object(value, "artifact")?;
        Ok(Self {
            path: as_string(get(pairs, "path")?, "path")?.to_string(),
            digest: as_digest(get(pairs, "sha256")?, "sha256")?,
            bytes: as_bytes(get(pairs, "bytes")?, "bytes")?,
            executable: as_bool(get(pairs, "executable")?, "executable")?,
        })
    }
}

/// One task's outcome in a manifest (section 3.3).
///
/// `artifacts` is sorted by path; construction through
/// [`TaskRecord::new`] enforces the sort. A record with status
/// [`TaskStatus::Skipped`] has an absent exit code, the empty blob
/// digest for both streams, and no artifacts, by construction of
/// the scheduler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskRecord {
    /// The task identifier.
    pub task_id: String,
    /// The execution digest of the task's spec (section 5.3).
    pub exec_digest: Digest,
    /// The terminal status of the task.
    pub status: TaskStatus,
    /// The child exit code, when the child exited with one. Absent
    /// for skipped tasks, timed out tasks, and death by signal.
    pub exit_code: Option<i32>,
    /// The blob digest of the captured stdout stream.
    pub stdout_digest: Digest,
    /// The blob digest of the captured stderr stream.
    pub stderr_digest: Digest,
    /// The collected artifacts, sorted by path.
    pub artifacts: Vec<ArtifactRecord>,
}

impl TaskRecord {
    /// Builds a record, sorting `artifacts` by path so the
    /// framing order of section 5.2 holds by construction.
    ///
    /// # Panics
    ///
    /// Panics if two artifacts share a path. No run can produce
    /// that, because collection holds one entry per declared
    /// output, so a duplicate here is a programming error rather
    /// than data, the same assignment [`Manifest::digest`] makes
    /// for its domain. The parse path reports the same shape as
    /// [`ManifestError::DuplicateArtifactPath`] instead, because
    /// there it is data.
    #[must_use]
    pub fn new(
        task_id: String,
        exec_digest: Digest,
        status: TaskStatus,
        exit_code: Option<i32>,
        stdout_digest: Digest,
        stderr_digest: Digest,
        artifacts: Vec<ArtifactRecord>,
    ) -> Self {
        let mut artifacts = artifacts;
        artifacts.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
        for window in artifacts.windows(2) {
            assert!(
                window[0].path != window[1].path,
                "duplicate artifact path {:?} in a built record",
                window[0].path
            );
        }
        Self {
            task_id,
            exec_digest,
            status,
            exit_code,
            stdout_digest,
            stderr_digest,
            artifacts,
        }
    }

    /// The `verirun/v1/task` framing digest of this record, over
    /// the artifact framing digests in path order.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    pub fn record_digest(&self, factory: &dyn HasherFactory) -> Digest {
        let framing: Vec<Digest> = self
            .artifacts
            .iter()
            .map(|artifact| artifact.framing_digest(factory))
            .collect();
        digest::task_digest(
            factory,
            &self.task_id,
            &self.exec_digest,
            self.status,
            self.exit_code,
            &self.stdout_digest,
            &self.stderr_digest,
            &framing,
        )
    }

    /// Every blob digest this record names, deduplicated by
    /// digest: the stdout and stderr digests and every artifact
    /// content digest. Verification re-hashes each distinct digest
    /// exactly once (INV-LAT-3).
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    pub fn named_digests(&self) -> Vec<Digest> {
        let mut out: Vec<Digest> = Vec::new();
        for digest in std::iter::once(&self.stdout_digest)
            .chain(std::iter::once(&self.stderr_digest))
            .chain(self.artifacts.iter().map(|artifact| &artifact.digest))
        {
            if !out.contains(digest) {
                out.push(*digest);
            }
        }
        out
    }

    /// The value form of section 9.1.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    pub fn to_value(&self) -> Value {
        let exit_code = self
            .exit_code
            .map_or(Value::Null, |code| Value::Number(f64::from(code)));
        Value::Object(vec![
            ("task_id".to_string(), Value::String(self.task_id.clone())),
            (
                "exec_digest".to_string(),
                Value::String(self.exec_digest.to_hex()),
            ),
            (
                "status".to_string(),
                Value::String(self.status.as_str().to_string()),
            ),
            ("exit_code".to_string(), exit_code),
            (
                "stdout_sha256".to_string(),
                Value::String(self.stdout_digest.to_hex()),
            ),
            (
                "stderr_sha256".to_string(),
                Value::String(self.stderr_digest.to_hex()),
            ),
            (
                "artifacts".to_string(),
                Value::Array(
                    self.artifacts
                        .iter()
                        .map(ArtifactRecord::to_value)
                        .collect(),
                ),
            ),
        ])
    }

    /// Parses the value form back into a record.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError`] when a field is missing, mistyped,
    /// holds an invalid digest, names an unknown status, or names
    /// one artifact path twice.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
        let pairs = as_object(value, "task")?;
        let mut artifacts = match get(pairs, "artifacts")? {
            Value::Array(items) => {
                let mut out = Vec::with_capacity(items.len());
                for item in items {
                    out.push(ArtifactRecord::from_value(item)?);
                }
                out
            }
            _ => {
                return Err(ManifestError::WrongType {
                    field: "artifacts",
                    expected: "an array",
                });
            }
        };
        // No run can produce two artifacts at one path, because
        // collection holds one entry per declared output, so a
        // duplicate is rejected rather than carried into the
        // framing. The check runs on the sorted order
        // construction will hold, and it runs here, before
        // construction, because on this path a duplicate is
        // data to report, not a programming error to panic on.
        artifacts.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
        let task_id = as_string(get(pairs, "task_id")?, "task_id")?.to_string();
        if let Some(window) = artifacts
            .windows(2)
            .find(|window| window[0].path == window[1].path)
        {
            return Err(ManifestError::DuplicateArtifactPath {
                task_id,
                path: window[0].path.clone(),
            });
        }
        Ok(Self::new(
            task_id,
            as_digest(get(pairs, "exec_digest")?, "exec_digest")?,
            as_status(get(pairs, "status")?)?,
            as_exit_code(get(pairs, "exit_code")?)?,
            as_digest(get(pairs, "stdout_sha256")?, "stdout_sha256")?,
            as_digest(get(pairs, "stderr_sha256")?, "stderr_sha256")?,
            artifacts,
        ))
    }
}

/// A whole run's commitment: the task records, sorted by task id,
/// and the Merkle root over their record digests (section 9.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
    /// The task records, sorted by task id.
    pub tasks: Vec<TaskRecord>,
    /// The Merkle root stored in the manifest value form.
    /// Verification recomputes it from the record fields alone and
    /// compares (section 9.3).
    pub merkle_root: Digest,
}

impl Manifest {
    /// Builds a manifest from records in any order: the records
    /// are sorted by task id and the Merkle root is computed over
    /// their record digests in that order.
    ///
    /// # Panics
    ///
    /// Panics if two records share a task id. The only producer
    /// is the scheduler over a validated run, whose task ids are
    /// unique by validation, so a duplicate here is a programming
    /// error rather than data, the same assignment
    /// [`Manifest::digest`] makes for its domain. The parse path
    /// reports the same shape as
    /// [`ManifestError::DuplicateTaskId`] instead, because there
    /// it is data.
    #[must_use]
    pub fn build(factory: &dyn HasherFactory, mut records: Vec<TaskRecord>) -> Self {
        records.sort_by(|left, right| left.task_id.as_bytes().cmp(right.task_id.as_bytes()));
        for window in records.windows(2) {
            assert!(
                window[0].task_id != window[1].task_id,
                "duplicate task id {:?} in a built manifest",
                window[0].task_id
            );
        }
        let leaves: Vec<Digest> = records
            .iter()
            .map(|record| record.record_digest(factory))
            .collect();
        let merkle_root = digest::merkle_root(factory, &leaves);
        Self {
            tasks: records,
            merkle_root,
        }
    }

    /// The Merkle root recomputed from the record fields alone,
    /// ignoring the stored root. Equal to `merkle_root` in any
    /// manifest this build produced.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    pub fn recompute_root(&self, factory: &dyn HasherFactory) -> Digest {
        let leaves: Vec<Digest> = self
            .tasks
            .iter()
            .map(|record| record.record_digest(factory))
            .collect();
        digest::merkle_root(factory, &leaves)
    }

    /// The value form of section 9.1: an object with `format`,
    /// `merkle_root`, and `tasks` fields, and exactly those fields.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    #[must_use]
    pub fn to_value(&self) -> Value {
        Value::Object(vec![
            (
                "format".to_string(),
                Value::String(MANIFEST_FORMAT.to_string()),
            ),
            (
                "merkle_root".to_string(),
                Value::String(self.merkle_root.to_hex()),
            ),
            (
                "tasks".to_string(),
                Value::Array(self.tasks.iter().map(TaskRecord::to_value).collect()),
            ),
        ])
    }

    /// Parses the value form back into a manifest. The stored
    /// Merkle root is carried as read; comparing it against
    /// [`Manifest::recompute_root`] is the verifier's job.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError`] when the format tag differs from
    /// [`MANIFEST_FORMAT`], a field is missing or mistyped, a
    /// record fails to parse, or two records share a task id.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
        let pairs = as_object(value, "manifest")?;
        let format = as_string(get(pairs, "format")?, "format")?;
        if format != MANIFEST_FORMAT {
            return Err(ManifestError::WrongFormat {
                found: format.to_string(),
            });
        }
        let merkle_root = as_digest(get(pairs, "merkle_root")?, "merkle_root")?;
        let mut tasks = match get(pairs, "tasks")? {
            Value::Array(items) => {
                let mut out = Vec::with_capacity(items.len());
                for item in items {
                    out.push(TaskRecord::from_value(item)?);
                }
                out
            }
            _ => {
                return Err(ManifestError::WrongType {
                    field: "tasks",
                    expected: "an array",
                });
            }
        };
        // Records are stored sorted by task id, as in a built
        // manifest. Sorting here means a stored order that differs
        // re-encodes to different bytes, which verification
        // reports as a non-canonical manifest (section 9.3).
        tasks.sort_by(|left, right| left.task_id.as_bytes().cmp(right.task_id.as_bytes()));
        // No run can produce two records for one task id, and a
        // consumer keyed by task id would silently drop one of
        // them, so a duplicate is rejected rather than carried.
        // Sorted order puts duplicates side by side.
        for window in tasks.windows(2) {
            if window[0].task_id == window[1].task_id {
                return Err(ManifestError::DuplicateTaskId {
                    task_id: window[0].task_id.clone(),
                });
            }
        }
        Ok(Self { tasks, merkle_root })
    }

    /// The canonical bytes of the manifest: the bytes that are
    /// stored as its blob.
    ///
    /// # Errors
    ///
    /// Returns [`CanonicalError`] if a record field falls outside
    /// the canonical number domain, which construction prevents.
    ///
    /// # Panics
    ///
    /// Never panics in the core implementation.
    pub fn canonical_bytes(&self) -> Result<Vec<u8>, CanonicalError> {
        let mut out = Vec::new();
        canonical::encode(&self.to_value(), &mut out)?;
        Ok(out)
    }

    /// The manifest digest: the blob digest of the canonical
    /// bytes. This is the digest `verirun verify` takes.
    ///
    /// # Panics
    ///
    /// Panics if a record field falls outside the canonical
    /// number domain, which construction and parsing both
    /// prevent: the failure is a programming error, not data.
    #[must_use]
    pub fn digest(&self, factory: &dyn HasherFactory) -> Digest {
        let bytes = self
            .canonical_bytes()
            .expect("manifest fields are in the canonical domain by construction");
        digest::hash_bytes(factory, digest::DomainTag::Blob, &bytes)
    }
}

const fn as_object<'a>(
    value: &'a Value,
    field: &'static str,
) -> Result<&'a Vec<(String, Value)>, ManifestError> {
    match value {
        Value::Object(pairs) => Ok(pairs),
        _ => Err(ManifestError::WrongType {
            field,
            expected: "an object",
        }),
    }
}

fn get<'a>(pairs: &'a [(String, Value)], field: &'static str) -> Result<&'a Value, ManifestError> {
    pairs
        .iter()
        .find(|(key, _)| key == field)
        .map(|(_, value)| value)
        .ok_or(ManifestError::MissingField { field })
}

fn as_string<'a>(value: &'a Value, field: &'static str) -> Result<&'a str, ManifestError> {
    match value {
        Value::String(text) => Ok(text),
        _ => Err(ManifestError::WrongType {
            field,
            expected: "a string",
        }),
    }
}

fn as_digest(value: &Value, field: &'static str) -> Result<Digest, ManifestError> {
    let text = as_string(value, field)?;
    Digest::from_hex(text).map_err(|source| ManifestError::InvalidDigest { field, source })
}

const fn as_bool(value: &Value, field: &'static str) -> Result<bool, ManifestError> {
    match value {
        Value::Bool(flag) => Ok(*flag),
        _ => Err(ManifestError::WrongType {
            field,
            expected: "a boolean",
        }),
    }
}

#[allow(
    clippy::float_cmp,
    reason = "the domain checks are exactness tests on parsed values: a field is valid only when the number is exactly integral"
)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "the value is range-checked against 0..=9007199254740991 and exact integrality immediately before the conversion, so the conversion is exact"
)]
fn as_bytes(value: &Value, field: &'static str) -> Result<u64, ManifestError> {
    match value {
        Value::Number(number) => {
            if *number < 0.0 || *number > canonical::MAX_SAFE_INTEGER || number.fract() != 0.0 {
                return Err(ManifestError::InvalidNumber {
                    field,
                    detail: format!(
                        "byte length must be an integer between 0 and 9007199254740991, found {number}"
                    ),
                });
            }
            Ok(*number as u64)
        }
        _ => Err(ManifestError::WrongType {
            field,
            expected: "a number",
        }),
    }
}

#[allow(
    clippy::float_cmp,
    reason = "the domain checks are exactness tests on parsed values: a field is valid only when the number is exactly integral"
)]
fn as_exit_code(value: &Value) -> Result<Option<i32>, ManifestError> {
    match value {
        Value::Null => Ok(None),
        Value::Number(number) => {
            if *number < f64::from(i32::MIN)
                || *number > f64::from(i32::MAX)
                || number.fract() != 0.0
            {
                return Err(ManifestError::InvalidNumber {
                    field: "exit_code",
                    detail: format!(
                        "exit code must be an integer in the i32 range, found {number}"
                    ),
                });
            }
            #[allow(
                clippy::cast_possible_truncation,
                reason = "the value was range-checked against the i32 bounds immediately above"
            )]
            Ok(Some(*number as i32))
        }
        _ => Err(ManifestError::WrongType {
            field: "exit_code",
            expected: "an integer or null",
        }),
    }
}

fn as_status(value: &Value) -> Result<TaskStatus, ManifestError> {
    let text = as_string(value, "status")?;
    match text {
        "succeeded" => Ok(TaskStatus::Succeeded),
        "failed" => Ok(TaskStatus::Failed),
        "timed_out" => Ok(TaskStatus::TimedOut),
        "cached" => Ok(TaskStatus::Cached),
        "skipped" => Ok(TaskStatus::Skipped),
        _ => Err(ManifestError::UnknownStatus {
            found: text.to_string(),
        }),
    }
}

/// Which compared fields of one task record differ between two
/// manifests (section 9.4).
///
/// The compared fields are exactly the ones section 9.4 names:
/// the status, the exit code, the artifact list, and the two
/// log digests. A record whose execution digest differs while
/// every compared field matches is equivalent under the diff
/// semantics: the execution digest is a cause, and the diff
/// reports effects.
#[allow(
    clippy::struct_excessive_bools,
    reason = "the five compared fields of section 9.4 are independent by design; the struct is the field-by-field report"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangedFields {
    /// The terminal status differs.
    pub status: bool,
    /// The exit code differs.
    pub exit_code: bool,
    /// The artifact list differs in path, digest, length, or
    /// executable flag.
    pub artifacts: bool,
    /// The stdout blob digest differs.
    pub stdout: bool,
    /// The stderr blob digest differs.
    pub stderr: bool,
}

impl ChangedFields {
    /// Whether any compared field differs.
    #[must_use]
    pub const fn any(&self) -> bool {
        self.status || self.exit_code || self.artifacts || self.stdout || self.stderr
    }
}

/// How one task differs between two manifests (section 9.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskDifference {
    /// The task appears only in the first manifest.
    OnlyInFirst,
    /// The task appears only in the second manifest.
    OnlyInSecond,
    /// The task appears in both, with differing compared fields.
    Changed(ChangedFields),
}

/// One task's difference between two manifests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskDiff {
    /// The task the difference belongs to.
    pub task_id: String,
    /// The difference.
    pub difference: TaskDifference,
}

/// Compares two manifests record by record, by task id
/// (section 9.4; INV-CLI-4).
///
/// The result is in task id order and holds one entry per task
/// that is present on one side only or whose compared fields
/// differ. An empty result means the runs are equivalent in
/// every compared field. Both manifests are assumed verified
/// by the caller; comparison itself is pure.
#[allow(
    clippy::missing_const_for_fn,
    reason = "the implementation walks both manifests' records; it cannot be const"
)]
#[must_use]
pub fn diff_manifests(first: &Manifest, second: &Manifest) -> Vec<TaskDiff> {
    let first_by_id: std::collections::BTreeMap<&str, &TaskRecord> = first
        .tasks
        .iter()
        .map(|record| (record.task_id.as_str(), record))
        .collect();
    let second_by_id: std::collections::BTreeMap<&str, &TaskRecord> = second
        .tasks
        .iter()
        .map(|record| (record.task_id.as_str(), record))
        .collect();
    let ids: std::collections::BTreeSet<&str> = first_by_id
        .keys()
        .chain(second_by_id.keys())
        .copied()
        .collect();
    let mut differences = Vec::new();
    for task_id in ids {
        match (first_by_id.get(task_id), second_by_id.get(task_id)) {
            (Some(_), None) => differences.push(TaskDiff {
                task_id: task_id.to_string(),
                difference: TaskDifference::OnlyInFirst,
            }),
            (None, Some(_)) => differences.push(TaskDiff {
                task_id: task_id.to_string(),
                difference: TaskDifference::OnlyInSecond,
            }),
            (Some(left), Some(right)) => {
                let fields = ChangedFields {
                    status: left.status != right.status,
                    exit_code: left.exit_code != right.exit_code,
                    artifacts: left.artifacts != right.artifacts,
                    stdout: left.stdout_digest != right.stdout_digest,
                    stderr: left.stderr_digest != right.stderr_digest,
                };
                if fields.any() {
                    differences.push(TaskDiff {
                        task_id: task_id.to_string(),
                        difference: TaskDifference::Changed(fields),
                    });
                }
            }
            (None, None) => {}
        }
    }
    differences
}