argentor-orchestrator 1.4.7

Multi-agent orchestration, task queues, and deployment for Argentor
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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
//! TOML-based Workflow DSL for declarative pipeline definitions.
//!
//! Parses TOML workflow files into the executable [`WorkflowDefinition`] used
//! by the [`WorkflowEngine`].  This allows non-Rust developers to author
//! multi-step agent pipelines with a simple, human-readable syntax.
//!
//! # Example TOML
//!
//! ```toml
//! [workflow]
//! name = "code-review-pipeline"
//! description = "Automated code review with security scan"
//! version = "1.0"
//!
//! [[steps]]
//! id = "analyze"
//! name = "Code Analysis"
//! type = "agent"
//! role = "code_analyst"
//! prompt = "Analyze the following code for quality issues: {{input}}"
//! tools = ["code_analysis", "file_read"]
//! timeout_seconds = 60
//!
//! [[steps]]
//! id = "security"
//! name = "Security Scan"
//! type = "agent"
//! role = "security_auditor"
//! prompt = "Scan for security vulnerabilities: {{steps.analyze.output}}"
//! tools = ["secret_scanner", "prompt_guard"]
//! depends_on = ["analyze"]
//!
//! [[steps]]
//! id = "review"
//! name = "Final Review"
//! type = "agent"
//! role = "tech_lead"
//! prompt = "Review analysis and security findings, produce final report"
//! depends_on = ["analyze", "security"]
//!
//! [[steps]]
//! id = "notify"
//! name = "Send Notification"
//! type = "http"
//! url = "{{env.WEBHOOK_URL}}"
//! method = "POST"
//! body = '{"status": "complete", "report": "{{steps.review.output}}"}'
//! depends_on = ["review"]
//!
//! [triggers]
//! cron = "0 9 * * MON"
//! webhook = true
//! ```

use argentor_core::{ArgentorError, ArgentorResult};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::Path;

use crate::workflow::{
    FailureAction, StepCondition, StepType, WorkflowDefinition, WorkflowStepDef, WorkflowTrigger,
};

// ---------------------------------------------------------------------------
// TOML schema types
// ---------------------------------------------------------------------------

/// Top-level structure of a TOML workflow file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowToml {
    /// Workflow metadata.
    pub workflow: WorkflowMeta,
    /// Ordered list of pipeline steps.
    pub steps: Vec<StepToml>,
    /// Optional trigger configuration.
    pub triggers: Option<TriggerConfig>,
    /// Optional workflow-level variables for template interpolation.
    pub variables: Option<HashMap<String, String>>,
}

/// Metadata about the workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowMeta {
    /// Unique name used as the workflow identifier.
    pub name: String,
    /// Human-readable description.
    pub description: Option<String>,
    /// Semantic version string.
    pub version: Option<String>,
    /// Author or team name.
    pub author: Option<String>,
    /// Freeform tags for categorization.
    pub tags: Option<Vec<String>>,
    /// Default maximum retries for any step (overridable per step).
    pub max_retries: Option<u32>,
    /// Overall workflow timeout in seconds.
    pub timeout_seconds: Option<u64>,
}

/// A single step in the TOML workflow definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepToml {
    /// Unique identifier within the workflow.
    pub id: String,
    /// Human-readable step name.
    pub name: String,
    /// Step kind: `"agent"`, `"http"`, `"condition"`, `"delay"`,
    /// `"notification"`, `"assign_human"`.
    #[serde(rename = "type")]
    pub step_type: String,

    // -- Agent fields --
    /// Agent role (required for `type = "agent"`).
    pub role: Option<String>,
    /// Prompt template with `{{...}}` placeholders.
    pub prompt: Option<String>,
    /// List of tool names the agent may use.
    pub tools: Option<Vec<String>>,
    /// Model override (e.g., `"claude-3-opus"`).
    pub model: Option<String>,

    // -- HTTP fields --
    /// Target URL (required for `type = "http"`).
    pub url: Option<String>,
    /// HTTP method (default `"POST"`).
    pub method: Option<String>,
    /// HTTP headers.
    pub headers: Option<HashMap<String, String>>,
    /// Request body template.
    pub body: Option<String>,

    // -- Condition fields --
    /// Boolean expression (required for `type = "condition"`).
    pub condition: Option<String>,
    /// Step id to jump to when condition is true.
    pub on_true: Option<String>,
    /// Step id to jump to when condition is false.
    pub on_false: Option<String>,

    // -- Delay fields --
    /// Seconds to wait (required for `type = "delay"`).
    pub delay_seconds: Option<u64>,

    // -- Notification fields --
    /// Notification channel (required for `type = "notification"`).
    pub channel: Option<String>,
    /// Message template for notifications.
    pub message: Option<String>,

    // -- Assign human fields --
    /// Team to assign to (required for `type = "assign_human"`).
    pub team: Option<String>,

    // -- Common fields --
    /// Step ids that must complete before this step runs.
    pub depends_on: Option<Vec<String>>,
    /// Maximum execution time in seconds.
    pub timeout_seconds: Option<u64>,
    /// Number of retries on failure.
    pub retry: Option<u32>,
    /// Failure strategy: `"skip"`, `"abort"`, `"retry"`, or a step id to
    /// jump to.
    pub on_failure: Option<String>,
    /// Guard condition expression; step runs only when this evaluates true.
    pub run_if: Option<String>,
}

/// Trigger configuration for the workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TriggerConfig {
    /// Cron expression (e.g., `"0 9 * * MON"`).
    pub cron: Option<String>,
    /// Whether the workflow can be triggered by a webhook.
    pub webhook: Option<bool>,
    /// Event name that triggers the workflow.
    pub on_event: Option<String>,
}

