wasm4pm-compat 26.6.23

Minimal paper-complete, feature-capped Rust process-evidence crate. Start with compatibility. Graduate to execution.
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Petri-net shapes — typed places/transitions/arcs and const-generic soundness.
//!
//! ## What this module IS
//!
//! - The structural shape of a (workflow) Petri net: bipartite typed arcs,
//!   `WfNetConst<SOUNDNESS>` carrying a non-forgeable soundness typestate, and
//!   `SeparableWfNet` whose private seal makes a separability claim unforgeable.
//!
//! ## What this module is **NOT**
//!
//! - **Not** a soundness checker or token-replay engine. The soundness *witness*
//!   is issued by a proof token; this crate never *computes* soundness, fires a
//!   transition, or explores a marking graph.
//!
//! Structure only. Graduate to `wasm4pm` to *decide* soundness or replay tokens.

use crate::law::SoundnessState;
pub use crate::models::{Arc, ArcDirection, PetriNet, PetriNetRefusal, Place, Transition};
use std::fmt;
use std::marker::PhantomData;

// ── Marking ──────────────────────────────────────────────────────────────────

/// A token distribution over places — the runtime state of a Petri net.
#[derive(Debug, Clone, Default)]
pub struct Marking {
    tokens: Vec<(String, usize)>,
}

impl Marking {
    pub fn new(tokens: impl IntoIterator<Item = (String, usize)>) -> Self {
        Marking {
            tokens: tokens.into_iter().collect(),
        }
    }

    pub fn empty() -> Self {
        Marking::default()
    }

    pub fn is_empty(&self) -> bool {
        self.tokens.is_empty()
    }

    pub fn tokens(&self) -> &[(String, usize)] {
        &self.tokens
    }
}

// ── PetriRefusal ─────────────────────────────────────────────────────────────

/// Named refusal variants for Petri net validation laws.
///
/// Every variant names a specific law from van der Aalst's workflow net theory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PetriRefusal {
    MissingInitialMarking,
    MissingFinalMarking,
    DeadTransition,
    UnsafeNet,
    UnboundedNet,
    ObjectTypeNotPreserved,
    InvalidVariableArc,
    SoundnessNotWitnessed,
    InvalidCancellationRegion,
    InvalidInstanceBounds,
}

impl fmt::Display for PetriRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let law = match self {
            PetriRefusal::MissingInitialMarking => "MissingInitialMarking",
            PetriRefusal::MissingFinalMarking => "MissingFinalMarking",
            PetriRefusal::DeadTransition => "DeadTransition",
            PetriRefusal::UnsafeNet => "UnsafeNet",
            PetriRefusal::UnboundedNet => "UnboundedNet",
            PetriRefusal::ObjectTypeNotPreserved => "ObjectTypeNotPreserved",
            PetriRefusal::InvalidVariableArc => "InvalidVariableArc",
            PetriRefusal::SoundnessNotWitnessed => "SoundnessNotWitnessed",
            PetriRefusal::InvalidCancellationRegion => "InvalidCancellationRegion",
            PetriRefusal::InvalidInstanceBounds => "InvalidInstanceBounds",
        };
        write!(f, "Petri-net refused by law: {law}")
    }
}

impl std::error::Error for PetriRefusal {}

// ── WfNet typestate ───────────────────────────────────────────────────────────

/// Typestate marker: soundness has been asserted (not verified by replay).
pub struct SoundnessClaimed;

/// Typestate marker: soundness has been witnessed by token replay.
pub struct SoundnessWitnessed;

/// Default typestate: no soundness claim has been made yet.
pub struct SoundnessUnknown;

/// Alias for compatibility.
pub type Unchecked = SoundnessUnknown;

/// A workflow net — a Petri net with a designated final marking.
///
/// The typestate parameter `S` tracks soundness evidence:
/// - `WfNet<SoundnessUnknown>` — no soundness claim made
/// - `WfNet<SoundnessClaimed>` — caller asserted soundness via `claim_sound()`
/// - `WfNet<SoundnessWitnessed>` — soundness verified by token replay
pub struct WfNet<S = SoundnessUnknown> {
    net: PetriNet,
    final_marking: Marking,
    _s: PhantomData<S>,
}

