statum-core 0.7.0

Core types for representing legal workflow and protocol states explicitly in Rust
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
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
/// Static introspection surface emitted for a generated Statum machine.
pub trait MachineIntrospection {
    /// Machine-scoped state identifier emitted by `#[machine]`.
    type StateId: Copy + Eq + core::hash::Hash + 'static;

    /// Machine-scoped transition-site identifier emitted by `#[machine]`.
    type TransitionId: Copy + Eq + core::hash::Hash + 'static;

    /// Static graph descriptor for the machine family.
    const GRAPH: &'static MachineGraph<Self::StateId, Self::TransitionId>;
}

/// Runtime accessor for transition descriptors that may be supplied by a
/// distributed registration surface.
#[derive(Clone, Copy)]
pub struct TransitionInventory<S: 'static, T: 'static> {
    get: fn() -> &'static [TransitionDescriptor<S, T>],
}

impl<S, T> TransitionInventory<S, T> {
    /// Creates a transition inventory from a `'static` getter.
    pub const fn new(get: fn() -> &'static [TransitionDescriptor<S, T>]) -> Self {
        Self { get }
    }

    /// Returns the transition descriptors as a slice.
    pub fn as_slice(&self) -> &'static [TransitionDescriptor<S, T>] {
        (self.get)()
    }
}

impl<S, T> core::ops::Deref for TransitionInventory<S, T> {
    type Target = [TransitionDescriptor<S, T>];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<S, T> core::fmt::Debug for TransitionInventory<S, T> {
    fn fmt(
        &self,
        formatter: &mut core::fmt::Formatter<'_>,
    ) -> core::result::Result<(), core::fmt::Error> {
        formatter.debug_tuple("TransitionInventory").finish()
    }
}

impl<S, T> core::cmp::PartialEq for TransitionInventory<S, T> {
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self.as_slice(), other.as_slice())
    }
}

impl<S, T> core::cmp::Eq for TransitionInventory<S, T> {}

/// Runtime accessor for transition presentation metadata that may be supplied
/// by a distributed registration surface.
#[derive(Clone, Copy)]
pub struct TransitionPresentationInventory<T: 'static, M: 'static = ()> {
    get: fn() -> &'static [TransitionPresentation<T, M>],
}

impl<T, M> TransitionPresentationInventory<T, M> {
    /// Creates a transition presentation inventory from a `'static` getter.
    pub const fn new(get: fn() -> &'static [TransitionPresentation<T, M>]) -> Self {
        Self { get }
    }

    /// Returns the transition presentation descriptors as a slice.
    pub fn as_slice(&self) -> &'static [TransitionPresentation<T, M>] {
        (self.get)()
    }
}

impl<T, M> core::ops::Deref for TransitionPresentationInventory<T, M> {
    type Target = [TransitionPresentation<T, M>];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T, M> core::fmt::Debug for TransitionPresentationInventory<T, M> {
    fn fmt(
        &self,
        formatter: &mut core::fmt::Formatter<'_>,
    ) -> core::result::Result<(), core::fmt::Error> {
        formatter
            .debug_tuple("TransitionPresentationInventory")
            .finish()
    }
}

impl<T, M> core::cmp::PartialEq for TransitionPresentationInventory<T, M> {
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self.as_slice(), other.as_slice())
    }
}

impl<T, M> core::cmp::Eq for TransitionPresentationInventory<T, M> {}

/// Runtime accessor for erased transition descriptors supplied by a
/// distributed machine inventory.
#[derive(Clone, Copy)]
pub struct LinkedTransitionInventory {
    get: fn() -> &'static [LinkedTransitionDescriptor],
}

impl LinkedTransitionInventory {
    /// Creates a linked transition inventory from a `'static` getter.
    pub const fn new(get: fn() -> &'static [LinkedTransitionDescriptor]) -> Self {
        Self { get }
    }

    /// Returns the linked transition descriptors as a slice.
    pub fn as_slice(&self) -> &'static [LinkedTransitionDescriptor] {
        (self.get)()
    }
}

impl core::ops::Deref for LinkedTransitionInventory {
    type Target = [LinkedTransitionDescriptor];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl core::fmt::Debug for LinkedTransitionInventory {
    fn fmt(
        &self,
        formatter: &mut core::fmt::Formatter<'_>,
    ) -> core::result::Result<(), core::fmt::Error> {
        formatter.debug_tuple("LinkedTransitionInventory").finish()
    }
}

impl core::cmp::PartialEq for LinkedTransitionInventory {
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self.as_slice(), other.as_slice())
    }
}

impl core::cmp::Eq for LinkedTransitionInventory {}

/// Identity for one concrete machine state.
pub trait MachineStateIdentity: MachineIntrospection {
    /// The state id for this concrete machine instantiation.
    const STATE_ID: Self::StateId;
}

/// Optional human-facing metadata layered on top of a machine graph.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MachinePresentation<
    S: 'static,
    T: 'static,
    MachineMeta: 'static = (),
    StateMeta: 'static = (),
    TransitionMeta: 'static = (),
> {
    /// Optional machine-level presentation metadata.
    pub machine: Option<MachinePresentationDescriptor<MachineMeta>>,
    /// Optional state-level presentation metadata keyed by state id.
    pub states: &'static [StatePresentation<S, StateMeta>],
    /// Optional transition-level presentation metadata keyed by transition id.
    pub transitions: TransitionPresentationInventory<T, TransitionMeta>,
}

