shipper-core 0.4.0

Core library behind the `shipper` CLI: engine, planning, state, registry, and remediation primitives for `cargo publish` workspaces.
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
//! End-of-run consistency check between `events.jsonl` and `state.json`.
//!
//! **Layer:** state (layer 3).
//!
//! Per [docs/INVARIANTS.md](https://github.com/EffortlessMetrics/shipper/blob/main/docs/INVARIANTS.md),
//! `events.jsonl` is the authoritative truth and `state.json` is a projection.
//! They must agree on which packages were published. This module surfaces
//! any drift loudly at the end of a run so an operator (or auditor) doesn't
//! silently trust a stale or corrupted projection.
//!
//! See [issue #93](https://github.com/EffortlessMetrics/shipper/issues/93).

use std::collections::BTreeSet;
use std::path::Path;

use anyhow::{Context, Result, bail};

use shipper_types::{
    EventType, ExecutionState, PackageState, Receipt, ReconciliationReport, StateEventDrift,
};

use super::events::EventLog;
use super::rebuild::{StateRebuildOptions, rebuild_state_from_events};

/// Verify that `events.jsonl` and the in-memory `ExecutionState` agree on which
/// packages are Published.
///
/// Reads the event log from disk and compares the set of packages with a
/// `PackagePublished` event against the set of packages whose current state
/// is `PackageState::Published`. Returns a [`StateEventDrift`] describing any
/// mismatch; use [`StateEventDrift::is_consistent`] to branch.
///
/// Only an I/O failure reading the event log surfaces as `Err`; a disagreement
/// is a legitimate result of the check and returned as `Ok(drift)`.
pub fn verify_events_state_consistency(
    events_path: &Path,
    state: &ExecutionState,
) -> Result<StateEventDrift> {
    let log = EventLog::read_from_file(events_path).with_context(|| {
        format!(
            "failed to read event log for consistency check: {}",
            events_path.display()
        )
    })?;

    // Package labels that have a `PackagePublished` event in events.jsonl, or a
    // trusted resume skip event documenting a previously published package.
    // Labels are the `package` field of the event (format: `name@version`).
    let events_published: BTreeSet<String> = log
        .all_events()
        .iter()
        .filter(|e| match &e.event_type {
            EventType::PackagePublished { .. } => true,
            EventType::PackageSkipped { reason } => reason == "resume: state already published",
            _ => false,
        })
        .map(|e| e.package.clone())
        .collect();

    // Package labels that are currently marked `Published` in state.json.
    // The `packages` map is keyed by `name@version`.
    let state_published: BTreeSet<String> = state
        .packages
        .iter()
        .filter(|(_, pr)| matches!(pr.state, PackageState::Published))
        .map(|(k, _)| k.clone())
        .collect();

    let in_events_only: Vec<String> = events_published
        .difference(&state_published)
        .cloned()
        .collect();
    let in_state_only: Vec<String> = state_published
        .difference(&events_published)
        .cloned()
        .collect();

    Ok(StateEventDrift {
        in_events_only,
        in_state_only,
    })
}

/// Render a human-readable summary of a drift report. Used by the Reporter
/// to surface the finding loudly at end of run.
pub fn format_drift_summary(drift: &StateEventDrift) -> String {
    if drift.is_consistent() {
        return "events.jsonl and state.json are consistent".to_string();
    }

    let mut lines = Vec::new();
    lines.push("state/event drift detected (events.jsonl is authoritative):".to_string());
    if !drift.in_events_only.is_empty() {
        lines.push(format!(
            "  published in events.jsonl but NOT in state.json ({}): {}",
            drift.in_events_only.len(),
            drift.in_events_only.join(", ")
        ));
    }
    if !drift.in_state_only.is_empty() {
        lines.push(format!(
            "  marked published in state.json but NO event ({}): {}",
            drift.in_state_only.len(),
            drift.in_state_only.join(", ")
        ));
    }
    lines.join("\n")
}