/// Phantom-typed proof carrier for workflow net soundness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WfNetSoundnessProofOf<Net> {
    _seal: (),
    _marker: std::marker::PhantomData<Net>,
}

impl<Net> WfNetSoundnessProofOf<Net> {
    #[allow(dead_code)]
    pub(crate) fn new() -> Self {
        WfNetSoundnessProofOf {
            _seal: (),
            _marker: std::marker::PhantomData,
        }
    }
}

impl WfNet<SoundnessUnknown> {
    pub fn new(net: PetriNet, final_marking: Marking) -> Self {
        WfNet {
            net,
            final_marking,
            _s: PhantomData,
        }
    }

    #[must_use]
    pub fn claim_sound(self) -> WfNet<SoundnessClaimed> {
        WfNet {
            net: self.net,
            final_marking: self.final_marking,
            _s: PhantomData,
        }
    }
}

impl<S> WfNet<S> {
    pub fn validate(&self) -> Result<(), PetriRefusal> {
        if self.final_marking.is_empty() {
            return Err(PetriRefusal::MissingFinalMarking);
        }
        Ok(())
    }

    #[must_use]
    pub fn final_marking(&self) -> Option<&Marking> {
        if self.final_marking.is_empty() {
            None
        } else {
            Some(&self.final_marking)
        }
    }

    pub fn net(&self) -> &PetriNet {
        &self.net
    }
}

// ── ObjectCentricPetriNet ─────────────────────────────────────────────────────

/// A Petri net extended with object-type annotations on arcs,
/// per the OCPN model from van der Aalst et al.
#[derive(Debug, Clone)]
pub struct ObjectCentricPetriNet {
    net: PetriNet,
    object_types: Vec<String>,
}

impl ObjectCentricPetriNet {
    pub fn new(net: PetriNet, object_types: impl IntoIterator<Item = String>) -> Self {
        ObjectCentricPetriNet {
            net,
            object_types: object_types.into_iter().collect(),
        }
    }

    pub fn net(&self) -> &PetriNet {
        &self.net
    }
    pub fn object_types(&self) -> &[String] {
        &self.object_types
    }

    pub fn validate(&self) -> Result<(), PetriRefusal> {
        let type_set: std::collections::HashSet<&str> =
            self.object_types.iter().map(|s| s.as_str()).collect();
        for arc in &self.net.arcs {
            if let Some((ref ot, _)) = arc.object_type {
                if !type_set.contains(ot.as_str()) {
                    return Err(PetriRefusal::ObjectTypeNotPreserved);
                }
            }
        }
        Ok(())
    }
}

// ── PetriNet/Place/Transition accessor methods ────────────────────────────────

impl Place {
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl Transition {
    pub fn id(&self) -> &str {
        &self.id
    }
    pub fn label(&self) -> &str {
        &self.label
    }
    pub fn is_silent(&self) -> bool {
        self.is_invisible.unwrap_or(false)
    }
    pub fn silent(id: &str) -> Self {
        Transition {
            id: id.to_owned(),
            label: String::new(),
            is_invisible: Some(true),
        }
    }
}

impl PetriNet {
    pub fn places(&self) -> &[Place] {
        &self.places
    }
    pub fn transitions(&self) -> &[Transition] {
        &self.transitions
    }
    pub fn arcs(&self) -> &[Arc] {
        &self.arcs
    }
    /// The initial marking as a read-only, hash-backed view. Structure only:
    /// it reads token counts; it fires no transition.
    ///
    /// ```
    /// use wasm4pm_compat::petri::{PetriNet, Place, Transition, Arc, Marking};
    /// let net = PetriNet::new(
    ///     [Place::new("p0"), Place::new("p1")],
    ///     [Transition::new("t0", "fire")],
    ///     [Arc::place_to_transition("p0", "t0"), Arc::transition_to_place("t0", "p1")],
    ///     Marking::new([("p0".to_string(), 1)]),
    /// );
    /// let m = net.initial_marking();
    /// assert_eq!(m.tokens_on("p0"), 1);
    /// assert_eq!(m.tokens_on("p1"), 0); // unmarked place → 0
    /// ```
    pub fn initial_marking(&self) -> RuntimeMarking<'_> {
        RuntimeMarking { net: self }
    }
}