impl<S, T, MachineMeta, StateMeta, TransitionMeta>
    MachinePresentation<S, T, MachineMeta, StateMeta, TransitionMeta>
where
    S: Copy + Eq + 'static,
    T: Copy + Eq + 'static,
{
    /// Finds state presentation metadata by id.
    pub fn state(&self, id: S) -> Option<&StatePresentation<S, StateMeta>> {
        self.states.iter().find(|state| state.id == id)
    }

    /// Finds transition presentation metadata by id.
    pub fn transition(&self, id: T) -> Option<&TransitionPresentation<T, TransitionMeta>> {
        self.transitions
            .iter()
            .find(|transition| transition.id == id)
    }
}

/// Optional machine-level presentation metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MachinePresentationDescriptor<M: 'static = ()> {
    /// Optional short human-facing machine label.
    pub label: Option<&'static str>,
    /// Optional longer human-facing machine description.
    pub description: Option<&'static str>,
    /// Consumer-owned typed machine metadata.
    pub metadata: M,
}

/// Optional state-level presentation metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StatePresentation<S: 'static, M: 'static = ()> {
    /// Typed state identifier.
    pub id: S,
    /// Optional short human-facing state label.
    pub label: Option<&'static str>,
    /// Optional longer human-facing state description.
    pub description: Option<&'static str>,
    /// Consumer-owned typed state metadata.
    pub metadata: M,
}

/// Optional transition-level presentation metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TransitionPresentation<T: 'static, M: 'static = ()> {
    /// Typed transition-site identifier.
    pub id: T,
    /// Optional short human-facing transition label.
    pub label: Option<&'static str>,
    /// Optional longer human-facing transition description.
    pub description: Option<&'static str>,
    /// Consumer-owned typed transition metadata.
    pub metadata: M,
}

/// A runtime record of one chosen transition.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RecordedTransition<S: 'static, T: 'static> {
    /// Rust-facing identity of the machine family.
    pub machine: MachineDescriptor,
    /// Exact source state where the transition was taken.
    pub from: S,
    /// Exact transition site that was chosen.
    pub transition: T,
    /// Exact target state that actually happened at runtime.
    pub chosen: S,
}

impl<S, T> RecordedTransition<S, T>
where
    S: 'static,
    T: 'static,
{
    /// Builds a runtime transition record from typed machine ids.
    pub const fn new(machine: MachineDescriptor, from: S, transition: T, chosen: S) -> Self {
        Self {
            machine,
            from,
            transition,
            chosen,
        }
    }

    /// Finds the static transition descriptor for this runtime event.
    pub fn transition_in<'a>(
        &self,
        graph: &'a MachineGraph<S, T>,
    ) -> Option<&'a TransitionDescriptor<S, T>>
    where
        S: Copy + Eq,
        T: Copy + Eq,
    {
        let descriptor = graph.transition(self.transition)?;
        if descriptor.from == self.from && descriptor.to.contains(&self.chosen) {
            Some(descriptor)
        } else {
            None
        }
    }

    /// Finds the static source-state descriptor for this runtime event.
    pub fn source_state_in<'a>(
        &self,
        graph: &'a MachineGraph<S, T>,
    ) -> Option<&'a StateDescriptor<S>>
    where
        S: Copy + Eq,
        T: Copy + Eq,
    {
        self.transition_in(graph)?;
        graph.state(self.from)
    }

    /// Finds the static chosen-target descriptor for this runtime event.
    pub fn chosen_state_in<'a>(
        &self,
        graph: &'a MachineGraph<S, T>,
    ) -> Option<&'a StateDescriptor<S>>
    where
        S: Copy + Eq,
        T: Copy + Eq,
    {
        self.transition_in(graph)?;
        graph.state(self.chosen)
    }
}

/// Runtime recording helpers layered on top of static machine introspection.
pub trait MachineTransitionRecorder: MachineStateIdentity {
    /// Records a runtime transition if `transition` is valid from `Self::STATE_ID`
    /// and `chosen` is one of its legal target states.
    fn try_record_transition(
        transition: Self::TransitionId,
        chosen: Self::StateId,
    ) -> Option<RecordedTransition<Self::StateId, Self::TransitionId>> {
        let graph = Self::GRAPH;
        let descriptor = graph.transition(transition)?;
        if descriptor.from != Self::STATE_ID || !descriptor.to.contains(&chosen) {
            return None;
        }

        Some(RecordedTransition::new(
            graph.machine,
            Self::STATE_ID,
            transition,
            chosen,
        ))
    }

    /// Records a runtime transition using a typed target machine state.
    fn try_record_transition_to<Next>(
        transition: Self::TransitionId,
    ) -> Option<RecordedTransition<Self::StateId, Self::TransitionId>>
    where
        Next: MachineStateIdentity<StateId = Self::StateId, TransitionId = Self::TransitionId>,
    {
        Self::try_record_transition(transition, Next::STATE_ID)
    }
}

impl<M> MachineTransitionRecorder for M where M: MachineStateIdentity {}

/// Linked compiled machine families visible to the current build.
#[doc(hidden)]
#[linkme::distributed_slice]
pub static __STATUM_LINKED_MACHINES: [LinkedMachineGraph];

/// Returns every linked compiled machine family visible to the current build.
pub fn linked_machines() -> &'static [LinkedMachineGraph] {
    &__STATUM_LINKED_MACHINES
}

