bzzz-core 0.1.0

Bzzz core library - Declarative orchestration engine for AI Agents
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
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
//! SwarmFile v1
//!
//! SwarmFile defines how multiple Agent capabilities compose into a higher-order capability.
//!
//! It defines:
//! - workers: The Agent specs that participate in this swarm
//! - flow: The orchestration pattern (sequence, parallel, conditional, loop, etc.)
//! - failure behavior: What happens when a step fails
//! - timeout behavior: Time limits for the entire swarm
//! - output behavior: How outputs are collected and returned
//! - interface: Typed input/output contract (optional, enables composition)
//! - expose: Mapping from internal step outputs to external interface outputs

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{InputSchema, OutputSchema, RunError, RuntimeKind};

/// Default value for failure_inherit field
fn default_failure_inherit() -> bool {
    true
}

/// Maximum nesting depth for delegate patterns
pub const MAX_NESTING_DEPTH: u32 = 10;

/// SwarmFile version
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SwarmApiVersion {
    /// Version 1
    #[serde(rename = "bzzz.dev/v1")]
    #[default]
    V1,
}

/// Kind of resource (always "Swarm" for SwarmFile)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SwarmKind {
    /// Swarm resource
    #[default]
    Swarm,
}

/// Unique identifier for a Swarm
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SwarmId(pub String);

impl SwarmId {
    /// Create a new SwarmId
    pub fn new(name: impl Into<String>) -> Self {
        SwarmId(name.into())
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// SwarmFile Interface definition (mirrors AgentSpec.Interface, without tools)
///
/// SwarmFile.Interface does NOT include `tools` because swarms orchestrate agents,
/// not expose direct tool interfaces.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SwarmInterface {
    /// Input schema definition
    #[serde(default)]
    pub input: Option<InputSchema>,
    /// Output schema definition
    #[serde(default)]
    pub output: Option<OutputSchema>,
}

impl SwarmInterface {
    /// Create a new empty interface
    pub fn new() -> Self {
        SwarmInterface::default()
    }

    /// Set input schema
    pub fn with_input(mut self, input: InputSchema) -> Self {
        self.input = Some(input);
        self
    }

    /// Set output schema
    pub fn with_output(mut self, output: OutputSchema) -> Self {
        self.output = Some(output);
        self
    }
}

/// Expose mapping entry - maps internal step outputs to external interface outputs
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExposeMapping {
    /// Output field name in external interface
    pub name: String,
    /// Source expression (step output reference, e.g., "steps.parser.output.items")
    pub from: String,
    /// Optional transform expression (reserved for v2)
    #[serde(default)]
    pub transform: Option<String>,
}

impl ExposeMapping {
    /// Create a new expose mapping
    pub fn new(name: impl Into<String>, from: impl Into<String>) -> Self {
        ExposeMapping {
            name: name.into(),
            from: from.into(),
            transform: None,
        }
    }

    /// Set transform expression (reserved for v2)
    pub fn with_transform(mut self, transform: impl Into<String>) -> Self {
        self.transform = Some(transform.into());
        self
    }
}

/// Inline worker definition - allows defining a worker without an AgentSpec file
///
/// Inline workers are useful for:
/// - Simple command-based workers
/// - Dynamic orchestration scenarios where workers are defined at runtime
/// - Ad-hoc workflows without external spec files
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InlineWorker {
    /// Command to execute
    ///
    /// The command is executed directly by the runtime.
    /// Example: `python process.py`, `./scripts/analyze.sh`
    pub command: String,
    /// Optional environment variables for the command
    #[serde(default)]
    pub env: HashMap<String, String>,
}

impl InlineWorker {
    /// Create a new inline worker with a command
    pub fn new(command: impl Into<String>) -> Self {
        InlineWorker {
            command: command.into(),
            env: HashMap::new(),
        }
    }

    /// Add an environment variable
    pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }
}

/// Worker definition - a participating Agent in a Swarm
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Worker {
    /// Unique name for this worker within the swarm
    pub name: String,
    /// Path to the Agent Spec file (mutually exclusive with `a2a` and `inline`)
    #[serde(default)]
    pub spec: Option<std::path::PathBuf>,
    /// A2A endpoint URL (mutually exclusive with `spec` and `inline`)
    #[serde(default)]
    pub a2a: Option<String>,
    /// Inline worker definition (mutually exclusive with `spec` and `a2a`)
    #[serde(default)]
    pub inline: Option<InlineWorker>,
    /// Optional runtime override
    #[serde(default)]
    pub runtime: Option<RuntimeKind>,
    /// Optional input mapping
    ///
    /// Values support parameter substitution expressions (e.g., `{{input.x}}`)
    /// and can be any JSON value type (string, number, boolean, array, object).
    /// String values are a subset of JSON values, ensuring backward compatibility.
    #[serde(default)]
    pub input: HashMap<String, Value>,
    /// Optional output mapping
    ///
    /// Values support parameter substitution expressions (e.g., `{{steps.worker.output.y}}`)
    /// and can be any JSON value type (string, number, boolean, array, object).
    /// String values are a subset of JSON values, ensuring backward compatibility.
    #[serde(default)]
    pub output: HashMap<String, Value>,
    /// Optional per-worker timeout. Overrides SwarmFile-level timeout for this worker.
    #[serde(default, with = "serde_duration_opt")]
    pub timeout: Option<Duration>,
}

impl Worker {
    /// Create a new worker with a local Agent Spec file
    pub fn new(name: impl Into<String>, spec: impl Into<std::path::PathBuf>) -> Self {
        Worker {
            name: name.into(),
            spec: Some(spec.into()),
            a2a: None,
            inline: None,
            runtime: None,
            input: HashMap::new(),
            output: HashMap::new(),
            timeout: None,
        }
    }

    /// Create a new A2A worker (remote agent via A2A protocol)
    pub fn new_a2a(name: impl Into<String>, url: impl Into<String>) -> Self {
        Worker {
            name: name.into(),
            spec: None,
            a2a: Some(url.into()),
            inline: None,
            runtime: None,
            input: HashMap::new(),
            output: HashMap::new(),
            timeout: None,
        }
    }

    /// Create a new inline worker (direct command execution)
    pub fn new_inline(name: impl Into<String>, command: impl Into<String>) -> Self {
        Worker {
            name: name.into(),
            spec: None,
            a2a: None,
            inline: Some(InlineWorker::new(command)),
            runtime: None,
            input: HashMap::new(),
            output: HashMap::new(),
            timeout: None,
        }
    }

    /// Set runtime override
    pub fn with_runtime(mut self, runtime: RuntimeKind) -> Self {
        self.runtime = Some(runtime);
        self
    }

    /// Add an input mapping with a string value
    ///
    /// Convenience method for common string values.
    /// For complex values, use `with_input_value`.
    pub fn with_input(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.input.insert(key.into(), Value::String(value.into()));
        self
    }

    /// Add an input mapping with any JSON value
    pub fn with_input_value(mut self, key: impl Into<String>, value: Value) -> Self {
        self.input.insert(key.into(), value);
        self
    }

    /// Add an output mapping with a string value
    ///
    /// Convenience method for common string values.
    /// For complex values, use `with_output_value`.
    pub fn with_output(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.output.insert(key.into(), Value::String(value.into()));
        self
    }

    /// Add an output mapping with any JSON value
    pub fn with_output_value(mut self, key: impl Into<String>, value: Value) -> Self {
        self.output.insert(key.into(), value);
        self
    }

    /// Set per-worker timeout. Overrides SwarmFile-level timeout for this worker.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

/// Task definition for workflow pattern - a unit of work with dependencies
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowTask {
    /// Task name (must match a worker name)
    pub name: String,
    /// List of task names that must complete before this task can run
    #[serde(default)]
    pub depends_on: Vec<String>,
}

impl WorkflowTask {
    /// Create a new workflow task
    pub fn new(name: impl Into<String>) -> Self {
        WorkflowTask {
            name: name.into(),
            depends_on: vec![],
        }
    }