/// Read-only view of the initial marking backed by the PetriNet's PackedKeyTable.
pub struct RuntimeMarking<'a> {
    net: &'a PetriNet,
}

impl<'a> RuntimeMarking<'a> {
    /// Returns the token count on a named place, or 0 if not marked.
    pub fn tokens_on(&self, place_id: &str) -> usize {
        use crate::dense_kernel::fnv1a_64;
        let hash = fnv1a_64(place_id.as_bytes());
        *self.net.initial_marking.get(hash).unwrap_or(&0)
    }
}

// ── Marking::tokens_on ───────────────────────────────────────────────────────

impl Marking {
    /// Returns the token count on a named place, or 0 if absent.
    pub fn tokens_on(&self, place_id: &str) -> usize {
        self.tokens
            .iter()
            .find(|(id, _)| id == place_id)
            .map(|(_, n)| *n)
            .unwrap_or(0)
    }
}

// ── BipartiteArcConst ─────────────────────────────────────────────────────────

use crate::law::ArcDirectionConst;

pub struct BipartiteArcConst<const DIR: ArcDirectionConst, W> {
    place_id: String,
    transition_id: String,
    weight: W,
}

impl<const DIR: ArcDirectionConst, W: Copy> BipartiteArcConst<DIR, W> {
    pub fn new(place_id: &str, transition_id: &str, weight: W) -> Self {
        BipartiteArcConst {
            place_id: place_id.to_owned(),
            transition_id: transition_id.to_owned(),
            weight,
        }
    }
    pub fn place_id(&self) -> &str {
        &self.place_id
    }
    pub fn transition_id(&self) -> &str {
        &self.transition_id
    }
    pub fn weight(&self) -> W {
        self.weight
    }
    pub fn direction(&self) -> ArcDirectionConst {
        DIR
    }
}

// ── InitialFinalMarkingPair ───────────────────────────────────────────────────

pub struct InitialFinalMarkingPair {
    pub initial: Marking,
    pub final_marking: Marking,
}

impl InitialFinalMarkingPair {
    pub fn new(initial: Marking, final_marking: Marking) -> Self {
        InitialFinalMarkingPair {
            initial,
            final_marking,
        }
    }
    pub fn validate(&self) -> Result<(), PetriRefusal> {
        for (p_init, t_init) in self.initial.tokens() {
            if *t_init > 0 && self.final_marking.tokens_on(p_init) > 0 {
                return Err(PetriRefusal::UnsafeNet);
            }
        }
        Ok(())
    }
}

// ── Node-kind markers and typed arc structs ───────────────────────────────────

/// Sealed marker: this type represents a place node.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct PlaceNodeMarker;

pub trait IsPlaceNode: Default + Clone + Copy {}
impl IsPlaceNode for PlaceNodeMarker {}

/// Sealed marker: this type represents a transition node.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct TransitionNodeMarker;

pub trait IsTransitionNode: Default + Clone + Copy {}
impl IsTransitionNode for TransitionNodeMarker {}

pub trait IsValidArc {}

/// A pre-incidence (place → transition) arc carrying a typed weight.
///
/// The phantom types `P` and `T` name the place and transition namespaces;
/// the weight type `W` names the arc multiplicity type (usually `u32`).
pub struct PlaceToTransitionArc<P, T, W> {
    w: W,
    _p: PhantomData<(P, T)>,
}

impl<P, T, W: Copy> PlaceToTransitionArc<P, T, W> {
    pub fn new(weight: W) -> Self {
        PlaceToTransitionArc {
            w: weight,
            _p: PhantomData,
        }
    }
    pub fn weight(&self) -> W {
        self.w
    }
}

impl<P, T, W> IsValidArc for PlaceToTransitionArc<P, T, W> {}

