wasm4pm-compat 26.6.5

Minimal paper-complete, feature-capped Rust process-evidence crate. Start with compatibility. Graduate to execution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Conformance **verdict** shape — **structure only, does NOT compute conformance**.
//!
//! This module represents the *shape* of a conformance result: bounded fitness,
//! precision, and F1 scores, a list of deviations, and the alignment move
//! markers that classify each step. It is a **verdict carrier**, not a checker.
//!
//! ## What this module **IS**
//!
//! - Bounded `[0, 1]` newtypes [`crate::conformance::Fitness`], [`crate::conformance::Precision`], [`crate::conformance::F1`] that *carry* a
//!   score but never *derive* one.
//! - The [`crate::conformance::Deviation`] shape and the alignment move markers [`crate::conformance::SyncMove`],
//!   [`crate::conformance::LogOnlyMove`], [`crate::conformance::ModelOnlyMove`].
//! - The aggregate [`crate::conformance::ConformanceVerdict`] shape.
//! - A first-class [`crate::conformance::ConformanceRefusal`] surface naming exactly why a verdict
//!   cannot be admitted.
//!
//! ## What this module is **NOT**
//!
//! - **Not** a token-replay engine, an alignment computer, or a precision
//!   estimator. The newtypes *hold* values produced elsewhere (e.g. by
//!   `wasm4pm`); they never compute fitness from a log and a model.
//!
//! ## Graduation
//!
//! When you need to **compute** fitness / precision / alignments, graduate to
//! the `wasm4pm` engine (via the `wasm4pm` feature). This module only certifies
//! that a verdict is *well-shaped and in-bounds*.

use core::marker::PhantomData;

use crate::law::{IsTrue, QualityMetricKind, Require};

// ── Compile-time bounded metric ──────────────────────────────────────────────

/// A quality metric with its value expressed as a rational `NUM / DEN` in
/// `[0, 1]` at the **type level**.
///
/// `Metric<KIND, 2, 1>` does **not compile**: `2 / 1 > 1` violates
/// `Between01`. This turns out-of-range scores into a compile error instead
/// of a runtime panic.
///
/// Structure-only — it carries the claim, never computes it.
///
/// ```
/// # #![feature(generic_const_exprs, adt_const_params)]
/// # #![allow(incomplete_features)]
/// use wasm4pm_compat::conformance::{
///     Metric, FitnessConst, PrecisionConst, F1Const,
///     GeneralizationConst, SimplicityConst,
/// };
/// use wasm4pm_compat::law::QualityMetricKind;
/// let _: FitnessConst<3, 4> = Metric::new();         // 0.75 fitness
/// let _: PrecisionConst<1, 2> = Metric::new();       // 0.5 precision
/// let _: F1Const<0, 1> = Metric::new();              // 0.0 F1
/// let _: GeneralizationConst<7, 8> = Metric::new();  // 0.875 generalization
/// let _: SimplicityConst<1, 1> = Metric::new();      // 1.0 simplicity
/// ```
///
/// ```compile_fail
/// use wasm4pm_compat::conformance::FitnessConst;
/// let _: FitnessConst<2, 1> = FitnessConst::new(); // 2/1 > 1: compile error
/// ```
pub struct Metric<const KIND: QualityMetricKind, const NUM: u64, const DEN: u64>
where
    // DEVELOPER NOTE — if this bound fails you will see:
    //   "the trait bound `Require<false>: IsTrue` is not satisfied"
    // This means: DEN == 0 — the denominator of a quality metric must be ≥ 1.
    // Fix: choose DEN ≥ 1. Example: FitnessConst<3,4> means 0.75 fitness.
    Require<{ DEN > 0 }>: IsTrue,
    // DEVELOPER NOTE — if this bound fails you will see:
    //   "the trait bound `Require<false>: IsTrue` is not satisfied"
    // This means: NUM > DEN — the metric value NUM/DEN exceeds 1.0. Quality
    // metrics (fitness, precision, F1, generalization, simplicity) are defined
    // on [0, 1]. Fix: ensure NUM ≤ DEN (e.g. FitnessConst<3,4> not <4,3>).
    Require<{ NUM <= DEN }>: IsTrue,
{
    _private: (),
}