    /// Add a dependency
    pub fn with_depends_on(mut self, deps: Vec<String>) -> Self {
        self.depends_on = deps;
        self
    }
}

/// Orchestration pattern type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FlowPattern {
    /// Sequential execution of workers
    Sequence {
        /// Worker names in execution order
        #[serde(default)]
        steps: Vec<String>,
    },
    /// Parallel execution of workers
    Parallel {
        /// Worker names to execute concurrently
        #[serde(default)]
        branches: Vec<String>,
        /// Fail fast or wait for all
        #[serde(default)]
        fail_fast: bool,
    },
    /// Conditional execution
    Conditional {
        /// Condition expression
        condition: String,
        /// Branch to take if true
        then: String,
        /// Branch to take if false
        #[serde(default)]
        else_: Option<String>,
    },
    /// Loop execution
    Loop {
        /// Variable to iterate over
        over: String,
        /// Worker to execute in each iteration
        do_: String,
        /// Maximum iterations (0 = unlimited)
        #[serde(default)]
        max_iterations: u32,
    },
    /// Delegate to another Swarm
    Delegate {
        /// Path to the delegate SwarmFile (optional)
        ///
        /// If provided, delegates to a nested SwarmFile.
        /// If not provided, uses worker_expr for dynamic worker selection.
        #[serde(default)]
        swarm: Option<PathBuf>,
        /// Input mapping for nested pattern
        ///
        /// Maps parent scope values to nested pattern inputs.
        /// Values support parameter substitution expressions.
        #[serde(default)]
        input_mapping: HashMap<String, Value>,
        /// Output mapping from nested pattern
        ///
        /// Maps nested pattern outputs to parent scope.
        /// Values support parameter substitution expressions.
        #[serde(default)]
        output_mapping: HashMap<String, Value>,
        /// Whether to inherit failure behavior from parent
        ///
        /// If true, nested pattern failure propagates to parent.
        /// If false, nested pattern failure is handled locally.
        #[serde(default = "default_failure_inherit")]
        failure_inherit: bool,
        /// Dynamic worker selection expression (P2-5)
        ///
        /// Expression that resolves to a worker name from the swarm's workers list.
        /// Example: `{{input.processor_type}}` selects worker matching input value.
        ///
        /// Mutually exclusive with `swarm` - if both are provided, `swarm` takes precedence.
        #[serde(default)]
        worker_expr: Option<String>,
        /// Fallback worker when expression fails or no match (P2-5)
        ///
        /// Worker name to use when:
        /// - Expression evaluation fails
        /// - Resolved worker name not found in workers list
        ///
        /// If not provided and selection fails, the delegate pattern fails.
        #[serde(default)]
        fallback: Option<String>,
    },
    /// Supervisor pattern - monitor and restart
    Supervisor {
        /// Workers to supervise
        workers: Vec<String>,
        /// Restart policy
        #[serde(default)]
        restart_policy: RestartPolicy,
        /// Recovery escalation policy (Retry → Replan → Decompose)
        #[serde(default)]
        recovery_policy: Option<RecoveryPolicy>,
    },
    /// Compete pattern - first to complete wins
    Compete {
        /// Competing workers
        workers: Vec<String>,
    },
    /// Escalation pattern - escalate on failure
    Escalation {
        /// Primary worker
        primary: String,
        /// Escalation chain
        chain: Vec<String>,
    },
    /// Alongside pattern - run alongside main flow
    Alongside {
        /// Main worker
        main: String,
        /// Side workers (run in background)
        side: Vec<String>,
    },
    /// Workflow pattern - DAG-based execution with explicit dependencies
    Workflow {
        /// Tasks to execute (each task references a worker by name)
        tasks: Vec<WorkflowTask>,
        /// Optional synthesis worker to aggregate all task outputs
        #[serde(default)]
        synthesis: Option<String>,
    },
}

impl FlowPattern {
    /// Get the pattern type name
    pub fn type_name(&self) -> &'static str {
        match self {
            FlowPattern::Sequence { .. } => "sequence",
            FlowPattern::Parallel { .. } => "parallel",
            FlowPattern::Conditional { .. } => "conditional",
            FlowPattern::Loop { .. } => "loop",
            FlowPattern::Delegate { .. } => "delegate",
            FlowPattern::Supervisor { .. } => "supervisor",
            FlowPattern::Compete { .. } => "compete",
            FlowPattern::Escalation { .. } => "escalation",
            FlowPattern::Alongside { .. } => "alongside",
            FlowPattern::Workflow { .. } => "workflow",
        }
    }

    /// Get worker names statically referenced in this pattern.
    ///
    /// Dynamic expressions (e.g., `Delegate.worker_expr`) are skipped.
    /// Only static worker name literals are returned.
    pub fn referenced_worker_names(&self) -> Vec<&str> {
        match self {
            FlowPattern::Sequence { steps } => steps.iter().map(String::as_str).collect(),
            FlowPattern::Parallel { branches, .. } => {
                branches.iter().map(String::as_str).collect()
            }
            FlowPattern::Conditional { then, else_, .. } => {
                let mut names = vec![then.as_str()];
                if let Some(e) = else_ {
                    names.push(e.as_str());
                }
                names
            }
            FlowPattern::Loop { do_, .. } => vec![do_.as_str()],
            FlowPattern::Delegate { fallback, .. } => {
                // worker_expr is a dynamic expression — skip validation
                // fallback is a static worker name — validate if present
                if let Some(f) = fallback {
                    vec![f.as_str()]
                } else {
                    vec![]
                }
            }
            FlowPattern::Supervisor { workers, .. } => {
                workers.iter().map(String::as_str).collect()
            }
            FlowPattern::Compete { workers } => workers.iter().map(String::as_str).collect(),
            FlowPattern::Escalation { primary, chain } => {
                let mut names = vec![primary.as_str()];
                names.extend(chain.iter().map(String::as_str));
                names
            }
            FlowPattern::Alongside { main, side } => {
                let mut names = vec![main.as_str()];
                names.extend(side.iter().map(String::as_str));
                names
            }
            FlowPattern::Workflow { tasks, synthesis } => {
                let mut names: Vec<&str> = tasks.iter().map(|t| t.name.as_str()).collect();
                if let Some(s) = synthesis {
                    names.push(s.as_str());
                }
                names
            }
        }
    }
}

/// Restart policy for supervisor pattern
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RestartPolicy {
    /// Never restart
    Never,
    /// Restart on failure
    #[default]
    OnFailure,
    /// Always restart
    Always,
}

/// Recovery escalation policy for supervisor pattern
///
/// Defines a three-phase failure recovery strategy:
/// 1. Retry: Simple retry of the failed worker
/// 2. Replan: Try a different worker/expression
/// 3. Decompose: Break down the task into smaller pieces
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub struct RecoveryPolicy {
    /// Phase 1: Simple retry - number of retry attempts before escalation
    #[serde(default = "default_retry_attempts")]
    pub retry_attempts: u32,
    /// Phase 2: Replan - alternative worker expression to try
    #[serde(default)]
    pub replan_expr: Option<String>,
    /// Phase 2: Fallback worker when replan expression fails
    #[serde(default)]
    pub replan_fallback: Option<String>,
    /// Phase 3: Decompose - sub-swarm to delegate to
    #[serde(default)]
    pub decompose_swarm: Option<PathBuf>,
    /// Phase 3: Input mapping for decompose swarm
    #[serde(default)]
    pub decompose_input: HashMap<String, Value>,
    /// Phase 3: Output mapping from decompose swarm
    #[serde(default)]
    pub decompose_output: HashMap<String, Value>,
}

fn default_retry_attempts() -> u32 {
    3
}

impl RecoveryPolicy {
    /// Create a default recovery policy with 3 retry attempts
    pub fn new() -> Self {
        RecoveryPolicy {
            retry_attempts: default_retry_attempts(),
            replan_expr: None,
            replan_fallback: None,
            decompose_swarm: None,
            decompose_input: HashMap::new(),
            decompose_output: HashMap::new(),
        }
    }

    /// Set retry attempts
    pub fn with_retry_attempts(mut self, attempts: u32) -> Self {
        self.retry_attempts = attempts;
        self
    }

    /// Set replan expression
    pub fn with_replan(mut self, expr: impl Into<String>) -> Self {
        self.replan_expr = Some(expr.into());
        self
    }

    /// Set replan fallback worker
    pub fn with_replan_fallback(mut self, fallback: impl Into<String>) -> Self {
        self.replan_fallback = Some(fallback.into());
        self
    }

    /// Set decompose swarm
    pub fn with_decompose(mut self, swarm: impl Into<PathBuf>) -> Self {
        self.decompose_swarm = Some(swarm.into());
        self
    }

    /// Set decompose input mapping
    pub fn with_decompose_input(mut self, input: HashMap<String, Value>) -> Self {
        self.decompose_input = input;
        self
    }

    /// Set decompose output mapping
    pub fn with_decompose_output(mut self, output: HashMap<String, Value>) -> Self {
        self.decompose_output = output;
        self
    }
}

/// Failure behavior
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum FailureBehavior {
    /// Fail the entire swarm immediately
    #[default]
    FailFast,
    /// Continue with remaining steps
    Continue,
    /// Ignore failure and mark as success
    Ignore,
}

