rvoip-sip 0.2.1

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
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
//! YAML-based state table loader for session coordination
//!
//! This module loads state tables from YAML files, focusing on coordination
//! between dialog-core and media-core layers without duplicating their logic.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;
use tracing::{debug, info};

use super::{
    Action, Condition, ConditionUpdates, EventTemplate, EventType, Guard, Role, SessionId,
    StateKey, StateTable, StateTableBuilder, Transition,
};
use crate::errors::{Result, SessionError};
use crate::types::{CallState, FailureReason};

/// YAML representation of the complete state table
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YamlStateTable {
    /// Version of the state table format
    pub version: String,

    /// Metadata about the state table
    #[serde(default)]
    pub metadata: YamlMetadata,

    /// List of valid states
    #[serde(default)]
    pub states: Vec<YamlStateDefinition>,

    /// List of coordination conditions
    #[serde(default)]
    pub conditions: Vec<YamlConditionDefinition>,

    /// List of state transitions
    pub transitions: Vec<YamlTransition>,
}

/// Metadata about the state table
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct YamlMetadata {
    /// Description of the state table's purpose
    #[serde(default)]
    pub description: String,

    /// Author of the state table
    #[serde(default)]
    pub author: String,

    /// Date of last modification
    #[serde(default)]
    pub date: String,
}

/// Definition of a state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YamlStateDefinition {
    /// Name of the state
    pub name: String,

    /// Description of what this state represents
    #[serde(default)]
    pub description: String,
}

/// Definition of a coordination condition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YamlConditionDefinition {
    /// Name of the condition
    pub name: String,

    /// Description of what this condition tracks
    #[serde(default)]
    pub description: String,

    /// Default value
    #[serde(default)]
    pub default: bool,
}

/// YAML representation of a single transition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct YamlTransition {
    /// Role this transition applies to (UAC, UAS, or Both)
    pub role: String,

    /// Current state
    pub state: String,

    /// Event that triggers this transition
    pub event: YamlEvent,

    /// Guards that must be satisfied
    #[serde(default)]
    pub guards: Vec<YamlGuard>,

    /// Actions to execute
    #[serde(default)]
    pub actions: Vec<YamlAction>,

    /// Next state to transition to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_state: Option<String>,

    /// Condition updates to apply
    #[serde(default, skip_serializing_if = "YamlConditionUpdates::is_empty")]
    pub conditions: YamlConditionUpdates,

    /// Events to publish
    #[serde(default)]
    pub publish: Vec<String>,

    /// Description of this transition
    #[serde(default)]
    pub description: String,
}

/// YAML representation of an event
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum YamlEvent {
    /// Simple event (just a string)
    Simple(String),

    /// Complex event with type and parameters
    Complex {
        #[serde(rename = "type")]
        event_type: String,

        #[serde(flatten)]
        parameters: HashMap<String, serde_yaml::Value>,
    },
}

/// YAML representation of a guard condition
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum YamlGuard {
    /// Simple guard (just a string)
    Simple(String),

    /// Complex guard with parameters
    Complex {
        #[serde(rename = "type")]
        guard_type: String,

        #[serde(flatten)]
        parameters: HashMap<String, serde_yaml::Value>,
    },
}

/// YAML representation of an action
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum YamlAction {
    /// Simple action (just a string)
    Simple(String),

    /// Complex action with parameters
    Complex {
        #[serde(rename = "type")]
        action_type: String,

        #[serde(flatten)]
        parameters: HashMap<String, serde_yaml::Value>,
    },
}

/// YAML representation of condition updates
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct YamlConditionUpdates {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dialog_established: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_session_ready: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub sdp_negotiated: Option<bool>,
}

impl YamlConditionUpdates {
    fn is_empty(&self) -> bool {
        self.dialog_established.is_none()
            && self.media_session_ready.is_none()
            && self.sdp_negotiated.is_none()
    }
}

/// Default state table embedded in the binary
const DEFAULT_STATE_TABLE_YAML: &str = include_str!("../../state_tables/default.yaml");

/// YAML table loader
pub struct YamlTableLoader {
    /// Builder for constructing the state table
    builder: StateTableBuilder,

    /// Loaded YAML data
    yaml_data: Option<YamlStateTable>,
}

impl YamlTableLoader {
    /// Create a new YAML table loader
    pub fn new() -> Self {
        Self {
            builder: StateTableBuilder::new(),
            yaml_data: None,
        }
    }

    /// Load the default embedded state table
    pub fn load_default() -> Result<StateTable> {
        Self::load_embedded_default()
    }

    /// Load the embedded default state table (always succeeds)
    pub fn load_embedded_default() -> Result<StateTable> {
        let mut loader = Self::new();
        loader
            .load_from_string(DEFAULT_STATE_TABLE_YAML)
            .expect("Embedded default state table must be valid");
        loader.build()
    }

    /// Load state table from a file
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<StateTable> {
        let mut loader = Self::new();

        let yaml_content = fs::read_to_string(path.as_ref())
            .map_err(|e| SessionError::InternalError(format!("Failed to read YAML file: {}", e)))?;

        loader.load_from_string(&yaml_content)?;
        loader.build()
    }