/// Verify the end-of-run evidence packet before `receipt.json` becomes the
/// durable summary.
///
/// This check is stricter than [`verify_events_state_consistency`]: it compares
/// the current state projection, the receipt that is about to be written, the
/// event-derived state projection, and reconciliation evidence when
/// reconciliation events exist. Drift is returned as an error so finalization
/// cannot produce a misleading receipt.
pub fn verify_finalization_consistency(
    events_path: &Path,
    state: &ExecutionState,
    receipt: &Receipt,
    reconciliation_report: Option<&ReconciliationReport>,
) -> Result<()> {
    let event_log = EventLog::read_from_file(events_path).with_context(|| {
        format!(
            "failed to read event log for finalization consistency check: {}",
            events_path.display()
        )
    })?;
    let rebuilt_state = rebuild_state_from_events(
        events_path,
        StateRebuildOptions::new(receipt.registry.clone()).with_fallback_plan_id(&receipt.plan_id),
    )
    .with_context(|| {
        format!(
            "failed to rebuild state projection from events for finalization check: {}",
            events_path.display()
        )
    })?;

    let mut findings = Vec::new();
    let trusted_resume_terminal_skips = trusted_resume_terminal_skips(&event_log);
    verify_plan_ids(receipt, &rebuilt_state, &mut findings);
    verify_state_matches_events(
        state,
        &rebuilt_state,
        &trusted_resume_terminal_skips,
        &mut findings,
    );
    verify_receipt_matches_state(state, receipt, &mut findings);
    verify_reconciliation_evidence(&event_log, receipt, reconciliation_report, &mut findings);

    if findings.is_empty() {
        return Ok(());
    }

    bail!(
        "release evidence drift detected; refusing to write receipt.json\n{}",
        findings
            .into_iter()
            .map(|finding| format!("  - {finding}"))
            .collect::<Vec<_>>()
            .join("\n")
    )
}

fn verify_plan_ids(receipt: &Receipt, rebuilt_state: &ExecutionState, findings: &mut Vec<String>) {
    if rebuilt_state.plan_id != receipt.plan_id {
        findings.push(format!(
            "events plan_id {} does not match receipt plan_id {}",
            rebuilt_state.plan_id, receipt.plan_id
        ));
    }
}

fn verify_state_matches_events(
    state: &ExecutionState,
    rebuilt_state: &ExecutionState,
    trusted_resume_terminal_skips: &BTreeSet<String>,
    findings: &mut Vec<String>,
) {
    for (key, progress) in &state.packages {
        match rebuilt_state.packages.get(key) {
            Some(event_progress) if event_progress.state == progress.state => {}
            Some(event_progress)
                if matches!(
                    (&progress.state, &event_progress.state),
                    (PackageState::Published, PackageState::Skipped { .. })
                ) && trusted_resume_terminal_skips.contains(key) => {}
            Some(event_progress)
                if matches!(
                    (&progress.state, &event_progress.state),
                    (PackageState::Skipped { .. }, PackageState::Skipped { .. })
                ) && trusted_resume_terminal_skips.contains(key) => {}
            Some(event_progress) => findings.push(format!(
                "{key} state drift: state.json says {}; events project {}",
                state_name(&progress.state),
                state_name(&event_progress.state)
            )),
            None if matches!(progress.state, PackageState::Pending) => {}
            None => findings.push(format!(
                "{key} state drift: state.json says {} but events contain no package projection",
                state_name(&progress.state)
            )),
        }
    }

    for (key, progress) in &rebuilt_state.packages {
        if !state.packages.contains_key(key) {
            findings.push(format!(
                "{key} state drift: events project {} but state.json has no package entry",
                state_name(&progress.state)
            ));
        }
    }
}

fn trusted_resume_terminal_skips(event_log: &EventLog) -> BTreeSet<String> {
    event_log
        .all_events()
        .iter()
        .filter_map(|event| match &event.event_type {
            EventType::PackageSkipped { reason }
                if reason.starts_with("resume: state already ") =>
            {
                Some(event.package.clone())
            }
            _ => None,
        })
        .collect()
}