/// Output behavior
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum OutputBehavior {
    /// Collect all outputs
    All,
    /// Only last step's output
    #[default]
    Last,
    /// Custom aggregation
    Aggregate,
}

/// SwarmFile v1
///
/// Defines how multiple Agent capabilities compose into a higher-order capability.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SwarmFile {
    /// API version
    #[serde(rename = "apiVersion")]
    pub api_version: SwarmApiVersion,
    /// Resource kind
    pub kind: SwarmKind,
    /// Unique identifier
    pub id: SwarmId,
    /// Participating workers
    pub workers: Vec<Worker>,
    /// Orchestration flow
    pub flow: FlowPattern,
    /// Default runtime for all workers (worker-level override takes precedence)
    #[serde(default)]
    pub runtime: Option<RuntimeKind>,
    /// Failure behavior
    #[serde(default)]
    pub on_failure: FailureBehavior,
    /// Timeout for the entire swarm
    #[serde(default, with = "serde_duration_opt")]
    pub timeout: Option<Duration>,
    /// Output behavior
    #[serde(default)]
    pub output: OutputBehavior,
    /// Interface definition (typed input/output contract)
    #[serde(default)]
    pub interface: SwarmInterface,
    /// Output exposure mapping
    #[serde(default)]
    pub expose: Vec<ExposeMapping>,
    /// Path to the SwarmFile (set when loaded)
    #[serde(skip)]
    pub file_path: Option<PathBuf>,
}

mod serde_duration_opt {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(value: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(d) => d.as_secs().serialize(serializer),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt = Option::<u64>::deserialize(deserializer)?;
        Ok(opt.map(Duration::from_secs))
    }
}

impl SwarmFile {
    /// Create a new SwarmFile with the given ID
    pub fn new(id: impl Into<String>, flow: FlowPattern) -> Self {
        SwarmFile {
            api_version: SwarmApiVersion::V1,
            kind: SwarmKind::Swarm,
            id: SwarmId::new(id),
            workers: Vec::new(),
            flow,
            runtime: None,
            on_failure: FailureBehavior::default(),
            timeout: None,
            output: OutputBehavior::default(),
            interface: SwarmInterface::default(),
            expose: Vec::new(),
            file_path: None,
        }
    }

    /// Add a worker
    pub fn with_worker(mut self, worker: Worker) -> Self {
        self.workers.push(worker);
        self
    }

    /// Add multiple workers
    pub fn with_workers(mut self, workers: Vec<Worker>) -> Self {
        self.workers.extend(workers);
        self
    }

    /// Set failure behavior
    pub fn with_failure_behavior(mut self, behavior: FailureBehavior) -> Self {
        self.on_failure = behavior;
        self
    }

    /// Set default runtime
    pub fn with_runtime(mut self, runtime: RuntimeKind) -> Self {
        self.runtime = Some(runtime);
        self
    }

    /// Set timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set output behavior
    pub fn with_output_behavior(mut self, behavior: OutputBehavior) -> Self {
        self.output = behavior;
        self
    }

    /// Set interface definition
    pub fn with_interface(mut self, interface: SwarmInterface) -> Self {
        self.interface = interface;
        self
    }

    /// Add an expose mapping
    pub fn with_expose(mut self, expose: ExposeMapping) -> Self {
        self.expose.push(expose);
        self
    }

    /// Set all expose mappings
    pub fn with_exposes(mut self, exposes: Vec<ExposeMapping>) -> Self {
        self.expose = exposes;
        self
    }

    /// Validate the SwarmFile
    pub fn validate(&self) -> Result<(), RunError> {
        // Check ID is not empty
        if self.id.0.is_empty() {
            return Err(RunError::InvalidConfig {
                message: "SwarmFile ID cannot be empty".into(),
            });
        }

        // Check workers
        for worker in &self.workers {
            if worker.name.is_empty() {
                return Err(RunError::InvalidConfig {
                    message: "Worker name cannot be empty".into(),
                });
            }

            // Check mutual exclusivity of spec, a2a, and inline
            let has_spec = worker.spec.is_some();
            let has_a2a = worker.a2a.is_some();
            let has_inline = worker.inline.is_some();

            // Count how many worker definition types are specified
            let count = has_spec as usize + has_a2a as usize + has_inline as usize;

            if count == 0 {
                return Err(RunError::InvalidConfig {
                    message: format!(
                        "Worker '{}' must have one of: spec, a2a, or inline",
                        worker.name
                    ),
                });
            }

            if count > 1 {
                return Err(RunError::InvalidConfig {
                    message: format!(
                        "Worker '{}' has conflicting definitions (spec, a2a, inline are mutually exclusive)",
                        worker.name
                    ),
                });
            }

            // Check inline worker has non-empty command
            if let Some(inline) = &worker.inline {
                if inline.command.is_empty() {
                    return Err(RunError::InvalidConfig {
                        message: format!(
                            "Worker '{}' inline definition has empty command",
                            worker.name
                        ),
                    });
                }
            }
        }

        // Check expose mappings
        for mapping in &self.expose {
            if mapping.name.is_empty() {
                return Err(RunError::InvalidConfig {
                    message: "Expose mapping name cannot be empty".into(),
                });
            }
            if mapping.from.is_empty() {
                return Err(RunError::InvalidConfig {
                    message: "Expose mapping 'from' cannot be empty".into(),
                });
            }
        }

        // Check for duplicate expose names
        let mut seen_names = std::collections::HashSet::new();
        for mapping in &self.expose {
            if seen_names.contains(&mapping.name) {
                return Err(RunError::InvalidConfig {
                    message: format!("Duplicate expose name: {}", mapping.name),
                });
            }
            seen_names.insert(&mapping.name);
        }

        // Check that all statically referenced workers exist in the workers list
        let worker_names: std::collections::HashSet<&str> =
            self.workers.iter().map(|w| w.name.as_str()).collect();
        let pattern_type = self.flow.type_name();
        for name in self.flow.referenced_worker_names() {
            if !worker_names.contains(name) {
                return Err(RunError::InvalidConfig {
                    message: format!(
                        "pattern '{}' references undefined worker '{}'",
                        pattern_type, name
                    ),
                });
            }
        }

        // Check for circular nesting (DAG check)
        if let Some(path) = &self.file_path {
            self.validate_no_circular_nesting(path, &mut std::collections::HashSet::new())?;
        }

        // Check workflow pattern specific validation
        if let FlowPattern::Workflow { tasks, synthesis } = &self.flow {
            // Check for duplicate task names
            let mut task_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
            for task in tasks {
                if task_names.contains(task.name.as_str()) {
                    return Err(RunError::InvalidConfig {
                        message: format!("duplicate task name in workflow: {}", task.name),
                    });
                }
                task_names.insert(task.name.as_str());
            }

            // Check that all depends_on references exist
            for task in tasks {
                for dep in &task.depends_on {
                    if !task_names.contains(dep.as_str()) {
                        return Err(RunError::InvalidConfig {
                            message: format!(
                                "Task '{}' depends on undefined task '{}'",
                                task.name, dep
                            ),
                        });
                    }
                }
            }

            // Check for cycles using DFS
            if has_workflow_cycle(tasks) {
                return Err(RunError::InvalidConfig {
                    message: "workflow contains a cycle in dependencies".into(),
                });
            }

            // Check synthesis worker exists if specified
            if let Some(synth) = synthesis {
                if !worker_names.contains(synth.as_str()) {
                    return Err(RunError::InvalidConfig {
                        message: format!(
                            "Workflow synthesis worker '{}' not found in workers list",
                            synth
                        ),
                    });
                }
            }
        }

        Ok(())
    }
}

/// Check if workflow tasks contain circular dependencies.
///
/// Uses iterative DFS to detect cycles in the dependency graph.
/// Returns true if a cycle is found.
fn has_workflow_cycle(tasks: &[WorkflowTask]) -> bool {
    // Build adjacency map: task_name -> list of tasks that depend on it
    let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
    for task in tasks {
        for dep in &task.depends_on {
            adj.entry(dep.as_str()).or_default().push(task.name.as_str());
        }
    }

    // Track visited and in-progress nodes
    let mut visited: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let mut in_progress: std::collections::HashSet<&str> = std::collections::HashSet::new();

    // Iterative DFS using explicit stack
    // Each stack entry is (node, is_backtrack)
    // is_backtrack=true means we're finishing the node (removing from in_progress)
    for task in tasks {
        let start = task.name.as_str();
        if visited.contains(start) {
            continue;
        }

        let mut stack: Vec<(&str, bool)> = vec![(start, false)];

        while let Some((node, is_backtrack)) = stack.pop() {
            if is_backtrack {
                // Backtrack: remove from in_progress
                in_progress.remove(node);
                continue;
            }

            if visited.contains(node) {
                continue;
            }

            // Check for cycle: node is being processed
            if in_progress.contains(node) {
                return true; // Cycle detected
            }

            // Mark as in-progress and push backtrack marker
            in_progress.insert(node);
            stack.push((node, true));

            // Push neighbors
            if let Some(neighbors) = adj.get(node) {
                for neighbor in neighbors {
                    if !visited.contains(neighbor) {
                        stack.push((neighbor, false));
                    }
                }
            }
        }

        // Mark all reachable nodes as visited
        visited.extend(in_progress.iter().copied());
    }

    false
}