    /// Load state table from a string
    pub fn load_from_string(&mut self, yaml_content: &str) -> Result<()> {
        Self::validate_raw_yaml_content(yaml_content)?;

        let yaml_data: YamlStateTable = serde_yaml::from_str(yaml_content)
            .map_err(|e| SessionError::InternalError(format!("Failed to parse YAML: {}", e)))?;

        // Validate version - accept both 1.x and 2.x versions
        if !yaml_data.version.starts_with("1.") && !yaml_data.version.starts_with("2.") {
            return Err(SessionError::InternalError(format!(
                "Unsupported state table version: {} (expected 1.x or 2.x)",
                yaml_data.version
            )));
        }

        info!(
            "Loaded state table version {} with {} transitions",
            yaml_data.version,
            yaml_data.transitions.len()
        );

        self.yaml_data = Some(yaml_data);
        Ok(())
    }

    /// Merge another YAML file into the current table
    pub fn merge_file<P: AsRef<Path>>(&mut self, path: P) -> Result<&mut Self> {
        let yaml_content = fs::read_to_string(path.as_ref()).map_err(|e| {
            SessionError::InternalError(format!("Failed to read YAML file for merge: {}", e))
        })?;

        self.merge_string(&yaml_content)?;
        Ok(self)
    }

    /// Merge YAML content into the current table
    pub fn merge_string(&mut self, yaml_content: &str) -> Result<()> {
        Self::validate_raw_yaml_content(yaml_content)?;

        let merge_data: YamlStateTable = serde_yaml::from_str(yaml_content).map_err(|e| {
            SessionError::InternalError(format!("Failed to parse YAML for merge: {}", e))
        })?;

        if let Some(ref mut yaml_data) = self.yaml_data {
            let num_transitions = merge_data.transitions.len();
            // Merge transitions
            yaml_data.transitions.extend(merge_data.transitions);

            // Merge states (avoiding duplicates)
            for state in merge_data.states {
                if !yaml_data.states.iter().any(|s| s.name == state.name) {
                    yaml_data.states.push(state);
                }
            }

            // Merge conditions (avoiding duplicates)
            for condition in merge_data.conditions {
                if !yaml_data
                    .conditions
                    .iter()
                    .any(|c| c.name == condition.name)
                {
                    yaml_data.conditions.push(condition);
                }
            }

            info!("Merged {} transitions into state table", num_transitions);
        } else {
            self.yaml_data = Some(merge_data);
        }

        Ok(())
    }

    /// Build the final state table from loaded YAML
    pub fn build(mut self) -> Result<StateTable> {
        let yaml_data = self
            .yaml_data
            .take()
            .ok_or_else(|| SessionError::InternalError("No YAML data loaded".to_string()))?;

        self.validate_yaml_data(&yaml_data)?;

        // Process each transition
        for yaml_transition in yaml_data.transitions {
            match self.convert_transition(yaml_transition) {
                Ok((key, transition)) => {
                    // Normal transition
                    self.builder.add_raw_transition(key, transition);
                }
                Err(SessionError::InternalError(msg))
                    if msg.starts_with("WILDCARD_TRANSITION:") =>
                {
                    // Parse wildcard transition data
                    let parts: Vec<&str> = msg
                        .strip_prefix("WILDCARD_TRANSITION:")
                        .unwrap()
                        .split(':')
                        .collect();
                    if parts.len() == 3 {
                        // Deserialize the components
                        if let (Ok(role), Ok(event), Ok(transition)) = (
                            serde_json::from_str::<Role>(parts[0]),
                            serde_json::from_str::<EventType>(parts[1]),
                            serde_json::from_str::<Transition>(parts[2]),
                        ) {
                            // Add wildcard transition
                            self.builder
                                .add_wildcard_transition(role, event, transition);
                        } else {
                            tracing::warn!("Failed to parse wildcard transition data");
                        }
                    }
                }
                Err(e) => return Err(e),
            }
        }

        Ok(self.builder.build())
    }

    fn validation_error(errors: Vec<String>) -> SessionError {
        SessionError::InternalError(format!(
            "State table YAML validation failed:\n- {}",
            errors.join("\n- ")
        ))
    }