/// A post-incidence (transition → place) arc carrying a typed weight.
pub struct TransitionToPlaceArc<T, P, W> {
    w: W,
    _p: PhantomData<(T, P)>,
}

impl<T, P, W: Copy> TransitionToPlaceArc<T, P, W> {
    pub fn new(weight: W) -> Self {
        TransitionToPlaceArc {
            w: weight,
            _p: PhantomData,
        }
    }
    pub fn weight(&self) -> W {
        self.w
    }
}

impl<T, P, W> IsValidArc for TransitionToPlaceArc<T, P, W> {}

pub struct SeparableWfNetMarker;

// The private `_seal` field is the non-forgeability mechanism, NOT an
// accidental near-`#[non_exhaustive]`. `#[non_exhaustive]` would not reproduce
// the "field `_seal` is private" compile error that the
// `wfnet_to_powl_nonseparable` type-law receipt asserts, and it permits
// struct-literal construction within this crate. Keep the private field.
#[allow(clippy::manual_non_exhaustive)]
pub struct SeparableWfNet<
    const S: SoundnessState,
    const FC: FreeChoiceMarker = { FreeChoiceMarker::General },
> {
    pub net: WfNetConst<S, FC>,
    /// Non-forgeable seal: this private field prevents constructing a
    /// separability claim via struct-literal syntax outside
    /// [`SeparableWfNet::declare_separable`] (Kourani, Park & van der Aalst
    /// 2026, Theorem 4.3). Without it, a non-separable WF-net could be forged
    /// into the POWL conversion path.
    _seal: (),
}

impl<const S: SoundnessState, const FC: FreeChoiceMarker> SeparableWfNet<S, FC> {
    pub fn declare_separable(net: WfNetConst<S, FC>) -> Self {
        SeparableWfNet { net, _seal: () }
    }

    pub fn into_powl(
        self,
        context_label: impl Into<String>,
    ) -> (crate::powl::Powl, crate::powl::WfNet2PowlWitness) {
        (
            crate::powl::Powl::new(),
            crate::powl::WfNet2PowlWitness::new_internal(context_label),
        )
    }
}

// ── WfNetConst — const-generic soundness typestate ────────────────────────────

mod wfnet_seal {
    pub(super) struct WfNetSeal;
}

/// Proof token that soundness has been verified (crate-internal only).
pub struct SoundnessProof(wfnet_seal::WfNetSeal);

#[allow(dead_code)] // reserved: issued by soundness-witnessing logic not yet in this crate
impl SoundnessProof {
    pub(crate) fn new() -> Self {
        SoundnessProof(wfnet_seal::WfNetSeal)
    }
}

/// The subclass marker for Free-Choice Petri Nets vs. General Workflow Nets.
///
/// Under Free-Choice nets (Desel 1995), soundness is decidable in polynomial time,
/// whereas general WF-nets require PSPACE-complete complexity.
#[derive(core::marker::ConstParamTy, PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub enum FreeChoiceMarker {
    /// The net is structurally free-choice, enabling the polynomial-time soundness checking path.
    FreeChoice,
    /// The net is general, requiring the PSPACE-complete soundness checking path.
    General,
}

/// A workflow net whose soundness state and free-choice classification are embedded as const generic parameters.
///
/// `SoundnessState::Unknown` is freely constructible.
/// `SoundnessState::Claimed` is reachable via `.claim_sound()`.
/// `SoundnessState::Witnessed` requires a `SoundnessProof` token — non-forgeable.
///
/// The `FC` const-generic parameter allows distinguishing free-choice nets from general ones at the type level.
pub struct WfNetConst<
    const SOUNDNESS: SoundnessState,
    const FC: FreeChoiceMarker = { FreeChoiceMarker::General },
> {
    _seal: (),
}

impl WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::General }> {
    pub fn new() -> Self {
        WfNetConst { _seal: () }
    }

    /// Advance: Unknown → Claimed (type-level re-tag, zero cost).
    #[must_use]
    pub fn claim_sound(
        self,
    ) -> WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::General }> {
        WfNetConst { _seal: () }
    }
}