impl SwarmFile {
    /// Validate no circular nesting in delegate patterns
    ///
    /// Performs a DAG check to ensure no SwarmFile references itself
    /// through delegate patterns (directly or indirectly).
    ///
    /// # Arguments
    /// * `current_path` - Path to the current SwarmFile being validated
    /// * `visited` - Set of already visited paths (for cycle detection)
    ///
    /// # Errors
    /// Returns `RunError::InvalidConfig` if a circular reference is detected.
    pub fn validate_no_circular_nesting(
        &self,
        current_path: &Path,
        visited: &mut std::collections::HashSet<PathBuf>,
    ) -> Result<(), RunError> {
        // Check if we've already visited this path (cycle detected)
        let canonical_path = current_path
            .canonicalize()
            .map_err(|e| RunError::InvalidConfig {
                message: format!("Failed to resolve path {}: {}", current_path.display(), e),
            })?;

        if visited.contains(&canonical_path) {
            return Err(RunError::InvalidConfig {
                message: format!(
                    "Circular nesting detected: {} references already-visited SwarmFile",
                    current_path.display()
                ),
            });
        }

        // Add current path to visited set
        visited.insert(canonical_path.clone());

        // Check delegate patterns (only for swarm delegation, not worker_expr)
        if let FlowPattern::Delegate {
            swarm: Some(swarm_path),
            ..
        } = &self.flow
        {
            // Resolve delegate path relative to current SwarmFile's directory
            let base_dir = current_path.parent().unwrap_or(std::path::Path::new("."));
            let delegate_path = base_dir.join(swarm_path);

            // Check if delegate file exists
            if delegate_path.exists() {
                // Load delegate SwarmFile and recursively validate
                let delegate_swarm = SwarmFile::from_yaml_file(&delegate_path)?;

                // Recursively check delegate for circular references
                delegate_swarm.validate_no_circular_nesting(&delegate_path, visited)?;
            }
        }

        Ok(())
    }

    /// Get the maximum nesting depth from this SwarmFile
    ///
    /// Returns the depth of delegate nesting (0 if no delegates).
    /// Used to enforce the MAX_NESTING_DEPTH limit.
    pub fn nesting_depth(&self) -> Result<u32, RunError> {
        self.compute_nesting_depth(&mut std::collections::HashSet::new())
    }

    /// Internal method to compute nesting depth with cycle detection
    fn compute_nesting_depth(
        &self,
        visited: &mut std::collections::HashSet<PathBuf>,
    ) -> Result<u32, RunError> {
        match &self.flow {
            FlowPattern::Delegate {
                swarm: Some(swarm_path),
                ..
            } => {
                // Get the path for this SwarmFile
                let current_path = self.file_path.clone().unwrap_or_default();

                // Check for cycles first
                if current_path.exists() {
                    let canonical =
                        current_path
                            .canonicalize()
                            .map_err(|e| RunError::InvalidConfig {
                                message: format!("Failed to resolve path: {}", e),
                            })?;

                    if visited.contains(&canonical) {
                        return Err(RunError::InvalidConfig {
                            message: "Circular nesting detected while computing depth".into(),
                        });
                    }
                    visited.insert(canonical);
                }

                // Resolve delegate path
                let base_dir = current_path.parent().unwrap_or(std::path::Path::new("."));
                let delegate_path = base_dir.join(swarm_path);

                // If delegate doesn't exist, depth is 1 (placeholder)
                if !delegate_path.exists() {
                    return Ok(1);
                }

                // Load delegate and compute its depth
                let delegate_swarm = SwarmFile::from_yaml_file(&delegate_path)?;
                let child_depth = delegate_swarm.compute_nesting_depth(visited)?;

                // Check against max depth
                let total_depth = 1 + child_depth;
                if total_depth > MAX_NESTING_DEPTH {
                    return Err(RunError::InvalidConfig {
                        message: format!(
                            "Nesting depth {} exceeds maximum allowed {}",
                            total_depth, MAX_NESTING_DEPTH
                        ),
                    });
                }

                Ok(total_depth)
            }
            // Non-delegate patterns have depth 0
            _ => Ok(0),
        }
    }

    /// Load from a YAML file
    pub fn from_yaml_file(path: &PathBuf) -> Result<Self, RunError> {
        let content = std::fs::read_to_string(path).map_err(|e| RunError::InvalidConfig {
            message: format!("Failed to read {}: {}", path.display(), e),
        })?;

        let mut swarm: SwarmFile =
            serde_yaml::from_str(&content).map_err(|e| RunError::InvalidConfig {
                message: format!("Failed to parse YAML: {}", e),
            })?;

        swarm.file_path = Some(path.clone());
        swarm.validate()?;
        Ok(swarm)
    }

    /// Save to a YAML file
    pub fn to_yaml_file(&self, path: &PathBuf) -> Result<(), RunError> {
        let content = serde_yaml::to_string(self).map_err(|e| RunError::InvalidConfig {
            message: format!("Failed to serialize: {}", e),
        })?;

        std::fs::write(path, content).map_err(|e| RunError::InvalidConfig {
            message: format!("Failed to write {}: {}", path.display(), e),
        })?;

        Ok(())
    }

    /// Check if this SwarmFile represents a simple task that can skip full orchestration.
    ///
    /// A simple task meets these criteria:
    /// 1. Exactly one worker
    /// 2. Pattern is a simple execution path (single-step sequence, or single worker pattern)
    ///
    /// Simple tasks can be executed directly without full scope propagation overhead.
    pub fn is_simple(&self) -> bool {
        // Must have exactly one worker
        if self.workers.len() != 1 {
            return false;
        }

        // Check pattern simplicity
        match &self.flow {
            // Single-step sequence is simple
            FlowPattern::Sequence { steps } => steps.len() == 1,

            // Single-worker patterns that can run directly
            FlowPattern::Supervisor { workers, .. } => workers.len() == 1,
            FlowPattern::Escalation { primary, chain } => chain.is_empty() && primary == &self.workers[0].name,
            FlowPattern::Alongside { main, side } => side.is_empty() && main == &self.workers[0].name,

            // Compete with single worker is effectively just running that worker
            FlowPattern::Compete { workers } => workers.len() == 1,

            // Parallel with single branch is simple
            FlowPattern::Parallel { branches, .. } => branches.len() == 1,

            // Conditional, Loop, Delegate, Workflow are inherently complex (require scope/evaluation)
            FlowPattern::Conditional { .. } => false,
            FlowPattern::Loop { .. } => false,
            FlowPattern::Delegate { .. } => false,
            FlowPattern::Workflow { .. } => false,
        }
    }
}

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

    #[test]
    fn test_swarm_file_creation() {
        let swarm = SwarmFile::new("test-swarm", FlowPattern::Sequence { steps: vec![] });
        assert_eq!(swarm.id.as_str(), "test-swarm");
        assert_eq!(swarm.api_version, SwarmApiVersion::V1);
        // New fields have defaults
        assert!(swarm.interface.input.is_none());
        assert!(swarm.interface.output.is_none());
        assert!(swarm.expose.is_empty());
    }

    #[test]
    fn test_worker() {
        let worker = Worker::new("agent1", "agent.yaml")
            .with_runtime(RuntimeKind::Local)
            .with_input("key", "value");

        assert_eq!(worker.name, "agent1");
        assert_eq!(worker.runtime, Some(RuntimeKind::Local));
        assert_eq!(
            worker.input.get("key"),
            Some(&Value::String("value".to_string()))
        );
    }

    #[test]
    fn test_worker_complex_input() {
        // Test with complex JSON value (array)
        let worker = Worker::new("agent2", "agent.yaml")
            .with_input_value(
                "items",
                Value::Array(vec![
                    Value::String("a".to_string()),
                    Value::String("b".to_string()),
                ]),
            )
            .with_input_value(
                "config",
                Value::Object(serde_json::Map::from_iter(vec![(
                    "timeout".to_string(),
                    Value::Number(30.into()),
                )])),
            );

        assert!(worker.input.get("items").unwrap().is_array());
        assert!(worker.input.get("config").unwrap().is_object());
    }

    // ===== Inline Worker Tests =====

    #[test]
    fn test_inline_worker_creation() {
        let worker = Worker::new_inline("processor", "python process.py");

        assert_eq!(worker.name, "processor");
        assert!(worker.inline.is_some());
        assert_eq!(worker.inline.unwrap().command, "python process.py");
        assert!(worker.spec.is_none());
        assert!(worker.a2a.is_none());
    }

    #[test]
    fn test_inline_worker_with_env() {
        let inline = InlineWorker::new("./scripts/analyze.sh")
            .with_env("DEBUG", "true")
            .with_env("PATH", "/usr/local/bin");

        assert_eq!(inline.command, "./scripts/analyze.sh");
        assert_eq!(inline.env.get("DEBUG"), Some(&"true".to_string()));
        assert_eq!(inline.env.get("PATH"), Some(&"/usr/local/bin".to_string()));
    }

    #[test]
    fn test_inline_worker_yaml_parsing() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: inline-test