impl<const KIND: QualityMetricKind, const NUM: u64, const DEN: u64> Default
    for Metric<KIND, NUM, DEN>
where
    Require<{ DEN > 0 }>: IsTrue,
    Require<{ NUM <= DEN }>: IsTrue,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const KIND: QualityMetricKind, const NUM: u64, const DEN: u64> Metric<KIND, NUM, DEN>
where
    Require<{ DEN > 0 }>: IsTrue,
    Require<{ NUM <= DEN }>: IsTrue,
{
    /// Constructs a `Metric` — only possible when `NUM / DEN ∈ [0, 1]`.
    ///
    /// ```
    /// # #![feature(generic_const_exprs, adt_const_params)]
    /// # #![allow(incomplete_features)]
    /// use wasm4pm_compat::conformance::FitnessConst;
    /// let _: FitnessConst<3, 4> = FitnessConst::new();
    /// ```
    pub const fn new() -> Self {
        Metric { _private: () }
    }

    /// The numerator of the metric value.
    ///
    /// ```
    /// use wasm4pm_compat::conformance::FitnessConst;
    /// assert_eq!(FitnessConst::<3, 4>::new().num(), 3);
    /// ```
    pub const fn num(&self) -> u64 {
        NUM
    }

    /// The denominator of the metric value.
    ///
    /// ```
    /// use wasm4pm_compat::conformance::FitnessConst;
    /// assert_eq!(FitnessConst::<3, 4>::new().den(), 4);
    /// ```
    pub const fn den(&self) -> u64 {
        DEN
    }
}

/// Compile-time bounded fitness score: `NUM / DEN ∈ [0, 1]`.
pub type FitnessConst<const NUM: u64, const DEN: u64> =
    Metric<{ QualityMetricKind::Fitness }, NUM, DEN>;

/// Compile-time bounded precision score: `NUM / DEN ∈ [0, 1]`.
pub type PrecisionConst<const NUM: u64, const DEN: u64> =
    Metric<{ QualityMetricKind::Precision }, NUM, DEN>;

/// Compile-time bounded F1 score: `NUM / DEN ∈ [0, 1]`.
pub type F1Const<const NUM: u64, const DEN: u64> = Metric<{ QualityMetricKind::F1 }, NUM, DEN>;

/// Compile-time bounded generalization score: `NUM / DEN ∈ [0, 1]`.
///
/// Generalization measures how well a discovered model covers traces that were
/// *not* in the discovery log — a high score means the model does not overfit
/// to the training log. Defined by van der Aalst (2016) as one of the four
/// canonical quality dimensions alongside fitness, precision, and simplicity.
///
/// `GeneralizationConst<2, 1>` does **not compile** — `2/1 > 1` violates the
/// `Between01` bound.
///
/// ```
/// # #![feature(generic_const_exprs, adt_const_params)]
/// # #![allow(incomplete_features)]
/// use wasm4pm_compat::conformance::GeneralizationConst;
/// let _: GeneralizationConst<7, 8> = GeneralizationConst::new(); // 0.875
/// let _: GeneralizationConst<0, 1> = GeneralizationConst::new(); // 0.0
/// let _: GeneralizationConst<1, 1> = GeneralizationConst::new(); // 1.0
/// ```
///
/// ```compile_fail
/// use wasm4pm_compat::conformance::GeneralizationConst;
/// let _: GeneralizationConst<2, 1> = GeneralizationConst::new(); // 2/1 > 1
/// ```
pub type GeneralizationConst<const NUM: u64, const DEN: u64> =
    Metric<{ QualityMetricKind::Generalization }, NUM, DEN>;