fn verify_receipt_matches_state(
    state: &ExecutionState,
    receipt: &Receipt,
    findings: &mut Vec<String>,
) {
    for package in &receipt.packages {
        let key = format!("{}@{}", package.name, package.version);
        match state.packages.get(&key) {
            Some(progress) if progress.state == package.state => {}
            Some(progress) => findings.push(format!(
                "{key} receipt drift: receipt says {}; state.json says {}",
                state_name(&package.state),
                state_name(&progress.state)
            )),
            None => findings.push(format!(
                "{key} receipt drift: receipt has package but state.json has no package entry"
            )),
        }
    }
}

fn verify_reconciliation_evidence(
    event_log: &EventLog,
    receipt: &Receipt,
    reconciliation_report: Option<&ReconciliationReport>,
    findings: &mut Vec<String>,
) {
    let reconciled_packages: BTreeSet<String> = event_log
        .all_events()
        .iter()
        .filter(|event| matches!(event.event_type, EventType::PublishReconciled { .. }))
        .map(|event| event.package.clone())
        .collect();

    if reconciled_packages.is_empty() {
        if reconciliation_report.is_some() {
            findings.push(
                "reconciliation.json is present but events contain no reconciliation outcomes"
                    .to_string(),
            );
        }
        return;
    }

    let Some(report) = reconciliation_report else {
        findings.push(format!(
            "events contain reconciliation outcomes for {} but reconciliation.json was not produced",
            reconciled_packages.into_iter().collect::<Vec<_>>().join(", ")
        ));
        return;
    };

    if report.plan_id != receipt.plan_id {
        findings.push(format!(
            "reconciliation plan_id {} does not match receipt plan_id {}",
            report.plan_id, receipt.plan_id
        ));
    }

    let report_packages: BTreeSet<String> = report
        .records
        .iter()
        .map(|record| record.package.clone())
        .collect();

    for package in reconciled_packages.difference(&report_packages) {
        findings.push(format!(
            "{package} reconciliation drift: event outcome is missing from reconciliation.json"
        ));
    }
    for package in report_packages.difference(&reconciled_packages) {
        findings.push(format!(
            "{package} reconciliation drift: reconciliation.json has no matching event outcome"
        ));
    }
}