workers:
  - name: processor
    inline:
      command: python process.py
      env:
        DEBUG: "true"
flow:
  type: sequence
  steps: [processor]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "inline-test");
        assert_eq!(parsed.workers.len(), 1);

        let worker = &parsed.workers[0];
        assert_eq!(worker.name, "processor");
        assert!(worker.inline.is_some());
        assert!(worker.spec.is_none());
        assert!(worker.a2a.is_none());

        let inline = worker.inline.as_ref().unwrap();
        assert_eq!(inline.command, "python process.py");
        assert_eq!(inline.env.get("DEBUG"), Some(&"true".to_string()));
    }

    #[test]
    fn test_inline_worker_yaml_roundtrip() {
        let swarm = SwarmFile::new(
            "inline-demo",
            FlowPattern::Sequence {
                steps: vec!["worker1".into()],
            },
        )
        .with_worker(Worker::new_inline("worker1", "echo hello"));

        let yaml = serde_yaml::to_string(&swarm).unwrap();
        let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(parsed.id, swarm.id);
        assert_eq!(parsed.workers.len(), 1);
        assert!(parsed.workers[0].inline.is_some());
    }

    #[test]
    fn test_inline_worker_validation() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Sequence {
                steps: vec!["inline_worker".into()],
            },
        )
        .with_worker(Worker::new_inline("inline_worker", "python script.py"));
        assert!(swarm.validate().is_ok());
    }

    #[test]
    fn test_inline_worker_minimal_yaml() {
        // Inline worker with minimal config (no env)
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: minimal-inline
workers:
  - name: simple
    inline:
      command: echo "hello"
flow:
  type: sequence
  steps: [simple]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert!(parsed.validate().is_ok());

        let inline = parsed.workers[0].inline.as_ref().unwrap();
        assert_eq!(inline.command, "echo \"hello\"");
        assert!(inline.env.is_empty());
    }

    #[test]
    fn test_inline_worker_backward_compatibility() {
        // SwarmFile without inline should still parse correctly
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: legacy-swarm
workers:
  - name: agent1
    spec: agent.yaml
flow:
  type: sequence
  steps: [agent1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "legacy-swarm");
        assert!(parsed.workers[0].inline.is_none());
        assert!(parsed.validate().is_ok());
    }

    #[test]
    fn test_worker_validation_missing_definition() {
        // Worker with no spec, a2a, or inline should fail validation
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: missing-def
workers:
  - name: worker1
flow:
  type: sequence
  steps: [worker1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        let err = parsed.validate().unwrap_err();
        assert!(err.to_string().contains("must have one of"));
    }

    #[test]
    fn test_worker_validation_conflicting_spec_and_inline() {
        // Worker with both spec and inline should fail validation
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: conflict-spec-inline
workers:
  - name: worker1
    spec: agent.yaml
    inline:
      command: echo hello
flow:
  type: sequence
  steps: [worker1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        let err = parsed.validate().unwrap_err();
        assert!(err.to_string().contains("conflicting definitions"));
    }

    #[test]
    fn test_worker_validation_conflicting_a2a_and_inline() {
        // Worker with both a2a and inline should fail validation
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: conflict-a2a-inline
workers:
  - name: worker1
    a2a: https://agent.example.com
    inline:
      command: echo hello
flow:
  type: sequence
  steps: [worker1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        let err = parsed.validate().unwrap_err();
        assert!(err.to_string().contains("conflicting definitions"));
    }

    #[test]
    fn test_worker_validation_conflicting_spec_and_a2a() {
        // Worker with both spec and a2a should fail validation
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: conflict-spec-a2a
workers:
  - name: worker1
    spec: agent.yaml
    a2a: https://agent.example.com
flow:
  type: sequence
  steps: [worker1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        let err = parsed.validate().unwrap_err();
        assert!(err.to_string().contains("conflicting definitions"));
    }

    #[test]
    fn test_inline_worker_empty_command_validation() {
        // Inline worker with empty command should fail validation
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: empty-command
workers:
  - name: worker1
    inline:
      command: ""
flow:
  type: sequence
  steps: [worker1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        let err = parsed.validate().unwrap_err();
        assert!(err.to_string().contains("empty command"));
    }

    #[test]
    fn test_flow_patterns() {
        let sequence = FlowPattern::Sequence {
            steps: vec!["step1".into(), "step2".into()],
        };
        assert!(matches!(sequence, FlowPattern::Sequence { .. }));

        let parallel = FlowPattern::Parallel {
            branches: vec!["a".into(), "b".into()],
            fail_fast: true,
        };
        assert!(matches!(parallel, FlowPattern::Parallel { .. }));

        let conditional = FlowPattern::Conditional {
            condition: "x > 0".into(),
            then: "a".into(),
            else_: Some("b".into()),
        };
        assert!(matches!(conditional, FlowPattern::Conditional { .. }));
    }

    #[test]
    fn test_swarm_validation() {
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_worker(Worker::new("w1", "agent.yaml"));
        assert!(swarm.validate().is_ok());

        let invalid = SwarmFile::new("", FlowPattern::Sequence { steps: vec![] });
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn test_yaml_roundtrip() {
        let swarm = SwarmFile::new(
            "test-swarm",
            FlowPattern::Sequence {
                steps: vec!["a".into()],
            },
        )
        .with_worker(Worker::new("agent1", "agent.yaml"))
        .with_timeout(Duration::from_secs(60));

        let yaml = serde_yaml::to_string(&swarm).unwrap();
        let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(parsed.id, swarm.id);
        assert_eq!(parsed.workers.len(), 1);
        assert_eq!(parsed.timeout, swarm.timeout);
    }

    #[test]
    fn test_all_patterns() {
        // Test all P0 patterns
        let patterns = vec![
            FlowPattern::Sequence { steps: vec![] },
            FlowPattern::Parallel {
                branches: vec![],
                fail_fast: false,
            },
            FlowPattern::Conditional {
                condition: "true".into(),
                then: "a".into(),
                else_: None,
            },
            FlowPattern::Loop {
                over: "items".into(),
                do_: "process".into(),
                max_iterations: 0,
            },
            FlowPattern::Delegate {
                swarm: Some(PathBuf::from("sub.yaml")),
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
            FlowPattern::Supervisor {
                workers: vec![],
                restart_policy: RestartPolicy::OnFailure,
                recovery_policy: None,
            },
            FlowPattern::Compete { workers: vec![] },
            FlowPattern::Escalation {
                primary: "main".into(),
                chain: vec![],
            },
            FlowPattern::Alongside {
                main: "main".into(),
                side: vec![],
            },
        ];

        for pattern in patterns {
            let swarm = SwarmFile::new("test", pattern.clone());
            let yaml = serde_yaml::to_string(&swarm).unwrap();
            let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();
            assert_eq!(parsed.flow, pattern);
        }
    }

    // ===== New tests for SwarmInterface and ExposeMapping =====

    #[test]
    fn test_swarm_interface_creation() {
        // Empty interface
        let empty = SwarmInterface::new();
        assert!(empty.input.is_none());
        assert!(empty.output.is_none());

        // Interface with schemas
        let interface = SwarmInterface::new()
            .with_input(InputSchema::new(serde_json::json!({
                "type": "object",
                "properties": { "query": { "type": "string" } },
                "required": ["query"]
            })))
            .with_output(OutputSchema::new(serde_json::json!({
                "type": "object",
                "properties": { "result": { "type": "string" } }
            })));

        assert!(interface.input.is_some());
        assert!(interface.output.is_some());
    }

    #[test]
    fn test_expose_mapping_creation() {
        let mapping = ExposeMapping::new("results", "steps.parser.output.items");
        assert_eq!(mapping.name, "results");
        assert_eq!(mapping.from, "steps.parser.output.items");
        assert!(mapping.transform.is_none());

        // With transform (reserved for v2)
        let with_transform = mapping.with_transform("uppercase");
        assert_eq!(with_transform.transform, Some("uppercase".to_string()));
    }

    #[test]
    fn test_swarm_with_interface() {
        let swarm = SwarmFile::new(
            "data-processor",
            FlowPattern::Sequence {
                steps: vec!["fetcher".into()],
            },
        )
        .with_interface(
            SwarmInterface::new()
                .with_input(InputSchema::new(serde_json::json!({
                    "type": "object",
                    "properties": { "query": { "type": "string" } }
                })))
                .with_output(OutputSchema::new(serde_json::json!({
                    "type": "object",
                    "properties": { "results": { "type": "array" } }
                }))),
        );

        assert!(swarm.interface.input.is_some());
        assert!(swarm.interface.output.is_some());
    }

    #[test]
    fn test_swarm_with_expose() {
        let swarm = SwarmFile::new(
            "processor",
            FlowPattern::Sequence {
                steps: vec!["parser".into()],
            },
        )
        .with_expose(ExposeMapping::new("results", "steps.parser.output.items"))
        .with_expose(ExposeMapping::new("count", "steps.parser.output.total"));

        assert_eq!(swarm.expose.len(), 2);
        assert_eq!(swarm.expose[0].name, "results");
        assert_eq!(swarm.expose[1].name, "count");
    }

    #[test]
    fn test_swarm_with_exposes() {
        let exposes = vec![
            ExposeMapping::new("results", "steps.parser.output.items"),
            ExposeMapping::new("count", "steps.parser.output.total"),
        ];
        let swarm = SwarmFile::new("processor", FlowPattern::Sequence { steps: vec![] })
            .with_exposes(exposes);

        assert_eq!(swarm.expose.len(), 2);
    }

    #[test]
    fn test_expose_validation_duplicate_names() {
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_expose(ExposeMapping::new("result", "steps.a.output.x"))
            .with_expose(ExposeMapping::new("result", "steps.b.output.y")); // Duplicate name

        assert!(swarm.validate().is_err());
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("Duplicate expose name"));
    }

    #[test]
    fn test_expose_validation_empty_name() {
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_expose(ExposeMapping::new("", "steps.a.output.x"));

        assert!(swarm.validate().is_err());
        let err = swarm.validate().unwrap_err();
        assert!(err
            .to_string()
            .contains("Expose mapping name cannot be empty"));
    }

    #[test]
    fn test_expose_validation_empty_from() {
        let mapping = ExposeMapping {
            name: "result".to_string(),
            from: "".to_string(),
            transform: None,
        };
        let swarm =
            SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] }).with_expose(mapping);

        assert!(swarm.validate().is_err());
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("'from' cannot be empty"));
    }

    #[test]
    fn test_interface_yaml_roundtrip() {
        let swarm = SwarmFile::new(
            "api",
            FlowPattern::Sequence {
                steps: vec!["step1".into()],
            },
        )
        .with_interface(
            SwarmInterface::new()
                .with_input(InputSchema::new(serde_json::json!({
                    "type": "object",
                    "properties": { "query": { "type": "string" } }
                })))
                .with_output(OutputSchema::new(serde_json::json!({
                    "type": "object",
                    "properties": { "result": { "type": "string" } }
                }))),
        )
        .with_expose(ExposeMapping::new("result", "steps.step1.output.value"));

        let yaml = serde_yaml::to_string(&swarm).unwrap();
        let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(parsed.id, swarm.id);
        assert!(parsed.interface.input.is_some());
        assert!(parsed.interface.output.is_some());
        assert_eq!(parsed.expose.len(), 1);
        assert_eq!(parsed.expose[0].name, "result");
    }

    #[test]
    fn test_backward_compatibility_no_interface() {
        // SwarmFile without interface should still parse correctly
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: legacy-swarm
workers:
  - name: agent1
    spec: agent.yaml
flow:
  type: sequence
  steps: [agent1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "legacy-swarm");
        assert!(parsed.interface.input.is_none());
        assert!(parsed.interface.output.is_none());
        assert!(parsed.expose.is_empty());
        assert!(parsed.validate().is_ok());
    }

    #[test]
    fn test_interface_yaml_parsing() {
        // Parse YAML with interface and expose
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: data-processor
interface:
  input:
    schema:
      type: object
      properties:
        query:
          type: string
      required: [query]
    required: true
  output:
    schema:
      type: object
      properties:
        results:
          type: array
        count:
          type: integer
      required: [results, count]
workers:
  - name: parser
    spec: parser.yaml
flow:
  type: sequence
  steps: [parser]
expose:
  - name: results
    from: steps.parser.output.items
  - name: count
    from: steps.parser.output.total
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "data-processor");
        assert!(parsed.interface.input.is_some());
        assert!(parsed.interface.output.is_some());
        assert_eq!(parsed.expose.len(), 2);
        assert!(parsed.validate().is_ok());
    }

    // ===== Tests for Runtime Selection =====

    #[test]
    fn test_swarm_with_runtime() {
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] })
            .with_runtime(RuntimeKind::Docker);

        assert_eq!(swarm.runtime, Some(RuntimeKind::Docker));
    }

    #[test]
    fn test_swarm_runtime_yaml_roundtrip() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Sequence {
                steps: vec!["step1".into()],
            },
        )
        .with_worker(Worker::new("w1", "agent.yaml"))
        .with_runtime(RuntimeKind::Docker);

        let yaml = serde_yaml::to_string(&swarm).unwrap();
        let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();

        assert_eq!(parsed.runtime, Some(RuntimeKind::Docker));
    }

    #[test]
    fn test_swarm_runtime_backward_compatible() {
        // SwarmFile without runtime should still parse correctly
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: test-swarm
workers:
  - name: agent1
    spec: agent.yaml
flow:
  type: sequence
  steps: [agent1]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "test-swarm");
        assert_eq!(parsed.runtime, None);
    }

    #[test]
    fn test_worker_runtime_override() {
        let worker = Worker::new("agent1", "agent.yaml").with_runtime(RuntimeKind::Http);

        assert_eq!(worker.runtime, Some(RuntimeKind::Http));
    }

    #[test]
    fn test_swarm_with_worker_runtime_override_yaml() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: test-swarm