/// Compile-time bounded simplicity score: `NUM / DEN ∈ [0, 1]`.
///
/// Simplicity measures the structural parsimony of a process model — simpler
/// models (fewer nodes, arcs, and duplicate activities) score higher. Defined
/// by van der Aalst (2016) as one of the four canonical quality dimensions.
///
/// `SimplicityConst<2, 1>` does **not compile** — `2/1 > 1` violates the
/// `Between01` bound.
///
/// ```
/// # #![feature(generic_const_exprs, adt_const_params)]
/// # #![allow(incomplete_features)]
/// use wasm4pm_compat::conformance::SimplicityConst;
/// let _: SimplicityConst<1, 2> = SimplicityConst::new(); // 0.5
/// let _: SimplicityConst<0, 1> = SimplicityConst::new(); // 0.0
/// let _: SimplicityConst<1, 1> = SimplicityConst::new(); // 1.0
/// ```
///
/// ```compile_fail
/// use wasm4pm_compat::conformance::SimplicityConst;
/// let _: SimplicityConst<3, 2> = SimplicityConst::new(); // 3/2 > 1
/// ```
pub type SimplicityConst<const NUM: u64, const DEN: u64> =
    Metric<{ QualityMetricKind::Simplicity }, NUM, DEN>;

// ── All-five quality profile ─────────────────────────────────────────────────

/// A compile-time quality profile grouping all five van der Aalst metric types.
///
/// Carries **fitness**, **precision**, **F1**, **generalization**, and
/// **simplicity** as const-generic rational values `NUM/DEN ∈ [0, 1]`.
/// Every individual metric slot enforces the `Between01` law: a profile with
/// any out-of-range component does **not compile**.
///
/// This is **structure only**: it describes a quality claim, never computes one.
/// Graduate to `wasm4pm` to derive these values from a log and a model.
///
/// ## Parameters
///
/// | Pair | Metric |
/// |------|--------|
/// | `FN` / `FD` | Fitness numerator / denominator |
/// | `PN` / `PD` | Precision numerator / denominator |
/// | `EN` / `ED` | F1 numerator / denominator |
/// | `GN` / `GD` | Generalization numerator / denominator |
/// | `SN` / `SD` | Simplicity numerator / denominator |
///
/// ```
/// # #![feature(generic_const_exprs, adt_const_params)]
/// # #![allow(incomplete_features)]
/// use wasm4pm_compat::conformance::QualityProfile;
/// // fitness=0.9, precision=0.8, f1=0.85, generalization=0.75, simplicity=0.95
/// let _: QualityProfile<9,10, 4,5, 17,20, 3,4, 19,20> = QualityProfile::new();
/// ```
///
/// ```compile_fail
/// # #![feature(generic_const_exprs, adt_const_params)]
/// # #![allow(incomplete_features)]
/// use wasm4pm_compat::conformance::QualityProfile;
/// // fitness=2/1 > 1: compile error
/// let _: QualityProfile<2,1, 1,1, 1,1, 1,1, 1,1> = QualityProfile::new();
/// ```
#[allow(clippy::type_complexity)]
pub struct QualityProfile<
    const FN: u64,
    const FD: u64,
    const PN: u64,
    const PD: u64,
    const EN: u64,
    const ED: u64,
    const GN: u64,
    const GD: u64,
    const SN: u64,
    const SD: u64,