impl WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::FreeChoice }> {
    pub fn new() -> Self {
        WfNetConst { _seal: () }
    }

    /// Advance: Unknown → Claimed (type-level re-tag, zero cost).
    #[must_use]
    pub fn claim_sound(
        self,
    ) -> WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::FreeChoice }> {
        WfNetConst { _seal: () }
    }
}

impl WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::General }> {
    /// Advance: Claimed → Witnessed, guarded by a `SoundnessProof` token.
    ///
    /// `SoundnessProof` is only constructible inside the petri module, making
    /// this transition non-forgeable from external code.
    #[must_use]
    pub fn witness_soundness(
        self,
        _proof: SoundnessProof,
    ) -> WfNetConst<{ SoundnessState::Witnessed }, { FreeChoiceMarker::General }> {
        WfNetConst { _seal: () }
    }
}

impl WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::FreeChoice }> {
    /// Advance: Claimed → Witnessed, guarded by a `SoundnessProof` token.
    ///
    /// `SoundnessProof` is only constructible inside the petri module, making
    /// this transition non-forgeable from external code.
    #[must_use]
    pub fn witness_soundness(
        self,
        _proof: SoundnessProof,
    ) -> WfNetConst<{ SoundnessState::Witnessed }, { FreeChoiceMarker::FreeChoice }> {
        WfNetConst { _seal: () }
    }
}

impl<const S: SoundnessState, const FC: FreeChoiceMarker> WfNetConst<S, FC> {
    pub fn soundness_state(&self) -> SoundnessState {
        S
    }

    pub fn free_choice_state(&self) -> FreeChoiceMarker {
        FC
    }
}

impl WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::General }> {
    /// Declare the net as Free-Choice after structural verification (re-tags at type level).
    #[must_use]
    pub fn into_free_choice(
        self,
    ) -> WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::FreeChoice }> {
        WfNetConst { _seal: () }
    }
}

impl WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::General }> {
    /// Declare the net as Free-Choice after structural verification (re-tags at type level).
    #[must_use]
    pub fn into_free_choice(
        self,
    ) -> WfNetConst<{ SoundnessState::Claimed }, { FreeChoiceMarker::FreeChoice }> {
        WfNetConst { _seal: () }
    }
}

impl WfNetConst<{ SoundnessState::Witnessed }, { FreeChoiceMarker::General }> {
    /// Declare the net as Free-Choice after structural verification (re-tags at type level).
    #[must_use]
    pub fn into_free_choice(
        self,
    ) -> WfNetConst<{ SoundnessState::Witnessed }, { FreeChoiceMarker::FreeChoice }> {
        WfNetConst { _seal: () }
    }
}

impl Default for WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::General }> {
    fn default() -> Self {
        WfNetConst { _seal: () }
    }
}

impl Default for WfNetConst<{ SoundnessState::Unknown }, { FreeChoiceMarker::FreeChoice }> {
    fn default() -> Self {
        WfNetConst { _seal: () }
    }
}

// ── WfNetQuery ────────────────────────────────────────────────────────────────

/// Query interface for WF-net structural properties (reserved for future use).
pub trait WfNetQuery {
    /// The soundness state of this WF-net as a runtime value.
    fn soundness_state(&self) -> SoundnessState;
    /// The free-choice classification of this WF-net.
    fn free_choice_state(&self) -> FreeChoiceMarker;
}

impl<const S: SoundnessState, const FC: FreeChoiceMarker> WfNetQuery for WfNetConst<S, FC> {
    fn soundness_state(&self) -> SoundnessState {
        S
    }
    fn free_choice_state(&self) -> FreeChoiceMarker {
        FC
    }
}

// =============================================================================
// Stochastic Petri Nets
// =============================================================================

/// A stochastic weight representing a probability value `NUM / DEN` in `[0, 1]`.
///
/// Encodes the Leemans (2019) stochastic choice constraint: out-of-bounds weights
/// (e.g. numerator > denominator, or denominator == 0) are rejected at compile time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StochasticArcWeight<const NUM: u64, const DEN: u64>
where
    crate::law::Require<{ DEN > 0 }>: crate::law::IsTrue,
    crate::law::Require<{ NUM <= DEN }>: crate::law::IsTrue,
{
    _inner: crate::law::Between01<NUM, DEN>,
}