runtime: Docker
workers:
  - name: agent1
    spec: agent.yaml
    runtime: Http
  - name: agent2
    spec: agent.yaml
flow:
  type: sequence
  steps: [agent1, agent2]
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();

        // Swarm-level default is Docker
        assert_eq!(parsed.runtime, Some(RuntimeKind::Docker));

        // Worker 1 overrides to Http
        assert_eq!(parsed.workers[0].runtime, Some(RuntimeKind::Http));

        // Worker 2 uses default (None means use swarm default)
        assert_eq!(parsed.workers[1].runtime, None);
    }

    // ===== P2-1: Tests for Delegate Pattern Nesting =====

    #[test]
    fn test_delegate_pattern_with_input_output_mapping() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: Some(PathBuf::from("sub.yaml")),
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::from([(
                    "query".to_string(),
                    Value::String("{{input.search}}".to_string()),
                )]),
                output_mapping: HashMap::from([(
                    "result".to_string(),
                    Value::String("{{steps.delegate.output.data}}".to_string()),
                )]),
                failure_inherit: true,
            },
        );

        // Verify the pattern can be created and serialized
        let yaml = serde_yaml::to_string(&swarm).unwrap();
        let parsed: SwarmFile = serde_yaml::from_str(&yaml).unwrap();

        assert!(matches!(parsed.flow, FlowPattern::Delegate { .. }));
    }

    #[test]
    fn test_delegate_pattern_yaml_parsing() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: parent-swarm
workers:
  - name: prep
    spec: prep.yaml