/// Linked compiled validator-entry surfaces visible to the current build.
#[doc(hidden)]
#[linkme::distributed_slice]
pub static __STATUM_LINKED_VALIDATOR_ENTRIES: [LinkedValidatorEntryDescriptor];

/// Returns every linked compiled validator-entry surface visible to the current
/// build.
pub fn linked_validator_entries() -> &'static [LinkedValidatorEntryDescriptor] {
    &__STATUM_LINKED_VALIDATOR_ENTRIES
}

/// Linked exact relation records visible to the current build.
#[doc(hidden)]
#[linkme::distributed_slice]
pub static __STATUM_LINKED_RELATIONS: [LinkedRelationDescriptor];

/// Returns every linked exact relation record visible to the current build.
pub fn linked_relations() -> &'static [LinkedRelationDescriptor] {
    &__STATUM_LINKED_RELATIONS
}

/// Linked attested transition routes visible to the current build.
#[doc(hidden)]
#[linkme::distributed_slice]
pub static __STATUM_LINKED_VIA_ROUTES: [LinkedViaRouteDescriptor];

/// Returns every linked attested transition route visible to the current
/// build.
pub fn linked_via_routes() -> &'static [LinkedViaRouteDescriptor] {
    &__STATUM_LINKED_VIA_ROUTES
}

/// Linked reference-type declarations visible to the current build.
#[doc(hidden)]
#[linkme::distributed_slice]
pub static __STATUM_LINKED_REFERENCE_TYPES: [LinkedReferenceTypeDescriptor];

/// Returns every linked reference-type declaration visible to the current
/// build.
pub fn linked_reference_types() -> &'static [LinkedReferenceTypeDescriptor] {
    &__STATUM_LINKED_REFERENCE_TYPES
}

/// Structural machine graph emitted from macro-generated metadata.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MachineGraph<S: 'static, T: 'static> {
    /// Rust-facing identity of the machine family.
    pub machine: MachineDescriptor,
    /// All states known to the machine.
    pub states: &'static [StateDescriptor<S>],
    /// All transition sites known to the machine.
    pub transitions: TransitionInventory<S, T>,
}

impl<S, T> MachineGraph<S, T>
where
    S: Copy + Eq + 'static,
    T: Copy + Eq + 'static,
{
    /// Finds a state descriptor by id.
    pub fn state(&self, id: S) -> Option<&StateDescriptor<S>> {
        self.states.iter().find(|state| state.id == id)
    }

    /// Finds a transition descriptor by id.
    pub fn transition(&self, id: T) -> Option<&TransitionDescriptor<S, T>> {
        self.transitions
            .iter()
            .find(|transition| transition.id == id)
    }

    /// Yields all transition sites originating from `state`.
    pub fn transitions_from(
        &self,
        state: S,
    ) -> impl Iterator<Item = &TransitionDescriptor<S, T>> + '_ {
        self.transitions
            .iter()
            .filter(move |transition| transition.from == state)
    }

    /// Finds the transition site for `method_name` on `state`.
    pub fn transition_from_method(
        &self,
        state: S,
        method_name: &str,
    ) -> Option<&TransitionDescriptor<S, T>> {
        self.transitions
            .iter()
            .find(|transition| transition.from == state && transition.method_name == method_name)
    }

    /// Yields all transition sites that share the same method name.
    pub fn transitions_named<'a>(
        &'a self,
        method_name: &'a str,
    ) -> impl Iterator<Item = &'a TransitionDescriptor<S, T>> + 'a {
        self.transitions
            .iter()
            .filter(move |transition| transition.method_name == method_name)
    }

    /// Returns the exact legal target states for a transition site.
    pub fn legal_targets(&self, id: T) -> Option<&'static [S]> {
        self.transition(id).map(|transition| transition.to)
    }
}

/// Erased machine graph emitted for codebase-level export over the linked
/// build.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LinkedMachineGraph {
    /// Rust-facing identity of the machine family.
    pub machine: MachineDescriptor,
    /// Optional human-facing machine label.
    pub label: Option<&'static str>,
    /// Optional human-facing machine description.
    pub description: Option<&'static str>,
    /// Optional longer-form source documentation from outer rustdoc comments.
    pub docs: Option<&'static str>,
    /// All states known to the machine.
    pub states: &'static [LinkedStateDescriptor],
    /// All transition sites known to the machine.
    pub transitions: LinkedTransitionInventory,
    /// Direct machine-like payload references written in state data.
    pub static_links: &'static [StaticMachineLinkDescriptor],
}

impl LinkedMachineGraph {
    /// Finds a state descriptor by Rust state name.
    pub fn state(&self, rust_name: &str) -> Option<&LinkedStateDescriptor> {
        self.states
            .iter()
            .find(|state| state.rust_name == rust_name)
    }

    /// Yields all transition sites originating from `state`.
    pub fn transitions_from(
        &self,
        state: &'static str,
    ) -> impl Iterator<Item = &LinkedTransitionDescriptor> + '_ {
        self.transitions
            .iter()
            .filter(move |transition| transition.from == state)
    }

    /// Finds the transition site for `method_name` on `state`.
    pub fn transition_from_method(
        &self,
        state: &'static str,
        method_name: &str,
    ) -> Option<&LinkedTransitionDescriptor> {
        self.transitions
            .iter()
            .find(|transition| transition.from == state && transition.method_name == method_name)
    }
}