> where
    // DEVELOPER NOTE — if any bound below fails you will see:
    //   "the trait bound `Require<false>: IsTrue` is not satisfied"
    // Each pair (FN/FD, PN/PD, EN/ED, GN/GD, SN/SD) must represent a rational
    // in [0,1]: denominator > 0 and numerator ≤ denominator.
    // The first failing pair names which metric slot is out-of-range:
    //   FD/FN = fitness, PD/PN = precision, ED/EN = F1,
    //   GD/GN = generalization, SD/SN = simplicity.
    Require<{ FD > 0 }>: IsTrue,
    Require<{ FN <= FD }>: IsTrue,
    Require<{ PD > 0 }>: IsTrue,
    Require<{ PN <= PD }>: IsTrue,
    Require<{ ED > 0 }>: IsTrue,
    Require<{ EN <= ED }>: IsTrue,
    Require<{ GD > 0 }>: IsTrue,
    Require<{ GN <= GD }>: IsTrue,
    Require<{ SD > 0 }>: IsTrue,
    Require<{ SN <= SD }>: IsTrue,
{
    /// The fitness component.
    pub fitness: FitnessConst<FN, FD>,
    /// The precision component.
    pub precision: PrecisionConst<PN, PD>,
    /// The F1 component.
    pub f1: F1Const<EN, ED>,
    /// The generalization component.
    pub generalization: GeneralizationConst<GN, GD>,
    /// The simplicity component.
    pub simplicity: SimplicityConst<SN, SD>,
}

impl<
        const FN: u64,
        const FD: u64,
        const PN: u64,
        const PD: u64,
        const EN: u64,
        const ED: u64,
        const GN: u64,
        const GD: u64,
        const SN: u64,
        const SD: u64,
    > QualityProfile<FN, FD, PN, PD, EN, ED, GN, GD, SN, SD>
where
    Require<{ FD > 0 }>: IsTrue,
    Require<{ FN <= FD }>: IsTrue,
    Require<{ PD > 0 }>: IsTrue,
    Require<{ PN <= PD }>: IsTrue,
    Require<{ ED > 0 }>: IsTrue,
    Require<{ EN <= ED }>: IsTrue,
    Require<{ GD > 0 }>: IsTrue,
    Require<{ GN <= GD }>: IsTrue,
    Require<{ SD > 0 }>: IsTrue,
    Require<{ SN <= SD }>: IsTrue,
{
    /// Constructs a `QualityProfile` — only possible when all five `NUM/DEN`
    /// pairs are in `[0, 1]`.
    ///
    /// ```
    /// # #![feature(generic_const_exprs, adt_const_params)]
    /// # #![allow(incomplete_features)]
    /// use wasm4pm_compat::conformance::QualityProfile;
    /// let p: QualityProfile<1,1, 1,1, 1,1, 1,1, 1,1> = QualityProfile::new();
    /// assert_eq!(p.fitness.num(), 1);
    /// assert_eq!(p.simplicity.den(), 1);
    /// ```
    pub const fn new() -> Self {
        Self {
            fitness: Metric::new(),
            precision: Metric::new(),
            f1: Metric::new(),
            generalization: Metric::new(),
            simplicity: Metric::new(),
        }
    }
}

impl<
        const FN: u64,
        const FD: u64,
        const PN: u64,
        const PD: u64,
        const EN: u64,
        const ED: u64,
        const GN: u64,
        const GD: u64,
        const SN: u64,
        const SD: u64,
    > Default for QualityProfile<FN, FD, PN, PD, EN, ED, GN, GD, SN, SD>
where
    Require<{ FD > 0 }>: IsTrue,
    Require<{ FN <= FD }>: IsTrue,
    Require<{ PD > 0 }>: IsTrue,
    Require<{ PN <= PD }>: IsTrue,
    Require<{ ED > 0 }>: IsTrue,
    Require<{ EN <= ED }>: IsTrue,
    Require<{ GD > 0 }>: IsTrue,
    Require<{ GN <= GD }>: IsTrue,
    Require<{ SD > 0 }>: IsTrue,
    Require<{ SN <= SD }>: IsTrue,
{
    fn default() -> Self {
        Self::new()
    }
}

// ── Quality dimension enum ───────────────────────────────────────────────────

