ai-agents-state 1.0.0-rc.15

State machine for AI Agents framework
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
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
use ai_agents_core::{AgentError, Result};
use ai_agents_disambiguation::StateDisambiguationOverride;
use ai_agents_process::ProcessConfig;
use ai_agents_reasoning::{ReasoningConfig, ReflectionConfig};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, HashSet};

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PromptMode {
    #[default]
    Append,
    Replace,
    Prepend,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateConfig {
    pub initial: String,
    #[serde(default)]
    pub states: HashMap<String, StateDefinition>,
    #[serde(default)]
    pub global_transitions: Vec<Transition>,
    #[serde(default)]
    pub fallback: Option<String>,
    #[serde(default)]
    pub max_no_transition: Option<u32>,

    /// Whether to re-generate a response after state transitions (default: true).
    #[serde(default = "default_true")]
    pub regenerate_on_transition: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct StateDefinition {
    #[serde(default)]
    pub prompt: Option<String>,

    #[serde(default)]
    pub prompt_mode: PromptMode,

    #[serde(default)]
    pub llm: Option<String>,

    #[serde(default)]
    pub skills: Vec<String>,

    /// Tool availability for this state.
    /// - `None` (omitted in YAML): inherit from parent or agent-level tools
    /// - `Some([])` (`tools: []` in YAML): explicitly no tools available
    /// - `Some([...])`: only these tools available
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ToolRef>>,

    #[serde(default)]
    pub transitions: Vec<Transition>,

    #[serde(default)]
    pub max_turns: Option<u32>,

    #[serde(default)]
    pub timeout_to: Option<String>,

    #[serde(default)]
    pub initial: Option<String>,

    #[serde(default)]
    pub states: Option<HashMap<String, StateDefinition>>,

    #[serde(default = "default_inherit_parent")]
    pub inherit_parent: bool,

    #[serde(default)]
    pub on_enter: Vec<StateAction>,

    /// Actions on re-entering a previously visited state. Falls back to on_enter if empty.
    #[serde(default)]
    pub on_reenter: Vec<StateAction>,

    #[serde(default)]
    pub on_exit: Vec<StateAction>,

    /// Per-state override: skip re-generation on entering this state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub regenerate_on_enter: Option<bool>,

    /// Context extractors: pull structured data from user input into context.
    #[serde(default)]
    pub extract: Vec<ContextExtractor>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ReasoningConfig>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reflection: Option<ReflectionConfig>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disambiguation: Option<StateDisambiguationOverride>,

    /// Per-state process pipeline override (replaces agent-level pipeline for this state).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process: Option<ProcessConfig>,

    /// Delegate state messages to a registry agent by ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegate: Option<String>,

    /// Context mode for delegated states.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegate_context: Option<DelegateContextMode>,

    /// Run multiple registry agents concurrently in this state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub concurrent: Option<ConcurrentStateConfig>,

    /// Run a multi-agent group chat in this state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_chat: Option<GroupChatStateConfig>,

    /// Run a sequential agent pipeline in this state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pipeline: Option<PipelineStateConfig>,

    /// Run an LLM-directed handoff chain in this state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handoff: Option<HandoffStateConfig>,
}

fn default_inherit_parent() -> bool {
    true
}

fn default_true() -> bool {
    true
}

fn default_extractor_llm() -> String {
    "router".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolRef {
    Simple(String),
    Conditional {
        id: String,
        condition: ToolCondition,
    },
}

impl ToolRef {
    pub fn id(&self) -> &str {
        match self {
            ToolRef::Simple(id) => id,
            ToolRef::Conditional { id, .. } => id,
        }
    }

    pub fn condition(&self) -> Option<&ToolCondition> {
        match self {
            ToolRef::Simple(_) => None,
            ToolRef::Conditional { condition, .. } => Some(condition),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolCondition {
    Context(HashMap<String, ContextMatcher>),
    State(StateMatcher),
    AfterTool(String),
    ToolResult {
        tool: String,
        result: HashMap<String, Value>,
    },
    Semantic {
        when: String,
        #[serde(default = "default_semantic_llm")]
        llm: String,
        #[serde(default = "default_threshold")]
        threshold: f32,
    },
    Time(TimeMatcher),
    All(Vec<ToolCondition>),
    Any(Vec<ToolCondition>),
    Not(Box<ToolCondition>),
}

fn default_semantic_llm() -> String {
    "router".to_string()
}

fn default_threshold() -> f32 {
    0.7
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ContextMatcher {
    // Order matters for serde untagged: structured variants must come before
    // Exact(Value) because Value matches any valid JSON — including objects
    // like `{ "exists": true }` or `{ "eq": "admin" }` that should be parsed
    // as Exists or Compare instead.
    Exists { exists: bool },
    Compare(CompareOp),
    Exact(Value),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompareOp {
    Eq(Value),
    Neq(Value),
    Gt(f64),
    Gte(f64),
    Lt(f64),
    Lte(f64),
    In(Vec<Value>),
    Contains(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct StateMatcher {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub turn_count: Option<CompareOp>,
    #[serde(default)]
    pub previous: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TimeMatcher {
    #[serde(default)]
    pub hours: Option<CompareOp>,
    #[serde(default)]
    pub day_of_week: Option<Vec<String>>,
    #[serde(default)]
    pub timezone: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TransitionTiming {
    /// Evaluate after the assistant response is available.
    PostResponse,
    /// Evaluate before main response generation when the route is response independent.
    PreResponse,
    /// Evaluate in parallel with a draft response when explicitly enabled.
    Parallel,
}

impl Default for TransitionTiming {
    fn default() -> Self {
        Self::PostResponse
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transition {
    pub to: String,
    #[serde(default)]
    pub when: String,
    #[serde(default)]
    pub guard: Option<TransitionGuard>,
    /// Intent label for deterministic routing after disambiguation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<String>,
    #[serde(default = "default_auto")]
    pub auto: bool,
    #[serde(default)]
    pub priority: u8,

    /// Minimum turns before this transition can fire again after last use.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cooldown_turns: Option<u32>,

    /// Controls whether the transition can be selected before a response exists.
    #[serde(default)]
    pub timing: TransitionTiming,

    /// Marks transitions whose condition needs the assistant response text.
    #[serde(default)]
    pub requires_response: bool,

    /// Allows this transition to run current-state extractors before pre-response selection.
    #[serde(default)]
    pub run_extractors: bool,
}

fn default_auto() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TransitionGuard {
    Expression(String),
    Conditions(GuardConditions),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GuardConditions {
    All(Vec<String>),
    Any(Vec<String>),
    Context(HashMap<String, ContextMatcher>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StateAction {
    Tool {
        tool: String,
        #[serde(default)]
        args: Option<Value>,
    },
    Skill {
        skill: String,
    },
    Prompt {
        prompt: String,
        #[serde(default)]
        llm: Option<String>,
        #[serde(default)]
        store_as: Option<String>,
    },
    SetContext {
        set_context: HashMap<String, Value>,
    },
}

/// Extract structured data from conversation into context via LLM.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextExtractor {
    /// Context key to store the extracted value.
    pub key: String,

    /// Short description of what to extract (LLM-based).
    #[serde(default)]
    pub description: Option<String>,

    /// Custom LLM extraction prompt (takes precedence over `description`).
    #[serde(default)]
    pub llm_extract: Option<String>,

    /// LLM alias for extraction (default: "router").
    #[serde(default = "default_extractor_llm")]
    pub llm: String,

    /// If true, extraction failure is logged as a warning.
    #[serde(default)]
    pub required: bool,
}

//
// Multi-agent orchestration config types for state delegation, concurrent execution, and group chat.
//

/// Context mode for delegated states.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DelegateContextMode {
    /// Delegated agent receives only the user's current message.
    #[default]
    InputOnly,
    /// Parent summarizes recent conversation via router LLM.
    Summary,
    /// Parent passes full recent message history.
    Full,
}

/// Config for running multiple registry agents concurrently.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcurrentStateConfig {
    /// Agent IDs in the registry (simple list or weighted entries).
    pub agents: Vec<ConcurrentAgentRef>,
    /// Jinja2 template for input sent to each agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,
    /// How to aggregate results from all agents.
    pub aggregation: AggregationConfig,
    /// Minimum agents that must succeed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_required: Option<usize>,
    /// What to do when some agents fail.
    #[serde(default)]
    pub on_partial_failure: PartialFailureAction,
    /// Per-agent timeout in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Parent conversation context forwarded to each agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_mode: Option<DelegateContextMode>,
}

/// Either a plain agent ID string or a weighted entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ConcurrentAgentRef {
    Id(String),
    Weighted { id: String, weight: f64 },
}

impl ConcurrentAgentRef {
    pub fn id(&self) -> &str {
        match self {
            Self::Id(id) => id,
            Self::Weighted { id, .. } => id,
        }
    }

    pub fn weight(&self) -> f64 {
        match self {
            Self::Id(_) => 1.0,
            Self::Weighted { weight, .. } => *weight,
        }
    }
}

/// How to aggregate results from concurrent agents.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregationConfig {
    /// Aggregation strategy.
    pub strategy: AggregationStrategy,
    /// LLM alias for synthesis or vote extraction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub synthesizer_llm: Option<String>,
    /// Custom prompt for LLM synthesis.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub synthesizer_prompt: Option<String>,
    /// Voting sub-config.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vote: Option<VoteConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AggregationStrategy {
    Voting,
    LlmSynthesis,
    FirstWins,
    All,
}

/// Voting config for concurrent agent aggregation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoteConfig {
    #[serde(default)]
    pub method: VoteMethod,
    #[serde(default)]
    pub tiebreaker: TiebreakerStrategy,
    /// Custom prompt for extracting a vote from each agent's response.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vote_prompt: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoteMethod {
    #[default]
    Majority,
    Weighted,
    Unanimous,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TiebreakerStrategy {
    #[default]
    First,
    Random,
    RouterDecides,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PartialFailureAction {
    #[default]
    ProceedWithAvailable,
    Abort,
}

/// Group chat state config for multi-agent conversation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupChatStateConfig {
    /// Participant agent IDs with optional roles.
    pub participants: Vec<ChatParticipant>,
    /// Conversation style.
    #[serde(default)]
    pub style: ChatStyle,
    /// Maximum conversation rounds.
    #[serde(default = "default_max_rounds")]
    pub max_rounds: u32,
    /// Chat manager config.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manager: Option<ChatManagerConfig>,
    /// When and how to terminate.
    #[serde(default)]
    pub termination: TerminationConfig,
    /// Debate-specific config.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub debate: Option<DebateStyleConfig>,
    /// Maker-checker-specific config.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maker_checker: Option<MakerCheckerConfig>,
    /// Total timeout for the group chat in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Jinja2 template for the topic sent to participants.
    /// {{ user_input }} is the user's message. {{ context.<key> }} accesses context values. When omitted, the raw user message is used as the topic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,
    /// Parent conversation context included in the topic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_mode: Option<DelegateContextMode>,
}

/// A participant in a group chat.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatParticipant {
    /// Agent ID in the registry.
    pub id: String,
    /// Role description visible to all participants.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChatStyle {
    #[default]
    Brainstorm,
    Debate,
    MakerChecker,
    Consensus,
}

/// Chat manager config for controlling turn order.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatManagerConfig {
    /// Registry agent ID for chat management.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,
    /// Built-in turn policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<TurnMethod>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnMethod {
    RoundRobin,
    Random,
    LlmDirected,
}

/// Termination config for group chat.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerminationConfig {
    #[serde(default)]
    pub method: TerminationMethod,
    #[serde(default = "default_stall_rounds")]
    pub max_stall_rounds: u32,
}

impl Default for TerminationConfig {
    fn default() -> Self {
        Self {
            method: TerminationMethod::default(),
            max_stall_rounds: default_stall_rounds(),
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TerminationMethod {
    #[default]
    ManagerDecides,
    MaxRounds,
    ConsensusReached,
}

/// Debate-specific config for group chat.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebateStyleConfig {
    #[serde(default = "default_debate_rounds")]
    pub rounds: u32,
    /// Agent ID that synthesizes the final answer.
    pub synthesizer: String,
}

/// Maker-checker-specific config for group chat.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MakerCheckerConfig {
    #[serde(default = "default_maker_checker_iterations")]
    pub max_iterations: u32,
    /// LLM-evaluated acceptance criteria.
    pub acceptance_criteria: String,
    #[serde(default)]
    pub on_max_iterations: MaxIterationsAction,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaxIterationsAction {
    #[default]
    AcceptLast,
    Escalate,
    Fail,
}

fn default_max_rounds() -> u32 {
    5
}
fn default_stall_rounds() -> u32 {
    2
}
fn default_debate_rounds() -> u32 {
    3
}
fn default_maker_checker_iterations() -> u32 {
    3
}

/// Config for a pipeline state type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineStateConfig {
    pub stages: Vec<PipelineStageEntry>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Parent conversation context forwarded to the first stage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_mode: Option<DelegateContextMode>,
}

/// A single stage in a pipeline state.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PipelineStageEntry {
    /// Simple agent ID string.
    Id(String),
    /// Agent with optional input template.
    Config {
        id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        input: Option<String>,
    },
}

impl PipelineStageEntry {
    pub fn id(&self) -> &str {
        match self {
            Self::Id(id) => id,
            Self::Config { id, .. } => id,
        }
    }

    pub fn input(&self) -> Option<&str> {
        match self {
            Self::Id(_) => None,
            Self::Config { input, .. } => input.as_deref(),
        }
    }
}

/// Config for a handoff state type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandoffStateConfig {
    pub initial_agent: String,
    pub available_agents: Vec<String>,

    #[serde(default = "default_max_handoffs")]
    pub max_handoffs: u32,

    /// Jinja2 template for the input sent to the initial agent.
    /// {{ user_input }} is the user's message. {{ context.<key> }} accesses context values. When omitted, the raw user message is forwarded directly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,
    /// Parent conversation context forwarded to the initial agent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_mode: Option<DelegateContextMode>,
}

fn default_max_handoffs() -> u32 {
    5
}

fn validate_transition_timing(
    transition: &Transition,
    scope: &str,
    state_path: Option<&str>,
) -> Result<()> {
    if transition.requires_response && !matches!(transition.timing, TransitionTiming::PostResponse)
    {
        let location = state_path
            .map(|path| format!("State '{}'", path))
            .unwrap_or_else(|| "Global transition".to_string());
        return Err(AgentError::InvalidSpec(format!(
            "{} has response-dependent transition '{}' with non-post-response timing",
            location, transition.to
        )));
    }
    if matches!(transition.timing, TransitionTiming::Parallel)
        && transition.guard.is_none()
        && transition.intent.is_none()
        && transition.when.trim().is_empty()
    {
        return Err(AgentError::InvalidSpec(format!(
            "{} transition '{}' uses parallel timing without a guard, intent, or when condition",
            scope, transition.to
        )));
    }
    if matches!(transition.timing, TransitionTiming::PreResponse) {
        if transition.guard.is_none() && transition.intent.is_none() {
            return Err(AgentError::InvalidSpec(format!(
                "{} transition '{}' uses pre-response timing without a guard or intent",
                scope, transition.to
            )));
        }
        if !transition.when.trim().is_empty() {
            return Err(AgentError::InvalidSpec(format!(
                "{} transition '{}' uses pre-response timing with response-dependent when text",
                scope, transition.to
            )));
        }
    }
    Ok(())
}

impl StateConfig {
    pub fn validate(&self) -> Result<()> {
        if self.initial.is_empty() {
            return Err(AgentError::InvalidSpec(
                "State machine initial state cannot be empty".into(),
            ));
        }
        if !self.states.contains_key(&self.initial) {
            return Err(AgentError::InvalidSpec(format!(
                "Initial state '{}' not found in states",
                self.initial
            )));
        }
        for transition in &self.global_transitions {
            validate_transition_timing(transition, "Global", None)?;
            if !self.is_valid_transition_target(&transition.to, &[], &self.states) {
                return Err(AgentError::InvalidSpec(format!(
                    "Global transition targets unknown state '{}'",
                    transition.to
                )));
            }
        }

        self.validate_states(&self.states, &[])?;

        // Warn about unreachable states (non-fatal)
        for warning in self.check_reachability() {
            tracing::warn!("{}", warning);
        }

        Ok(())
    }

    fn validate_states(
        &self,
        states: &HashMap<String, StateDefinition>,
        parent_path: &[String],
    ) -> Result<()> {
        for (name, def) in states {
            let current_path: Vec<String> = parent_path
                .iter()
                .cloned()
                .chain(std::iter::once(name.clone()))
                .collect();

            for transition in &def.transitions {
                let path = current_path.join(".");
                validate_transition_timing(transition, "State", Some(&path))?;

                if !self.is_valid_transition_target(&transition.to, &current_path, states) {
                    return Err(AgentError::InvalidSpec(format!(
                        "State '{}' has transition to unknown state '{}'",
                        current_path.join("."),
                        transition.to
                    )));
                }
            }

            if let Some(ref timeout_state) = def.timeout_to {
                if !self.is_valid_transition_target(timeout_state, &current_path, states) {
                    return Err(AgentError::InvalidSpec(format!(
                        "State '{}' has timeout_to unknown state '{}'",
                        current_path.join("."),
                        timeout_state
                    )));
                }
            }

            if let Some(ref sub_states) = def.states {
                if let Some(ref initial) = def.initial {
                    if !sub_states.contains_key(initial) {
                        return Err(AgentError::InvalidSpec(format!(
                            "State '{}' has initial sub-state '{}' that doesn't exist",
                            current_path.join("."),
                            initial
                        )));
                    }
                }
                self.validate_states(sub_states, &current_path)?;
            }
        }
        Ok(())
    }

    fn is_valid_transition_target(
        &self,
        target: &str,
        current_path: &[String],
        states: &HashMap<String, StateDefinition>,
    ) -> bool {
        if target.starts_with('^') {
            let target_name = &target[1..];
            return self.states.contains_key(target_name);
        }

        if states.contains_key(target) {
            return true;
        }

        if current_path.len() > 1 {
            let parent_path = &current_path[..current_path.len() - 1];
            if let Some(parent_states) = self.get_states_at_path(parent_path) {
                if parent_states.contains_key(target) {
                    return true;
                }
            }
        }

        self.states.contains_key(target)
    }

    fn get_states_at_path(&self, path: &[String]) -> Option<&HashMap<String, StateDefinition>> {
        let mut current = &self.states;
        for segment in path {
            if let Some(def) = current.get(segment) {
                if let Some(ref sub_states) = def.states {
                    current = sub_states;
                } else {
                    return None;
                }
            } else {
                return None;
            }
        }
        Some(current)
    }

    pub fn get_state(&self, path: &str) -> Option<&StateDefinition> {
        let parts: Vec<&str> = path.split('.').collect();
        self.get_state_by_path(&parts)
    }

    fn get_state_by_path(&self, path: &[&str]) -> Option<&StateDefinition> {
        if path.is_empty() {
            return None;
        }

        let mut current = self.states.get(path[0])?;
        for segment in &path[1..] {
            if let Some(ref sub_states) = current.states {
                current = sub_states.get(*segment)?;
            } else {
                return None;
            }
        }
        Some(current)
    }

    /// Resolve a transition target to a full dotted state path.
    /// Order: `^prefix` (parent-level) → top-level → sibling → child → fallback literal.
    pub fn resolve_full_path(&self, current_path: &str, target: &str) -> String {
        if target.starts_with('^') {
            return target[1..].to_string();
        }

        if self.states.contains_key(target) {
            return target.to_string();
        }

        if !current_path.is_empty() {
            let parts: Vec<&str> = current_path.split('.').collect();
            if parts.len() > 1 {
                let parent_path = parts[..parts.len() - 1].join(".");
                let potential = format!("{}.{}", parent_path, target);
                if self.get_state(&potential).is_some() {
                    return potential;
                }
            }

            let potential = format!("{}.{}", current_path, target);
            if self.get_state(&potential).is_some() {
                return potential;
            }
        }

        target.to_string()
    }

    /// Check for unreachable states. Returns warning messages.
    pub fn check_reachability(&self) -> Vec<String> {
        let mut reachable: HashSet<String> = HashSet::new();
        reachable.insert(self.initial.clone());

        if let Some(ref fb) = self.fallback {
            reachable.insert(fb.clone());
        }
        for gt in &self.global_transitions {
            reachable.insert(self.normalize_target(&gt.to));
        }

        let mut queue: Vec<String> = reachable.iter().cloned().collect();
        while let Some(state_path) = queue.pop() {
            if let Some(def) = self.get_state(&state_path) {
                for t in &def.transitions {
                    let target = self.resolve_full_path(&state_path, &t.to);
                    if reachable.insert(target.clone()) {
                        queue.push(target);
                    }
                }
                if let Some(ref timeout) = def.timeout_to {
                    let target = self.resolve_full_path(&state_path, timeout);
                    if reachable.insert(target.clone()) {
                        queue.push(target);
                    }
                }
                if let (Some(initial), Some(_sub)) = (&def.initial, &def.states) {
                    let sub_path = format!("{}.{}", state_path, initial);
                    if reachable.insert(sub_path.clone()) {
                        queue.push(sub_path);
                    }
                }
            }
        }

        let all_states = self.collect_all_state_paths(&self.states, &[]);
        let mut warnings = Vec::new();
        for state_path in &all_states {
            if !reachable.contains(state_path) {
                warnings.push(format!(
                    "State '{}' appears unreachable — no transitions lead to it",
                    state_path
                ));
            }
        }
        warnings
    }

    fn normalize_target(&self, target: &str) -> String {
        if target.starts_with('^') {
            target[1..].to_string()
        } else {
            target.to_string()
        }
    }

    fn collect_all_state_paths(
        &self,
        states: &HashMap<String, StateDefinition>,
        parent: &[String],
    ) -> Vec<String> {
        let mut paths = Vec::new();
        for (name, def) in states {
            let mut current: Vec<String> = parent.to_vec();
            current.push(name.clone());
            paths.push(current.join("."));
            if let Some(ref sub) = def.states {
                paths.extend(self.collect_all_state_paths(sub, &current));
            }
        }
        paths
    }
}

impl StateDefinition {
    pub fn has_sub_states(&self) -> bool {
        self.states.as_ref().map(|s| !s.is_empty()).unwrap_or(false)
    }

    pub fn get_effective_tools<'a>(
        &'a self,
        parent: Option<&'a StateDefinition>,
    ) -> Option<Vec<&'a ToolRef>> {
        match &self.tools {
            // Explicitly set (including empty): use as-is, no inheritance
            Some(tools) => Some(tools.iter().collect()),
            // Not set: inherit from parent if available
            None => {
                if !self.inherit_parent {
                    return None;
                }
                parent
                    .and_then(|p| p.tools.as_ref())
                    .map(|t| t.iter().collect())
            }
        }
    }

    pub fn get_effective_skills<'a>(
        &'a self,
        parent: Option<&'a StateDefinition>,
    ) -> Vec<&'a String> {
        if !self.inherit_parent || parent.is_none() {
            return self.skills.iter().collect();
        }

        let parent = parent.unwrap();
        let mut skills: Vec<&'a String> = parent.skills.iter().collect();
        skills.extend(self.skills.iter());
        skills
    }
}

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

    #[test]
    fn test_transition_timing_defaults_to_post_response() {
        let yaml = r#"
to: next
when: "ready"
"#;
        let transition: Transition = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(transition.timing, TransitionTiming::PostResponse);
        assert!(!transition.requires_response);
        assert!(!transition.run_extractors);
    }

    #[test]
    fn test_state_config_deserialize() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    prompt: "Welcome!"
    transitions:
      - to: support
        when: "user needs help"
        auto: true
  support:
    prompt: "How can I help?"
    llm: fast
    tools:
      - search
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.initial, "greeting");
        assert_eq!(config.states.len(), 2);
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_prompt_mode_default() {
        let def = StateDefinition::default();
        assert_eq!(def.prompt_mode, PromptMode::Append);
    }

    #[test]
    fn test_response_dependent_pre_response_transition_is_invalid() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    transitions:
      - to: done
        when: "after answer"
        timing: pre_response
        requires_response: true
  done:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_parallel_transition_timing_accepts_response_independent_condition() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    transitions:
      - to: done
        when: "ready"
        timing: parallel
  done:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_parallel_transition_without_condition_is_invalid() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    transitions:
      - to: done
        timing: parallel
  done:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let err = config.validate().unwrap_err();
        assert!(err.to_string().contains("parallel timing without"));
    }

    #[test]
    fn test_pre_response_when_without_guard_or_intent_is_invalid() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    transitions:
      - to: done
        when: "ready"
        timing: pre_response
  done:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_pre_response_with_when_text_is_invalid() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    transitions:
      - to: done
        when: "ready"
        guard:
          context:
            ready:
              eq: true
        timing: pre_response
  done:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_invalid_initial_state() {
        let config = StateConfig {
            initial: "nonexistent".into(),
            states: HashMap::new(),
            global_transitions: vec![],
            fallback: None,
            max_no_transition: None,
            regenerate_on_transition: true,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_invalid_transition_target() {
        let mut states = HashMap::new();
        states.insert(
            "start".into(),
            StateDefinition {
                transitions: vec![Transition {
                    to: "nonexistent".into(),
                    when: "always".into(),
                    guard: None,
                    intent: None,
                    auto: true,
                    priority: 0,
                    cooldown_turns: None,
                    timing: TransitionTiming::PostResponse,
                    requires_response: false,
                    run_extractors: false,
                }],
                ..Default::default()
            },
        );
        let config = StateConfig {
            initial: "start".into(),
            states,
            global_transitions: vec![],
            fallback: None,
            max_no_transition: None,
            regenerate_on_transition: true,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_hierarchical_states() {
        let yaml = r#"
initial: problem_solving
states:
  problem_solving:
    initial: gathering_info
    prompt: "Solving customer problem"
    states:
      gathering_info:
        prompt: "Ask questions"
        transitions:
          - to: proposing_solution
            when: "understood"
      proposing_solution:
        prompt: "Offer solution"
        transitions:
          - to: ^closing
            when: "resolved"
  closing:
    prompt: "Thank you"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.validate().is_ok());
        assert!(
            config
                .states
                .get("problem_solving")
                .unwrap()
                .has_sub_states()
        );
    }

    #[test]
    fn test_tool_ref_simple() {
        let yaml = r#"
tools:
  - calculator
  - search
"#;
        #[derive(Deserialize)]
        struct Test {
            tools: Vec<ToolRef>,
        }
        let t: Test = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(t.tools.len(), 2);
        assert_eq!(t.tools[0].id(), "calculator");
    }

    #[test]
    fn test_tool_ref_conditional() {
        let yaml = r#"
tools:
  - calculator
  - id: admin_tool
    condition:
      context:
        user.role: "admin"
"#;
        #[derive(Deserialize)]
        struct Test {
            tools: Vec<ToolRef>,
        }
        let t: Test = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(t.tools.len(), 2);
        assert_eq!(t.tools[1].id(), "admin_tool");
        assert!(t.tools[1].condition().is_some());
    }

    #[test]
    fn test_transition_with_guard() {
        let yaml = r#"
to: next_state
when: "user wants to proceed"
guard: "{{ context.has_data }}"
auto: true
priority: 10
"#;
        let t: Transition = serde_yaml::from_str(yaml).unwrap();
        assert!(t.guard.is_some());
        assert_eq!(t.priority, 10);
    }

    #[test]
    fn test_state_action() {
        let yaml = r#"
- tool: log_event
  args:
    event: "entered"
- skill: greeting_skill
- set_context:
    entered: true
"#;
        let actions: Vec<StateAction> = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(actions.len(), 3);
        match &actions[0] {
            StateAction::Tool { tool, .. } => assert_eq!(tool, "log_event"),
            _ => panic!("Expected Tool action"),
        }
        match &actions[1] {
            StateAction::Skill { skill } => assert_eq!(skill, "greeting_skill"),
            _ => panic!("Expected Skill action"),
        }
        match &actions[2] {
            StateAction::SetContext { set_context } => {
                assert!(set_context.contains_key("entered"));
            }
            _ => panic!("Expected SetContext action"),
        }
    }

    #[test]
    fn test_complex_tool_condition() {
        let yaml = r#"
id: refund_tool
condition:
  all:
    - context:
        user.verified: true
    - semantic:
        when: "user wants refund"
        threshold: 0.85
"#;
        let tool: ToolRef = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(tool.id(), "refund_tool");
        match tool.condition().unwrap() {
            ToolCondition::All(conditions) => assert_eq!(conditions.len(), 2),
            _ => panic!("Expected All condition"),
        }
    }

    #[test]
    fn test_state_get_path() {
        let yaml = r#"
initial: problem_solving
states:
  problem_solving:
    initial: gathering_info
    states:
      gathering_info:
        prompt: "Ask"
      proposing:
        prompt: "Propose"
  closing:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.get_state("problem_solving").is_some());
        assert!(config.get_state("problem_solving.gathering_info").is_some());
        assert!(config.get_state("closing").is_some());
        assert!(config.get_state("nonexistent").is_none());
    }

    #[test]
    fn test_resolve_full_path() {
        let yaml = r#"
initial: problem_solving
states:
  problem_solving:
    initial: gathering_info
    states:
      gathering_info:
        prompt: "Ask"
      proposing:
        prompt: "Propose"
  closing:
    prompt: "Done"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();

        assert_eq!(
            config.resolve_full_path("problem_solving.gathering_info", "proposing"),
            "problem_solving.proposing"
        );
        assert_eq!(
            config.resolve_full_path("problem_solving.gathering_info", "^closing"),
            "closing"
        );
        assert_eq!(
            config.resolve_full_path("problem_solving", "closing"),
            "closing"
        );
    }

    #[test]
    fn test_inherit_parent() {
        let parent = StateDefinition {
            tools: Some(vec![ToolRef::Simple("parent_tool".into())]),
            skills: vec!["parent_skill".into()],
            ..Default::default()
        };

        let child = StateDefinition {
            tools: Some(vec![ToolRef::Simple("child_tool".into())]),
            skills: vec!["child_skill".into()],
            inherit_parent: true,
            ..Default::default()
        };

        let effective_tools = child.get_effective_tools(Some(&parent)).unwrap();
        assert_eq!(effective_tools.len(), 1); // explicit tools override, no merge

        let effective_skills = child.get_effective_skills(Some(&parent));
        assert_eq!(effective_skills.len(), 2);
    }

    #[test]
    fn test_no_inherit_parent() {
        let parent = StateDefinition {
            tools: Some(vec![ToolRef::Simple("parent_tool".into())]),
            ..Default::default()
        };

        let child = StateDefinition {
            tools: Some(vec![ToolRef::Simple("child_tool".into())]),
            inherit_parent: false,
            ..Default::default()
        };

        let effective_tools = child.get_effective_tools(Some(&parent)).unwrap();
        assert_eq!(effective_tools.len(), 1);
        assert_eq!(effective_tools[0].id(), "child_tool");
    }

    #[test]
    fn test_tools_none_inherits() {
        let parent = StateDefinition {
            tools: Some(vec![ToolRef::Simple("parent_tool".into())]),
            ..Default::default()
        };

        let child = StateDefinition {
            tools: None, // not specified → inherit
            inherit_parent: true,
            ..Default::default()
        };

        let effective_tools = child.get_effective_tools(Some(&parent)).unwrap();
        assert_eq!(effective_tools.len(), 1);
        assert_eq!(effective_tools[0].id(), "parent_tool");
    }

    #[test]
    fn test_tools_empty_means_no_tools() {
        let parent = StateDefinition {
            tools: Some(vec![ToolRef::Simple("parent_tool".into())]),
            ..Default::default()
        };

        let child = StateDefinition {
            tools: Some(vec![]), // explicitly empty → no tools
            inherit_parent: true,
            ..Default::default()
        };

        let effective_tools = child.get_effective_tools(Some(&parent)).unwrap();
        assert!(effective_tools.is_empty());
    }

    #[test]
    fn test_state_with_disambiguation_override() {
        let yaml = r#"
initial: greeting
states:
  greeting:
    prompt: "Hello"
    transitions:
      - to: payment
        when: "User wants to pay"
  payment:
    prompt: "Processing payment"
    disambiguation:
      threshold: 0.95
      require_confirmation: true
      required_clarity:
        - recipient
        - amount
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let payment = config.get_state("payment").unwrap();
        let disambig = payment.disambiguation.as_ref().unwrap();
        assert_eq!(disambig.threshold, Some(0.95));
        assert!(disambig.require_confirmation);
        assert_eq!(disambig.required_clarity.len(), 2);
        assert!(disambig.required_clarity.contains(&"recipient".to_string()));

        let greeting = config.get_state("greeting").unwrap();
        assert!(greeting.disambiguation.is_none());
    }

    #[test]
    fn test_context_extractor_vec_deserialize() {
        let yaml = r#"
initial: a
states:
  a:
    extract:
      - key: user_email
        description: "The user's email address"
      - key: order_id
        llm_extract: "Extract the order ID"
        required: true
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let state = config.get_state("a").unwrap();
        assert_eq!(state.extract.len(), 2);
        assert_eq!(state.extract[0].key, "user_email");
        assert_eq!(
            state.extract[0].description.as_deref(),
            Some("The user's email address")
        );
        assert!(!state.extract[0].required);
        assert_eq!(state.extract[0].llm, "router");
        assert_eq!(state.extract[1].key, "order_id");
        assert!(state.extract[1].required);
        assert!(state.extract[1].llm_extract.is_some());
    }

    #[test]
    fn test_context_extractor_default_empty() {
        let yaml = r#"
initial: a
states:
  a:
    prompt: "Hello"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let state = config.get_state("a").unwrap();
        assert!(state.extract.is_empty());
    }

    #[test]
    fn test_state_process_override_deserialize() {
        let yaml = r#"
initial: a
states:
  a:
    process:
      input:
        - type: normalize
          config:
            trim: true
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let state = config.get_state("a").unwrap();
        assert!(state.process.is_some());
        assert_eq!(state.process.as_ref().unwrap().input.len(), 1);
    }

    #[test]
    fn test_state_process_default_none() {
        let yaml = r#"
initial: a
states:
  a:
    prompt: "Hello"
"#;
        let config: StateConfig = serde_yaml::from_str(yaml).unwrap();
        let state = config.get_state("a").unwrap();
        assert!(state.process.is_none());
    }
}