/// Whether one machine family is a local protocol machine or a higher-level
/// composition machine.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MachineRole {
    /// Ordinary local protocol machine.
    Protocol,
    /// Higher-level machine that composes other machines or exact handoff
    /// evidence into one workspace flow.
    Composition,
}

/// Rust-facing identity for a machine family.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MachineDescriptor {
    /// `module_path!()` for the source module that owns the machine.
    pub module_path: &'static str,
    /// Fully qualified Rust type path for the machine family.
    pub rust_type_path: &'static str,
    /// Whether this machine is a protocol machine or a composition machine.
    pub role: MachineRole,
}

/// Static descriptor for one generated state id.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StateDescriptor<S: 'static> {
    /// Typed state identifier.
    pub id: S,
    /// Rust variant name of the state marker.
    pub rust_name: &'static str,
    /// Whether the state carries `state_data`.
    pub has_data: bool,
}

/// Erased state descriptor carried by the linked machine inventory.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LinkedStateDescriptor {
    /// Rust variant name of the state marker.
    pub rust_name: &'static str,
    /// Optional human-facing state label.
    pub label: Option<&'static str>,
    /// Optional human-facing state description.
    pub description: Option<&'static str>,
    /// Optional longer-form source documentation from outer rustdoc comments.
    pub docs: Option<&'static str>,
    /// Whether the state carries `state_data`.
    pub has_data: bool,
    /// Whether the machine exposes direct construction for this state.
    pub direct_construction_available: bool,
}

/// Static descriptor for one transition site.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TransitionDescriptor<S: 'static, T: 'static> {
    /// Typed transition-site identifier.
    pub id: T,
    /// Rust method name for the transition site.
    pub method_name: &'static str,
    /// Exact source state for the transition site.
    pub from: S,
    /// Exact legal target states for the transition site.
    pub to: &'static [S],
}

/// Erased transition descriptor carried by the linked machine inventory.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LinkedTransitionDescriptor {
    /// Rust method name for the transition site.
    pub method_name: &'static str,
    /// Optional human-facing transition label.
    pub label: Option<&'static str>,
    /// Optional human-facing transition description.
    pub description: Option<&'static str>,
    /// Optional longer-form source documentation from outer rustdoc comments.
    pub docs: Option<&'static str>,
    /// Exact source state for the transition site.
    pub from: &'static str,
    /// Exact legal target states for the transition site.
    pub to: &'static [&'static str],
}

/// One direct machine-like payload reference written in state data.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StaticMachineLinkDescriptor {
    /// Source state that carries the nested machine payload.
    pub from_state: &'static str,
    /// Field name for named payloads; `None` for tuple payloads.
    pub field_name: Option<&'static str>,
    /// Machine-path suffix segments written in the payload type.
    pub to_machine_path: &'static [&'static str],
    /// Target state marker name taken from the payload type's first generic.
    pub to_state: &'static str,
}

/// Exact relation kinds exported by the linked build.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkedRelationKind {
    /// A state payload type points at another machine state.
    StatePayload,
    /// A machine struct field type points at another machine state.
    MachineField,
    /// A transition parameter type points at another machine state.
    TransitionParam,
}

/// Why one exact relation was inferred.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkedRelationBasis {
    /// The target was visible directly in the scanned type syntax.
    DirectTypeSyntax,
    /// The target came from a canonical `statum::Attested<_, Route>` wrapper
    /// visible directly in the scanned type syntax.
    AttestedTypeSyntax,
    /// The scanned type resolved through one declared reference type.
    DeclaredReferenceType,
    /// The target was declared explicitly through `#[via(...)]`.
    ViaDeclaration,
}

/// Exact target written into one linked relation record.
#[derive(Clone, Copy, Debug)]
pub enum LinkedRelationTarget {
    /// A directly visible machine target written in the scanned type syntax.
    DirectMachine {
        /// Exact machine path segments resolved from the source type.
        machine_path: &'static [&'static str],
        /// Compiler-resolved concrete machine type identity. The codebase
        /// export strips the state generic and uses the remaining machine
        /// family path as the exact join key, even when the source syntax
        /// names a public re-export like `flows::task::Flow`.
        resolved_machine_type_name: fn() -> &'static str,
        /// Target state marker name.
        state: &'static str,
    },
    /// A nominal reference type that must resolve through one declaration.
    DeclaredReferenceType {
        /// Compiler-resolved type identity getter for the named reference type.
        resolved_type_name: fn() -> &'static str,
    },
    /// One exact producer route carried through a canonical
    /// `statum::Attested<_, Route>` wrapper or declared through `#[via(...)]`
    /// without a direct machine target at the consumer site.
    AttestedProducerRoute {
        /// Machine module path that owns the attested route namespace.
        via_module_path: &'static str,
        /// Human-facing attested route name, such as `Capture`.
        route_name: &'static str,
        /// Compiler-resolved route marker type identity. This is the exact join
        /// key across producer registrations and consumer declarations, even
        /// when the consumer names a public re-export path.
        resolved_route_type_name: fn() -> &'static str,
        /// Stable route id used to join consumer declarations with producer
        /// attested transition metadata.
        route_id: u64,
    },
    /// An attested route declared through `#[via(...)]`.
    AttestedRoute {
        /// Machine module path that owns the attested route namespace.
        via_module_path: &'static str,
        /// Human-facing attested route name, such as `Capture`.
        route_name: &'static str,
        /// Compiler-resolved route marker type identity. This is the exact
        /// join key across producer registrations and consumer declarations,
        /// even when the consumer names a public re-export path.
        resolved_route_type_name: fn() -> &'static str,
        /// Stable route id used to join consumer declarations with producer
        /// attested transition metadata.
        route_id: u64,
        /// Exact target machine path segments carried by the attested inner
        /// machine type.
        machine_path: &'static [&'static str],
        /// Compiler-resolved concrete target machine type identity for the
        /// attested inner machine. The codebase export strips the state
        /// generic and uses the remaining machine family path as the exact
        /// join key.
        resolved_machine_type_name: fn() -> &'static str,
        /// Target state marker name carried by the attested inner machine type.
        state: &'static str,
    },
}