    fn validate_raw_yaml_content(yaml_content: &str) -> Result<()> {
        let raw: serde_yaml::Value = serde_yaml::from_str(yaml_content)
            .map_err(|e| SessionError::InternalError(format!("Failed to parse YAML: {}", e)))?;

        let mut errors = Vec::new();
        let allowed_condition_updates: HashSet<&str> = [
            "dialog_established",
            "media_session_ready",
            "sdp_negotiated",
        ]
        .into_iter()
        .collect();

        let transitions = raw.get("transitions").and_then(|value| value.as_sequence());

        if let Some(transitions) = transitions {
            for (index, transition) in transitions.iter().enumerate() {
                let Some(mapping) = transition.as_mapping() else {
                    errors.push(format!("transition #{} is not a mapping", index + 1));
                    continue;
                };

                let Some(conditions) = mapping
                    .get(&serde_yaml::Value::String("conditions".to_string()))
                    .and_then(|value| value.as_mapping())
                else {
                    continue;
                };

                for key in conditions.keys() {
                    let Some(key) = key.as_str() else {
                        errors.push(format!(
                            "transition #{} has a non-string condition update key",
                            index + 1
                        ));
                        continue;
                    };

                    if !allowed_condition_updates.contains(key) {
                        errors.push(format!(
                            "transition #{} uses unsupported condition update '{}'",
                            index + 1,
                            key
                        ));
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Self::validation_error(errors))
        }
    }

    fn validate_yaml_data(&self, yaml_data: &YamlStateTable) -> Result<()> {
        let mut errors = Vec::new();
        let mut seen_transitions: HashMap<(Role, String, String), usize> = HashMap::new();

        let declared_states: HashSet<String> = yaml_data
            .states
            .iter()
            .map(|state| state.name.clone())
            .collect();
        let should_validate_declared_states = !declared_states.is_empty();

        for (index, transition) in yaml_data.transitions.iter().enumerate() {
            let line_hint = format!("transition #{}", index + 1);
            let role = match transition.role.to_lowercase().as_str() {
                "uac" => Role::UAC,
                "uas" | "server" => Role::UAS,
                "both" => Role::Both,
                _ => {
                    errors.push(format!(
                        "{} has invalid role '{}'",
                        line_hint, transition.role
                    ));
                    continue;
                }
            };

            if should_validate_declared_states {
                for (field, state) in [
                    ("state", Some(transition.state.as_str())),
                    ("next_state", transition.next_state.as_deref()),
                ] {
                    let Some(state) = state else { continue };
                    if state == "Any" || state == "*" {
                        continue;
                    }
                    if !declared_states.contains(state) {
                        errors.push(format!(
                            "{} references undeclared {} '{}'",
                            line_hint, field, state
                        ));
                    }
                }
            }

            let event = match self.parse_event(transition.event.clone()) {
                Ok(event) => event.normalize(),
                Err(err) => {
                    errors.push(format!("{} has invalid event: {}", line_hint, err));
                    continue;
                }
            };
            let event_key = format!("{:?}", event);
            let key = (role, transition.state.clone(), event_key.clone());
            if let Some(previous) = seen_transitions.insert(key, index + 1) {
                errors.push(format!(
                    "{} duplicates transition #{} for role={:?}, state={}, event={}",
                    line_hint, previous, role, transition.state, event_key
                ));
            }

            for action in &transition.actions {
                if let Err(err) = self.parse_action(action.clone()) {
                    errors.push(format!("{} has invalid action: {}", line_hint, err));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Self::validation_error(errors))
        }
    }

    /// Convert a YAML transition to internal format
    /// Returns a special error for wildcard transitions
    fn convert_transition(&self, yaml: YamlTransition) -> Result<(StateKey, Transition)> {
        // Convert role
        let role = match yaml.role.to_lowercase().as_str() {
            "uac" => Role::UAC,
            "uas" => Role::UAS,
            "both" => Role::Both,
            "server" => Role::UAS, // Accept Server as alias for UAS
            _ => {
                return Err(SessionError::InternalError(format!(
                    "Invalid role: {}",
                    yaml.role
                )))
            }
        };

        // Check if this is a wildcard state
        let is_wildcard = yaml.state == "Any" || yaml.state == "*";

        // Convert state (use Idle as placeholder for wildcards)
        let state = if is_wildcard {
            CallState::Idle // Placeholder, won't be used
        } else {
            self.parse_call_state(&yaml.state)?
        };

        // Convert event
        let event = self.parse_event(yaml.event)?;

        // Create state key
        let key = StateKey {
            role,
            state,
            event: event.clone(),
        };

        // Convert guards
        let guards = yaml
            .guards
            .into_iter()
            .map(|g| self.parse_guard(g))
            .collect::<Result<Vec<_>>>()?;

        // Convert actions
        let actions = yaml
            .actions
            .into_iter()
            .map(|a| self.parse_action(a))
            .collect::<Result<Vec<_>>>()?;

        // Convert next state
        let next_state = yaml
            .next_state
            .map(|s| self.parse_call_state(&s))
            .transpose()?;

        // Convert condition updates
        let condition_updates = ConditionUpdates {
            dialog_established: yaml.conditions.dialog_established,
            media_session_ready: yaml.conditions.media_session_ready,
            sdp_negotiated: yaml.conditions.sdp_negotiated,
        };

        // Convert publish events
        let publish_events = yaml
            .publish
            .into_iter()
            .map(|e| self.parse_event_template(&e))
            .collect::<Result<Vec<_>>>()?;

        // Create transition
        let transition = Transition {
            guards,
            actions,
            next_state,
            condition_updates,
            publish_events,
        };

        // If this is a wildcard, return a special error that includes the transition data
        if is_wildcard {
            // We'll use a special error to signal wildcard transitions
            return Err(SessionError::InternalError(format!(
                "WILDCARD_TRANSITION:{}:{}:{}",
                serde_json::to_string(&role).unwrap_or_default(),
                serde_json::to_string(&event).unwrap_or_default(),
                serde_json::to_string(&transition).unwrap_or_default()
            )));
        }

        Ok((key, transition))
    }

    /// Parse a call state from string
    fn parse_call_state(&self, state: &str) -> Result<CallState> {
        match state {
            "Idle" => Ok(CallState::Idle),
            "Initiating" => Ok(CallState::Initiating),
            "CancelPending" => Ok(CallState::CancelPending),
            "Cancelling" => Ok(CallState::Cancelling),
            "Ringing" => Ok(CallState::Ringing),
            "Answering" => Ok(CallState::Answering),
            "AnsweringHangupPending" => Ok(CallState::AnsweringHangupPending),
            "EarlyMedia" => Ok(CallState::EarlyMedia),
            "Active" => Ok(CallState::Active),
            "HoldPending" => Ok(CallState::HoldPending),
            "OnHold" => Ok(CallState::OnHold),
            "Resuming" => Ok(CallState::Resuming),
            "Bridged" => Ok(CallState::Bridged),
            "Transferring" => Ok(CallState::Transferring),
            "TransferringCall" => Ok(CallState::TransferringCall),
            "Terminating" => Ok(CallState::Terminating),
            "Terminated" => Ok(CallState::Terminated),
            "Muted" => Ok(CallState::Muted),
            "ConsultationCall" => Ok(CallState::ConsultationCall),
            "Cancelled" => Ok(CallState::Cancelled),

            // Registration states
            "Registering" => Ok(CallState::Registering),
            "Registered" => Ok(CallState::Registered),
            "Unregistering" => Ok(CallState::Unregistering),

            // Subscription/Presence states
            "Subscribing" => Ok(CallState::Subscribing),
            "Subscribed" => Ok(CallState::Subscribed),
            "Publishing" => Ok(CallState::Publishing),

            // Authentication and routing states
            "Authenticating" => Ok(CallState::Authenticating),
            "Messaging" => Ok(CallState::Messaging),

            _ if state.starts_with("Failed") => {
                // Parse Failed(reason) states
                Ok(CallState::Failed(FailureReason::Other))
            }
            _ => Err(SessionError::InternalError(format!(
                "Invalid call state: {}",
                state
            ))),
        }
    }

    /// Parse an event from YAML representation
    fn parse_event(&self, event: YamlEvent) -> Result<EventType> {
        match event {
            YamlEvent::Simple(name) => self.parse_event_by_name(&name),
            YamlEvent::Complex {
                event_type,
                parameters,
            } => {
                // Handle complex events with parameters
                match event_type.as_str() {
                    "MakeCall" => {
                        let target = parameters
                            .get("target")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        Ok(EventType::MakeCall { target })
                    }
                    "IncomingCall" | "IncomingCallAutoAccept" => {
                        let from = parameters
                            .get("from")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        let sdp = parameters
                            .get("sdp")
                            .and_then(|v| v.as_str())
                            .map(String::from);
                        if event_type == "IncomingCallAutoAccept" {
                            Ok(EventType::IncomingCallAutoAccept { from, sdp })
                        } else {
                            Ok(EventType::IncomingCall { from, sdp })
                        }
                    }
                    "SendEarlyMedia" => {
                        let sdp = parameters
                            .get("sdp")
                            .and_then(|v| v.as_str())
                            .map(String::from);
                        Ok(EventType::SendEarlyMedia { sdp })
                    }
                    "AuthRequired" => {
                        let status_code = parameters
                            .get("status_code")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(0) as u16;
                        let challenge = parameters
                            .get("challenge")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        let method = parameters
                            .get("method")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        Ok(EventType::AuthRequired {
                            status_code,
                            challenge,
                            method,
                        })
                    }
                    _ => self.parse_event_by_name(&event_type),
                }
            }
        }
    }

    /// Parse an event by name
    fn parse_event_by_name(&self, name: &str) -> Result<EventType> {
        match name {
            // Application events
            "MakeCall" => Ok(EventType::MakeCall {
                target: String::new(),
            }),
            "AcceptCall" => Ok(EventType::AcceptCall),
            "RejectCall" => Ok(EventType::RejectCall {
                status: 0,
                reason: String::new(),
            }),
            "RedirectCall" => Ok(EventType::RedirectCall {
                status: 0,
                contacts: Vec::new(),
            }),
            "SendEarlyMedia" => Ok(EventType::SendEarlyMedia { sdp: None }),
            "AuthRequired" => Ok(EventType::AuthRequired {
                status_code: 0,
                challenge: String::new(),
                method: String::new(),
            }),
            // RFC 4028 §6 — 422 Session Interval Too Small. Field-less YAML
            // name maps to a default `min_se_secs: 0`; the runtime event
            // carries the actual floor from dialog-core's parser.
            "SessionIntervalTooSmall" => Ok(EventType::SessionIntervalTooSmall { min_se_secs: 0 }),
            // RFC 3261 §22.2 — backward-compat alias. The dedicated
            // Registration401 path has been retired in favor of the shared
            // AuthRequired event, but externally-authored state tables may
            // still reference the old name.
            "Registration401" => Ok(EventType::AuthRequired {
                status_code: 401,
                challenge: String::new(),
                method: "REGISTER".to_string(),
            }),
            "HangupCall" => Ok(EventType::HangupCall),
            "CancelCall" => Ok(EventType::CancelCall),
            "HoldCall" => Ok(EventType::HoldCall),
            "ResumeCall" => Ok(EventType::ResumeCall),

            // Dialog events (abstracted)
            "DialogProgress" | "Dialog180Ringing" => Ok(EventType::Dialog180Ringing),
            "Dialog183SessionProgress" => Ok(EventType::Dialog183SessionProgress),
            "DialogEstablished" | "Dialog200OK" => Ok(EventType::Dialog200OK),
            "DialogFailed" => Ok(EventType::Dialog4xxFailure(400)),
            "Dialog4xxFailure" => Ok(EventType::Dialog4xxFailure(400)),
            "Dialog5xxFailure" => Ok(EventType::Dialog5xxFailure(500)),
            "Dialog6xxFailure" => Ok(EventType::Dialog6xxFailure(600)),
            "Dialog487RequestTerminated" => Ok(EventType::Dialog487RequestTerminated),
            "Dialog3xxRedirect" => Ok(EventType::Dialog3xxRedirect {
                status: 0,
                targets: Vec::new(),
            }),
            "ReinviteGlare" => Ok(EventType::ReinviteGlare),
            "ReinviteReceived" => Ok(EventType::ReinviteReceived { sdp: None }),
            "UpdateReceived" => Ok(EventType::UpdateReceived { sdp: None }),
            // ACK delivered to UAS — drives the Answering → Active transition
            // that promotes the dialog from early to confirmed. Without this
            // entry the YAML "DialogACK" event falls through to
            // `EventType::MediaEvent("DialogACK")` and the transition never
            // fires.
            "DialogACK" => Ok(EventType::DialogACK),
            "DialogBYE" => Ok(EventType::DialogBYE),
            "DialogCANCEL" => Ok(EventType::DialogCANCEL),
            "DialogTimeout" => Ok(EventType::DialogTimeout),
            "DialogTerminated" => Ok(EventType::DialogTerminated),

            // Gateway-specific BYE events
            "InboundBYE" | "OutboundBYE" => Ok(EventType::DialogBYE),
            "IncomingCall" => Ok(EventType::IncomingCall {
                from: String::new(),
                sdp: None,
            }),
            "IncomingCallAutoAccept" => Ok(EventType::IncomingCallAutoAccept {
                from: String::new(),
                sdp: None,
            }),

            // Media events
            "MediaReady" => Ok(EventType::MediaEvent("media_session_created".to_string())),
            "MediaFlowing" => Ok(EventType::MediaEvent("media_flow_established".to_string())),
            "MediaFailed" => Ok(EventType::MediaEvent("media_failed".to_string())),
            "SDPNegotiated" => Ok(EventType::MediaEvent("sdp_negotiated".to_string())),

            // Internal coordination
            "CheckReadiness" => Ok(EventType::CheckConditions),
            "PublishEstablished" => Ok(EventType::PublishCallEstablished),

            // Bridge events
            "BridgeToSession" | "BridgeSessions" => Ok(EventType::BridgeSessions {
                other_session: SessionId::new(),
            }),

            // Transfer events
            // "BlindTransfer" event removed
            "TransferRequested" => Ok(EventType::TransferRequested {
                refer_to: String::new(),
                transfer_type: String::new(),
                transaction_id: String::new(),
            }),
            // "TransferComplete" event removed

            // Internal transfer coordination events
            "InternalProceedWithTransfer" => Ok(EventType::InternalProceedWithTransfer),
            "InternalMakeTransferCall" => Ok(EventType::InternalMakeTransferCall),
            "InternalTransferCallEstablished" => Ok(EventType::InternalTransferCallEstablished),

            // Registration events
            "StartRegistration" => Ok(EventType::StartRegistration),
            "Registration200OK" => Ok(EventType::Registration200OK),
            // "Registration401" is aliased above to EventType::AuthRequired
            // (shared event with INVITE auth). Do not re-add the legacy
            // binding here; the alias intentionally takes priority.
            "RetryRegistration" => Ok(EventType::RetryRegistration),
            "RefreshRegistration" => Ok(EventType::RefreshRegistration),
            "RegistrationFailed" => Ok(EventType::RegistrationFailed(0)),
            "StartUnregistration" => Ok(EventType::StartUnregistration),
            "Unregistration200OK" => Ok(EventType::Unregistration200OK),
            "UnregistrationFailed" => Ok(EventType::UnregistrationFailed),
            "UnregisterRequest" => Ok(EventType::UnregisterRequest),
            "RegistrationExpired" => Ok(EventType::RegistrationExpired),

            // Subscription events
            "StartSubscription" => Ok(EventType::StartSubscription),
            "ReceiveNOTIFY" => Ok(EventType::ReceiveNOTIFY),
            "SendNOTIFY" => Ok(EventType::SendNOTIFY),
            "SubscriptionAccepted" => Ok(EventType::SubscriptionAccepted),
            "SubscriptionFailed" => Ok(EventType::SubscriptionFailed(0)),
            "SubscriptionExpired" => Ok(EventType::SubscriptionExpired),
            "UnsubscribeRequest" => Ok(EventType::UnsubscribeRequest),

            // Message events
            "SendMessage" => Ok(EventType::SendMessage),
            "ReceiveMESSAGE" => Ok(EventType::ReceiveMESSAGE),
            "MessageDelivered" => Ok(EventType::MessageDelivered),
            "MessageFailed" => Ok(EventType::MessageFailed(0)),

            // SIP_API_DESIGN_2 §7.1 — builder-staged outbound events.
            // Each `coord.<verb>(..).send()` dispatches one of these so
            // the YAML row drives `Action::Send<METHOD>WithOptions`.
            "SendOutboundInvite" => Ok(EventType::SendOutboundInvite),
            "SendOutboundReInvite" => Ok(EventType::SendOutboundReInvite),
            "SendOutboundBye" => Ok(EventType::SendOutboundBye),
            "SendOutboundCancel" => Ok(EventType::SendOutboundCancel),
            "SendOutboundRefer" => Ok(EventType::SendOutboundRefer),
            "SendOutboundNotify" => Ok(EventType::SendOutboundNotify),
            "SendOutboundInfo" => Ok(EventType::SendOutboundInfo),
            "SendOutboundUpdate" => Ok(EventType::SendOutboundUpdate),
            "SendOutboundMessage" => Ok(EventType::SendOutboundMessage),
            "SendOutboundOptions" => Ok(EventType::SendOutboundOptions),
            "SendOutboundSubscribe" => Ok(EventType::SendOutboundSubscribe),
            "SendOutboundRegister" => Ok(EventType::SendOutboundRegister),

            _ => Err(SessionError::InternalError(format!(
                "Unknown YAML event '{}': add a matching arm in \
                 state_table/yaml_loader.rs::parse_event_by_name or remove \
                 the YAML reference.",
                name
            ))),
        }
    }

    /// Parse a guard from YAML representation
    fn parse_guard(&self, guard: YamlGuard) -> Result<Guard> {
        match guard {
            YamlGuard::Simple(name) => self.parse_guard_by_name(&name),
            YamlGuard::Complex { guard_type, .. } => self.parse_guard_by_name(&guard_type),
        }
    }

    /// Parse a guard by name
    fn parse_guard_by_name(&self, name: &str) -> Result<Guard> {
        match name {
            "HasLocalSDP" => Ok(Guard::HasLocalSDP),
            "HasRemoteSDP" => Ok(Guard::HasRemoteSDP),
            "DialogEstablished" => Ok(Guard::DialogEstablished),
            "MediaReady" => Ok(Guard::MediaReady),
            "SDPNegotiated" => Ok(Guard::SDPNegotiated),
            "AllConditionsMet" | "all_conditions_met" => Ok(Guard::AllConditionsMet),
            "IsIdle" => Ok(Guard::IsIdle),
            "InActiveCall" => Ok(Guard::InActiveCall),
            "IsRegistered" => Ok(Guard::IsRegistered),
            "IsSubscribed" => Ok(Guard::IsSubscribed),
            "HasActiveSubscription" => Ok(Guard::HasActiveSubscription),
            "HasPendingReinvite" => Ok(Guard::HasPendingReinvite),
            "OtherSessionActive" => Ok(Guard::Custom(name.to_string())),
            _ => {
                debug!("Unknown guard '{}', treating as custom", name);
                Ok(Guard::Custom(name.to_string()))
            }
        }
    }

    /// Parse an action from YAML representation
    fn parse_action(&self, action: YamlAction) -> Result<Action> {
        match action {
            YamlAction::Simple(name) => self.parse_action_by_name(&name),
            YamlAction::Complex {
                action_type,
                parameters,
            } => {
                // Handle parameterized actions
                match action_type.as_str() {
                    "SendSIPResponse" => {
                        let code = parameters
                            .get("code")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(200) as u16;
                        let reason = parameters
                            .get("reason")
                            .and_then(|v| v.as_str())
                            .unwrap_or("OK")
                            .to_string();
                        Ok(Action::SendSIPResponse(code, reason))
                    }
                    "SetCondition" => {
                        let condition = parameters
                            .get("condition")
                            .and_then(|v| v.as_str())
                            .unwrap_or("dialog_established");
                        let value = parameters
                            .get("value")
                            .and_then(|v| v.as_bool())
                            .unwrap_or(true);

                        let cond = match condition {
                            "dialog_established" => Condition::DialogEstablished,
                            "media_session_ready" => Condition::MediaSessionReady,
                            "sdp_negotiated" => Condition::SDPNegotiated,
                            _ => {
                                return Err(SessionError::InternalError(format!(
                                    "Invalid condition: {}",
                                    condition
                                )))
                            }
                        };

                        Ok(Action::SetCondition(cond, value))
                    }
                    _ => self.parse_action_by_name(&action_type),
                }
            }
        }
    }

    /// Parse an action by name
    fn parse_action_by_name(&self, name: &str) -> Result<Action> {
        match name {
            // Dialog actions
            "CreateDialog" => Ok(Action::CreateDialog),
            "GenerateLocalSDP" => Ok(Action::GenerateLocalSDP),
            "SendINVITE" | "TriggerDialogINVITE" => Ok(Action::SendINVITE),
            "SendACK" => Ok(Action::SendACK),
            "SendBYE" => Ok(Action::SendBYE),
            "SendRejectResponse" => Ok(Action::SendRejectResponse),
            "SendRedirectResponse" => Ok(Action::SendRedirectResponse),
            "RetryWithContact" => Ok(Action::RetryWithContact),
            "ScheduleReinviteRetry" => Ok(Action::ScheduleReinviteRetry),
            "ClearPendingReinvite" => Ok(Action::ClearPendingReinvite),
            // SendCANCEL legacy variant deleted per Phase 5 — YAML now
            // emits SendCANCELWithOptions exclusively. Keep an alias so
            // historical YAML still parses for the duration of the
            // deprecation cycle.
            "SendCANCEL" | "SendCANCELWithOptions" => Ok(Action::SendCANCELWithOptions),
            "SendReINVITE" => Ok(Action::SendReINVITE),

            // Media actions
            "CreateMediaSession" => Ok(Action::CreateMediaSession),
            "StartMediaSession" => Ok(Action::StartMediaSession),
            // StopMediaSession/StopMedia aliases map to CleanupMedia — the
            // two used to be distinct but StopMediaSession was broken (see
            // MediaAdapter history), so they're unified now.
            "StopMediaSession" | "StopMedia" => Ok(Action::CleanupMedia),
            "NegotiateSDPAsUAC" => Ok(Action::NegotiateSDPAsUAC),
            "NegotiateSDPAsUAS" => Ok(Action::NegotiateSDPAsUAS),
            "PrepareEarlyMediaSDP" => Ok(Action::PrepareEarlyMediaSDP),
            "SwitchToPassThroughOnActive" => Ok(Action::SwitchToPassThroughOnActive),
            "StoreAuthChallenge" => Ok(Action::StoreAuthChallenge),
            "SendINVITEWithAuth" => Ok(Action::SendINVITEWithAuth),
            "SendINVITEWithBumpedSessionExpires" => Ok(Action::SendINVITEWithBumpedSessionExpires),
            "SendREGISTERWithAuth" => Ok(Action::SendREGISTERWithAuth),
            "SendRequestWithAuth" => Ok(Action::SendRequestWithAuth),
            "SuspendMedia" => Ok(Action::Custom("SuspendMedia".to_string())),
            "ResumeMedia" => Ok(Action::Custom("ResumeMedia".to_string())),

            // State updates
            "StoreLocalSDP" => Ok(Action::StoreLocalSDP),
            "StoreRemoteSDP" => Ok(Action::StoreRemoteSDP),
            "StoreNegotiatedConfig" => Ok(Action::StoreNegotiatedConfig),

            // Callbacks
            "TriggerCallEstablished" | "PublishEstablished" => Ok(Action::TriggerCallEstablished),
            "TriggerCallTerminated" => Ok(Action::TriggerCallTerminated),

            // Cleanup
            "StartDialogCleanup" => Ok(Action::StartDialogCleanup),
            "StartMediaCleanup" => Ok(Action::StartMediaCleanup),
            "CleanupDialog" => Ok(Action::CleanupDialog),
            "CleanupMedia" => Ok(Action::CleanupMedia),

            // Registration actions
            "SendREGISTER" => Ok(Action::SendREGISTER),
            "SendUnREGISTER" | "SendREGISTERWithExpires0" => Ok(Action::SendUnREGISTER),
            "ProcessRegistrationResponse" => Ok(Action::ProcessRegistrationResponse),

            // Subscription actions
            "SendSUBSCRIBE" => Ok(Action::SendSUBSCRIBE),
            "ProcessNOTIFY" => Ok(Action::ProcessNOTIFY),
            // SendNOTIFY legacy variant deleted per Phase 5; alias kept
            // for the deprecation cycle so historical YAML parses.
            "SendNOTIFY" | "SendNOTIFYWithOptions" => Ok(Action::SendNOTIFYWithOptions),

            // Message actions
            "SendMESSAGE" => Ok(Action::SendMESSAGE),
            "ProcessMESSAGE" => Ok(Action::ProcessMESSAGE),

            // Bridge/Conference helpers that are still real state-machine
            // actions. Media bridging itself is direct-wired through the
            // coordinator/media adapter and must not appear in YAML as a
            // Custom no-op.
            "HoldOriginalCall" | "HoldCurrentCall" => Ok(Action::HoldCurrentCall),
            "ResumeOriginalCall" => Ok(Action::RestoreMediaFlow),

            // REFER response action (keep for proper REFER handling)
            "SendReferAccepted" => Ok(Action::SendReferAccepted),

            // RFC 3515 §2.4.5 progress NOTIFYs.
            "SendRefer100Trying" => Ok(Action::SendRefer100Trying),
            "SendTransferNotifyRinging" => Ok(Action::SendTransferNotifyRinging),
            "SendTransferNotifySuccess" => Ok(Action::SendTransferNotifySuccess),
            "SendTransferNotifyFailure" => Ok(Action::SendTransferNotifyFailure),

            // Internal
            "CheckReadiness" => Ok(Action::Custom("CheckReadiness".to_string())),

            // SIP_API_DESIGN_2 §7.1 — unified outbound dispatch through
            // the option stash. Builder `.send()` stages
            // `pending_<method>_options` and queues
            // `EventType::SendOutbound<METHOD>`; the YAML transition row
            // emits `Send<METHOD>WithOptions` which reads the stash.
            "SendINVITEWithOptions" => Ok(Action::SendINVITEWithOptions),
            "SendReINVITEWithOptions" => Ok(Action::SendReINVITEWithOptions),
            "SendREGISTERWithOptions" => Ok(Action::SendREGISTERWithOptions),
            "SendSUBSCRIBEWithOptions" => Ok(Action::SendSUBSCRIBEWithOptions),
            "SendMESSAGEWithOptions" => Ok(Action::SendMESSAGEWithOptions),
            // SendNOTIFYWithOptions/SendCANCELWithOptions handled by
            // their legacy-alias arms above (Phase 5 consolidation).
            "SendBYEWithOptions" => Ok(Action::SendBYEWithOptions),
            "SendREFERWithOptions" => Ok(Action::SendREFERWithOptions),
            "SendINFOWithOptions" => Ok(Action::SendINFOWithOptions),
            "SendUPDATEWithOptions" => Ok(Action::SendUPDATEWithOptions),
            "SendOPTIONSWithOptions" => Ok(Action::SendOPTIONSWithOptions),

            // §7.3 invariant #2 — clear the stash on final-response
            // transitions (200 / 4xx / 5xx / 6xx / timeout).
            "ClearPendingINVITEOptions" => Ok(Action::ClearPendingINVITEOptions),
            "ClearPendingReINVITEOptions" => Ok(Action::ClearPendingReINVITEOptions),
            "ClearPendingREGISTEROptions" => Ok(Action::ClearPendingREGISTEROptions),
            "ClearPendingSUBSCRIBEOptions" => Ok(Action::ClearPendingSUBSCRIBEOptions),
            "ClearPendingMESSAGEOptions" => Ok(Action::ClearPendingMESSAGEOptions),
            "ClearPendingNOTIFYOptions" => Ok(Action::ClearPendingNOTIFYOptions),
            "ClearPendingBYEOptions" => Ok(Action::ClearPendingBYEOptions),
            "ClearPendingCANCELOptions" => Ok(Action::ClearPendingCANCELOptions),
            "ClearPendingREFEROptions" => Ok(Action::ClearPendingREFEROptions),
            "ClearPendingINFOOptions" => Ok(Action::ClearPendingINFOOptions),
            "ClearPendingUPDATEOptions" => Ok(Action::ClearPendingUPDATEOptions),
            "ClearPendingOPTIONSOptions" => Ok(Action::ClearPendingOPTIONSOptions),

            // Unknown action — drift detection. Previously silently fell through
            // to `Action::Custom(name)`, which masked dead YAML entries pointing
            // at long-removed action variants. Now a hard error so additions
            // and deletions stay synchronized between the YAML and the Rust
            // `Action` enum. Intentional custom hooks (e.g. "SuspendMedia",
            // "ResumeMedia", "CheckReadiness") must be listed explicitly above.
            _ => Err(SessionError::InternalError(format!(
                "Unknown YAML action '{}': add a matching arm in \
                 state_table/yaml_loader.rs::parse_action_by_name or remove \
                 the YAML reference.",
                name
            ))),
        }
    }

    /// Parse an event template for publishing
    fn parse_event_template(&self, name: &str) -> Result<EventTemplate> {
        match name {
            "SessionCreated" => Ok(EventTemplate::SessionCreated),
            "StateChanged" => Ok(EventTemplate::StateChanged),
            "CallEstablished" => Ok(EventTemplate::CallEstablished),
            "CallTerminated" => Ok(EventTemplate::CallTerminated),
            "CallFailed" => Ok(EventTemplate::CallFailed),
            "CallCancelled" => Ok(EventTemplate::CallCancelled),
            "MediaFlowEstablished" => Ok(EventTemplate::MediaFlowEstablished),
            "CallRinging" => Ok(EventTemplate::Custom("CallRinging".to_string())),
            "CallOnHold" => Ok(EventTemplate::CallOnHold),
            "CallResumed" => Ok(EventTemplate::CallResumed),
            "SessionsBridged" => Ok(EventTemplate::Custom("SessionsBridged".to_string())),
            "TransferSucceeded" => Ok(EventTemplate::Custom("TransferSucceeded".to_string())),
            _ => Ok(EventTemplate::Custom(name.to_string())),
        }
    }
}

impl Default for YamlTableLoader {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parse_simple_yaml() {
        let yaml = r#"
version: "1.0"
transitions:
  - role: UAC
    state: Idle
    event: MakeCall
    next_state: Initiating
    actions:
      - SendINVITE
    publish:
      - SessionCreated
"#;

        let mut loader = YamlTableLoader::new();
        loader.load_from_string(yaml).expect("Failed to load YAML");
        let table = loader.build().expect("Failed to build table");

        // Verify the transition was added
        let key = StateKey {
            role: Role::UAC,
            state: CallState::Idle,
            event: EventType::MakeCall {
                target: String::new(),
            },
        };

        assert!(table.has_transition(&key));
    }

    #[test]
    fn test_complex_event_parsing() {
        let yaml = r#"
version: "1.0"
transitions:
  - role: UAC
    state: Idle
    event:
      type: MakeCall
      target: "sip:bob@example.com"
    next_state: Initiating
"#;

        let mut loader = YamlTableLoader::new();
        loader.load_from_string(yaml).expect("Failed to load YAML");
        loader.build().expect("Failed to build table");
    }

    #[test]
    fn test_condition_updates() {
        let yaml = r#"
version: "1.0"
transitions:
  - role: Both
    state: Active
    event: CheckReadiness
    conditions:
      dialog_established: true
      media_session_ready: true
      sdp_negotiated: true
"#;

        let mut loader = YamlTableLoader::new();
        loader.load_from_string(yaml).expect("Failed to load YAML");
        let table = loader.build().expect("Failed to build table");

        let key = StateKey {
            role: Role::Both,
            state: CallState::Active,
            event: EventType::CheckConditions,
        };

        let transition = table.get_transition(&key).expect("Transition not found");
        assert!(transition
            .condition_updates
            .dialog_established
            .unwrap_or(false));
    }

    /// The embedded `default.yaml` loads without hitting the
    /// `UnknownAction` drift-detection arm. If this regresses, either the
    /// YAML introduced a new action name or an `Action` variant was removed
    /// without also deleting the corresponding YAML entry.
    #[test]
    fn default_yaml_loads_with_no_unknown_actions() {
        // `load_embedded_default` constructs the loader + parses the
        // embedded YAML + builds the `MasterStateTable`. An
        // `Err(SessionError::InternalError("Unknown YAML action ..."))`
        // at parse time is the failure mode we want to catch.
        YamlTableLoader::load_embedded_default().expect(
            "embedded default.yaml failed to load cleanly — \
                     check for dead YAML action names or missing \
                     parse_action_by_name arms",
        );
    }

    /// Every `YamlAction::Simple` name that reaches `parse_action_by_name`
    /// lands on a real variant rather than a `Custom` silent fallback
    /// (unless explicitly allow-listed). The reverse direction — that every
    /// `Action` variant is reachable from at least one YAML name — is
    /// asserted by `default_yaml_loads_with_no_unknown_actions` together
    /// with the CI expectation that new YAML names accompany every new
    /// variant.
    /// Compile-time invariant: rvoip-sip's `MediaSessionId` is the
    /// same type as `rvoip_media_core::DialogId`. If this test stops
    /// compiling the alias has been broken — see Sprint 2.5 P5
    /// (`MEDIA_PLANE_LAYERING_FOLLOWUPS.md`).
    #[test]
    fn media_session_id_is_alias_of_media_core_dialog_id() {
        let _: super::super::types::MediaSessionId = rvoip_media_core::DialogId::new_v4();
    }

    #[test]
    fn parse_action_by_name_hard_errors_on_unknown_names() {
        let loader = YamlTableLoader::new();
        let err = loader
            .parse_action_by_name("ThisNameDoesNotExist42")
            .expect_err("unknown YAML action must be a hard error, not Custom fallback");
        let msg = format!("{:?}", err);
        assert!(
            msg.contains("Unknown YAML action"),
            "unexpected error for unknown action: {}",
            msg,
        );
    }
}