/// The four canonical quality dimensions for process model evaluation, plus the
/// F1 harmonic mean, as defined by van der Aalst (2016).
///
/// This is a **runtime** companion to [`crate::law::QualityMetricKind`] in `law.rs`.
/// `QualityMetricKind` is a `ConstParamTy` enum used as a const generic
/// parameter; `QualityDimension` is an ordinary enum for runtime dispatch,
/// pattern matching, and storing dimension metadata alongside a score.
///
/// ## What this is
///
/// - A closed enum naming each quality dimension.
/// - Usable in `match` to dispatch on dimension at runtime.
/// - Derivable, cloneable, and hashable — suitable for maps and error messages.
///
/// ## What this is not
///
/// - Not a metric value or score carrier — use [`crate::conformance::Fitness`], [`crate::conformance::Precision`], etc.
/// - Not a const-generic param — use [`crate::law::QualityMetricKind`] for that.
/// - Not an engine concern — no computation happens here.
///
/// ## Paper
///
/// van der Aalst (2016). *Process Mining: Data Science in Action*. §9.
/// The four orthogonal dimensions are fitness, precision, generalization, and
/// simplicity. F1 is the harmonic mean of fitness and precision.
///
/// ```
/// use wasm4pm_compat::conformance::QualityDimension;
/// let all = [
///     QualityDimension::Fitness,
///     QualityDimension::Precision,
///     QualityDimension::F1,
///     QualityDimension::Generalization,
///     QualityDimension::Simplicity,
/// ];
/// assert_eq!(all.len(), 5);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QualityDimension {
    /// Token-replay or alignment-based fitness: how much of the observed
    /// log behaviour the model can replay.
    Fitness,
    /// Precision: how much of the model's behaviour appears in the log
    /// (inverse of over-generalisation).
    Precision,
    /// F1: harmonic mean of fitness and precision — a balanced quality score.
    F1,
    /// Generalization: how well the model covers traces *not* in the
    /// discovery log (resistance to over-fitting).
    Generalization,
    /// Simplicity: structural parsimony of the process model — fewer
    /// redundant nodes and arcs score higher.
    Simplicity,
}

impl core::fmt::Display for QualityDimension {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let name = match self {
            QualityDimension::Fitness => "fitness",
            QualityDimension::Precision => "precision",
            QualityDimension::F1 => "f1",
            QualityDimension::Generalization => "generalization",
            QualityDimension::Simplicity => "simplicity",
        };
        write!(f, "{name}")
    }
}

// ── Alignment move markers ──────────────────────────────────────────────────

/// Witness: a **synchronous move** — log and model agree on a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct SyncMove;

/// Witness: a **log-only move** — the log had a step the model could not match
/// (an *insertion* relative to the model).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct LogOnlyMove;

/// Witness: a **model-only move** — the model required a step the log did not
/// show (a *skip* / missing activity).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ModelOnlyMove;

// ── Bounded score newtypes ──────────────────────────────────────────────────

/// A fitness score in the closed unit interval `[0, 1]`.
///
/// `#[repr(transparent)]` over `f64`. It **carries** a verdict; it does **NOT**
/// compute one. Construction is fallible: out-of-range values yield `None`.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Fitness(f64);