impl PartialEq for LinkedRelationTarget {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::DirectMachine {
                    machine_path: left_machine_path,
                    resolved_machine_type_name: left_type_name,
                    state: left_state,
                },
                Self::DirectMachine {
                    machine_path: right_machine_path,
                    resolved_machine_type_name: right_type_name,
                    state: right_state,
                },
            ) => {
                left_machine_path == right_machine_path
                    && left_type_name() == right_type_name()
                    && left_state == right_state
            }
            (
                Self::DeclaredReferenceType {
                    resolved_type_name: left_name,
                },
                Self::DeclaredReferenceType {
                    resolved_type_name: right_name,
                },
            ) => left_name() == right_name(),
            (
                Self::AttestedProducerRoute {
                    via_module_path: left_module_path,
                    route_name: left_route_name,
                    resolved_route_type_name: left_type_name,
                    route_id: left_route_id,
                },
                Self::AttestedProducerRoute {
                    via_module_path: right_module_path,
                    route_name: right_route_name,
                    resolved_route_type_name: right_type_name,
                    route_id: right_route_id,
                },
            ) => {
                left_module_path == right_module_path
                    && left_route_name == right_route_name
                    && left_type_name() == right_type_name()
                    && left_route_id == right_route_id
            }
            (
                Self::AttestedRoute {
                    via_module_path: left_module_path,
                    route_name: left_route_name,
                    resolved_route_type_name: left_type_name,
                    route_id: left_route_id,
                    machine_path: left_machine_path,
                    resolved_machine_type_name: left_machine_type_name,
                    state: left_state,
                },
                Self::AttestedRoute {
                    via_module_path: right_module_path,
                    route_name: right_route_name,
                    resolved_route_type_name: right_type_name,
                    route_id: right_route_id,
                    machine_path: right_machine_path,
                    resolved_machine_type_name: right_machine_type_name,
                    state: right_state,
                },
            ) => {
                left_module_path == right_module_path
                    && left_route_name == right_route_name
                    && left_type_name() == right_type_name()
                    && left_route_id == right_route_id
                    && left_machine_path == right_machine_path
                    && left_machine_type_name() == right_machine_type_name()
                    && left_state == right_state
            }
            _ => false,
        }
    }
}

impl Eq for LinkedRelationTarget {}

/// One exact relation source exported by the linked build.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkedRelationSource {
    /// A state payload type produced the relation.
    StatePayload {
        /// Source state that carries the relation.
        state: &'static str,
        /// Named field for named payloads; `None` for tuple payloads.
        field_name: Option<&'static str>,
    },
    /// A machine struct field produced the relation.
    MachineField {
        /// Named field for named structs; `None` for tuple structs.
        field_name: Option<&'static str>,
        /// Stable field position within the machine struct.
        field_index: usize,
    },
    /// One transition parameter produced the relation.
    TransitionParam {
        /// Source state where the transition is defined.
        state: &'static str,
        /// Transition method name.
        transition: &'static str,
        /// Stable non-receiver parameter index.
        param_index: usize,
        /// Simple identifier name when available.
        param_name: Option<&'static str>,
    },
}

/// One exact machine relation carried by the linked build inventory.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LinkedRelationDescriptor {
    /// Rust-facing identity of the source machine family.
    pub machine: MachineDescriptor,
    /// Exact relation kind.
    pub kind: LinkedRelationKind,
    /// Exact relation source.
    pub source: LinkedRelationSource,
    /// Why Statum considered this relation exact.
    pub basis: LinkedRelationBasis,
    /// Exact relation target.
    pub target: LinkedRelationTarget,
}

/// One producer transition that can generate an attested route value.
#[derive(Clone, Copy, Debug)]
pub struct LinkedViaRouteDescriptor {
    /// Rust-facing identity of the producer machine family.
    pub machine: MachineDescriptor,
    /// Machine-module path that owns the generated `machine::via` namespace.
    pub via_module_path: &'static str,
    /// Human-facing route name, such as `Capture`.
    pub route_name: &'static str,
    /// Compiler-resolved route marker type identity used to join producer
    /// inventories with consumer `#[via(...)]` declarations.
    pub resolved_route_type_name: fn() -> &'static str,
    /// Stable route id shared with `LinkedRelationTarget::AttestedRoute`.
    pub route_id: u64,
    /// Rust transition method name on the producer machine.
    pub transition: &'static str,
    /// Exact producer source state.
    pub source_state: &'static str,
    /// Exact producer target state.
    pub target_state: &'static str,
}

impl PartialEq for LinkedViaRouteDescriptor {
    fn eq(&self, other: &Self) -> bool {
        self.machine == other.machine
            && self.via_module_path == other.via_module_path
            && self.route_name == other.route_name
            && (self.resolved_route_type_name)() == (other.resolved_route_type_name)()
            && self.route_id == other.route_id
            && self.transition == other.transition
            && self.source_state == other.source_state
            && self.target_state == other.target_state
    }
}