impl<const NUM: u64, const DEN: u64> StochasticArcWeight<NUM, DEN>
where
    crate::law::Require<{ DEN > 0 }>: crate::law::IsTrue,
    crate::law::Require<{ NUM <= DEN }>: crate::law::IsTrue,
{
    /// Construct a new compile-time stochastic weight.
    pub const fn new() -> Self {
        Self {
            _inner: crate::law::Between01::new(),
        }
    }

    /// Returns the numerator of the weight.
    pub const fn num(&self) -> u64 {
        NUM
    }

    /// Returns the denominator of the weight.
    pub const fn den(&self) -> u64 {
        DEN
    }
}

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

/// Unit-struct marker representing an immediate transition.
/// Fired instantly when enabled; conflicts are resolved using relative probability weights.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct ImmediateTransition;

/// Unit-struct marker representing a timed transition.
/// Fired stochastically after a delay determined by its firing rate.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct TimedTransition;

mod private {
    pub trait Sealed {}
    impl Sealed for super::ImmediateTransition {}
    impl Sealed for super::TimedTransition {}
}

/// Trait implemented by valid stochastic transition kind markers.
///
/// This trait is sealed to prevent users from implementing it for arbitrary types.
pub trait IsStochasticTransitionKind: private::Sealed + Default + Copy {}

impl IsStochasticTransitionKind for ImmediateTransition {}
impl IsStochasticTransitionKind for TimedTransition {}

/// A transition in a stochastic Petri net, type-stamped with its structural kind.
///
/// This is a zero-cost wrapper around a transition identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StochasticTransition<KIND: IsStochasticTransitionKind> {
    pub id: String,
    _kind: PhantomData<KIND>,
}

impl<KIND: IsStochasticTransitionKind> StochasticTransition<KIND> {
    /// Construct a new typed stochastic transition.
    pub fn new(id: &str) -> Self {
        Self {
            id: id.to_string(),
            _kind: PhantomData,
        }
    }

    /// The transition's identifier.
    pub fn id(&self) -> &str {
        &self.id
    }
}

// =============================================================================
// Petri Net Unfoldings
// =============================================================================

/// A Condition in a branching process / occurrence net, corresponding to a place instance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Condition {
    /// Unique identifier of this condition in the unfolding.
    pub id: String,
    /// Reference to the place ID in the original net.
    pub place_id: String,
}

impl Condition {
    pub fn new(id: impl Into<String>, place_id: impl Into<String>) -> Self {
        Condition {
            id: id.into(),
            place_id: place_id.into(),
        }
    }
}

/// An Event in a branching process / occurrence net, corresponding to a transition firing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Event {
    /// Unique identifier of this event in the unfolding.
    pub id: String,
    /// Reference to the transition ID in the original net.
    pub transition_id: String,
}

impl Event {
    pub fn new(id: impl Into<String>, transition_id: impl Into<String>) -> Self {
        Event {
            id: id.into(),
            transition_id: transition_id.into(),
        }
    }
}

/// A Branching Process (occurrence net) of a Petri net.
///
/// Under Murata 1989, the branching process is acyclic, and every condition
/// has at most one incoming event. The type parameter `Net` binds the branching
/// process to the original Petri net type, enforcing type safety.
#[derive(Debug, Clone, PartialEq)]
pub struct BranchingProcess<Net = PetriNet> {
    pub conditions: Vec<Condition>,
    pub events: Vec<Event>,
    pub arcs: Vec<Arc>,
    _marker: std::marker::PhantomData<Net>,
}

impl<Net> BranchingProcess<Net> {
    pub fn new(conditions: Vec<Condition>, events: Vec<Event>, arcs: Vec<Arc>) -> Self {
        BranchingProcess {
            conditions,
            events,
            arcs,
            _marker: std::marker::PhantomData,
        }
    }