impl Fitness {
    /// Construct a fitness, returning `None` unless `0.0 <= value <= 1.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Fitness;
    /// assert!(Fitness::new(1.0).is_some());
    /// assert!(Fitness::new(1.5).is_none());
    /// assert!(Fitness::new(-0.1).is_none());
    /// ```
    #[must_use]
    pub fn new(value: f64) -> Option<Self> {
        if value.is_finite() && (0.0..=1.0).contains(&value) {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The carried score as a raw `f64` in `[0, 1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Fitness;
    /// assert_eq!(Fitness::new(0.85).unwrap().get(), 0.85);
    /// ```
    pub fn get(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for Fitness {
    /// Formats the fitness score as a human-readable percentage, e.g. `"85.00%"`.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.2}%", self.0 * 100.0)
    }
}

/// A precision score in the closed unit interval `[0, 1]`.
///
/// `#[repr(transparent)]` over `f64`. It **carries** a verdict; it does **NOT**
/// compute one.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Precision(f64);

impl Precision {
    /// Construct a precision, returning `None` unless `0.0 <= value <= 1.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Precision;
    /// assert!(Precision::new(0.0).is_some());
    /// assert!(Precision::new(2.0).is_none());
    /// ```
    #[must_use]
    pub fn new(value: f64) -> Option<Self> {
        if value.is_finite() && (0.0..=1.0).contains(&value) {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The carried score as a raw `f64` in `[0, 1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Precision;
    /// assert_eq!(Precision::new(0.7).unwrap().get(), 0.7);
    /// ```
    pub fn get(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for Precision {
    /// Formats the precision score as a human-readable percentage, e.g. `"70.00%"`.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.2}%", self.0 * 100.0)
    }
}

/// An F1 score in the closed unit interval `[0, 1]`.
///
/// `#[repr(transparent)]` over `f64`. It **carries** a verdict; it does **NOT**
/// compute one (it does not even derive itself from fitness and precision —
/// that derivation is an engine concern).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct F1(f64);

impl F1 {
    /// Construct an F1, returning `None` unless `0.0 <= value <= 1.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::F1;
    /// assert!(F1::new(0.5).is_some());
    /// assert!(F1::new(f64::NAN).is_none());
    /// ```
    #[must_use]
    pub fn new(value: f64) -> Option<Self> {
        if value.is_finite() && (0.0..=1.0).contains(&value) {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The carried score as a raw `f64` in `[0, 1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::F1;
    /// assert_eq!(F1::new(0.5).unwrap().get(), 0.5);
    /// ```
    pub fn get(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for F1 {
    /// Formats the F1 score as a human-readable percentage, e.g. `"50.00%"`.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.2}%", self.0 * 100.0)
    }
}

/// A generalization score in the closed unit interval `[0, 1]`.
///
/// `#[repr(transparent)]` over `f64`. It **carries** a verdict; it does **NOT**
/// compute one. Generalization measures how well a discovered model covers
/// traces *not* present in the discovery log (the opposite of overfitting).
/// Graduate to `wasm4pm` to compute this value.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Generalization(f64);

impl Generalization {
    /// Construct a generalization score, returning `None` unless
    /// `0.0 <= value <= 1.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Generalization;
    /// assert!(Generalization::new(0.9).is_some());
    /// assert!(Generalization::new(1.1).is_none());
    /// assert!(Generalization::new(f64::INFINITY).is_none());
    /// ```
    #[must_use]
    pub fn new(value: f64) -> Option<Self> {
        if value.is_finite() && (0.0..=1.0).contains(&value) {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The carried score as a raw `f64` in `[0, 1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Generalization;
    /// assert_eq!(Generalization::new(0.9).unwrap().get(), 0.9);
    /// ```
    pub fn get(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for Generalization {
    /// Formats the generalization score as a human-readable percentage, e.g. `"90.00%"`.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.2}%", self.0 * 100.0)
    }
}

/// A simplicity score in the closed unit interval `[0, 1]`.
///
/// `#[repr(transparent)]` over `f64`. It **carries** a verdict; it does **NOT**
/// compute one. Simplicity measures the structural parsimony of a process model;
/// models with fewer redundant nodes and arcs score higher. Graduate to `wasm4pm`
/// to compute this value.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Simplicity(f64);

impl Simplicity {
    /// Construct a simplicity score, returning `None` unless
    /// `0.0 <= value <= 1.0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Simplicity;
    /// assert!(Simplicity::new(0.0).is_some());
    /// assert!(Simplicity::new(1.0).is_some());
    /// assert!(Simplicity::new(-0.5).is_none());
    /// ```
    #[must_use]
    pub fn new(value: f64) -> Option<Self> {
        if value.is_finite() && (0.0..=1.0).contains(&value) {
            Some(Self(value))
        } else {
            None
        }
    }

    /// The carried score as a raw `f64` in `[0, 1]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::Simplicity;
    /// assert_eq!(Simplicity::new(0.6).unwrap().get(), 0.6);
    /// ```
    pub fn get(self) -> f64 {
        self.0
    }
}

impl core::fmt::Display for Simplicity {
    /// Formats the simplicity score as a human-readable percentage, e.g. `"60.00%"`.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.2}%", self.0 * 100.0)
    }
}

// ── Deviation and verdict shapes ────────────────────────────────────────────

/// A single deviation in a conformance verdict, tagged with a move witness `M`.
///
/// The witness `M` (e.g. [`LogOnlyMove`], [`ModelOnlyMove`]) records the
/// alignment-move family at the type level. This is **structure only**: it
/// describes *where* and *what kind* of deviation occurred, carried as an opaque
/// label; it never *computes* the alignment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Deviation<M = ()> {
    /// The position in the trace where the deviation was observed.
    pub position: usize,
    /// An opaque label describing the deviating activity / move.
    pub label: String,
    /// Type-level witness of the alignment-move family.
    pub witness: PhantomData<M>,
}

impl<M> Deviation<M> {
    /// Construct a witnessed deviation at a position with a label.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::{Deviation, LogOnlyMove};
    /// let d = Deviation::<LogOnlyMove>::new(3, "unexpected_refund");
    /// assert_eq!(d.position, 3);
    /// ```
    pub fn new(position: usize, label: impl Into<String>) -> Self {
        Self {
            position,
            label: label.into(),
            witness: PhantomData,
        }
    }
}

/// An aggregate conformance verdict: the carried scores plus the deviation path.
///
/// The top-level **shape** of a conformance result. It does **NOT** compute
/// fitness, precision, F1, generalization, simplicity, or alignments — those
/// values are produced by an engine and merely *carried* here. Graduate to
/// `wasm4pm` to compute them.
///
/// All four van der Aalst quality dimensions are represented:
/// fitness, precision, generalization, and simplicity, together with the
/// harmonic F1 of fitness and precision.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConformanceVerdict {
    /// The carried fitness score, if available.
    pub fitness: Option<Fitness>,
    /// The carried precision score, if available.
    pub precision: Option<Precision>,
    /// The carried F1 score (harmonic mean of fitness and precision), if available.
    pub f1: Option<F1>,
    /// The carried generalization score, if available.
    pub generalization: Option<Generalization>,
    /// The carried simplicity score, if available.
    pub simplicity: Option<Simplicity>,
    /// The deviation path (untyped at the collection level).
    pub deviations: Vec<Deviation>,
}

impl ConformanceVerdict {
    /// Construct an empty verdict (no scores, no deviations).
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::ConformanceVerdict;
    /// let v = ConformanceVerdict::new();
    /// assert!(v.fitness.is_none());
    /// assert!(v.deviations.is_empty());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the verdict reports a perfectly-fitting, deviation-free result.
    ///
    /// Returns `true` only if fitness is present and equal to `1.0` and there
    /// are no deviations.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::conformance::{ConformanceVerdict, Fitness};
    /// let mut v = ConformanceVerdict::new();
    /// assert!(!v.is_perfect());
    /// v.fitness = Fitness::new(1.0);
    /// assert!(v.is_perfect());
    /// ```
    pub fn is_perfect(&self) -> bool {
        self.deviations.is_empty() && matches!(self.fitness, Some(f) if f.get() == 1.0)
    }
}

impl core::fmt::Display for ConformanceVerdict {
    /// Formats the verdict as a compact human-readable summary.
    ///
    /// Present scores are shown as percentages; absent slots are shown as `"—"`.
    /// Deviation count is appended.
    ///
    /// Example: `"fitness=85.00% precision=72.00% f1=77.78% generalization=— simplicity=— deviations=3"`
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        fn fmt_score<T: core::fmt::Display>(
            f: &mut core::fmt::Formatter<'_>,
            label: &str,
            slot: &Option<T>,
        ) -> core::fmt::Result {
            match slot {
                Some(v) => write!(f, "{label}={v}"),
                None => write!(f, "{label}=\u{2014}"),
            }
        }

        fmt_score(f, "fitness", &self.fitness)?;
        f.write_str(" ")?;
        fmt_score(f, "precision", &self.precision)?;
        f.write_str(" ")?;
        fmt_score(f, "f1", &self.f1)?;
        f.write_str(" ")?;
        fmt_score(f, "generalization", &self.generalization)?;
        f.write_str(" ")?;
        fmt_score(f, "simplicity", &self.simplicity)?;
        write!(f, " deviations={}", self.deviations.len())
    }
}

/// First-class refusal law for conformance verdicts.
///
/// Every variant names a **specific** structural law — never a bare
/// "InvalidInput". Refusals here are about *missing or out-of-shape verdict
/// inputs*, not about a failing check.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConformanceRefusal {
    /// A verdict was requested without an admitted log to verdict against.
    MissingLog,
    /// A verdict was requested without an admitted model to verdict against.
    MissingModel,
    /// A deviation was reported but its alignment path was absent.
    MissingDeviationPath,
    /// A fitness score was demanded but none was carried.
    FitnessUnavailable,
    /// A precision score was demanded but none was carried.
    PrecisionUnavailable,
    /// An F1 score was demanded but none was carried.
    F1Unavailable,
    /// A generalization score was demanded but none was carried.
    GeneralizationUnavailable,
    /// A simplicity score was demanded but none was carried.
    SimplicityUnavailable,
}

impl core::fmt::Display for ConformanceRefusal {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let law = match self {
            ConformanceRefusal::MissingLog => "MissingLog",
            ConformanceRefusal::MissingModel => "MissingModel",
            ConformanceRefusal::MissingDeviationPath => "MissingDeviationPath",
            ConformanceRefusal::FitnessUnavailable => "FitnessUnavailable",
            ConformanceRefusal::PrecisionUnavailable => "PrecisionUnavailable",
            ConformanceRefusal::F1Unavailable => "F1Unavailable",
            ConformanceRefusal::GeneralizationUnavailable => "GeneralizationUnavailable",
            ConformanceRefusal::SimplicityUnavailable => "SimplicityUnavailable",
        };
        write!(f, "conformance verdict refused: {law}")
    }
}

// ── Token-replay statistics shape ───────────────────────────────────────────

/// Shape of a token-replay fitness result — produced/consumed/missing/remaining
/// token counts plus the derived fitness score.
///
/// This is **structure only**; no token game is played here. The five fields
/// mirror the `TokenReplayResult` in `wasm4pm-types` so that callers can pass
/// raw replay statistics across the compat boundary without depending on the
/// full `wasm4pm` engine.
///
/// Graduate to `wasm4pm` for actual token-replay computation.
///
/// ## Examples
///
/// ```
/// use wasm4pm_compat::conformance::TokenReplayResult;
/// let r = TokenReplayResult {
///     fitness: 0.9,
///     produced_tokens: 10,
///     consumed_tokens: 9,
///     missing_tokens: 1,
///     remaining_tokens: 0,
/// };
/// assert_eq!(r.fitness, 0.9);
/// assert_eq!(r.missing_tokens, 1);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct TokenReplayResult {
    /// Token-replay fitness score in `[0, 1]`.
    pub fitness: f64,
    /// Total tokens produced (fired) during replay.
    pub produced_tokens: usize,
    /// Total tokens consumed during replay.
    pub consumed_tokens: usize,
    /// Tokens that were missing (model required, log did not provide).
    pub missing_tokens: usize,
    /// Tokens remaining in the final marking after replay.
    pub remaining_tokens: usize,
}