impl Eq for LinkedViaRouteDescriptor {}

/// One declared reference type carried by the linked build inventory.
#[derive(Clone, Copy, Debug)]
pub struct LinkedReferenceTypeDescriptor {
    /// Human-facing Rust path of the declared reference type.
    pub rust_type_path: &'static str,
    /// Compiler-resolved type identity getter for the declared reference type.
    pub resolved_type_name: fn() -> &'static str,
    /// Exact machine path segments resolved from the declaration target.
    pub to_machine_path: &'static [&'static str],
    /// Compiler-resolved concrete machine type identity for the declared
    /// target machine.
    pub resolved_target_machine_type_name: fn() -> &'static str,
    /// Target state marker name written in the declaration.
    pub to_state: &'static str,
}

impl PartialEq for LinkedReferenceTypeDescriptor {
    fn eq(&self, other: &Self) -> bool {
        self.rust_type_path == other.rust_type_path
            && (self.resolved_type_name)() == (other.resolved_type_name)()
            && self.to_machine_path == other.to_machine_path
            && (self.resolved_target_machine_type_name)()
                == (other.resolved_target_machine_type_name)()
            && self.to_state == other.to_state
    }
}

impl Eq for LinkedReferenceTypeDescriptor {}


/// One declared validator-entry surface carried by the linked build inventory.
#[derive(Clone, Copy, Debug)]
pub struct LinkedValidatorEntryDescriptor {
    /// Rust-facing identity of the rebuilt machine family.
    pub machine: MachineDescriptor,
    /// `module_path!()` for the module that owns the `#[validators]` impl.
    pub source_module_path: &'static str,
    /// Human-facing source syntax for the persisted impl self type as written.
    pub source_type_display: &'static str,
    /// Compiler-resolved source type identity for this validator impl.
    pub resolved_source_type_name: fn() -> &'static str,
    /// Optional longer-form source documentation from outer rustdoc comments.
    pub docs: Option<&'static str>,
    /// State marker names this `#[validators]` impl can rebuild when it matches.
    pub target_states: &'static [&'static str],
}

impl PartialEq for LinkedValidatorEntryDescriptor {
    fn eq(&self, other: &Self) -> bool {
        self.machine == other.machine
            && self.source_module_path == other.source_module_path
            && self.source_type_display == other.source_type_display
            && (self.resolved_source_type_name)() == (other.resolved_source_type_name)()
            && self.docs == other.docs
            && self.target_states == other.target_states
    }
}

impl Eq for LinkedValidatorEntryDescriptor {}

#[cfg(test)]
mod tests {
    use super::{
        LinkedMachineGraph, LinkedStateDescriptor, LinkedTransitionDescriptor,
        LinkedTransitionInventory, LinkedValidatorEntryDescriptor, MachineDescriptor, MachineGraph,
        MachineIntrospection, MachinePresentation, MachinePresentationDescriptor, MachineRole,
        MachineStateIdentity, MachineTransitionRecorder, RecordedTransition, StateDescriptor,
        StatePresentation, StaticMachineLinkDescriptor, TransitionDescriptor, TransitionInventory,
        TransitionPresentation, TransitionPresentationInventory,
    };
    use core::marker::PhantomData;

    #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
    enum StateId {
        Draft,
        Review,
        Published,
    }

    #[derive(Clone, Copy)]
    struct TransitionId(&'static crate::__private::TransitionToken);

    impl TransitionId {
        const fn from_token(token: &'static crate::__private::TransitionToken) -> Self {
            Self(token)
        }
    }

    impl core::fmt::Debug for TransitionId {
        fn fmt(
            &self,
            formatter: &mut core::fmt::Formatter<'_>,
        ) -> core::result::Result<(), core::fmt::Error> {
            formatter.write_str("TransitionId(..)")
        }
    }

    impl core::cmp::PartialEq for TransitionId {
        fn eq(&self, other: &Self) -> bool {
            core::ptr::eq(self.0, other.0)
        }
    }

    impl core::cmp::Eq for TransitionId {}

    impl core::hash::Hash for TransitionId {
        fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
            let ptr = core::ptr::from_ref(self.0) as usize;
            <usize as core::hash::Hash>::hash(&ptr, state);
        }
    }

    static REVIEW_TARGETS: [StateId; 1] = [StateId::Review];
    static PUBLISH_TARGETS: [StateId; 1] = [StateId::Published];
    static SUBMIT_FROM_DRAFT_TOKEN: crate::__private::TransitionToken =
        crate::__private::TransitionToken::new();
    static PUBLISH_FROM_REVIEW_TOKEN: crate::__private::TransitionToken =
        crate::__private::TransitionToken::new();
    const SUBMIT_FROM_DRAFT: TransitionId = TransitionId::from_token(&SUBMIT_FROM_DRAFT_TOKEN);
    const PUBLISH_FROM_REVIEW: TransitionId = TransitionId::from_token(&PUBLISH_FROM_REVIEW_TOKEN);
    static STATES: [StateDescriptor<StateId>; 3] = [
        StateDescriptor {
            id: StateId::Draft,
            rust_name: "Draft",
            has_data: false,
        },
        StateDescriptor {
            id: StateId::Review,
            rust_name: "Review",
            has_data: true,
        },
        StateDescriptor {
            id: StateId::Published,
            rust_name: "Published",
            has_data: false,
        },
    ];
    static TRANSITIONS: [TransitionDescriptor<StateId, TransitionId>; 2] = [
        TransitionDescriptor {
            id: SUBMIT_FROM_DRAFT,
            method_name: "submit",
            from: StateId::Draft,
            to: &REVIEW_TARGETS,
        },
        TransitionDescriptor {
            id: PUBLISH_FROM_REVIEW,
            method_name: "publish",
            from: StateId::Review,
            to: &PUBLISH_TARGETS,
        },
    ];
    static TRANSITION_PRESENTATIONS: [TransitionPresentation<TransitionId, TransitionMeta>; 2] = [
        TransitionPresentation {
            id: SUBMIT_FROM_DRAFT,
            label: Some("Submit"),
            description: Some("Move work into review."),
            metadata: TransitionMeta {
                phase: Phase::Review,
                branch: false,
            },
        },
        TransitionPresentation {
            id: PUBLISH_FROM_REVIEW,
            label: Some("Publish"),
            description: Some("Complete the workflow."),
            metadata: TransitionMeta {
                phase: Phase::Output,
                branch: false,
            },
        },
    ];