// ---------------------------------------------------------------------------
// Template context & resolution
// ---------------------------------------------------------------------------

/// Context available during template variable resolution.
#[derive(Debug, Clone, Default)]
pub struct TemplateContext {
    /// The initial workflow input.
    pub input: String,
    /// Outputs keyed by step id.
    pub step_outputs: HashMap<String, String>,
    /// Workflow-level variables.
    pub variables: HashMap<String, String>,
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Severity of a validation finding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationSeverity {
    /// The workflow cannot be compiled.
    Error,
    /// The workflow can compile but may behave unexpectedly.
    Warning,
}

/// A single validation finding.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// The step that caused the error, if applicable.
    pub step_id: Option<String>,
    /// Human-readable description of the problem.
    pub message: String,
    /// Error or warning.
    pub severity: ValidationSeverity,
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let prefix = match self.severity {
            ValidationSeverity::Error => "ERROR",
            ValidationSeverity::Warning => "WARNING",
        };
        match &self.step_id {
            Some(id) => write!(f, "[{prefix}] step '{id}': {}", self.message),
            None => write!(f, "[{prefix}] {}", self.message),
        }
    }
}

// ---------------------------------------------------------------------------
// DSL parser / compiler
// ---------------------------------------------------------------------------

/// Entry point for the TOML workflow DSL.
///
/// Provides methods to parse, validate, and compile TOML workflow
/// definitions into the executable [`WorkflowDefinition`] consumed by the
/// [`WorkflowEngine`].
pub struct WorkflowDsl;

impl WorkflowDsl {
    /// Parse a TOML string into a [`WorkflowToml`].
    pub fn parse(toml_str: &str) -> ArgentorResult<WorkflowToml> {
        toml::from_str(toml_str)
            .map_err(|e| ArgentorError::Config(format!("TOML parse error: {e}")))
    }

    /// Parse a TOML file from disk.
    pub fn parse_file(path: &Path) -> ArgentorResult<WorkflowToml> {
        let content = std::fs::read_to_string(path).map_err(ArgentorError::Io)?;
        Self::parse(&content)
    }