flow:
  type: delegate
  swarm: child.yaml
  input_mapping:
    query: "{{input.search}}"
    limit: 10
  output_mapping:
    result: "{{steps.delegate.output.data}}"
  failure_inherit: true
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "parent-swarm");

        if let FlowPattern::Delegate {
            swarm,
            worker_expr,
            fallback,
            input_mapping,
            output_mapping: _,
            failure_inherit,
        } = &parsed.flow
        {
            assert_eq!(swarm, &Some(PathBuf::from("child.yaml")));
            assert!(worker_expr.is_none());
            assert!(fallback.is_none());
            assert_eq!(
                input_mapping.get("query"),
                Some(&Value::String("{{input.search}}".to_string()))
            );
            assert_eq!(input_mapping.get("limit"), Some(&Value::Number(10.into())));
            assert!(*failure_inherit);
        } else {
            panic!("Expected Delegate pattern");
        }
    }

    #[test]
    fn test_delegate_pattern_defaults() {
        // Test that delegate pattern with minimal config uses defaults
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: minimal-delegate
workers: []
flow:
  type: delegate
  swarm: sub.yaml
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();

        if let FlowPattern::Delegate {
            swarm,
            worker_expr,
            fallback,
            input_mapping,
            output_mapping,
            failure_inherit,
        } = &parsed.flow
        {
            assert_eq!(swarm, &Some(PathBuf::from("sub.yaml")));
            assert!(worker_expr.is_none());
            assert!(fallback.is_none());
            assert!(input_mapping.is_empty());
            assert!(output_mapping.is_empty());
            assert!(*failure_inherit); // Default is true
        } else {
            panic!("Expected Delegate pattern");
        }
    }

    // ===== P2-5: Tests for Dynamic Worker Selection =====

    #[test]
    fn test_delegate_pattern_with_worker_expr() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: dynamic-selector
workers:
  - name: processor_a
    spec: processor_a.yaml
  - name: processor_b
    spec: processor_b.yaml
  - name: default_worker
    spec: default.yaml
flow:
  type: delegate
  worker_expr: "{{input.processor_type}}"
  fallback: default_worker
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "dynamic-selector");

        if let FlowPattern::Delegate {
            swarm,
            worker_expr,
            fallback,
            input_mapping,
            output_mapping,
            failure_inherit,
        } = &parsed.flow
        {
            assert!(swarm.is_none());
            assert_eq!(worker_expr, &Some("{{input.processor_type}}".to_string()));
            assert_eq!(fallback, &Some("default_worker".to_string()));
            assert!(input_mapping.is_empty());
            assert!(output_mapping.is_empty());
            assert!(*failure_inherit);
        } else {
            panic!("Expected Delegate pattern");
        }
    }

    #[test]
    fn test_delegate_pattern_swarm_precedence_in_yaml() {
        // When both swarm and worker_expr are in YAML, swarm takes precedence
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: both-specified
workers: []
flow:
  type: delegate
  swarm: sub.yaml
  worker_expr: "{{input.worker}}"
  fallback: default
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();

        if let FlowPattern::Delegate {
            swarm,
            worker_expr,
            fallback,
            ..
        } = &parsed.flow
        {
            // Both should be parsed, executor will prefer swarm
            assert_eq!(swarm, &Some(PathBuf::from("sub.yaml")));
            assert_eq!(worker_expr, &Some("{{input.worker}}".to_string()));
            assert_eq!(fallback, &Some("default".to_string()));
        } else {
            panic!("Expected Delegate pattern");
        }
    }

    #[test]
    fn test_max_nesting_depth_constant() {
        // Verify the constant is accessible and has expected value
        assert_eq!(MAX_NESTING_DEPTH, 10);
    }

    #[test]
    fn test_nesting_depth_no_delegate() {
        let swarm = SwarmFile::new("test", FlowPattern::Sequence { steps: vec![] });
        let depth = swarm.nesting_depth().unwrap();
        assert_eq!(depth, 0);
    }

    // Note: Circular nesting and depth tests require actual files on disk
    // These are better suited for integration tests in tests/ directory

    // ===== Tests for flow→worker reference validation =====

    #[test]
    fn test_validate_sequence_undefined_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Sequence {
                steps: vec!["missing".into()],
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(
            err.to_string().contains("sequence"),
            "error should mention pattern type: {err}"
        );
        assert!(
            err.to_string().contains("missing"),
            "error should mention worker name: {err}"
        );
    }

    #[test]
    fn test_validate_sequence_valid_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Sequence {
                steps: vec!["w1".into()],
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"));
        assert!(swarm.validate().is_ok());
    }

    #[test]
    fn test_validate_parallel_undefined_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Parallel {
                branches: vec!["w1".into(), "ghost".into()],
                fail_fast: false,
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"));
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("parallel"));
        assert!(err.to_string().contains("ghost"));
    }

    #[test]
    fn test_validate_conditional_undefined_then() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Conditional {
                condition: "true".into(),
                then: "missing_then".into(),
                else_: None,
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("conditional"));
        assert!(err.to_string().contains("missing_then"));
    }

    #[test]
    fn test_validate_conditional_undefined_else() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Conditional {
                condition: "true".into(),
                then: "w1".into(),
                else_: Some("missing_else".into()),
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"));
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("conditional"));
        assert!(err.to_string().contains("missing_else"));
    }

    #[test]
    fn test_validate_loop_undefined_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Loop {
                over: "items".into(),
                do_: "missing_worker".into(),
                max_iterations: 0,
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("loop"));
        assert!(err.to_string().contains("missing_worker"));
    }

    #[test]
    fn test_validate_delegate_worker_expr_skipped() {
        // worker_expr is dynamic — should NOT trigger validation error even if no matching worker
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: None,
                worker_expr: Some("{{input.processor_type}}".into()),
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        );
        assert!(swarm.validate().is_ok());
    }

    #[test]
    fn test_validate_delegate_fallback_undefined() {
        // fallback is static — should trigger validation error if worker not found
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: None,
                worker_expr: Some("{{input.worker}}".into()),
                fallback: Some("missing_fallback".into()),
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("delegate"));
        assert!(err.to_string().contains("missing_fallback"));
    }

    #[test]
    fn test_validate_delegate_fallback_valid() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Delegate {
                swarm: None,
                worker_expr: Some("{{input.worker}}".into()),
                fallback: Some("default_worker".into()),
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        )
        .with_worker(Worker::new("default_worker", "default.yaml"));
        assert!(swarm.validate().is_ok());
    }

    #[test]
    fn test_validate_supervisor_undefined_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Supervisor {
                workers: vec!["w1".into(), "ghost".into()],
                restart_policy: RestartPolicy::OnFailure,
                recovery_policy: None,
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"));
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("supervisor"));
        assert!(err.to_string().contains("ghost"));
    }

    #[test]
    fn test_validate_compete_undefined_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Compete {
                workers: vec!["ghost".into()],
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("compete"));
        assert!(err.to_string().contains("ghost"));
    }

    #[test]
    fn test_validate_escalation_undefined_primary() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Escalation {
                primary: "missing_primary".into(),
                chain: vec![],
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("escalation"));
        assert!(err.to_string().contains("missing_primary"));
    }

    #[test]
    fn test_validate_escalation_undefined_chain_member() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Escalation {
                primary: "w1".into(),
                chain: vec!["w2".into(), "ghost".into()],
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"))
        .with_worker(Worker::new("w2", "w2.yaml"));
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("escalation"));
        assert!(err.to_string().contains("ghost"));
    }

    #[test]
    fn test_validate_alongside_undefined_main() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Alongside {
                main: "missing_main".into(),
                side: vec![],
            },
        );
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("alongside"));
        assert!(err.to_string().contains("missing_main"));
    }

    #[test]
    fn test_validate_alongside_undefined_side_worker() {
        let swarm = SwarmFile::new(
            "test",
            FlowPattern::Alongside {
                main: "main_worker".into(),
                side: vec!["side1".into(), "ghost".into()],
            },
        )
        .with_worker(Worker::new("main_worker", "main.yaml"))
        .with_worker(Worker::new("side1", "side1.yaml"));
        let err = swarm.validate().unwrap_err();
        assert!(err.to_string().contains("alongside"));
        assert!(err.to_string().contains("ghost"));
    }

    #[test]
    fn test_referenced_worker_names_all_patterns() {
        // Sequence
        let seq = FlowPattern::Sequence {
            steps: vec!["a".into(), "b".into()],
        };
        assert_eq!(seq.referenced_worker_names(), vec!["a", "b"]);

        // Parallel
        let par = FlowPattern::Parallel {
            branches: vec!["x".into(), "y".into()],
            fail_fast: false,
        };
        assert_eq!(par.referenced_worker_names(), vec!["x", "y"]);

        // Conditional with else
        let cond = FlowPattern::Conditional {
            condition: "true".into(),
            then: "t".into(),
            else_: Some("f".into()),
        };
        assert_eq!(cond.referenced_worker_names(), vec!["t", "f"]);

        // Conditional without else
        let cond_no_else = FlowPattern::Conditional {
            condition: "true".into(),
            then: "t".into(),
            else_: None,
        };
        assert_eq!(cond_no_else.referenced_worker_names(), vec!["t"]);

        // Loop
        let lp = FlowPattern::Loop {
            over: "items".into(),
            do_: "processor".into(),
            max_iterations: 0,
        };
        assert_eq!(lp.referenced_worker_names(), vec!["processor"]);

        // Delegate with worker_expr only → no static refs
        let del_dynamic = FlowPattern::Delegate {
            swarm: None,
            worker_expr: Some("{{input.w}}".into()),
            fallback: None,
            input_mapping: HashMap::new(),
            output_mapping: HashMap::new(),
            failure_inherit: true,
        };
        assert!(del_dynamic.referenced_worker_names().is_empty());

        // Delegate with fallback → fallback is static
        let del_fallback = FlowPattern::Delegate {
            swarm: None,
            worker_expr: Some("{{input.w}}".into()),
            fallback: Some("fb".into()),
            input_mapping: HashMap::new(),
            output_mapping: HashMap::new(),
            failure_inherit: true,
        };
        assert_eq!(del_fallback.referenced_worker_names(), vec!["fb"]);

        // Supervisor
        let sup = FlowPattern::Supervisor {
            workers: vec!["w1".into(), "w2".into()],
            restart_policy: RestartPolicy::OnFailure,
            recovery_policy: None,
        };
        assert_eq!(sup.referenced_worker_names(), vec!["w1", "w2"]);

        // Compete
        let comp = FlowPattern::Compete {
            workers: vec!["c1".into(), "c2".into()],
        };
        assert_eq!(comp.referenced_worker_names(), vec!["c1", "c2"]);

        // Escalation
        let esc = FlowPattern::Escalation {
            primary: "p".into(),
            chain: vec!["e1".into(), "e2".into()],
        };
        assert_eq!(esc.referenced_worker_names(), vec!["p", "e1", "e2"]);

        // Alongside
        let aln = FlowPattern::Alongside {
            main: "m".into(),
            side: vec!["s1".into(), "s2".into()],
        };
        assert_eq!(aln.referenced_worker_names(), vec!["m", "s1", "s2"]);
    }

    // ===== Recovery Policy Tests =====

    #[test]
    fn test_recovery_policy_yaml_parsing() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: recovery-test