    struct Workflow<S>(PhantomData<S>);
    struct DraftMarker;
    struct ReviewMarker;
    struct PublishedMarker;

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Phase {
        Intake,
        Review,
        Output,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct MachineMeta {
        phase: Phase,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct StateMeta {
        phase: Phase,
        term: &'static str,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct TransitionMeta {
        phase: Phase,
        branch: bool,
    }

    static PRESENTATION: MachinePresentation<
        StateId,
        TransitionId,
        MachineMeta,
        StateMeta,
        TransitionMeta,
    > = MachinePresentation {
        machine: Some(MachinePresentationDescriptor {
            label: Some("Workflow"),
            description: Some("Example presentation metadata for introspection."),
            metadata: MachineMeta {
                phase: Phase::Intake,
            },
        }),
        states: &[
            StatePresentation {
                id: StateId::Draft,
                label: Some("Draft"),
                description: Some("Work has not been submitted yet."),
                metadata: StateMeta {
                    phase: Phase::Intake,
                    term: "draft",
                },
            },
            StatePresentation {
                id: StateId::Review,
                label: Some("Review"),
                description: Some("Work is awaiting review."),
                metadata: StateMeta {
                    phase: Phase::Review,
                    term: "review",
                },
            },
            StatePresentation {
                id: StateId::Published,
                label: Some("Published"),
                description: Some("Work is complete."),
                metadata: StateMeta {
                    phase: Phase::Output,
                    term: "published",
                },
            },
        ],
        transitions: TransitionPresentationInventory::new(|| &TRANSITION_PRESENTATIONS),
    };

    impl<S> MachineIntrospection for Workflow<S> {
        type StateId = StateId;
        type TransitionId = TransitionId;

        const GRAPH: &'static MachineGraph<Self::StateId, Self::TransitionId> = &MachineGraph {
            machine: MachineDescriptor {
                module_path: "workflow",
                rust_type_path: "workflow::Machine",
                role: MachineRole::Protocol,
            },
            states: &STATES,
            transitions: TransitionInventory::new(|| &TRANSITIONS),
        };
    }

    impl MachineStateIdentity for Workflow<DraftMarker> {
        const STATE_ID: Self::StateId = StateId::Draft;
    }

    impl MachineStateIdentity for Workflow<ReviewMarker> {
        const STATE_ID: Self::StateId = StateId::Review;
    }

    impl MachineStateIdentity for Workflow<PublishedMarker> {
        const STATE_ID: Self::StateId = StateId::Published;
    }

    #[test]
    fn query_helpers_find_expected_items() {
        let graph = MachineGraph {
            machine: MachineDescriptor {
                module_path: "workflow",
                rust_type_path: "workflow::Machine",
                role: MachineRole::Protocol,
            },
            states: &STATES,
            transitions: TransitionInventory::new(|| &TRANSITIONS),
        };

        assert_eq!(
            graph.state(StateId::Review).map(|state| state.rust_name),
            Some("Review")
        );
        assert_eq!(
            graph
                .transition(PUBLISH_FROM_REVIEW)
                .map(|transition| transition.method_name),
            Some("publish")
        );
        assert_eq!(
            graph
                .transition_from_method(StateId::Draft, "submit")
                .map(|transition| transition.id),
            Some(SUBMIT_FROM_DRAFT)
        );
        assert_eq!(
            graph.legal_targets(SUBMIT_FROM_DRAFT),
            Some(REVIEW_TARGETS.as_slice())
        );
        assert_eq!(graph.transitions_from(StateId::Draft).count(), 1);
        assert_eq!(graph.transitions_named("publish").count(), 1);
    }

    #[test]
    fn runtime_transition_recording_joins_back_to_static_graph() {
        let event = Workflow::<DraftMarker>::try_record_transition_to::<Workflow<ReviewMarker>>(
            SUBMIT_FROM_DRAFT,
        )
        .expect("valid runtime transition");

        assert_eq!(
            event,
            RecordedTransition::new(
                MachineDescriptor {
                    module_path: "workflow",
                    rust_type_path: "workflow::Machine",
                    role: MachineRole::Protocol,
                },
                StateId::Draft,
                SUBMIT_FROM_DRAFT,
                StateId::Review,
            )
        );
        assert_eq!(
            Workflow::<DraftMarker>::GRAPH
                .transition(event.transition)
                .map(|transition| (transition.from, transition.to)),
            Some((StateId::Draft, REVIEW_TARGETS.as_slice()))
        );
        assert_eq!(
            event.source_state_in(Workflow::<DraftMarker>::GRAPH),
            Some(&StateDescriptor {
                id: StateId::Draft,
                rust_name: "Draft",
                has_data: false,
            })
        );
    }

    #[test]
    fn runtime_transition_recording_rejects_illegal_target_or_site() {
        assert!(Workflow::<DraftMarker>::try_record_transition(
            PUBLISH_FROM_REVIEW,
            StateId::Published,
        )
        .is_none());
        assert!(
            Workflow::<ReviewMarker>::try_record_transition_to::<Workflow<PublishedMarker>>(
                SUBMIT_FROM_DRAFT,
            )
            .is_none()
        );
    }

    #[test]
    fn presentation_queries_join_with_runtime_transitions() {
        let event = Workflow::<DraftMarker>::try_record_transition_to::<Workflow<ReviewMarker>>(
            SUBMIT_FROM_DRAFT,
        )
        .expect("valid runtime transition");

        assert_eq!(
            PRESENTATION.machine,
            Some(MachinePresentationDescriptor {
                label: Some("Workflow"),
                description: Some("Example presentation metadata for introspection."),
                metadata: MachineMeta {
                    phase: Phase::Intake,
                },
            })
        );
        assert_eq!(
            PRESENTATION.transition(event.transition),
            Some(&TransitionPresentation {
                id: SUBMIT_FROM_DRAFT,
                label: Some("Submit"),
                description: Some("Move work into review."),
                metadata: TransitionMeta {
                    phase: Phase::Review,
                    branch: false,
                },
            })
        );
        assert_eq!(
            PRESENTATION.state(event.chosen),
            Some(&StatePresentation {
                id: StateId::Review,
                label: Some("Review"),
                description: Some("Work is awaiting review."),
                metadata: StateMeta {
                    phase: Phase::Review,
                    term: "review",
                },
            })
        );
    }

    fn linked_transitions() -> &'static [LinkedTransitionDescriptor] {
        static TRANSITIONS: [LinkedTransitionDescriptor; 1] = [LinkedTransitionDescriptor {
            method_name: "submit",
            label: Some("Submit"),
            description: None,
            docs: Some("Submits the draft for review."),
            from: "Draft",
            to: &["Review"],
        }];
        &TRANSITIONS
    }