    /// Validate a parsed workflow, returning all findings.
    ///
    /// An empty vector means the workflow is valid.
    pub fn validate(toml: &WorkflowToml) -> Vec<ValidationError> {
        let mut errors = Vec::new();

        // Must have at least one step.
        if toml.steps.is_empty() {
            errors.push(ValidationError {
                step_id: None,
                message: "workflow has no steps".to_string(),
                severity: ValidationSeverity::Error,
            });
            return errors;
        }

        // Collect step ids for cross-referencing.
        let step_ids: HashSet<&str> = toml.steps.iter().map(|s| s.id.as_str()).collect();

        // Check for duplicate ids.
        {
            let mut seen = HashSet::new();
            for step in &toml.steps {
                if !seen.insert(&step.id) {
                    errors.push(ValidationError {
                        step_id: Some(step.id.clone()),
                        message: format!("duplicate step id '{}'", step.id),
                        severity: ValidationSeverity::Error,
                    });
                }
            }
        }

        // Per-step validation.
        for step in &toml.steps {
            // Validate step type and required fields.
            match step.step_type.as_str() {
                "agent" => {
                    if step.role.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "agent step requires 'role' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if step.prompt.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "agent step requires 'prompt' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
                "http" => {
                    if step.url.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "http step requires 'url' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
                "condition" => {
                    if step.condition.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "condition step requires 'condition' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if step.on_true.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "condition step requires 'on_true' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if step.on_false.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "condition step requires 'on_false' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    // Check that branch targets exist.
                    if let Some(ref target) = step.on_true {
                        if !step_ids.contains(target.as_str()) {
                            errors.push(ValidationError {
                                step_id: Some(step.id.clone()),
                                message: format!("on_true references unknown step '{target}'"),
                                severity: ValidationSeverity::Error,
                            });
                        }
                    }
                    if let Some(ref target) = step.on_false {
                        if !step_ids.contains(target.as_str()) {
                            errors.push(ValidationError {
                                step_id: Some(step.id.clone()),
                                message: format!("on_false references unknown step '{target}'"),
                                severity: ValidationSeverity::Error,
                            });
                        }
                    }
                }
                "delay" => {
                    if step.delay_seconds.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "delay step requires 'delay_seconds' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
                "notification" => {
                    if step.channel.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "notification step requires 'channel' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if step.message.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "notification step requires 'message' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
                "assign_human" => {
                    if step.team.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "assign_human step requires 'team' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if step.message.is_none() {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "assign_human step requires 'message' field".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
                unknown => {
                    errors.push(ValidationError {
                        step_id: Some(step.id.clone()),
                        message: format!("unknown step type '{unknown}'"),
                        severity: ValidationSeverity::Error,
                    });
                }
            }

            // Validate depends_on references.
            if let Some(ref deps) = step.depends_on {
                for dep in deps {
                    if !step_ids.contains(dep.as_str()) {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: format!("depends_on references unknown step '{dep}'"),
                            severity: ValidationSeverity::Error,
                        });
                    }
                    if dep == &step.id {
                        errors.push(ValidationError {
                            step_id: Some(step.id.clone()),
                            message: "step depends on itself".to_string(),
                            severity: ValidationSeverity::Error,
                        });
                    }
                }
            }

            // Validate on_failure if it looks like a goto target.
            if let Some(ref action) = step.on_failure {
                match action.as_str() {
                    "skip" | "abort" | "retry" => {}
                    target => {
                        if !step_ids.contains(target) {
                            errors.push(ValidationError {
                                step_id: Some(step.id.clone()),
                                message: format!(
                                    "on_failure value '{target}' is neither a known action \
                                     (skip/abort/retry) nor a valid step id"
                                ),
                                severity: ValidationSeverity::Error,
                            });
                        }
                    }
                }
            }

            // Warn if timeout is very large.
            if let Some(t) = step.timeout_seconds {
                if t > 3600 {
                    errors.push(ValidationError {
                        step_id: Some(step.id.clone()),
                        message: format!("timeout_seconds ({t}s) exceeds 1 hour"),
                        severity: ValidationSeverity::Warning,
                    });
                }
            }
        }

        // Circular dependency detection (topological sort via Kahn's algorithm).
        errors.extend(detect_cycles(&toml.steps));

        errors
    }

    /// Convert a parsed [`WorkflowToml`] into an executable
    /// [`WorkflowDefinition`].
    ///
    /// This performs validation first and returns the first error if the
    /// workflow is invalid.
    pub fn compile(toml: &WorkflowToml) -> ArgentorResult<WorkflowDefinition> {
        let validation_errors: Vec<_> = Self::validate(toml)
            .into_iter()
            .filter(|e| e.severity == ValidationSeverity::Error)
            .collect();
        if let Some(first) = validation_errors.first() {
            return Err(ArgentorError::Config(format!(
                "workflow validation failed: {first}"
            )));
        }

        let trigger = compile_trigger(&toml.triggers);

        let mut steps = Vec::with_capacity(toml.steps.len());
        for step_toml in &toml.steps {
            steps.push(compile_step(step_toml)?);
        }

        // Reorder steps based on dependency graph (topological sort) so the
        // linear WorkflowEngine can execute them in a valid order.
        let ordered = topological_sort(&toml.steps);
        let step_map: HashMap<&str, WorkflowStepDef> =
            steps.iter().map(|s| (s.id.as_str(), s.clone())).collect();
        let ordered_steps: Vec<WorkflowStepDef> = ordered
            .iter()
            .filter_map(|id| step_map.get(id.as_str()).cloned())
            .collect();

        Ok(WorkflowDefinition {
            id: toml.workflow.name.clone(),
            name: toml.workflow.name.clone(),
            description: toml.workflow.description.clone().unwrap_or_default(),
            trigger,
            steps: ordered_steps,
            timeout_seconds: toml.workflow.timeout_seconds,
        })
    }

    /// Parse a TOML string and compile it in one step.
    pub fn load(toml_str: &str) -> ArgentorResult<WorkflowDefinition> {
        let parsed = Self::parse(toml_str)?;
        Self::compile(&parsed)
    }

    /// Parse a TOML file and compile it in one step.
    pub fn load_file(path: &Path) -> ArgentorResult<WorkflowDefinition> {
        let parsed = Self::parse_file(path)?;
        Self::compile(&parsed)
    }

    /// Resolve template placeholders in a string.
    ///
    /// Supported patterns:
    /// - `{{input}}` — the workflow input value
    /// - `{{steps.<id>.output}}` — output of a previous step
    /// - `{{env.<VAR>}}` — environment variable
    /// - `{{variables.<key>}}` or `{{var.<key>}}` — workflow-level variable
    pub fn resolve_template(template: &str, context: &TemplateContext) -> String {
        let mut result = String::with_capacity(template.len());
        let mut remaining = template;

        while let Some(start) = remaining.find("{{") {
            result.push_str(&remaining[..start]);
            let after_open = &remaining[start + 2..];
            if let Some(end) = after_open.find("}}") {
                let key = after_open[..end].trim();
                let value = resolve_placeholder(key, context);
                result.push_str(&value);
                remaining = &after_open[end + 2..];
            } else {
                // No closing `}}` — keep the literal text.
                result.push_str(&remaining[start..]);
                remaining = "";
            }
        }
        result.push_str(remaining);
        result
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Resolve a single placeholder key to its value.
fn resolve_placeholder(key: &str, ctx: &TemplateContext) -> String {
    // {{input}}
    if key == "input" {
        return ctx.input.clone();
    }

    // {{steps.<id>.output}}
    if let Some(rest) = key.strip_prefix("steps.") {
        if let Some(step_id) = rest.strip_suffix(".output") {
            return ctx.step_outputs.get(step_id).cloned().unwrap_or_default();
        }
    }

    // {{env.<VAR>}}
    if let Some(var_name) = key.strip_prefix("env.") {
        return std::env::var(var_name).unwrap_or_default();
    }

    // {{variables.<key>}} or {{var.<key>}}
    if let Some(var_key) = key
        .strip_prefix("variables.")
        .or_else(|| key.strip_prefix("var."))
    {
        return ctx.variables.get(var_key).cloned().unwrap_or_default();
    }

    // Unknown placeholder — return empty.
    String::new()
}

/// Derive the [`WorkflowTrigger`] from the optional TOML trigger config.
fn compile_trigger(trigger: &Option<TriggerConfig>) -> WorkflowTrigger {
    match trigger {
        None => WorkflowTrigger::Manual,
        Some(tc) => {
            if let Some(ref cron_expr) = tc.cron {
                return WorkflowTrigger::Schedule {
                    cron: cron_expr.clone(),
                };
            }
            if let Some(ref event) = tc.on_event {
                return WorkflowTrigger::Webhook {
                    event: event.clone(),
                };
            }
            if tc.webhook == Some(true) {
                return WorkflowTrigger::Webhook {
                    event: "webhook".to_string(),
                };
            }
            WorkflowTrigger::Manual
        }
    }
}

/// Compile a single TOML step into a [`WorkflowStepDef`].
fn compile_step(s: &StepToml) -> ArgentorResult<WorkflowStepDef> {
    let step_type = match s.step_type.as_str() {
        "agent" => StepType::AgentTask {
            agent_role: s.role.clone().unwrap_or_default(),
            prompt_template: s.prompt.clone().unwrap_or_default(),
        },
        "http" => StepType::HttpCall {
            method: s.method.clone().unwrap_or_else(|| "POST".to_string()),
            url: s.url.clone().unwrap_or_default(),
            body_template: s.body.clone(),
        },
        "condition" => StepType::Condition {
            expression: s.condition.clone().unwrap_or_default(),
            if_true: s.on_true.clone().unwrap_or_default(),
            if_false: s.on_false.clone().unwrap_or_default(),
        },
        "delay" => StepType::Delay {
            seconds: s.delay_seconds.unwrap_or(0),
        },
        "notification" => StepType::Notification {
            channel: s.channel.clone().unwrap_or_default(),
            message_template: s.message.clone().unwrap_or_default(),
        },
        "assign_human" => StepType::AssignToHuman {
            team: s.team.clone().unwrap_or_default(),
            message: s.message.clone().unwrap_or_default(),
        },
        other => {
            return Err(ArgentorError::Config(format!(
                "unknown step type '{other}'"
            )));
        }
    };

    let on_failure = match s.on_failure.as_deref() {
        Some("skip") => FailureAction::Skip,
        Some("abort") | None => FailureAction::Abort,
        Some("retry") => FailureAction::Retry {
            max: s.retry.unwrap_or(3),
        },
        Some(step_id) => FailureAction::GoTo {
            step_id: step_id.to_string(),
        },
    };

    let condition = s.run_if.as_ref().map(|expr| {
        if expr == "previous_succeeded" {
            StepCondition::IfPreviousSucceeded
        } else {
            StepCondition::Expression(expr.clone())
        }
    });

    Ok(WorkflowStepDef {
        id: s.id.clone(),
        name: s.name.clone(),
        step_type,
        condition,
        on_failure,
        timeout_seconds: s.timeout_seconds,
    })
}

/// Detect cycles in the dependency graph.  Returns validation errors for any
/// cycle found.
fn detect_cycles(steps: &[StepToml]) -> Vec<ValidationError> {
    let ids: HashSet<&str> = steps.iter().map(|s| s.id.as_str()).collect();

    // Build adjacency list: step -> deps that precede it.
    let mut in_degree: HashMap<&str, usize> = HashMap::new();
    let mut dependents: HashMap<&str, Vec<&str>> = HashMap::new();

    for step in steps {
        in_degree.entry(step.id.as_str()).or_insert(0);
        if let Some(ref deps) = step.depends_on {
            for dep in deps {
                if ids.contains(dep.as_str()) {
                    dependents
                        .entry(dep.as_str())
                        .or_default()
                        .push(step.id.as_str());
                    *in_degree.entry(step.id.as_str()).or_insert(0) += 1;
                }
            }
        }
    }

    // Kahn's algorithm.
    let mut queue: Vec<&str> = in_degree
        .iter()
        .filter(|(_, &deg)| deg == 0)
        .map(|(&id, _)| id)
        .collect();

    let mut visited = 0usize;
    while let Some(node) = queue.pop() {
        visited += 1;
        if let Some(nexts) = dependents.get(node) {
            for &next in nexts {
                if let Some(deg) = in_degree.get_mut(next) {
                    *deg -= 1;
                    if *deg == 0 {
                        queue.push(next);
                    }
                }
            }
        }
    }

    if visited < ids.len() {
        // Find the steps that are part of a cycle.
        let cycle_steps: Vec<String> = in_degree
            .iter()
            .filter(|(_, &deg)| deg > 0)
            .map(|(&id, _)| id.to_string())
            .collect();
        vec![ValidationError {
            step_id: None,
            message: format!(
                "circular dependency detected among steps: [{}]",
                cycle_steps.join(", ")
            ),
            severity: ValidationSeverity::Error,
        }]
    } else {
        vec![]
    }
}

/// Topological sort of steps by their `depends_on` edges.
///
/// Steps with no dependencies come first.  This is used by [`WorkflowDsl::compile`]
/// to reorder steps into a valid execution sequence.
fn topological_sort(steps: &[StepToml]) -> Vec<String> {
    let ids: HashSet<&str> = steps.iter().map(|s| s.id.as_str()).collect();
    let mut in_degree: HashMap<&str, usize> = HashMap::new();
    let mut dependents: HashMap<&str, Vec<&str>> = HashMap::new();

    for step in steps {
        in_degree.entry(step.id.as_str()).or_insert(0);
        if let Some(ref deps) = step.depends_on {
            for dep in deps {
                if ids.contains(dep.as_str()) {
                    dependents
                        .entry(dep.as_str())
                        .or_default()
                        .push(step.id.as_str());
                    *in_degree.entry(step.id.as_str()).or_insert(0) += 1;
                }
            }
        }
    }

    let mut queue: Vec<&str> = in_degree
        .iter()
        .filter(|(_, &deg)| deg == 0)
        .map(|(&id, _)| id)
        .collect();
    // Sort for deterministic output.
    queue.sort();

    let mut result = Vec::with_capacity(steps.len());
    while let Some(node) = queue.pop() {
        result.push(node.to_string());
        let mut nexts: Vec<&str> = dependents
            .get(node)
            .map(Vec::as_slice)
            .unwrap_or(&[])
            .to_vec();
        nexts.sort();
        for next in nexts {
            if let Some(deg) = in_degree.get_mut(next) {
                *deg -= 1;
                if *deg == 0 {
                    // Insert sorted to keep deterministic order.
                    let pos = queue.partition_point(|&x| x >= next);
                    queue.insert(pos, next);
                }
            }
        }
    }

    result
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::io::Write as _;

    // -- Helpers ------------------------------------------------------------

    fn minimal_toml() -> &'static str {
        r#"
[workflow]
name = "minimal"

[[steps]]
id = "s1"
name = "Step 1"
type = "agent"
role = "coder"
prompt = "Do something"
"#
    }

    fn full_toml() -> &'static str {
        r#"
[workflow]
name = "full-pipeline"
description = "A full pipeline with all step types"
version = "2.0"
author = "test"
tags = ["ci", "review"]
max_retries = 3
timeout_seconds = 600

[variables]
project = "argentor"
env_name = "staging"

[[steps]]
id = "analyze"
name = "Code Analysis"
type = "agent"
role = "code_analyst"
prompt = "Analyze {{input}} for project {{var.project}}"
tools = ["lint", "complexity"]
timeout_seconds = 60

[[steps]]
id = "check_severity"
name = "Check Severity"
type = "condition"
condition = "severity > 5"
on_true = "block"
on_false = "notify"
depends_on = ["analyze"]

[[steps]]
id = "block"
name = "Block Merge"
type = "http"
url = "https://api.example.com/block"
method = "POST"
body = '{"pr": "{{input}}"}'
depends_on = ["check_severity"]

[[steps]]
id = "notify"
name = "Send Notification"
type = "notification"
channel = "slack"
message = "Analysis complete for {{var.project}}"
depends_on = ["check_severity"]

[[steps]]
id = "wait"
name = "Cooldown"
type = "delay"
delay_seconds = 30
depends_on = ["notify"]

[[steps]]
id = "escalate"
name = "Escalate to Human"
type = "assign_human"
team = "platform"
message = "Review needed"
depends_on = ["block"]

[triggers]
cron = "0 9 * * MON"
"#
    }

    // -- Parse tests --------------------------------------------------------

    #[test]
    fn test_parse_minimal() {
        let wf = WorkflowDsl::parse(minimal_toml()).unwrap();
        assert_eq!(wf.workflow.name, "minimal");
        assert_eq!(wf.steps.len(), 1);
        assert_eq!(wf.steps[0].step_type, "agent");
    }

    #[test]
    fn test_parse_full() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        assert_eq!(wf.workflow.name, "full-pipeline");
        assert_eq!(wf.workflow.version.as_deref(), Some("2.0"));
        assert_eq!(wf.workflow.author.as_deref(), Some("test"));
        assert_eq!(wf.steps.len(), 6);
        assert!(wf.triggers.is_some());
        assert!(wf.variables.is_some());
    }

    #[test]
    fn test_parse_invalid_toml() {
        let result = WorkflowDsl::parse("not valid {{{{ toml");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_step_types() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let types: Vec<&str> = wf.steps.iter().map(|s| s.step_type.as_str()).collect();
        assert!(types.contains(&"agent"));
        assert!(types.contains(&"condition"));
        assert!(types.contains(&"http"));
        assert!(types.contains(&"notification"));
        assert!(types.contains(&"delay"));
        assert!(types.contains(&"assign_human"));
    }

    #[test]
    fn test_parse_agent_fields() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let agent = wf.steps.iter().find(|s| s.id == "analyze").unwrap();
        assert_eq!(agent.role.as_deref(), Some("code_analyst"));
        assert!(agent.prompt.as_ref().unwrap().contains("{{input}}"));
        assert_eq!(agent.tools.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn test_parse_condition_fields() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let cond = wf.steps.iter().find(|s| s.id == "check_severity").unwrap();
        assert_eq!(cond.condition.as_deref(), Some("severity > 5"));
        assert_eq!(cond.on_true.as_deref(), Some("block"));
        assert_eq!(cond.on_false.as_deref(), Some("notify"));
    }

    #[test]
    fn test_parse_http_fields() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let http = wf.steps.iter().find(|s| s.id == "block").unwrap();
        assert_eq!(http.url.as_deref(), Some("https://api.example.com/block"));
        assert_eq!(http.method.as_deref(), Some("POST"));
        assert!(http.body.is_some());
    }

    #[test]
    fn test_parse_depends_on() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let escalate = wf.steps.iter().find(|s| s.id == "escalate").unwrap();
        assert_eq!(escalate.depends_on.as_ref().unwrap(), &["block"]);
    }