    pub fn conditions(&self) -> &[Condition] {
        &self.conditions
    }

    pub fn events(&self) -> &[Event] {
        &self.events
    }

    pub fn arcs(&self) -> &[Arc] {
        &self.arcs
    }
}

impl<Net> Default for BranchingProcess<Net> {
    fn default() -> Self {
        BranchingProcess {
            conditions: Vec::new(),
            events: Vec::new(),
            arcs: Vec::new(),
            _marker: std::marker::PhantomData,
        }
    }
}

/// An Unfolding Prefix of a branching process.
///
/// Under Murata 1989 and McMillan 1992, the unfolding prefix is a finite complete prefix
/// containing cut-off event designations that truncates infinite execution sequences.
#[derive(Debug, Clone, PartialEq)]
pub struct UnfoldingPrefix<Net = PetriNet> {
    pub process: BranchingProcess<Net>,
    pub cutoff_events: Vec<String>,
}

impl<Net> UnfoldingPrefix<Net> {
    pub fn new(process: BranchingProcess<Net>, cutoff_events: Vec<String>) -> Self {
        UnfoldingPrefix {
            process,
            cutoff_events,
        }
    }

    pub fn process(&self) -> &BranchingProcess<Net> {
        &self.process
    }

    pub fn cutoff_events(&self) -> &[String] {
        &self.cutoff_events
    }

    pub fn is_cutoff(&self, event_id: &str) -> bool {
        self.cutoff_events.iter().any(|id| id == event_id)
    }
}

impl<Net> Default for UnfoldingPrefix<Net> {
    fn default() -> Self {
        UnfoldingPrefix {
            process: BranchingProcess::default(),
            cutoff_events: Vec::new(),
        }
    }
}

/// `rem: T ⇸ P(T ∪ C \ {i, o})` — each task optionally names a cancellation
/// region. This struct carries the *shape* of that region: a named set of node
/// ids. Token-removal execution (the actual vacuuming) graduates to `wasm4pm`.
///
/// The `#[repr(transparent)]` newtype prevents a bare `Vec<String>` from being
/// accidentally passed where a `CancellationRegion` is required. It is zero-cost
/// to hold and clone.
///
/// Structure-only: carries ids, never fires.
#[repr(transparent)]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct CancellationRegion {
    /// The ids of nodes (places, conditions, tasks) in this cancellation region,
    /// excluding the initial and final place of the net (i, o).
    pub members: Vec<String>,
}

impl CancellationRegion {
    /// Construct a cancellation region from an iterator of node ids.
    ///
    /// ```
    /// use wasm4pm_compat::petri::CancellationRegion;
    /// let region = CancellationRegion::new(["t1", "t2", "c3"]);
    /// assert_eq!(region.members(), &["t1", "t2", "c3"]);
    /// ```
    pub fn new<I, S>(members: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        CancellationRegion {
            members: members.into_iter().map(Into::into).collect(),
        }
    }

    /// The node ids in this cancellation region.
    pub fn members(&self) -> &[String] {
        &self.members
    }
}

// ── YAWL multiple-instance bounds ───────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InstanceCreationKind {
    /// All child instances are created at the moment the task fires.
    Static,
    /// Child instances may be created incrementally during the task's lifetime.
    Dynamic,
}

/// A YAWL multiple-instance task specification: the four-tuple
/// `(min_instances, max_instances, threshold, creation_kind)`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultipleInstanceSpec {
    /// Minimum number of instances that must complete.
    pub min: u32,
    /// Maximum number of instances (`None` = unbounded / ∞).
    pub max: Option<u32>,
    /// Threshold for collective completion (`None` = all instances).
    pub threshold: Option<u32>,
    /// Whether child instances are created statically or dynamically.
    pub creation: InstanceCreationKind,
}

impl MultipleInstanceSpec {
    /// Construct a multiple-instance spec.
    pub fn new(
        min: u32,
        max: Option<u32>,
        threshold: Option<u32>,
        creation: InstanceCreationKind,
    ) -> Self {
        MultipleInstanceSpec {
            min,
            max,
            threshold,
            creation,
        }
    }