workers:
  - name: main
    spec: main.yaml
  - name: backup
    spec: backup.yaml
flow:
  type: supervisor
  workers: [main]
  restart_policy: on_failure
  recovery_policy:
    retry_attempts: 5
    replan_fallback: backup
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(parsed.id.as_str(), "recovery-test");

        if let FlowPattern::Supervisor {
            recovery_policy: Some(rp),
            ..
        } = &parsed.flow
        {
            assert_eq!(rp.retry_attempts, 5);
            assert_eq!(rp.replan_fallback, Some("backup".to_string()));
        } else {
            panic!("Expected Supervisor with recovery_policy");
        }
    }

    #[test]
    fn test_recovery_policy_default_retry_attempts() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: default-retry
workers:
  - name: main
    spec: main.yaml
flow:
  type: supervisor
  workers: [main]
  recovery_policy: {}
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();

        if let FlowPattern::Supervisor {
            recovery_policy: Some(rp),
            ..
        } = &parsed.flow
        {
            assert_eq!(rp.retry_attempts, 3); // Default
        } else {
            panic!("Expected Supervisor with recovery_policy");
        }
    }

    #[test]
    fn test_recovery_policy_decompose_swarm() {
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: decompose-test
workers:
  - name: main
    spec: main.yaml
flow:
  type: supervisor
  workers: [main]
  recovery_policy:
    retry_attempts: 2
    decompose_swarm: sub-tasks.yaml
    decompose_input:
      task: "{{input.query}}"
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();

        if let FlowPattern::Supervisor {
            recovery_policy: Some(rp),
            ..
        } = &parsed.flow
        {
            assert_eq!(rp.retry_attempts, 2);
            assert_eq!(rp.decompose_swarm, Some(PathBuf::from("sub-tasks.yaml")));
            assert_eq!(
                rp.decompose_input.get("task"),
                Some(&Value::String("{{input.query}}".to_string()))
            );
        } else {
            panic!("Expected Supervisor with recovery_policy");
        }
    }

    #[test]
    fn test_supervisor_without_recovery_policy() {
        // Backward compatibility: supervisor without recovery_policy should still work
        let yaml = r#"
apiVersion: bzzz.dev/v1
kind: swarm
id: no-recovery
workers:
  - name: main
    spec: main.yaml
flow:
  type: supervisor
  workers: [main]
  restart_policy: on_failure
"#;
        let parsed: SwarmFile = serde_yaml::from_str(yaml).unwrap();
        assert!(parsed.validate().is_ok());

        if let FlowPattern::Supervisor {
            recovery_policy,
            ..
        } = &parsed.flow
        {
            assert!(recovery_policy.is_none());
        } else {
            panic!("Expected Supervisor pattern");
        }
    }

    // ===== is_simple() Tests =====

    #[test]
    fn test_is_simple_single_step_sequence() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Sequence {
                steps: vec!["worker1".into()],
            },
        )
        .with_worker(Worker::new("worker1", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_multi_step_sequence() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Sequence {
                steps: vec!["w1".into(), "w2".into()],
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"))
        .with_worker(Worker::new("w2", "w2.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_single_worker_supervisor() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Supervisor {
                workers: vec!["main".into()],
                restart_policy: RestartPolicy::OnFailure,
                recovery_policy: None,
            },
        )
        .with_worker(Worker::new("main", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_multi_worker_supervisor() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Supervisor {
                workers: vec!["w1".into(), "w2".into()],
                restart_policy: RestartPolicy::OnFailure,
                recovery_policy: None,
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"))
        .with_worker(Worker::new("w2", "w2.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_single_compete() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Compete {
                workers: vec!["only".into()],
            },
        )
        .with_worker(Worker::new("only", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_multi_compete() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Compete {
                workers: vec!["w1".into(), "w2".into()],
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"))
        .with_worker(Worker::new("w2", "w2.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_single_branch_parallel() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Parallel {
                branches: vec!["only".into()],
                fail_fast: false,
            },
        )
        .with_worker(Worker::new("only", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_multi_branch_parallel() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Parallel {
                branches: vec!["w1".into(), "w2".into()],
                fail_fast: false,
            },
        )
        .with_worker(Worker::new("w1", "w1.yaml"))
        .with_worker(Worker::new("w2", "w2.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_escalation_no_chain() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Escalation {
                primary: "main".into(),
                chain: vec![],
            },
        )
        .with_worker(Worker::new("main", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_escalation_with_chain() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Escalation {
                primary: "main".into(),
                chain: vec!["backup".into()],
            },
        )
        .with_worker(Worker::new("main", "agent.yaml"))
        .with_worker(Worker::new("backup", "backup.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_alongside_no_side() {
        let swarm = SwarmFile::new(
            "simple",
            FlowPattern::Alongside {
                main: "worker1".into(),
                side: vec![],
            },
        )
        .with_worker(Worker::new("worker1", "agent.yaml"));
        assert!(swarm.is_simple());
    }

    #[test]
    fn test_is_simple_alongside_with_side() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Alongside {
                main: "main".into(),
                side: vec!["monitor".into()],
            },
        )
        .with_worker(Worker::new("main", "agent.yaml"))
        .with_worker(Worker::new("monitor", "monitor.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_conditional_always_complex() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Conditional {
                condition: "true".into(),
                then: "worker1".into(),
                else_: None,
            },
        )
        .with_worker(Worker::new("worker1", "agent.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_loop_always_complex() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Loop {
                over: "items".into(),
                do_: "worker1".into(),
                max_iterations: 0,
            },
        )
        .with_worker(Worker::new("worker1", "agent.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_delegate_always_complex() {
        let swarm = SwarmFile::new(
            "complex",
            FlowPattern::Delegate {
                swarm: Some(PathBuf::from("child.yaml")),
                worker_expr: None,
                fallback: None,
                input_mapping: HashMap::new(),
                output_mapping: HashMap::new(),
                failure_inherit: true,
            },
        )
        .with_worker(Worker::new("caller", "caller.yaml"));
        assert!(!swarm.is_simple());
    }

    #[test]
    fn test_is_simple_no_workers() {
        let swarm = SwarmFile::new("empty", FlowPattern::Sequence { steps: vec![] });
        assert!(!swarm.is_simple());
    }
}