    #[test]
    fn test_parse_triggers() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let triggers = wf.triggers.unwrap();
        assert_eq!(triggers.cron.as_deref(), Some("0 9 * * MON"));
    }

    #[test]
    fn test_parse_variables() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let vars = wf.variables.unwrap();
        assert_eq!(vars.get("project").unwrap(), "argentor");
    }

    // -- Validation tests ---------------------------------------------------

    #[test]
    fn test_validate_valid_workflow() {
        let wf = WorkflowDsl::parse(full_toml()).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        let real_errors: Vec<_> = errors
            .iter()
            .filter(|e| e.severity == ValidationSeverity::Error)
            .collect();
        assert!(real_errors.is_empty(), "unexpected errors: {real_errors:?}");
    }

    #[test]
    fn test_validate_no_steps() {
        let toml_str = r#"
[workflow]
name = "empty"
"#;
        // Need to manually add empty steps via serde.
        let mut wf = WorkflowDsl::parse(
            &format!("{toml_str}\n[[steps]]\nid = \"x\"\nname = \"x\"\ntype = \"agent\"\nrole = \"r\"\nprompt = \"p\""),
        )
        .unwrap();
        wf.steps.clear();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors.iter().any(|e| e.message.contains("no steps")));
    }

    #[test]
    fn test_validate_unknown_step_type() {
        let toml_str = r#"
[workflow]
name = "bad-type"

[[steps]]
id = "s1"
name = "Step 1"
type = "teleport"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("unknown step type 'teleport'")));
    }

    #[test]
    fn test_validate_missing_agent_role() {
        let toml_str = r#"
[workflow]
name = "missing-role"

[[steps]]
id = "s1"
name = "Step 1"
type = "agent"
prompt = "hello"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors.iter().any(|e| e.message.contains("requires 'role'")));
    }

    #[test]
    fn test_validate_missing_agent_prompt() {
        let toml_str = r#"
[workflow]
name = "missing-prompt"

[[steps]]
id = "s1"
name = "Step 1"
type = "agent"
role = "coder"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'prompt'")));
    }

    #[test]
    fn test_validate_missing_http_url() {
        let toml_str = r#"
[workflow]
name = "missing-url"

[[steps]]
id = "s1"
name = "Step 1"
type = "http"
method = "GET"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors.iter().any(|e| e.message.contains("requires 'url'")));
    }

    #[test]
    fn test_validate_missing_condition_fields() {
        let toml_str = r#"
[workflow]
name = "missing-cond"

[[steps]]
id = "s1"
name = "Step 1"
type = "condition"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'condition'")));
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'on_true'")));
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'on_false'")));
    }

    #[test]
    fn test_validate_missing_delay_seconds() {
        let toml_str = r#"
[workflow]
name = "missing-delay"

[[steps]]
id = "s1"
name = "Step 1"
type = "delay"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'delay_seconds'")));
    }

    #[test]
    fn test_validate_missing_notification_fields() {
        let toml_str = r#"
[workflow]
name = "missing-notif"

[[steps]]
id = "s1"
name = "Step 1"
type = "notification"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'channel'")));
        assert!(errors
            .iter()
            .any(|e| e.message.contains("requires 'message'")));
    }

    #[test]
    fn test_validate_unknown_dependency() {
        let toml_str = r#"
[workflow]
name = "bad-dep"

[[steps]]
id = "s1"
name = "Step 1"
type = "agent"
role = "coder"
prompt = "hello"
depends_on = ["nonexistent"]
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("references unknown step 'nonexistent'")));
    }

    #[test]
    fn test_validate_self_dependency() {
        let toml_str = r#"
[workflow]
name = "self-dep"

[[steps]]
id = "s1"
name = "Step 1"
type = "agent"
role = "coder"
prompt = "hello"
depends_on = ["s1"]
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("depends on itself")));
    }

    #[test]
    fn test_validate_circular_dependency() {
        let toml_str = r#"
[workflow]
name = "circular"

[[steps]]
id = "a"
name = "A"
type = "agent"
role = "r"
prompt = "p"
depends_on = ["b"]

[[steps]]
id = "b"
name = "B"
type = "agent"
role = "r"
prompt = "p"
depends_on = ["a"]
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("circular dependency")));
    }

    #[test]
    fn test_validate_condition_unknown_branch_target() {
        let toml_str = r#"
[workflow]
name = "bad-branch"

[[steps]]
id = "s1"
name = "Check"
type = "condition"
condition = "x > 1"
on_true = "ghost"
on_false = "s1"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors.iter().any(|e| e
            .message
            .contains("on_true references unknown step 'ghost'")));
    }

    #[test]
    fn test_validate_duplicate_step_ids() {
        let toml_str = r#"
[workflow]
name = "dups"

[[steps]]
id = "s1"
name = "First"
type = "agent"
role = "r"
prompt = "p"

[[steps]]
id = "s1"
name = "Second"
type = "agent"
role = "r"
prompt = "p"
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("duplicate step id")));
    }

    #[test]
    fn test_validate_large_timeout_warning() {
        let toml_str = r#"
[workflow]
name = "big-timeout"

[[steps]]
id = "s1"
name = "Slow Step"
type = "agent"
role = "r"
prompt = "p"
timeout_seconds = 7200
"#;
        let wf = WorkflowDsl::parse(toml_str).unwrap();
        let errors = WorkflowDsl::validate(&wf);
        assert!(errors.iter().any(|e| {
            e.severity == ValidationSeverity::Warning && e.message.contains("exceeds 1 hour")
        }));
    }

    // -- Compile tests ------------------------------------------------------

    #[test]
    fn test_compile_minimal() {
        let def = WorkflowDsl::load(minimal_toml()).unwrap();
        assert_eq!(def.id, "minimal");
        assert_eq!(def.steps.len(), 1);
        assert!(matches!(def.trigger, WorkflowTrigger::Manual));
    }

    #[test]
    fn test_compile_full() {
        let def = WorkflowDsl::load(full_toml()).unwrap();
        assert_eq!(def.id, "full-pipeline");
        assert_eq!(def.steps.len(), 6);
        assert!(matches!(
            def.trigger,
            WorkflowTrigger::Schedule { ref cron } if cron == "0 9 * * MON"
        ));
    }

    #[test]
    fn test_compile_step_types_round_trip() {
        let def = WorkflowDsl::load(full_toml()).unwrap();
        // Ensure each step type compiled correctly.
        let agent = def.steps.iter().find(|s| s.id == "analyze").unwrap();
        assert!(matches!(agent.step_type, StepType::AgentTask { .. }));

        let cond = def.steps.iter().find(|s| s.id == "check_severity").unwrap();
        assert!(matches!(cond.step_type, StepType::Condition { .. }));

        let http = def.steps.iter().find(|s| s.id == "block").unwrap();
        assert!(matches!(http.step_type, StepType::HttpCall { .. }));

        let notif = def.steps.iter().find(|s| s.id == "notify").unwrap();
        assert!(matches!(notif.step_type, StepType::Notification { .. }));

        let delay = def.steps.iter().find(|s| s.id == "wait").unwrap();
        assert!(matches!(delay.step_type, StepType::Delay { seconds: 30 }));

        let human = def.steps.iter().find(|s| s.id == "escalate").unwrap();
        assert!(matches!(human.step_type, StepType::AssignToHuman { .. }));
    }

    #[test]
    fn test_compile_failure_actions() {
        let toml_str = r#"
[workflow]
name = "failures"

[[steps]]
id = "s1"
name = "Skip on fail"
type = "agent"
role = "r"
prompt = "p"
on_failure = "skip"

[[steps]]
id = "s2"
name = "Abort on fail"
type = "agent"
role = "r"
prompt = "p"
on_failure = "abort"
depends_on = ["s1"]

[[steps]]
id = "s3"
name = "Retry on fail"
type = "agent"
role = "r"
prompt = "p"
on_failure = "retry"
retry = 5
depends_on = ["s2"]

[[steps]]
id = "s4"
name = "Goto on fail"
type = "agent"
role = "r"
prompt = "p"
on_failure = "s1"
depends_on = ["s3"]
"#;
        let def = WorkflowDsl::load(toml_str).unwrap();
        assert!(matches!(def.steps[0].on_failure, FailureAction::Skip));
        assert!(matches!(def.steps[1].on_failure, FailureAction::Abort));
        assert!(matches!(
            def.steps[2].on_failure,
            FailureAction::Retry { max: 5 }
        ));
        assert!(matches!(
            def.steps[3].on_failure,
            FailureAction::GoTo { ref step_id } if step_id == "s1"
        ));
    }

    #[test]
    fn test_compile_rejects_invalid() {
        let toml_str = r#"
[workflow]
name = "invalid"

[[steps]]
id = "s1"
name = "Bad"
type = "agent"
"#;
        let result = WorkflowDsl::load(toml_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_trigger_webhook() {
        let toml_str = r#"
[workflow]
name = "wh"

[triggers]
webhook = true

[[steps]]
id = "s1"
name = "S"
type = "agent"
role = "r"
prompt = "p"
"#;
        let def = WorkflowDsl::load(toml_str).unwrap();
        assert!(matches!(def.trigger, WorkflowTrigger::Webhook { .. }));
    }

    #[test]
    fn test_compile_trigger_event() {
        let toml_str = r#"
[workflow]
name = "evt"

[triggers]
on_event = "push"

[[steps]]
id = "s1"
name = "S"
type = "agent"
role = "r"
prompt = "p"
"#;
        let def = WorkflowDsl::load(toml_str).unwrap();
        assert!(matches!(
            def.trigger,
            WorkflowTrigger::Webhook { ref event } if event == "push"
        ));
    }

    #[test]
    fn test_compile_topological_order() {
        // c depends on b, b depends on a.  Even if TOML order is c, a, b,
        // the compiled output must be a, b, c.
        let toml_str = r#"
[workflow]
name = "topo"

[[steps]]
id = "c"
name = "C"
type = "agent"
role = "r"
prompt = "p"
depends_on = ["b"]

[[steps]]
id = "a"
name = "A"
type = "agent"
role = "r"
prompt = "p"

[[steps]]
id = "b"
name = "B"
type = "agent"
role = "r"
prompt = "p"
depends_on = ["a"]
"#;
        let def = WorkflowDsl::load(toml_str).unwrap();
        let ids: Vec<&str> = def.steps.iter().map(|s| s.id.as_str()).collect();
        let pos_a = ids.iter().position(|&x| x == "a").unwrap();
        let pos_b = ids.iter().position(|&x| x == "b").unwrap();
        let pos_c = ids.iter().position(|&x| x == "c").unwrap();
        assert!(pos_a < pos_b, "a must come before b");
        assert!(pos_b < pos_c, "b must come before c");
    }

    // -- Template resolution tests ------------------------------------------

    #[test]
    fn test_template_input() {
        let ctx = TemplateContext {
            input: "hello world".to_string(),
            ..Default::default()
        };
        assert_eq!(
            WorkflowDsl::resolve_template("Say: {{input}}", &ctx),
            "Say: hello world"
        );
    }

    #[test]
    fn test_template_step_output() {
        let mut ctx = TemplateContext::default();
        ctx.step_outputs
            .insert("analyze".to_string(), "all good".to_string());
        assert_eq!(
            WorkflowDsl::resolve_template("Result: {{steps.analyze.output}}", &ctx),
            "Result: all good"
        );
    }

    #[test]
    fn test_template_env_var() {
        std::env::set_var("ARGENTOR_TEST_DSL_VAR", "secret123");
        let ctx = TemplateContext::default();
        assert_eq!(
            WorkflowDsl::resolve_template("Key: {{env.ARGENTOR_TEST_DSL_VAR}}", &ctx),
            "Key: secret123"
        );
        std::env::remove_var("ARGENTOR_TEST_DSL_VAR");
    }

    #[test]
    fn test_template_variables() {
        let mut ctx = TemplateContext::default();
        ctx.variables
            .insert("project".to_string(), "argentor".to_string());
        assert_eq!(
            WorkflowDsl::resolve_template("Project: {{variables.project}}", &ctx),
            "Project: argentor"
        );
        assert_eq!(
            WorkflowDsl::resolve_template("Project: {{var.project}}", &ctx),
            "Project: argentor"
        );
    }

    #[test]
    fn test_template_unknown_placeholder() {
        let ctx = TemplateContext::default();
        assert_eq!(WorkflowDsl::resolve_template("{{unknown.thing}}", &ctx), "");
    }

    #[test]
    fn test_template_no_placeholders() {
        let ctx = TemplateContext::default();
        assert_eq!(
            WorkflowDsl::resolve_template("plain text", &ctx),
            "plain text"
        );
    }

    #[test]
    fn test_template_multiple_placeholders() {
        let mut ctx = TemplateContext {
            input: "code.rs".to_string(),
            ..Default::default()
        };
        ctx.step_outputs
            .insert("lint".to_string(), "3 warnings".to_string());
        let result =
            WorkflowDsl::resolve_template("File: {{input}}, Lint: {{steps.lint.output}}", &ctx);
        assert_eq!(result, "File: code.rs, Lint: 3 warnings");
    }

    #[test]
    fn test_template_unclosed_placeholder() {
        let ctx = TemplateContext::default();
        // Unclosed `{{` should be kept as-is.
        assert_eq!(
            WorkflowDsl::resolve_template("begin {{no_close", &ctx),
            "begin {{no_close"
        );
    }

    #[test]
    fn test_template_empty_env_var() {
        let ctx = TemplateContext::default();
        // Non-existent env var resolves to empty string.
        let result = WorkflowDsl::resolve_template("{{env.DOES_NOT_EXIST_XYZZY_1234}}", &ctx);
        assert_eq!(result, "");
    }

    // -- File I/O tests -----------------------------------------------------

    #[test]
    fn test_parse_file() {
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(minimal_toml().as_bytes()).unwrap();
        let wf = WorkflowDsl::parse_file(tmp.path()).unwrap();
        assert_eq!(wf.workflow.name, "minimal");
    }

    #[test]
    fn test_load_file() {
        let mut tmp = tempfile::NamedTempFile::new().unwrap();
        tmp.write_all(full_toml().as_bytes()).unwrap();
        let def = WorkflowDsl::load_file(tmp.path()).unwrap();
        assert_eq!(def.id, "full-pipeline");
        assert_eq!(def.steps.len(), 6);
    }

    #[test]
    fn test_parse_file_not_found() {
        let result = WorkflowDsl::parse_file(Path::new("/tmp/nonexistent_workflow.toml"));
        assert!(result.is_err());
    }

    // -- Integration: compile and run with WorkflowEngine -------------------

    #[tokio::test]
    async fn test_compile_and_run_with_engine() {
        use crate::workflow::WorkflowEngine;

        let def = WorkflowDsl::load(minimal_toml()).unwrap();
        let engine = WorkflowEngine::new();
        engine.register_workflow(def).await;

        let run_id = engine
            .start("minimal", serde_json::json!({}))
            .await
            .unwrap();
        let result = engine.run_to_completion(&run_id).await.unwrap();
        assert_eq!(result.status, crate::workflow::RunStatus::Completed);
    }

    // -- Validation error Display -------------------------------------------

    #[test]
    fn test_validation_error_display() {
        let err = ValidationError {
            step_id: Some("s1".to_string()),
            message: "missing role".to_string(),
            severity: ValidationSeverity::Error,
        };
        assert_eq!(format!("{err}"), "[ERROR] step 's1': missing role");

        let warn = ValidationError {
            step_id: None,
            message: "something odd".to_string(),
            severity: ValidationSeverity::Warning,
        };
        assert_eq!(format!("{warn}"), "[WARNING] something odd");
    }

    // -- Topological sort unit tests ----------------------------------------

    #[test]
    fn test_topological_sort_linear() {
        let steps = vec![
            StepToml {
                id: "c".into(),
                name: "C".into(),
                step_type: "agent".into(),
                depends_on: Some(vec!["b".into()]),
                role: None,
                prompt: None,
                tools: None,
                model: None,
                url: None,
                method: None,
                headers: None,
                body: None,
                condition: None,
                on_true: None,
                on_false: None,
                delay_seconds: None,
                channel: None,
                message: None,
                team: None,
                timeout_seconds: None,
                retry: None,
                on_failure: None,
                run_if: None,
            },
            StepToml {
                id: "a".into(),
                name: "A".into(),
                step_type: "agent".into(),
                depends_on: None,
                role: None,
                prompt: None,
                tools: None,
                model: None,
                url: None,
                method: None,
                headers: None,
                body: None,
                condition: None,
                on_true: None,
                on_false: None,
                delay_seconds: None,
                channel: None,
                message: None,
                team: None,
                timeout_seconds: None,
                retry: None,
                on_failure: None,
                run_if: None,
            },
            StepToml {
                id: "b".into(),
                name: "B".into(),
                step_type: "agent".into(),
                depends_on: Some(vec!["a".into()]),
                role: None,
                prompt: None,
                tools: None,
                model: None,
                url: None,
                method: None,
                headers: None,
                body: None,
                condition: None,
                on_true: None,
                on_false: None,
                delay_seconds: None,
                channel: None,
                message: None,
                team: None,
                timeout_seconds: None,
                retry: None,
                on_failure: None,
                run_if: None,
            },
        ];
        let sorted = topological_sort(&steps);
        assert_eq!(sorted, vec!["a", "b", "c"]);
    }
}