fn state_name(state: &PackageState) -> &'static str {
    match state {
        PackageState::Pending => "pending",
        PackageState::Uploaded => "uploaded",
        PackageState::Published => "published",
        PackageState::Skipped { .. } => "skipped",
        PackageState::Failed { .. } => "failed",
        PackageState::Ambiguous { .. } => "ambiguous",
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use chrono::Utc;
    use shipper_types::{
        EnvironmentFingerprint, PackageEvidence, PackageProgress, PackageReceipt, PublishEvent,
        ReconciliationEvidenceKind, ReconciliationEvidenceSource, ReconciliationOperatorAction,
        ReconciliationRecord, ReconciliationReport, ReconciliationTrigger, Registry,
    };
    use tempfile::tempdir;

    use super::*;
    use crate::state::events::{EVENTS_FILE, EventLog};

    fn pkg_progress(name: &str, version: &str, state: PackageState) -> (String, PackageProgress) {
        let key = format!("{name}@{version}");
        (
            key,
            PackageProgress {
                name: name.to_string(),
                version: version.to_string(),
                attempts: 1,
                state,
                last_updated_at: Utc::now(),
            },
        )
    }

    fn make_state(packages: Vec<(String, PackageProgress)>) -> ExecutionState {
        ExecutionState {
            state_version: "test".to_string(),
            plan_id: "test-plan".to_string(),
            registry: Registry {
                name: "crates-io".to_string(),
                api_base: "https://crates.io".to_string(),
                index_base: None,
            },
            attempt_history: Vec::new(),
            packages: packages.into_iter().collect::<BTreeMap<_, _>>(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    fn write_events(dir: &Path, events: Vec<PublishEvent>) {
        let mut log = EventLog::new();
        for e in events {
            log.record(e);
        }
        log.write_to_file(&dir.join(EVENTS_FILE))
            .expect("write events");
    }

    fn published_event(name: &str, version: &str) -> PublishEvent {
        PublishEvent {
            timestamp: Utc::now(),
            event_type: EventType::PackagePublished { duration_ms: 10 },
            package: format!("{name}@{version}"),
        }
    }

    fn plan_created_event() -> PublishEvent {
        PublishEvent {
            timestamp: Utc::now(),
            event_type: EventType::PlanCreated {
                plan_id: "test-plan".to_string(),
                package_count: 1,
            },
            package: "all".to_string(),
        }
    }

    fn receipt(packages: Vec<PackageReceipt>) -> Receipt {
        Receipt {
            receipt_version: "shipper.receipt.v2".to_string(),
            plan_id: "test-plan".to_string(),
            registry: Registry::crates_io(),
            started_at: Utc::now(),
            finished_at: Utc::now(),
            packages,
            event_log_path: Path::new(".shipper/events.jsonl").to_path_buf(),
            git_context: None,
            environment: EnvironmentFingerprint {
                shipper_version: "test".to_string(),
                cargo_version: None,
                rust_version: None,
                os: "test".to_string(),
                arch: "test".to_string(),
            },
            auth_evidence: None,
        }
    }

    fn package_receipt(name: &str, version: &str, state: PackageState) -> PackageReceipt {
        PackageReceipt {
            name: name.to_string(),
            version: version.to_string(),
            attempts: 1,
            state,
            started_at: Utc::now(),
            finished_at: Utc::now(),
            duration_ms: 10,
            evidence: PackageEvidence {
                attempts: vec![],
                readiness_checks: vec![],
            },
            compromised_at: None,
            compromised_by: None,
            superseded_by: None,
        }
    }

    fn reconciliation_report(package: &str) -> ReconciliationReport {
        let (name, version) = package.rsplit_once('@').expect("package label");
        ReconciliationReport {
            schema_version: "shipper.reconciliation.v1".to_string(),
            plan_id: "test-plan".to_string(),
            registry: Registry::crates_io(),
            generated_at: Utc::now(),
            evidence_sources: vec![ReconciliationEvidenceSource {
                kind: ReconciliationEvidenceKind::EventLog,
                path: ".shipper/events.jsonl".to_string(),
            }],
            records: vec![ReconciliationRecord {
                package: package.to_string(),
                name: name.to_string(),
                version: version.to_string(),
                trigger: ReconciliationTrigger::CargoAmbiguousExit,
                method: None,
                cargo_exit_class: Some(shipper_types::ErrorClass::Ambiguous),
                outcome: shipper_types::ReconciliationOutcome::Published {
                    attempts: 1,
                    elapsed_ms: 10,
                },
                operator_action: ReconciliationOperatorAction::MarkPublishedContinue,
            }],
        }
    }

    #[test]
    fn consistent_when_state_and_events_agree() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![published_event("a", "1.0.0"), published_event("b", "2.0.0")],
        );

        let state = make_state(vec![
            pkg_progress("a", "1.0.0", PackageState::Published),
            pkg_progress("b", "2.0.0", PackageState::Published),
        ]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(drift.is_consistent(), "expected no drift; got {:?}", drift);
    }

    #[test]
    fn consistent_when_resume_skip_documents_published_state() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![PublishEvent {
                timestamp: Utc::now(),
                event_type: EventType::PackageSkipped {
                    reason: "resume: state already published".to_string(),
                },
                package: "a@1.0.0".to_string(),
            }],
        );

        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(drift.is_consistent(), "expected no drift; got {:?}", drift);
    }

    #[test]
    fn detects_in_events_only() {
        // events says published, state says pending → resume would duplicate
        let td = tempdir().expect("tempdir");
        write_events(td.path(), vec![published_event("a", "1.0.0")]);

        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Pending)]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(!drift.is_consistent());
        assert_eq!(drift.in_events_only, vec!["a@1.0.0".to_string()]);
        assert!(drift.in_state_only.is_empty());
    }

    #[test]
    fn detects_in_state_only() {
        // state says published but no event recorded it → event log bypassed
        let td = tempdir().expect("tempdir");
        write_events(td.path(), vec![]);

        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(!drift.is_consistent());
        assert_eq!(drift.in_state_only, vec!["a@1.0.0".to_string()]);
        assert!(drift.in_events_only.is_empty());
    }

    #[test]
    fn drift_finalization_rejects_state_published_without_event_projection() {
        let td = tempdir().expect("tempdir");
        write_events(td.path(), vec![plan_created_event()]);
        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);
        let receipt = receipt(vec![package_receipt("a", "1.0.0", PackageState::Published)]);

        let err =
            verify_finalization_consistency(&td.path().join(EVENTS_FILE), &state, &receipt, None)
                .expect_err("state/event drift should fail finalization");

        assert!(
            err.to_string().contains("release evidence drift detected"),
            "{err:#}"
        );
        assert!(
            err.to_string()
                .contains("state.json says published but events contain no package projection"),
            "{err:#}"
        );
    }

    #[test]
    fn drift_finalization_accepts_reconciled_published_projection() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![
                plan_created_event(),
                PublishEvent {
                    timestamp: Utc::now(),
                    event_type: EventType::PublishReconciled {
                        outcome: shipper_types::ReconciliationOutcome::Published {
                            attempts: 1,
                            elapsed_ms: 10,
                        },
                    },
                    package: "a@1.0.0".to_string(),
                },
            ],
        );
        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);
        let receipt = receipt(vec![package_receipt("a", "1.0.0", PackageState::Published)]);
        let report = reconciliation_report("a@1.0.0");

        verify_finalization_consistency(
            &td.path().join(EVENTS_FILE),
            &state,
            &receipt,
            Some(&report),
        )
        .expect("reconciled published event should project to published state");
    }

    #[test]
    fn drift_finalization_accepts_trusted_resume_published_skip_projection() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![
                plan_created_event(),
                PublishEvent {
                    timestamp: Utc::now(),
                    event_type: EventType::PackageSkipped {
                        reason: "resume: state already published".to_string(),
                    },
                    package: "a@1.0.0".to_string(),
                },
            ],
        );
        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);
        let receipt = receipt(vec![]);

        verify_finalization_consistency(&td.path().join(EVENTS_FILE), &state, &receipt, None)
            .expect("trusted resume skip should not force receipt drift");
    }

    #[test]
    fn drift_finalization_requires_reconciliation_report_for_reconciled_events() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![
                plan_created_event(),
                PublishEvent {
                    timestamp: Utc::now(),
                    event_type: EventType::PublishReconciled {
                        outcome: shipper_types::ReconciliationOutcome::Published {
                            attempts: 1,
                            elapsed_ms: 10,
                        },
                    },
                    package: "a@1.0.0".to_string(),
                },
            ],
        );
        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);
        let receipt = receipt(vec![package_receipt("a", "1.0.0", PackageState::Published)]);

        let err =
            verify_finalization_consistency(&td.path().join(EVENTS_FILE), &state, &receipt, None)
                .expect_err("missing reconciliation report should fail finalization");

        assert!(
            err.to_string()
                .contains("reconciliation.json was not produced"),
            "{err:#}"
        );
    }

    #[test]
    fn drift_finalization_rejects_receipt_state_mismatch() {
        let td = tempdir().expect("tempdir");
        write_events(
            td.path(),
            vec![plan_created_event(), published_event("a", "1.0.0")],
        );
        let state = make_state(vec![pkg_progress("a", "1.0.0", PackageState::Published)]);
        let receipt = receipt(vec![package_receipt(
            "a",
            "1.0.0",
            PackageState::Skipped {
                reason: "manual mismatch".to_string(),
            },
        )]);

        let err =
            verify_finalization_consistency(&td.path().join(EVENTS_FILE), &state, &receipt, None)
                .expect_err("receipt/state drift should fail finalization");

        assert!(
            err.to_string()
                .contains("receipt drift: receipt says skipped; state.json says published"),
            "{err:#}"
        );
    }

    #[test]
    fn empty_state_and_empty_events_are_consistent() {
        let td = tempdir().expect("tempdir");
        // No events file written at all — read_from_file treats missing as empty.
        let state = make_state(vec![]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(drift.is_consistent());
    }

    #[test]
    fn ignores_non_published_packages() {
        // Packages in Failed/Skipped/Pending state shouldn't be checked.
        let td = tempdir().expect("tempdir");
        write_events(td.path(), vec![published_event("a", "1.0.0")]);

        let state = make_state(vec![
            pkg_progress("a", "1.0.0", PackageState::Published),
            pkg_progress(
                "b",
                "2.0.0",
                PackageState::Failed {
                    class: shipper_types::ErrorClass::Permanent,
                    message: "nope".to_string(),
                },
            ),
            pkg_progress(
                "c",
                "3.0.0",
                PackageState::Skipped {
                    reason: "already published".to_string(),
                },
            ),
            pkg_progress("d", "4.0.0", PackageState::Pending),
        ]);

        let drift = verify_events_state_consistency(&td.path().join(EVENTS_FILE), &state)
            .expect("check runs");
        assert!(
            drift.is_consistent(),
            "non-published states should not count"
        );
    }

    #[test]
    fn format_summary_consistent() {
        let drift = StateEventDrift::default();
        let s = format_drift_summary(&drift);
        assert!(s.contains("consistent"));
    }

    #[test]
    fn format_summary_mentions_both_sides() {
        let drift = StateEventDrift {
            in_events_only: vec!["a@1.0.0".to_string()],
            in_state_only: vec!["b@2.0.0".to_string()],
        };
        let s = format_drift_summary(&drift);
        assert!(s.contains("drift detected"));
        assert!(s.contains("a@1.0.0"));
        assert!(s.contains("b@2.0.0"));
    }

    // --- additional format_drift_summary edge cases ---

    #[test]
    fn format_summary_in_events_only_omits_state_section() {
        // When only events_only has entries, only that line should appear.
        let drift = StateEventDrift {
            in_events_only: vec!["a@1.0.0".to_string(), "b@2.0.0".to_string()],
            in_state_only: vec![],
        };
        let s = format_drift_summary(&drift);
        assert!(s.contains("drift detected"));
        assert!(s.contains("published in events.jsonl but NOT in state.json (2)"));
        assert!(s.contains("a@1.0.0, b@2.0.0"));
        // The state-only section MUST be suppressed when empty.
        assert!(
            !s.contains("marked published in state.json"),
            "state-only section must be omitted; got: {s}"
        );
    }

    #[test]
    fn format_summary_in_state_only_omits_events_section() {
        let drift = StateEventDrift {
            in_events_only: vec![],
            in_state_only: vec!["c@3.0.0".to_string()],
        };
        let s = format_drift_summary(&drift);
        assert!(s.contains("drift detected"));
        assert!(s.contains("marked published in state.json but NO event (1)"));
        assert!(s.contains("c@3.0.0"));
        // The events-only section MUST be suppressed when empty.
        assert!(
            !s.contains("published in events.jsonl but NOT in state.json"),
            "events-only section must be omitted; got: {s}"
        );
    }

    #[test]
    fn format_summary_lists_counts_and_joined_names() {
        // Three names on each side; count and join formatting should match.
        let drift = StateEventDrift {
            in_events_only: vec!["a@1".to_string(), "b@2".to_string(), "c@3".to_string()],
            in_state_only: vec!["x@1".to_string(), "y@2".to_string()],
        };
        let s = format_drift_summary(&drift);
        // Counts.
        assert!(s.contains("events.jsonl but NOT in state.json (3)"));
        assert!(s.contains("marked published in state.json but NO event (2)"));
        // Comma-space joining.
        assert!(s.contains("a@1, b@2, c@3"));
        assert!(s.contains("x@1, y@2"));
        // Authoritative-source breadcrumb is always present in the header.
        assert!(s.contains("events.jsonl is authoritative"));
    }

    #[test]
    fn format_summary_consistent_is_single_line() {
        // The "all good" branch should stay compact: no header, no bullets.
        let s = format_drift_summary(&StateEventDrift::default());
        assert!(s.contains("consistent"));
        assert!(s.contains("events.jsonl"));
        assert!(s.contains("state.json"));
        assert!(!s.contains('\n'));
    }
}