    /// Structurally validate the instance bounds.
    #[must_use = "check the shape-check result"]
    pub fn validate(&self) -> Result<(), PetriRefusal> {
        if self.min == 0 {
            return Err(PetriRefusal::InvalidInstanceBounds);
        }
        if let Some(max) = self.max {
            if self.min > max {
                return Err(PetriRefusal::InvalidInstanceBounds);
            }
        }
        Ok(())
    }
}

// ── YAWL multiple-instance bounds — compile-time law surface ────────────────

/// A YAWL multiple-instance spec with bounds enforced **at compile time**.
///
/// `MultipleInstanceSpecConst<MIN, MAX>` encodes the YAWL Definition 1 `nofi`
/// invariant `1 ≤ MIN ≤ MAX` as const-generic where-bounds so that a violation
/// is a **compile error**, not a runtime refusal.
///
/// Law: YAWL Definition 1 nofi — `min: N`, `max: N^∞`, `1 ≤ min ≤ max`.
pub struct MultipleInstanceSpecConst<const MIN: u32, const MAX: u32>
where
    crate::law::Require<{ MIN >= 1 }>: crate::law::IsTrue,
    crate::law::Require<{ MIN <= MAX }>: crate::law::IsTrue,
{
    _private: (),
}

impl<const MIN: u32, const MAX: u32> MultipleInstanceSpecConst<MIN, MAX>
where
    crate::law::Require<{ MIN >= 1 }>: crate::law::IsTrue,
    crate::law::Require<{ MIN <= MAX }>: crate::law::IsTrue,
{
    /// Construct a `MultipleInstanceSpecConst<MIN, MAX>` — only possible when
    /// `MIN >= 1` and `MIN <= MAX`.
    pub const fn new() -> Self {
        MultipleInstanceSpecConst { _private: () }
    }

    /// The minimum instance count encoded in the type.
    pub const fn min(&self) -> u32 {
        MIN
    }

    /// The maximum instance count encoded in the type.
    pub const fn max(&self) -> u32 {
        MAX
    }
}

impl<const MIN: u32, const MAX: u32> Default for MultipleInstanceSpecConst<MIN, MAX>
where
    crate::law::Require<{ MIN >= 1 }>: crate::law::IsTrue,
    crate::law::Require<{ MIN <= MAX }>: crate::law::IsTrue,
{
    fn default() -> Self {
        Self::new()
    }
}

/// A standalone, named error type for the *missing final marking* law.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct MissingFinalMarkingError;

impl core::fmt::Display for MissingFinalMarkingError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "WF-net refused by law: MissingFinalMarking")
    }
}

impl From<MissingFinalMarkingError> for PetriRefusal {
    fn from(_: MissingFinalMarkingError) -> Self {
        PetriRefusal::MissingFinalMarking
    }
}

pub struct BoundedWfNet<const PLACES: usize, const TRANSITIONS: usize>
where
    [(); PLACES + TRANSITIONS]:,
{
    pub places: [String; PLACES],
    pub transitions: [String; TRANSITIONS],
}

impl<const PLACES: usize, const TRANSITIONS: usize> BoundedWfNet<PLACES, TRANSITIONS>
where
    [(); PLACES + TRANSITIONS]:,
    crate::law::Require<{ PLACES + TRANSITIONS <= 4096 }>: crate::law::IsTrue,
{
    pub fn new(places: [String; PLACES], transitions: [String; TRANSITIONS]) -> Self {
        Self {
            places,
            transitions,
        }
    }
}

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

    #[test]
    fn soundness_proof_mints_and_advances_to_witnessed() {
        // SoundnessProof::new() is pub(crate) — this test is the only caller,
        // which is the point: it proves the sealed capability works end-to-end.
        let proof = SoundnessProof::new();
        let witnessed = WfNetConst::<{ SoundnessState::Unknown }>::new()
            .claim_sound()
            .witness_soundness(proof);
        assert_eq!(witnessed.soundness_state(), SoundnessState::Witnessed);
    }
}