    #[test]
    fn linked_machine_graph_helpers_work() {
        static STATES: [LinkedStateDescriptor; 2] = [
            LinkedStateDescriptor {
                rust_name: "Draft",
                label: None,
                description: None,
                docs: Some("Initial draft state."),
                has_data: false,
                direct_construction_available: true,
            },
            LinkedStateDescriptor {
                rust_name: "Review",
                label: Some("Review"),
                description: None,
                docs: Some("Review state with payload."),
                has_data: true,
                direct_construction_available: true,
            },
        ];
        static LINKS: [StaticMachineLinkDescriptor; 1] = [StaticMachineLinkDescriptor {
            from_state: "Review",
            field_name: None,
            to_machine_path: &["task", "Machine"],
            to_state: "Running",
        }];

        let linked = LinkedMachineGraph {
            machine: MachineDescriptor {
                module_path: "workflow",
                rust_type_path: "workflow::Machine",
                role: MachineRole::Protocol,
            },
            label: Some("Workflow"),
            description: None,
            docs: Some("Workflow machine docs."),
            states: &STATES,
            transitions: LinkedTransitionInventory::new(linked_transitions),
            static_links: &LINKS,
        };

        assert_eq!(linked.state("Review"), Some(&STATES[1]));
        assert_eq!(linked.docs, Some("Workflow machine docs."));
        assert_eq!(
            linked.state("Draft").and_then(|state| state.docs),
            Some("Initial draft state.")
        );
        assert_eq!(
            linked.transition_from_method("Draft", "submit"),
            Some(&linked_transitions()[0])
        );
        assert_eq!(
            linked_transitions()[0].docs,
            Some("Submits the draft for review.")
        );
        assert_eq!(linked.transitions_from("Draft").count(), 1);
        assert_eq!(linked.static_links, &LINKS);
    }

    #[test]
    fn linked_validator_entry_descriptor_exposes_declared_surface() {
        fn db_row_type_name() -> &'static str {
            "workflow::rows::DbRow"
        }

        static ENTRY: LinkedValidatorEntryDescriptor = LinkedValidatorEntryDescriptor {
            machine: MachineDescriptor {
                module_path: "workflow",
                rust_type_path: "workflow::Machine",
                role: MachineRole::Protocol,
            },
            source_module_path: "workflow::rows",
            source_type_display: "DbRow",
            resolved_source_type_name: db_row_type_name,
            docs: Some("Rebuilds workflow machines from database rows."),
            target_states: &["Draft", "Review"],
        };

        assert_eq!(ENTRY.machine.rust_type_path, "workflow::Machine");
        assert_eq!(ENTRY.source_module_path, "workflow::rows");
        assert_eq!(ENTRY.source_type_display, "DbRow");
        assert_eq!((ENTRY.resolved_source_type_name)(), "workflow::rows::DbRow");
        assert_eq!(
            ENTRY.docs,
            Some("Rebuilds workflow machines from database rows.")
        );
        assert_eq!(ENTRY.target_states, &["Draft", "Review"]);
    }
}