nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
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
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
//! YAML parser with span tracking using marked_yaml.
//!
//! This module provides the entry point for parsing YAML workflows
//! into the raw AST with full source position tracking.

use indexmap::IndexMap;
use marked_yaml::{parse_yaml, LoadError, Marker, Node, Span as MarkedSpan};

use super::action::{
    RawAgentAction, RawExecAction, RawFetchAction, RawInferAction, RawInvokeAction, RawTaskAction,
};
use super::mcp::{RawMcpConfig, RawMcpServer};
use super::task::{RawForEach, RawOutputConfig, RawRetryConfig, RawTask};
use super::workflow::{RawContextConfig, RawImportSpec, RawPkgConfig, RawWorkflow};
use crate::ast::decompose::{DecomposeSpec, DecomposeStrategy};
use crate::ast::structured::StructuredOutputSpec;
use crate::source::{ByteOffset, FileId, Span, Spanned};

/// Errors that can occur during parsing.
#[derive(Debug, Clone)]
pub struct ParseError {
    /// The error kind
    pub kind: ParseErrorKind,
    /// Location of the error (if available)
    pub span: Span,
    /// Error message
    pub message: String,
}

/// Kinds of parse errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseErrorKind {
    /// YAML syntax error
    Syntax,
    /// Missing required field
    MissingField,
    /// Invalid field type
    InvalidType,
    /// Unknown field
    UnknownField,
    /// Invalid schema version
    InvalidSchema,
}

impl ParseErrorKind {
    /// Get the error code for this kind.
    ///
    /// Parse-phase errors use NIKA-160..164 to avoid collision with
    /// the top-level NikaError workflow codes (NIKA-001..005).
    pub fn code(&self) -> &'static str {
        match self {
            Self::Syntax => "NIKA-160",
            Self::MissingField => "NIKA-161",
            Self::InvalidType => "NIKA-162",
            Self::UnknownField => "NIKA-163",
            Self::InvalidSchema => "NIKA-164",
        }
    }
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for ParseError {}

/// Convert a marked_yaml Marker to our ByteOffset.
fn marker_to_offset(marker: &Marker) -> ByteOffset {
    // marked_yaml uses character() for byte offset
    ByteOffset::new(marker.character() as u32)
}

/// Convert a marked_yaml Marker to a point Span.
fn marker_to_span(file: FileId, marker: &Marker) -> Span {
    let offset = marker_to_offset(marker);
    Span {
        file,
        start: offset,
        end: offset,
    }
}

/// Extract span from a LoadError if it carries a Marker.
///
/// Most LoadError variants include position information:
/// - TopLevelMustBeMapping(Marker)
/// - TopLevelMustBeSequence(Marker)
/// - UnexpectedAnchor(Marker)
/// - MappingKeyMustBeScalar(Marker)
/// - UnexpectedTag(Marker)
/// - ScanError(Marker, _)
/// - DuplicateKey(Box<DuplicateKeyInner>)
fn extract_span_from_load_error(file: FileId, error: &LoadError) -> Span {
    match error {
        LoadError::TopLevelMustBeMapping(marker)
        | LoadError::TopLevelMustBeSequence(marker)
        | LoadError::UnexpectedAnchor(marker)
        | LoadError::MappingKeyMustBeScalar(marker)
        | LoadError::UnexpectedTag(marker) => marker_to_span(file, marker),
        LoadError::ScanError(marker, _) => marker_to_span(file, marker),
        LoadError::DuplicateKey(inner) => {
            // DuplicateKeyInner has key: MarkedScalarNode, use its span
            marked_span_to_span(file, inner.key.span())
        }
    }
}

/// Convert a marked_yaml Span to our Span.
fn marked_span_to_span(file: FileId, span: &MarkedSpan) -> Span {
    match (span.start(), span.end()) {
        (Some(start), Some(end)) => Span {
            file,
            start: marker_to_offset(start),
            end: marker_to_offset(end),
        },
        (Some(start), None) => Span {
            file,
            start: marker_to_offset(start),
            end: marker_to_offset(start), // Point span
        },
        _ => Span::dummy(),
    }
}

/// Convert a marked_yaml Node span to our Span.
fn node_to_span(file: FileId, node: &Node) -> Span {
    marked_span_to_span(file, node.span())
}

/// Extract a spanned string from a YAML scalar node.
fn extract_string(file: FileId, node: &Node) -> Result<Spanned<String>, ParseError> {
    let span = node_to_span(file, node);
    match node {
        Node::Scalar(s) => Ok(Spanned::new(s.to_string(), span)),
        _ => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span,
            message: "expected string".to_string(),
        }),
    }
}

/// Get an optional string field from a mapping by key.
fn get_string_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<String>>, ParseError> {
    match map.get_node(key) {
        Some(node) => extract_string(file, node).map(Some),
        None => Ok(None),
    }
}

/// Get an optional f64 field from a mapping.
fn get_f64_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<f64>>, ParseError> {
    match map.get_node(key) {
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            let value: f64 = s.as_str().parse().map_err(|_| ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: format!("'{}' must be a number", key),
            })?;
            if !value.is_finite() {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span,
                    message: format!("'{}' must be a finite number (got {})", key, s.as_str()),
                });
            }
            Ok(Some(Spanned::new(value, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be a number", key),
        }),
        None => Ok(None),
    }
}

/// Get an optional u32 field from a mapping.
fn get_u32_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<u32>>, ParseError> {
    match map.get_node(key) {
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            let value: u32 = s.as_str().parse().map_err(|_| ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: format!("'{}' must be a positive integer", key),
            })?;
            Ok(Some(Spanned::new(value, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be a positive integer", key),
        }),
        None => Ok(None),
    }
}

/// Get an optional u64 field from a mapping.
fn get_u64_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<u64>>, ParseError> {
    match map.get_node(key) {
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            let value: u64 = s.as_str().parse().map_err(|_| ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: format!("'{}' must be a positive integer", key),
            })?;
            Ok(Some(Spanned::new(value, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be a positive integer", key),
        }),
        None => Ok(None),
    }
}

/// Get an optional bool field from a mapping.
fn get_bool_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<bool>>, ParseError> {
    match map.get_node(key) {
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            let value = match s.as_str().to_lowercase().as_str() {
                "true" | "yes" | "on" | "1" => true,
                "false" | "no" | "off" | "0" => false,
                _ => {
                    return Err(ParseError {
                        kind: ParseErrorKind::InvalidType,
                        span,
                        message: format!("'{}' must be a boolean", key),
                    });
                }
            };
            Ok(Some(Spanned::new(value, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be a boolean", key),
        }),
        None => Ok(None),
    }
}

/// Parse a string-to-string mapping (for headers, env vars).
#[allow(clippy::type_complexity)]
fn parse_string_map(
    file: FileId,
    parent: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<IndexMap<Spanned<String>, Spanned<String>>>>, ParseError> {
    match parent.get_node(key) {
        Some(Node::Mapping(m)) => {
            let span = marked_span_to_span(file, m.span());
            let mut result = IndexMap::new();

            for (k, v) in m.iter() {
                let key_span = marked_span_to_span(file, k.span());
                let key_str = Spanned::new(k.as_str().to_string(), key_span);
                let val = extract_string(file, v)?;
                result.insert(key_str, val);
            }

            Ok(Some(Spanned::new(result, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be a mapping", key),
        }),
        None => Ok(None),
    }
}

/// Parse an array of strings.
fn parse_string_array(
    file: FileId,
    parent: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<Vec<Spanned<String>>>>, ParseError> {
    match parent.get_node(key) {
        Some(Node::Sequence(seq)) => {
            let span = marked_span_to_span(file, seq.span());
            let items: Result<Vec<_>, _> =
                seq.iter().map(|node| extract_string(file, node)).collect();
            Ok(Some(Spanned::new(items?, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: format!("'{}' must be an array", key),
        }),
        None => Ok(None),
    }
}

/// Parse a JSON value from a node.
fn parse_json_value(
    file: FileId,
    parent: &marked_yaml::types::MarkedMappingNode,
    key: &str,
) -> Result<Option<Spanned<serde_json::Value>>, ParseError> {
    match parent.get_node(key) {
        Some(node) => {
            let span = node_to_span(file, node);
            let value = node_to_json(node);
            Ok(Some(Spanned::new(value, span)))
        }
        None => Ok(None),
    }
}

/// Convert a YAML node to a JSON value.
fn node_to_json(node: &Node) -> serde_json::Value {
    match node {
        Node::Scalar(s) => {
            let str_val = s.as_str();
            // Try parsing as different types
            if let Ok(n) = str_val.parse::<i64>() {
                serde_json::Value::Number(n.into())
            } else if let Ok(n) = str_val.parse::<f64>() {
                serde_json::Number::from_f64(n)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::String(str_val.to_string()))
            } else if str_val == "true" {
                serde_json::Value::Bool(true)
            } else if str_val == "false" {
                serde_json::Value::Bool(false)
            } else if str_val == "null" || str_val == "~" {
                serde_json::Value::Null
            } else {
                serde_json::Value::String(str_val.to_string())
            }
        }
        Node::Mapping(m) => {
            let obj: serde_json::Map<String, serde_json::Value> = m
                .iter()
                .map(|(k, v)| (k.as_str().to_string(), node_to_json(v)))
                .collect();
            serde_json::Value::Object(obj)
        }
        Node::Sequence(s) => {
            let arr: Vec<serde_json::Value> = s.iter().map(node_to_json).collect();
            serde_json::Value::Array(arr)
        }
    }
}

// ============================================================================
// Action Parsing (5 Verbs)
// ============================================================================

/// Parse the task action from the mapping (dispatches to verb-specific parsers).
fn parse_action(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<RawTaskAction>, ParseError> {
    // Reject tasks with multiple verbs (must have exactly 0 or 1)
    let verb_keys = ["infer", "exec", "fetch", "invoke", "agent"];
    let found: Vec<&str> = verb_keys
        .iter()
        .filter(|k| map.get_node(k).is_some())
        .copied()
        .collect();
    if found.len() > 1 {
        let span = marked_span_to_span(file, map.span());
        return Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span,
            message: format!(
                "task has multiple verbs ({}); each task must have exactly one",
                found.join(", ")
            ),
        });
    }

    // Check for infer verb
    if let Some(node) = map.get_node("infer") {
        let action = parse_infer_action(file, node)?;
        let span = node_to_span(file, node);
        return Ok(Some(RawTaskAction::Infer(Spanned::new(action, span))));
    }
    // Check for exec verb
    if let Some(node) = map.get_node("exec") {
        let action = parse_exec_action(file, node)?;
        let span = node_to_span(file, node);
        return Ok(Some(RawTaskAction::Exec(Spanned::new(action, span))));
    }
    // Check for fetch verb
    if let Some(node) = map.get_node("fetch") {
        let action = parse_fetch_action(file, node)?;
        let span = node_to_span(file, node);
        return Ok(Some(RawTaskAction::Fetch(Spanned::new(action, span))));
    }
    // Check for invoke verb
    if let Some(node) = map.get_node("invoke") {
        let action = parse_invoke_action(file, node)?;
        let span = node_to_span(file, node);
        return Ok(Some(RawTaskAction::Invoke(Spanned::new(action, span))));
    }
    // Check for agent verb
    if let Some(node) = map.get_node("agent") {
        let action = parse_agent_action(file, node)?;
        let span = node_to_span(file, node);
        return Ok(Some(RawTaskAction::Agent(Spanned::new(action, span))));
    }

    // No verb found — check for common misspellings before returning None.
    // Known non-verb task keys that are legitimate without a verb (e.g. decompose tasks).
    let known_non_verb_keys: &[&str] = &[
        "id",
        "description",
        "provider",
        "model",
        "with",
        "depends_on",
        "output",
        "for_each",
        "retry",
        "decompose",
        "structured",
        "artifact",
        "log",
        "concurrency",
        "fail_fast",
        "timeout",
    ];

    let task_keys: Vec<String> = map.iter().map(|(k, _)| k.as_str().to_string()).collect();
    let unrecognized: Vec<&str> = task_keys
        .iter()
        .map(|s| s.as_str())
        .filter(|k| !verb_keys.contains(k) && !known_non_verb_keys.contains(k))
        .collect();

    if !unrecognized.is_empty() {
        // Check if any unrecognized key looks like a misspelled verb
        let misspellings: Vec<(&str, &str)> = unrecognized
            .iter()
            .filter_map(|key| {
                verb_keys.iter().find_map(|verb| {
                    if is_likely_misspelling(key, verb) {
                        Some((*key, *verb))
                    } else {
                        None
                    }
                })
            })
            .collect();

        if !misspellings.is_empty() {
            let suggestions: Vec<String> = misspellings
                .iter()
                .map(|(key, verb)| format!("'{}' (did you mean '{}'?)", key, verb))
                .collect();
            let span = marked_span_to_span(file, map.span());
            return Err(ParseError {
                kind: ParseErrorKind::MissingField,
                span,
                message: format!(
                    "no valid verb found. Expected one of: {}. Possible misspelling: {}",
                    verb_keys.join(", "),
                    suggestions.join(", ")
                ),
            });
        }
    }

    Ok(None)
}

/// Check if `input` is a likely misspelling of `target` using edit distance.
/// Returns true if the strings are within edit distance 2 and share a common prefix.
fn is_likely_misspelling(input: &str, target: &str) -> bool {
    if input == target {
        return false;
    }
    let len_diff = (input.len() as isize - target.len() as isize).unsigned_abs();
    if len_diff > 2 {
        return false;
    }
    // Simple Levenshtein distance check (bounded to 2)
    levenshtein_bounded(input, target, 2) <= 2
}

/// Bounded Levenshtein distance. Returns distance or `bound + 1` if exceeded.
fn levenshtein_bounded(a: &str, b: &str, bound: usize) -> usize {
    let a_bytes = a.as_bytes();
    let b_bytes = b.as_bytes();
    let m = a_bytes.len();
    let n = b_bytes.len();

    if m.abs_diff(n) > bound {
        return bound + 1;
    }

    let mut prev: Vec<usize> = (0..=n).collect();
    let mut curr = vec![0; n + 1];

    for i in 1..=m {
        curr[0] = i;
        let mut min_in_row = curr[0];
        for j in 1..=n {
            let cost = if a_bytes[i - 1] == b_bytes[j - 1] {
                0
            } else {
                1
            };
            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
            min_in_row = min_in_row.min(curr[j]);
        }
        if min_in_row > bound {
            return bound + 1;
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[n]
}

/// Parse infer action - supports both shorthand (string) and full form (mapping).
///
/// # Content / Prompt Rules
///
/// - `infer: "prompt"` — shorthand, text-only
/// - `infer: { prompt: "..." }` — full form, text-only
/// - `infer: { content: [...] }` — vision mode, prompt optional
/// - `infer: { prompt: "...", content: [...] }` — prompt prepended as first Text part
/// - Error if neither `prompt` nor `content` is present
fn parse_infer_action(file: FileId, node: &Node) -> Result<RawInferAction, ParseError> {
    let span = node_to_span(file, node);

    match node {
        // Shorthand: infer: "prompt string"
        Node::Scalar(s) => Ok(RawInferAction {
            prompt: Spanned::new(s.as_str().to_string(), span),
            system: None,
            temperature: None,
            max_tokens: None,
            thinking: None,
            thinking_budget: None,
            content: None,
            response_format: None,
            guardrails: Vec::new(),
        }),
        // Full form: infer: { prompt: "...", temperature: ..., content: [...] }
        Node::Mapping(m) => {
            let prompt = get_string_field(file, m, "prompt")?;
            let content = parse_content_field(file, m)?;

            // Require at least one of prompt or content
            if prompt.is_none() && content.is_none() {
                return Err(ParseError {
                    kind: ParseErrorKind::MissingField,
                    span,
                    message: "infer action requires 'prompt' or 'content' field".to_string(),
                });
            }

            // If content is present but no prompt, use empty prompt (validated later)
            let prompt = prompt.unwrap_or_else(|| Spanned::new(String::new(), span));

            let guardrails = parse_guardrails_field(file, m)?;

            Ok(RawInferAction {
                prompt,
                system: get_string_field(file, m, "system")?,
                temperature: get_f64_field(file, m, "temperature")?,
                max_tokens: get_u32_field(file, m, "max_tokens")?,
                thinking: get_bool_field(file, m, "thinking")?.or(get_bool_field(
                    file,
                    m,
                    "extended_thinking",
                )?),
                thinking_budget: get_u32_field(file, m, "thinking_budget")?,
                content,
                response_format: get_string_field(file, m, "response_format")?,
                guardrails,
            })
        }
        _ => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span,
            message: "infer must be a string or mapping".to_string(),
        }),
    }
}

/// Parse the `content:` field from an infer mapping.
///
/// Returns `None` if the field is absent. Parses a YAML sequence where each
/// element is a mapping with `type`, and type-specific fields.
fn parse_content_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<Vec<crate::ast::content::RawContentPart>>>, ParseError> {
    use crate::ast::content::RawContentPart;

    let node = match map.get_node("content") {
        Some(n) => n,
        None => return Ok(None),
    };

    let span = node_to_span(file, node);

    let seq = match node {
        Node::Sequence(s) => s,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "content must be a sequence".to_string(),
            });
        }
    };

    if seq.is_empty() {
        return Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span,
            message: "content must not be empty".to_string(),
        });
    }

    let mut parts = Vec::with_capacity(seq.len());

    for item in seq.iter() {
        let item_span = node_to_span(file, item);
        let m = match item {
            Node::Mapping(m) => m,
            _ => {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span: item_span,
                    message: "each content part must be a mapping with 'type' field".to_string(),
                });
            }
        };

        let type_field = get_string_field(file, m, "type")?.ok_or_else(|| ParseError {
            kind: ParseErrorKind::MissingField,
            span: item_span,
            message: "content part requires 'type' field".to_string(),
        })?;

        let part = match type_field.value.as_str() {
            "text" => {
                let text = get_string_field(file, m, "text")?.ok_or_else(|| ParseError {
                    kind: ParseErrorKind::MissingField,
                    span: item_span,
                    message: "text content part requires 'text' field".to_string(),
                })?;
                RawContentPart::Text { text }
            }
            "image" => {
                let source = get_string_field(file, m, "source")?.ok_or_else(|| ParseError {
                    kind: ParseErrorKind::MissingField,
                    span: item_span,
                    message: "image content part requires 'source' field".to_string(),
                })?;
                let detail = get_string_field(file, m, "detail")?;
                RawContentPart::Image { source, detail }
            }
            "image_url" => {
                let url = get_string_field(file, m, "url")?.ok_or_else(|| ParseError {
                    kind: ParseErrorKind::MissingField,
                    span: item_span,
                    message: "image_url content part requires 'url' field".to_string(),
                })?;
                let detail = get_string_field(file, m, "detail")?;
                RawContentPart::ImageUrl { url, detail }
            }
            other => {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span: type_field.span,
                    message: format!(
                        "unknown content part type '{}', expected: text, image, image_url",
                        other
                    ),
                });
            }
        };

        parts.push(part);
    }

    Ok(Some(Spanned::new(parts, span)))
}

/// Parse exec action - supports both shorthand (string) and full form (mapping).
fn parse_exec_action(file: FileId, node: &Node) -> Result<RawExecAction, ParseError> {
    let span = node_to_span(file, node);

    match node {
        // Shorthand: exec: "command string"
        Node::Scalar(s) => Ok(RawExecAction {
            command: Spanned::new(s.as_str().to_string(), span),
            shell: None,
            working_dir: None,
            env: None,
            timeout_ms: None,
        }),
        // Full form
        Node::Mapping(m) => {
            let command = get_string_field(file, m, "command")?.ok_or_else(|| ParseError {
                kind: ParseErrorKind::MissingField,
                span,
                message: "exec action requires 'command' field".to_string(),
            })?;

            Ok(RawExecAction {
                command,
                shell: get_bool_field(file, m, "shell")?,
                working_dir: get_string_field(file, m, "working_dir")?
                    .or(get_string_field(file, m, "cwd")?),
                env: parse_string_map(file, m, "env")?,
                // timeout_ms is the primary field (milliseconds).
                // timeout is the schema alias (seconds) — convert to ms.
                timeout_ms: match get_u64_field(file, m, "timeout_ms")? {
                    Some(v) => Some(v),
                    None => get_u64_field(file, m, "timeout")?
                        .map(|s| Spanned::new(s.value * 1000, s.span)),
                },
            })
        }
        _ => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span,
            message: "exec must be a string or mapping".to_string(),
        }),
    }
}

/// Parse fetch action - always requires a mapping.
fn parse_fetch_action(file: FileId, node: &Node) -> Result<RawFetchAction, ParseError> {
    let span = node_to_span(file, node);

    let m = match node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "fetch must be a mapping".to_string(),
            });
        }
    };

    let url = get_string_field(file, m, "url")?.ok_or_else(|| ParseError {
        kind: ParseErrorKind::MissingField,
        span,
        message: "fetch action requires 'url' field".to_string(),
    })?;

    let extract = get_string_field(file, m, "extract")?;
    let selector = get_string_field(file, m, "selector")?;

    Ok(RawFetchAction {
        url,
        method: get_string_field(file, m, "method")?,
        headers: parse_string_map(file, m, "headers")?,
        body: get_string_field(file, m, "body")?,
        json: parse_json_value(file, m, "json")?,
        timeout_ms: match get_u64_field(file, m, "timeout_ms")? {
            Some(v) => Some(v),
            None => {
                get_u64_field(file, m, "timeout")?.map(|s| Spanned::new(s.value * 1000, s.span))
            }
        },
        follow_redirects: get_bool_field(file, m, "follow_redirects")?,
        response: get_string_field(file, m, "response")?,
        extract,
        selector,
    })
}

/// Parse invoke action - always requires a mapping.
fn parse_invoke_action(file: FileId, node: &Node) -> Result<RawInvokeAction, ParseError> {
    let span = node_to_span(file, node);

    let m = match node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "invoke must be a mapping".to_string(),
            });
        }
    };

    let tool = get_string_field(file, m, "tool")?.ok_or_else(|| ParseError {
        kind: ParseErrorKind::MissingField,
        span,
        message: "invoke action requires 'tool' field".to_string(),
    })?;

    Ok(RawInvokeAction {
        tool,
        params: parse_json_value(file, m, "params")?,
        mcp: get_string_field(file, m, "mcp")?.or(get_string_field(file, m, "server")?),
        timeout_ms: match get_u64_field(file, m, "timeout_ms")? {
            Some(v) => Some(v),
            None => {
                get_u64_field(file, m, "timeout")?.map(|s| Spanned::new(s.value * 1000, s.span))
            }
        },
    })
}

/// Parse agent action - always requires a mapping.
fn parse_agent_action(file: FileId, node: &Node) -> Result<RawAgentAction, ParseError> {
    let span = node_to_span(file, node);

    let m = match node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "agent must be a mapping".to_string(),
            });
        }
    };

    // Agent uses 'prompt' as primary field, 'goal' as legacy fallback
    let prompt = get_string_field(file, m, "prompt")?
        .or(get_string_field(file, m, "goal")?)
        .ok_or_else(|| ParseError {
            kind: ParseErrorKind::MissingField,
            span,
            message: "agent action requires 'prompt' field (or legacy 'goal')".to_string(),
        })?;

    Ok(RawAgentAction {
        prompt,
        tools: parse_string_array(file, m, "tools")?,
        max_iterations: get_u32_field(file, m, "max_iterations")?.or(get_u32_field(
            file,
            m,
            "max_turns",
        )?),
        max_tokens: get_u32_field(file, m, "max_tokens")?,
        from: get_string_field(file, m, "from")?,
        skills: parse_string_array(file, m, "skills")?,
        provider: get_string_field(file, m, "provider")?,
        model: get_string_field(file, m, "model")?,
        mcp: parse_string_array(file, m, "mcp")?,
        system: get_string_field(file, m, "system")?,
        temperature: get_f64_field(file, m, "temperature")?,
        token_budget: get_u32_field(file, m, "token_budget")?,
        extended_thinking: get_bool_field(file, m, "extended_thinking")?,
        thinking_budget: get_u32_field(file, m, "thinking_budget")?,
        depth_limit: get_u32_field(file, m, "depth_limit")?,
        tool_choice: get_string_field(file, m, "tool_choice")?,
        stop_sequences: parse_string_array(file, m, "stop_sequences")?,
        scope: get_string_field(file, m, "scope")?,
    })
}

// ============================================================================
// with:/depends_on:/for_each:/retry:/output: Parsing
// ============================================================================

/// Parse with: bindings.
///
/// Values are raw strings parsed by `parse_with_entry()` in Phase 2 (analyzer).
/// Examples:
///   - `data: step1` — simple task reference
///   - `temp: step1.data.temp ?? 20` — path + default
///   - `cfg: $env.API_KEY` — environment binding
///   - `val: step1.output | upper | trim` — with transforms
#[allow(clippy::type_complexity)]
fn parse_with_refs(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<IndexMap<Spanned<String>, Spanned<String>>>>, ParseError> {
    parse_string_map(file, map, "with")
}

/// Parse depends_on: ordering dependencies.
///
/// Pure ordering edges — no data flows through them.
/// Data dependencies are expressed via `with:` bindings.
fn parse_depends_on(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<Vec<Spanned<String>>>>, ParseError> {
    match map.get_node("depends_on") {
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            Ok(Some(Spanned::new(
                vec![Spanned::new(s.as_str().to_string(), span)],
                span,
            )))
        }
        Some(Node::Sequence(seq)) => {
            let span = marked_span_to_span(file, seq.span());
            let ids: Result<Vec<_>, _> = seq.iter().map(|n| extract_string(file, n)).collect();
            Ok(Some(Spanned::new(ids?, span)))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: "depends_on/flow must be a string or array of strings".to_string(),
        }),
        None => Ok(None),
    }
}

/// Parse for_each: iteration.
fn parse_for_each(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawForEach>>, ParseError> {
    match map.get_node("for_each") {
        Some(Node::Sequence(seq)) => {
            let span = marked_span_to_span(file, seq.span());
            // Array literal - serialize to JSON string for storage
            let arr: Vec<serde_json::Value> = seq.iter().map(node_to_json).collect();
            let items_str = serde_json::to_string(&arr).map_err(|e| ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: format!("failed to serialize for_each items: {}", e),
            })?;

            Ok(Some(Spanned::new(
                RawForEach {
                    items: Spanned::new(items_str, span),
                    as_var: get_string_field(file, map, "as")?,
                    parallel: get_u32_field(file, map, "concurrency")?
                        .or(get_u32_field(file, map, "parallel")?),
                    fail_fast: get_bool_field(file, map, "fail_fast")?,
                },
                span,
            )))
        }
        Some(Node::Scalar(s)) => {
            let span = marked_span_to_span(file, s.span());
            Ok(Some(Spanned::new(
                RawForEach {
                    items: Spanned::new(s.as_str().to_string(), span),
                    as_var: get_string_field(file, map, "as")?,
                    parallel: get_u32_field(file, map, "concurrency")?
                        .or(get_u32_field(file, map, "parallel")?),
                    fail_fast: get_bool_field(file, map, "fail_fast")?,
                },
                span,
            )))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: "for_each must be array or string".to_string(),
        }),
        None => Ok(None),
    }
}

/// Parse retry: configuration.
fn parse_retry(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawRetryConfig>>, ParseError> {
    match map.get_node("retry") {
        Some(Node::Mapping(m)) => {
            let span = marked_span_to_span(file, m.span());
            Ok(Some(Spanned::new(
                RawRetryConfig {
                    max_attempts: get_u32_field(file, m, "max_attempts")?
                        .or(get_u32_field(file, m, "max")?),
                    delay_ms: get_u64_field(file, m, "delay_ms")?
                        .or(get_u64_field(file, m, "delay")?),
                    backoff: get_f64_field(file, m, "backoff")?.or(get_f64_field(
                        file,
                        m,
                        "backoff_multiplier",
                    )?),
                },
                span,
            )))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: "retry must be a mapping".to_string(),
        }),
        None => Ok(None),
    }
}

/// Parse decompose: configuration.
fn parse_decompose(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<DecomposeSpec>>, ParseError> {
    match map.get_node("decompose") {
        Some(Node::Mapping(m)) => {
            let span = marked_span_to_span(file, m.span());

            let traverse = get_string_field(file, m, "traverse")?
                .ok_or_else(|| ParseError {
                    kind: ParseErrorKind::MissingField,
                    span,
                    message: "decompose missing required field 'traverse'".to_string(),
                })?
                .value;

            let source = get_string_field(file, m, "source")?
                .ok_or_else(|| ParseError {
                    kind: ParseErrorKind::MissingField,
                    span,
                    message: "decompose missing required field 'source'".to_string(),
                })?
                .value;

            let strategy = match get_string_field(file, m, "strategy")? {
                Some(s) => match s.value.as_str() {
                    "semantic" => DecomposeStrategy::Semantic,
                    "static" => DecomposeStrategy::Static,
                    "nested" => DecomposeStrategy::Nested,
                    other => {
                        return Err(ParseError {
                            kind: ParseErrorKind::InvalidType,
                            span: s.span,
                            message: format!(
                                "invalid decompose strategy '{}': expected semantic, static, or nested",
                                other
                            ),
                        });
                    }
                },
                None => DecomposeStrategy::default(),
            };

            let mcp_server = get_string_field(file, m, "mcp_server")?.map(|s| s.value);

            let max_items = get_u32_field(file, m, "max_items")?.map(|s| s.value as usize);

            let max_depth = get_u32_field(file, m, "max_depth")?.map(|s| s.value as usize);

            Ok(Some(Spanned::new(
                DecomposeSpec {
                    strategy,
                    traverse,
                    source,
                    mcp_server,
                    max_items,
                    max_depth,
                },
                span,
            )))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: "decompose must be a mapping".to_string(),
        }),
        None => Ok(None),
    }
}

/// Parse output: configuration.
fn parse_output(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawOutputConfig>>, ParseError> {
    match map.get_node("output") {
        Some(Node::Mapping(m)) => {
            let span = marked_span_to_span(file, m.span());
            Ok(Some(Spanned::new(
                RawOutputConfig {
                    format: get_string_field(file, m, "format")?,
                    schema: parse_json_value(file, m, "schema")?,
                    schema_ref: get_string_field(file, m, "schema_ref")?
                        .or(get_string_field(file, m, "$ref")?),
                    max_retries: get_u32_field(file, m, "max_retries")?,
                },
                span,
            )))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file, node),
            message: "output must be a mapping".to_string(),
        }),
        None => Ok(None),
    }
}

/// Parse structured: configuration (StructuredOutputSpec).
///
/// Supports shorthand (string path) or full mapping form:
/// ```yaml
/// structured: ./schemas/user.json          # shorthand
/// structured:                               # full form
///   schema: ./schemas/user.json
///   max_retries: 3
/// ```
fn parse_structured(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<StructuredOutputSpec>, ParseError> {
    match map.get_node("structured") {
        Some(node) => {
            let span = node_to_span(file, node);
            // Convert YAML node to JSON value, then deserialize via serde_json.
            // StructuredOutputSpec's custom Deserialize handles both string and map forms.
            let json_value = node_to_json(node);
            let spec: StructuredOutputSpec =
                serde_json::from_value(json_value).map_err(|e| ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span,
                    message: format!("invalid structured output config: {e}"),
                })?;
            Ok(Some(spec))
        }
        None => Ok(None),
    }
}

/// Parse the `guardrails:` field from an infer or agent mapping.
///
/// Guardrails are a YAML sequence of objects, each with a `type` field.
/// Uses serde deserialization via `GuardrailConfig` which is `#[serde(tag = "type")]`.
///
/// Returns an empty Vec if the field is absent.
fn parse_guardrails_field(
    file: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Vec<crate::ast::guardrails::GuardrailConfig>, ParseError> {
    match map.get_node("guardrails") {
        Some(node) => {
            let span = node_to_span(file, node);
            let json_value = node_to_json(node);
            serde_json::from_value(json_value).map_err(|e| ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: format!("invalid guardrails config: {e}"),
            })
        }
        None => Ok(Vec::new()),
    }
}

// ============================================================================
// Main Parser
// ============================================================================

/// Parse a YAML source string into a RawWorkflow.
///
/// This is the main entry point for Phase 1 parsing. The returned
/// RawWorkflow contains full span information for all nodes.
///
/// # Arguments
///
/// * `source` - The YAML source content
/// * `file_id` - The FileId from the SourceRegistry
///
/// # Returns
///
/// A RawWorkflow with span tracking, or a ParseError with location.
///
/// # Example
///
/// ```ignore
/// use nika::ast::raw;
/// use nika::source::SourceRegistry;
///
/// let mut sources = SourceRegistry::new();
/// let file_id = sources.add_file("workflow.yaml", content.clone());
/// let workflow = raw::parse(&content, file_id)?;
/// ```
pub fn parse(source: &str, file_id: FileId) -> Result<RawWorkflow, ParseError> {
    // Parse YAML with marked_yaml
    // The first argument is a source ID (we use file_id.0)
    let node = parse_yaml(file_id.0 as usize, source).map_err(|e| {
        // Extract span from LoadError variants that carry a Marker
        let span = extract_span_from_load_error(file_id, &e);
        ParseError {
            kind: ParseErrorKind::Syntax,
            span,
            message: format!("YAML syntax error: {}", e),
        }
    })?;

    // The root must be a mapping
    let map = match &node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, &node),
                message: "workflow must be a YAML mapping".to_string(),
            });
        }
    };

    // Parse workflow fields
    let mut workflow = RawWorkflow::default();
    workflow.span = node_to_span(file_id, &node);

    // Extract schema (required)
    workflow.schema = get_string_field(file_id, map, "schema")?.ok_or_else(|| ParseError {
        kind: ParseErrorKind::MissingField,
        span: workflow.span,
        message: "missing required field 'schema'".to_string(),
    })?;

    // Extract optional fields
    workflow.workflow = get_string_field(file_id, map, "workflow")?;
    workflow.description = get_string_field(file_id, map, "description")?;
    workflow.provider = get_string_field(file_id, map, "provider")?;
    workflow.model = get_string_field(file_id, map, "model")?;

    // Parse MCP server configurations
    workflow.mcp = parse_mcp_config(file_id, map)?;

    // Parse pkg configuration
    workflow.pkg = parse_pkg_config(file_id, map)?;

    // Parse context configuration
    workflow.context = parse_context_config(file_id, map)?;

    // Parse imports
    workflow.imports = parse_imports(file_id, map)?;

    // Parse inputs
    workflow.inputs = parse_inputs(file_id, map)?;

    // Parse artifacts config
    workflow.artifacts = match map.get_node("artifacts") {
        Some(node) => {
            let span = node_to_span(file_id, node);
            Some(Spanned::new(node_to_json(node), span))
        }
        None => None,
    };

    // Parse log config
    workflow.log = match map.get_node("log") {
        Some(node) => {
            let span = node_to_span(file_id, node);
            Some(Spanned::new(node_to_json(node), span))
        }
        None => None,
    };

    // Parse agents config
    workflow.agents = match map.get_node("agents") {
        Some(node) => {
            let span = node_to_span(file_id, node);
            Some(Spanned::new(node_to_json(node), span))
        }
        None => None,
    };

    // Parse tasks
    workflow.tasks = parse_tasks(file_id, map)?;

    Ok(workflow)
}

/// Parse the MCP configuration block from a workflow mapping.
fn parse_mcp_config(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawMcpConfig>>, ParseError> {
    // Look for "mcp:" mapping
    let mcp_node = match map.get_node("mcp") {
        Some(node) => node,
        None => return Ok(None),
    };

    let mcp_map = match mcp_node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, mcp_node),
                message: "mcp must be a mapping".to_string(),
            });
        }
    };

    let mcp_span = marked_span_to_span(file_id, mcp_map.span());
    let mut config = RawMcpConfig::default();

    // Support both formats:
    //   Nested: mcp: { servers: { novanet: { command: ... } } }
    //   Flat:   mcp: { novanet: { command: ... } }
    let servers_map = if let Some(servers_node) = mcp_map.get_node("servers") {
        match servers_node {
            Node::Mapping(m) => m,
            _ => {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span: node_to_span(file_id, servers_node),
                    message: "mcp.servers must be a mapping".to_string(),
                });
            }
        }
    } else {
        // Flat format: entries directly under mcp:
        mcp_map
    };

    for (key, value) in servers_map.iter() {
        let server_name = Spanned::new(
            key.as_str().to_string(),
            marked_span_to_span(file_id, key.span()),
        );

        let server = parse_mcp_server(file_id, value)?;
        config.servers.insert(server_name, server);
    }

    Ok(Some(Spanned::new(config, mcp_span)))
}

/// Parse a single MCP server configuration.
fn parse_mcp_server(file_id: FileId, node: &Node) -> Result<Spanned<RawMcpServer>, ParseError> {
    let span = node_to_span(file_id, node);

    let map = match node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "MCP server config must be a mapping".to_string(),
            });
        }
    };

    let server = RawMcpServer {
        command: get_string_field(file_id, map, "command")?,
        args: parse_string_array(file_id, map, "args")?,
        env: parse_string_map(file_id, map, "env")?,
        cwd: get_string_field(file_id, map, "cwd")?,
        url: get_string_field(file_id, map, "url")?,
        transport: get_string_field(file_id, map, "transport")?,
    };

    Ok(Spanned::new(server, span))
}

/// Parse pkg: configuration.
fn parse_pkg_config(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawPkgConfig>>, ParseError> {
    let pkg_node = match map.get_node("pkg") {
        Some(node) => node,
        None => return Ok(None),
    };

    let pkg_map = match pkg_node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, pkg_node),
                message: "pkg must be a mapping".to_string(),
            });
        }
    };

    let span = marked_span_to_span(file_id, pkg_map.span());
    let include = match parse_string_array(file_id, pkg_map, "include")? {
        Some(arr) => arr.value,
        None => Vec::new(),
    };

    Ok(Some(Spanned::new(RawPkgConfig { include }, span)))
}

/// Parse context: configuration.
fn parse_context_config(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<RawContextConfig>>, ParseError> {
    let ctx_node = match map.get_node("context") {
        Some(node) => node,
        None => return Ok(None),
    };

    let ctx_map = match ctx_node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, ctx_node),
                message: "context must be a mapping".to_string(),
            });
        }
    };

    let span = marked_span_to_span(file_id, ctx_map.span());
    let files = parse_string_map(file_id, ctx_map, "files")?.map(|s| s.value);

    Ok(Some(Spanned::new(RawContextConfig { files }, span)))
}

/// Parse imports: specification.
///
/// ```yaml
/// imports:
///   - path: ./partials/setup.nika.yaml
///     prefix: setup_
///   - path: pkg:@spn/core@1.0/seo.nika.yaml
/// ```
fn parse_imports(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<Vec<Spanned<RawImportSpec>>>>, ParseError> {
    // Accept both "imports:" (canonical) and "include:" (legacy alias)
    let imports_node = match map.get_node("imports").or_else(|| map.get_node("include")) {
        Some(node) => node,
        None => return Ok(None),
    };

    let seq = match imports_node {
        Node::Sequence(s) => s,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, imports_node),
                message: "imports must be a sequence".to_string(),
            });
        }
    };

    let outer_span = marked_span_to_span(file_id, seq.span());
    let mut specs = Vec::new();

    for item_node in seq.iter() {
        let item_span = node_to_span(file_id, item_node);

        let item_map = match item_node {
            Node::Mapping(m) => m,
            _ => {
                return Err(ParseError {
                    kind: ParseErrorKind::InvalidType,
                    span: item_span,
                    message: "import entry must be a mapping with 'path' field".to_string(),
                });
            }
        };

        let path = get_string_field(file_id, item_map, "path")?.ok_or_else(|| ParseError {
            kind: ParseErrorKind::MissingField,
            span: item_span,
            message: "import entry requires 'path' field".to_string(),
        })?;

        let prefix = get_string_field(file_id, item_map, "prefix")?;

        specs.push(Spanned::new(
            RawImportSpec {
                path,
                prefix,
                span: item_span,
            },
            item_span,
        ));
    }

    Ok(Some(Spanned::new(specs, outer_span)))
}

/// Parse inputs: parameters with defaults.
///
/// ```yaml
/// inputs:
///   locale: "fr-FR"
///   max_items: 10
/// ```
#[allow(clippy::type_complexity)]
fn parse_inputs(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Option<Spanned<IndexMap<Spanned<String>, Spanned<serde_json::Value>>>>, ParseError> {
    let inputs_node = match map.get_node("inputs") {
        Some(node) => node,
        None => return Ok(None),
    };

    let inputs_map = match inputs_node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span: node_to_span(file_id, inputs_node),
                message: "inputs must be a mapping".to_string(),
            });
        }
    };

    let span = marked_span_to_span(file_id, inputs_map.span());
    let mut result = IndexMap::new();

    for (k, v) in inputs_map.iter() {
        let key_span = marked_span_to_span(file_id, k.span());
        let key = Spanned::new(k.as_str().to_string(), key_span);
        let val_span = node_to_span(file_id, v);
        let val = Spanned::new(node_to_json(v), val_span);
        result.insert(key, val);
    }

    Ok(Some(Spanned::new(result, span)))
}

/// Parse the tasks array from a workflow mapping.
fn parse_tasks(
    file_id: FileId,
    map: &marked_yaml::types::MarkedMappingNode,
) -> Result<Spanned<Vec<Spanned<RawTask>>>, ParseError> {
    match map.get_node("tasks") {
        Some(Node::Sequence(seq)) => {
            let span = marked_span_to_span(file_id, seq.span());
            let tasks = seq
                .iter()
                .map(|task_node| parse_task(file_id, task_node))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Spanned::new(tasks, span))
        }
        Some(node) => Err(ParseError {
            kind: ParseErrorKind::InvalidType,
            span: node_to_span(file_id, node),
            message: "tasks must be a sequence".to_string(),
        }),
        None => {
            // No tasks field - return empty array with dummy span
            Ok(Spanned::dummy(Vec::new()))
        }
    }
}

/// Parse a single task from a YAML node.
fn parse_task(file_id: FileId, node: &Node) -> Result<Spanned<RawTask>, ParseError> {
    let span = node_to_span(file_id, node);

    let map = match node {
        Node::Mapping(m) => m,
        _ => {
            return Err(ParseError {
                kind: ParseErrorKind::InvalidType,
                span,
                message: "task must be a mapping".to_string(),
            });
        }
    };

    // Extract task id (required)
    let id = get_string_field(file_id, map, "id")?.ok_or_else(|| ParseError {
        kind: ParseErrorKind::MissingField,
        span,
        message: "task missing required field 'id'".to_string(),
    })?;

    // Extract optional fields
    let description = get_string_field(file_id, map, "description")?;
    let provider = get_string_field(file_id, map, "provider")?;
    let model = get_string_field(file_id, map, "model")?;

    // Parse all task fields
    let action = parse_action(file_id, map)?;
    let with_refs = parse_with_refs(file_id, map)?;
    let depends_on = parse_depends_on(file_id, map)?;
    let output = parse_output(file_id, map)?;
    let for_each = parse_for_each(file_id, map)?;
    let retry = parse_retry(file_id, map)?;
    let decompose = parse_decompose(file_id, map)?;
    let structured = parse_structured(file_id, map)?;

    // Parse artifact: config (task-level artifact output)
    let artifact = match map.get_node("artifact") {
        Some(node) => {
            let span = node_to_span(file_id, node);
            let value = node_to_json(node);
            Some(Spanned::new(value, span))
        }
        None => None,
    };

    // Parse log: config (task-level log override)
    let log = match map.get_node("log") {
        Some(node) => {
            let span = node_to_span(file_id, node);
            let value = node_to_json(node);
            Some(Spanned::new(value, span))
        }
        None => None,
    };

    // Parse standalone concurrency/fail_fast (used with decompose when no for_each)
    let standalone_concurrency = if for_each.is_none() {
        get_u32_field(file_id, map, "concurrency")?
    } else {
        None
    };
    let standalone_fail_fast = if for_each.is_none() {
        get_bool_field(file_id, map, "fail_fast")?
    } else {
        None
    };

    let task = RawTask {
        span,
        id,
        description,
        provider,
        model,
        action,
        with_refs,
        depends_on,
        output,
        for_each,
        retry,
        decompose,
        concurrency: standalone_concurrency,
        fail_fast: standalone_fail_fast,
        structured,
        artifact,
        log,
    };

    Ok(Spanned::new(task, span))
}

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

    const SIMPLE_WORKFLOW: &str = r#"
schema: "nika/workflow@0.12"
workflow: test-workflow
description: "A test workflow"
provider: claude
model: claude-sonnet-4-6

tasks:
  - id: task1
    description: "First task"

  - id: task2
    description: "Second task"
"#;

    #[test]
    fn test_parse_simple_workflow() {
        let file_id = FileId(0);
        let result = parse(SIMPLE_WORKFLOW, file_id);

        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
        let workflow = result.unwrap();

        assert_eq!(workflow.schema.value, "nika/workflow@0.12");
        assert_eq!(workflow.name(), "test-workflow");
        assert_eq!(
            workflow.description.as_ref().unwrap().value,
            "A test workflow"
        );
        assert_eq!(workflow.provider.as_ref().unwrap().value, "claude");
        assert_eq!(workflow.model.as_ref().unwrap().value, "claude-sonnet-4-6");
        assert_eq!(workflow.task_count(), 2);

        // Check spans are not dummy
        assert!(!workflow.schema.span.is_dummy());
        assert!(!workflow.tasks.span.is_dummy());
    }

    #[test]
    fn test_parse_task_ids() {
        let file_id = FileId(0);
        let workflow = parse(SIMPLE_WORKFLOW, file_id).unwrap();

        let task1 = workflow.get_task("task1");
        assert!(task1.is_some());
        assert_eq!(task1.unwrap().value.id.value, "task1");

        let task2 = workflow.get_task("task2");
        assert!(task2.is_some());
        assert_eq!(task2.unwrap().value.id.value, "task2");
    }

    #[test]
    fn test_parse_missing_schema() {
        let yaml = r#"
workflow: test
tasks: []
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::MissingField);
        assert!(err.message.contains("schema"));
    }

    #[test]
    fn test_parse_invalid_yaml() {
        let yaml = "invalid: yaml: syntax: [";
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::Syntax);
    }

    #[test]
    fn test_span_tracking() {
        let yaml = r#"schema: "nika/workflow@0.12"
workflow: my-workflow
tasks:
  - id: hello
"#;
        let file_id = FileId(0);
        let workflow = parse(yaml, file_id).unwrap();

        // Check that schema has correct span
        let schema_span = workflow.schema.span;
        assert!(!schema_span.is_dummy());

        // Check span bounds are reasonable
        assert!(schema_span.start.0 <= schema_span.end.0);
    }

    // =========================================================================
    // Verb Parsing Tests (5 Verbs)
    // =========================================================================

    #[test]
    fn test_parse_infer_shorthand() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: generate
    infer: "Generate a headline"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("generate").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Infer(action)) => {
                assert_eq!(action.value.prompt.value, "Generate a headline");
                assert!(action.value.temperature.is_none());
                assert!(action.value.system.is_none());
            }
            _ => panic!("Expected Infer action"),
        }
    }

    #[test]
    fn test_parse_infer_full_form() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: generate
    infer:
      prompt: "Generate content"
      system: "You are a helpful assistant"
      temperature: 0.7
      max_tokens: 1000
      thinking: true
      thinking_budget: 8000
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("generate").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Infer(action)) => {
                assert_eq!(action.value.prompt.value, "Generate content");
                assert_eq!(
                    action.value.system.as_ref().unwrap().value,
                    "You are a helpful assistant"
                );
                assert!((action.value.temperature.as_ref().unwrap().value - 0.7).abs() < 0.001);
                assert_eq!(action.value.max_tokens.as_ref().unwrap().value, 1000);
                assert!(action.value.thinking.as_ref().unwrap().value);
                assert_eq!(action.value.thinking_budget.as_ref().unwrap().value, 8000);
            }
            _ => panic!("Expected Infer action"),
        }
    }

    #[test]
    fn test_parse_exec_shorthand() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: build
    exec: "npm run build"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("build").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Exec(action)) => {
                assert_eq!(action.value.command.value, "npm run build");
                assert!(action.value.shell.is_none());
            }
            _ => panic!("Expected Exec action"),
        }
    }

    #[test]
    fn test_parse_exec_full_form() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: build
    exec:
      command: "npm run build"
      shell: true
      cwd: "/app"
      timeout: 30
      env:
        NODE_ENV: production
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("build").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Exec(action)) => {
                assert_eq!(action.value.command.value, "npm run build");
                assert!(action.value.shell.as_ref().unwrap().value);
                assert_eq!(action.value.working_dir.as_ref().unwrap().value, "/app");
                assert_eq!(action.value.timeout_ms.as_ref().unwrap().value, 30000);
                let env = action.value.env.as_ref().unwrap();
                assert!(env.value.values().any(|v| v.value == "production"));
            }
            _ => panic!("Expected Exec action"),
        }
    }

    #[test]
    fn test_parse_fetch_action() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: api_call
    fetch:
      url: "https://api.example.com/data"
      method: POST
      headers:
        Authorization: "Bearer token"
      timeout: 5
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("api_call").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Fetch(action)) => {
                assert_eq!(action.value.url.value, "https://api.example.com/data");
                assert_eq!(action.value.method.as_ref().unwrap().value, "POST");
                assert_eq!(action.value.timeout_ms.as_ref().unwrap().value, 5000); // 5 seconds * 1000
                let headers = action.value.headers.as_ref().unwrap();
                assert!(headers.value.values().any(|v| v.value.contains("Bearer")));
            }
            _ => panic!("Expected Fetch action"),
        }
    }

    #[test]
    fn test_parse_invoke_action() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: mcp_call
    invoke:
      tool: novanet_context
      mcp: novanet
      params:
        entity: "qr-code"
        locale: "fr-FR"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("mcp_call").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Invoke(action)) => {
                assert_eq!(action.value.tool.value, "novanet_context");
                assert_eq!(action.value.mcp.as_ref().unwrap().value, "novanet");
                assert!(action.value.params.is_some());
            }
            _ => panic!("Expected Invoke action"),
        }
    }

    #[test]
    fn test_parse_agent_action() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: research
    agent:
      prompt: "Research AI trends"
      tools:
        - nika:read
        - nika:write
      max_turns: 10
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("research").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Agent(action)) => {
                assert_eq!(action.value.prompt.value, "Research AI trends");
                let tools = action.value.tools.as_ref().unwrap();
                assert_eq!(tools.value.len(), 2);
                assert_eq!(tools.value[0].value, "nika:read");
                assert_eq!(action.value.max_iterations.as_ref().unwrap().value, 10);
            }
            _ => panic!("Expected Agent action"),
        }
    }

    #[test]
    fn test_parse_agent_prompt_is_primary_field() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: research
    agent:
      prompt: "Research AI trends"
      max_turns: 10
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("research").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Agent(action)) => {
                // Field must be named `prompt`, not `goal`
                assert_eq!(action.value.prompt.value, "Research AI trends");
            }
            _ => panic!("Expected Agent action"),
        }
    }

    #[test]
    fn test_parse_agent_goal_legacy_fallback() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: research
    agent:
      goal: "Legacy goal syntax"
      max_turns: 5
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("research").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Agent(action)) => {
                // Legacy `goal:` should still work as fallback
                assert_eq!(action.value.prompt.value, "Legacy goal syntax");
            }
            _ => panic!("Expected Agent action"),
        }
    }

    // =========================================================================
    // Task Configuration Parsing Tests
    // =========================================================================

    #[test]
    fn test_parse_with_refs_simple() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: step1
    infer: "Generate"
  - id: step2
    with:
      data: step1
    infer: "Process {{with.data}}"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("step2").unwrap();

        let with_refs = task.value.with_refs.as_ref().unwrap();
        assert_eq!(with_refs.value.len(), 1);

        let (alias, value) = with_refs.value.iter().next().unwrap();
        assert_eq!(alias.value, "data");
        assert_eq!(value.value, "step1");
    }

    #[test]
    fn test_parse_with_refs_binding_expr() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: step1
    infer: "Generate"
  - id: step2
    with:
      data: "step1"
      temp: "step1.data.temp ?? 20"
      cfg: "$env.API_KEY"
      val: "step1.output | upper | trim"
    infer: "Process"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("step2").unwrap();

        let with_refs = task.value.with_refs.as_ref().unwrap();
        assert_eq!(with_refs.value.len(), 4);

        let vals: Vec<&str> = with_refs.value.values().map(|v| v.value.as_str()).collect();
        assert_eq!(vals[0], "step1");
        assert_eq!(vals[1], "step1.data.temp ?? 20");
        assert_eq!(vals[2], "$env.API_KEY");
        assert_eq!(vals[3], "step1.output | upper | trim");
    }

    #[test]
    fn test_parse_depends_on_single() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: step1
    infer: "Generate"
  - id: step2
    depends_on: step1
    infer: "Process"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("step2").unwrap();

        let deps = task.value.depends_on.as_ref().unwrap();
        assert_eq!(deps.value.len(), 1);
        assert_eq!(deps.value[0].value, "step1");
    }

    #[test]
    fn test_parse_depends_on_multiple() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: step1
    infer: "Step 1"
  - id: step2
    infer: "Step 2"
  - id: step3
    depends_on: [step1, step2]
    infer: "Process"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("step3").unwrap();

        let deps = task.value.depends_on.as_ref().unwrap();
        assert_eq!(deps.value.len(), 2);
        assert_eq!(deps.value[0].value, "step1");
        assert_eq!(deps.value[1].value, "step2");
    }

    #[test]
    fn test_parse_imports() {
        let yaml = r#"
schema: "nika/workflow@0.12"
imports:
  - path: ./partials/setup.nika.yaml
    prefix: setup_
  - path: "pkg:@spn/core@1.0/seo.nika.yaml"
tasks:
  - id: main_task
    infer: "Main logic"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();

        let imports = workflow.imports.as_ref().unwrap();
        assert_eq!(imports.value.len(), 2);

        assert_eq!(
            imports.value[0].value.path.value,
            "./partials/setup.nika.yaml"
        );
        assert_eq!(
            imports.value[0].value.prefix.as_ref().unwrap().value,
            "setup_"
        );

        assert_eq!(
            imports.value[1].value.path.value,
            "pkg:@spn/core@1.0/seo.nika.yaml"
        );
        assert!(imports.value[1].value.prefix.is_none());
    }

    #[test]
    fn test_parse_inputs() {
        let yaml = r#"
schema: "nika/workflow@0.12"
inputs:
  locale: "fr-FR"
  max_items: 10
  debug: true
tasks:
  - id: main_task
    infer: "Main"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();

        let inputs = workflow.inputs.as_ref().unwrap();
        assert_eq!(inputs.value.len(), 3);

        let keys: Vec<&str> = inputs.value.keys().map(|k| k.value.as_str()).collect();
        assert_eq!(keys, vec!["locale", "max_items", "debug"]);

        assert_eq!(
            inputs.value.values().next().unwrap().value,
            serde_json::Value::String("fr-FR".to_string())
        );
    }

    #[test]
    fn test_parse_context_config() {
        let yaml = r#"
schema: "nika/workflow@0.12"
context:
  files:
    brand: ./context/brand.md
    data: ./context/data.json
tasks:
  - id: main
    infer: "Use brand: {{context.files.brand}}"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();

        let ctx = workflow.context.as_ref().unwrap();
        let files = ctx.value.files.as_ref().unwrap();
        assert_eq!(files.len(), 2);
        assert!(files.values().any(|v| v.value == "./context/brand.md"));
    }

    #[test]
    fn test_parse_pkg_config() {
        let yaml = r#"
schema: "nika/workflow@0.12"
pkg:
  include:
    - "github:user/repo"
    - "local:./path"
tasks:
  - id: main
    infer: "Main"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();

        let pkg = workflow.pkg.as_ref().unwrap();
        assert_eq!(pkg.value.include.len(), 2);
        assert_eq!(pkg.value.include[0].value, "github:user/repo");
    }

    #[test]
    fn test_parse_for_each_array() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: parallel
    for_each: ["a", "b", "c"]
    as: item
    concurrency: 3
    infer: "Process {{with.item}}"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("parallel").unwrap();

        let for_each = task.value.for_each.as_ref().unwrap();
        assert!(for_each.value.items.value.contains("["));
        assert_eq!(for_each.value.as_var.as_ref().unwrap().value, "item");
        assert_eq!(for_each.value.parallel.as_ref().unwrap().value, 3);
    }

    #[test]
    fn test_parse_for_each_binding() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: parallel
    for_each: "{{with.items}}"
    infer: "Process"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("parallel").unwrap();

        let for_each = task.value.for_each.as_ref().unwrap();
        assert_eq!(for_each.value.items.value, "{{with.items}}");
    }

    #[test]
    fn test_parse_retry_config() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: resilient
    retry:
      max_attempts: 3
      delay_ms: 1000
      backoff: 2.0
    infer: "Generate"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("resilient").unwrap();

        let retry = task.value.retry.as_ref().unwrap();
        assert_eq!(retry.value.max_attempts.as_ref().unwrap().value, 3);
        assert_eq!(retry.value.delay_ms.as_ref().unwrap().value, 1000);
        assert!((retry.value.backoff.as_ref().unwrap().value - 2.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_output_config() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: structured
    output:
      format: json
      schema:
        type: object
        properties:
          name:
            type: string
    infer: "Generate JSON"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("structured").unwrap();

        let output = task.value.output.as_ref().unwrap();
        assert_eq!(output.value.format.as_ref().unwrap().value, "json");
        assert!(output.value.schema.is_some());
    }

    // =========================================================================
    // Error Cases
    // =========================================================================

    #[test]
    fn test_parse_infer_missing_prompt() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: generate
    infer:
      temperature: 0.7
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::MissingField);
        assert!(err.message.contains("prompt"));
    }

    #[test]
    fn test_parse_fetch_missing_url() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: api_call
    fetch:
      method: GET
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::MissingField);
        assert!(err.message.contains("url"));
    }

    #[test]
    fn test_parse_invoke_missing_tool() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: mcp_call
    invoke:
      mcp: novanet
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::MissingField);
        assert!(err.message.contains("tool"));
    }

    #[test]
    fn test_parse_agent_missing_prompt() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: research
    agent:
      tools: [nika:read]
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::MissingField);
        assert!(err.message.contains("prompt"));
    }

    #[test]
    fn test_parse_rejects_multiple_verbs_in_task() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: ambiguous
    infer: "Generate something"
    exec: "echo hello"
"#;
        let result = parse(yaml, FileId(0));
        assert!(
            result.is_err(),
            "task with multiple verbs should be rejected"
        );
        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::InvalidType);
        assert!(
            err.message.contains("multiple verbs"),
            "error should mention multiple verbs, got: {}",
            err.message
        );
    }

    #[test]
    fn test_parse_invalid_temperature() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: generate
    infer:
      prompt: "Test"
      temperature: not_a_number
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert_eq!(err.kind, ParseErrorKind::InvalidType);
    }

    #[test]
    fn parse_rejects_yaml_nan_temperature() {
        // YAML .nan is rendered as ".nan" by marked_yaml, rejected by Rust's parse::<f64>()
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: test
    infer:
      prompt: "hello"
      temperature: .nan
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "YAML .nan temperature should be rejected");
    }

    #[test]
    fn parse_rejects_nan_string_temperature() {
        // "NaN" parses as f64::NaN successfully — caught by is_finite() check
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: test
    infer:
      prompt: "hello"
      temperature: NaN
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "NaN temperature should be rejected");
        let err = result.unwrap_err();
        assert!(
            err.message.contains("finite") || err.message.contains("number"),
            "Error should mention finite or number: {}",
            err.message
        );
    }

    #[test]
    fn parse_rejects_infinity_temperature() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: test
    infer:
      prompt: "hello"
      temperature: .inf
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "Infinity temperature should be rejected");
    }

    #[test]
    fn parse_rejects_inf_string_temperature() {
        // "inf" parses as f64::INFINITY — caught by is_finite() check
        let yaml = "schema: \"nika/workflow@0.12\"\ntasks:\n  - id: test\n    infer:\n      prompt: \"hello\"\n      temperature: inf\n";
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "inf temperature should be rejected");
    }

    #[test]
    fn parse_rejects_negative_infinity_temperature() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: test
    infer:
      prompt: "hello"
      temperature: -.inf
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "Negative infinity should be rejected");
    }

    // --- Edge cases: empty/malformed input ---

    #[test]
    fn parse_empty_string_errors() {
        let result = parse("", FileId(0));
        assert!(result.is_err(), "empty string should fail to parse");
    }

    #[test]
    fn parse_yaml_array_instead_of_map() {
        let result = parse("- item1\n- item2", FileId(0));
        assert!(result.is_err(), "YAML array root should be rejected");
    }

    #[test]
    fn parse_temperature_zero_is_valid() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: t
    infer:
      prompt: "hi"
      temperature: 0.0
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_ok(), "temperature 0.0 should be valid");
    }

    #[test]
    fn parse_temperature_one_is_valid() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: t
    infer:
      prompt: "hi"
      temperature: 1.0
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_ok(), "temperature 1.0 should be valid");
    }

    #[test]
    fn parse_whitespace_only_errors() {
        let result = parse("   \n\n  \t  ", FileId(0));
        assert!(result.is_err(), "whitespace-only input should fail");
    }

    // =========================================================================
    // Vision / Content Parsing Tests
    // =========================================================================

    #[test]
    fn parse_infer_with_content_text_and_image() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: vision-test
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: describe
    infer:
      content:
        - type: text
          text: "Describe this image"
        - type: image
          source: "blake3:abc123"
          detail: high
"#;
        let result = parse(yaml, FileId(0));
        assert!(
            result.is_ok(),
            "vision content should parse: {:?}",
            result.err()
        );
        let wf = result.unwrap();
        let task = &wf.tasks.value[0];
        match &task.value.action {
            Some(RawTaskAction::Infer(s)) => {
                let content = s.value.content.as_ref().expect("content should be Some");
                assert_eq!(content.value.len(), 2);
            }
            other => panic!("expected Some(Infer), got {:?}", other),
        }
    }

    #[test]
    fn parse_infer_content_only_no_prompt() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: vision-no-prompt
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer:
      content:
        - type: text
          text: "What is this?"
"#;
        let result = parse(yaml, FileId(0));
        assert!(
            result.is_ok(),
            "content without prompt should parse: {:?}",
            result.err()
        );
        let wf = result.unwrap();
        let task = &wf.tasks.value[0];
        match &task.value.action {
            Some(RawTaskAction::Infer(s)) => {
                assert!(
                    s.value.prompt.value.is_empty(),
                    "prompt should be empty string"
                );
                assert!(s.value.content.is_some(), "content should be present");
            }
            other => panic!("expected Some(Infer), got {:?}", other),
        }
    }

    #[test]
    fn parse_infer_prompt_and_content() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: both
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer:
      prompt: "Analyze carefully"
      content:
        - type: image
          source: "blake3:xyz"
"#;
        let result = parse(yaml, FileId(0));
        assert!(
            result.is_ok(),
            "prompt+content should parse: {:?}",
            result.err()
        );
        let wf = result.unwrap();
        let task = &wf.tasks.value[0];
        match &task.value.action {
            Some(RawTaskAction::Infer(s)) => {
                assert_eq!(s.value.prompt.value, "Analyze carefully");
                assert!(s.value.content.is_some());
            }
            other => panic!("expected Some(Infer), got {:?}", other),
        }
    }

    #[test]
    fn parse_infer_shorthand_still_works() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: shorthand
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer: "Just a simple prompt"
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_ok());
        let wf = result.unwrap();
        match &wf.tasks.value[0].value.action {
            Some(RawTaskAction::Infer(s)) => {
                assert_eq!(s.value.prompt.value, "Just a simple prompt");
                assert!(s.value.content.is_none());
            }
            other => panic!("expected Some(Infer), got {:?}", other),
        }
    }

    #[test]
    fn parse_infer_neither_prompt_nor_content_errors() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: err
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer:
      temperature: 0.5
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "neither prompt nor content should fail");
        let err = result.unwrap_err();
        assert!(err.message.contains("prompt") || err.message.contains("content"));
    }

    #[test]
    fn parse_infer_content_invalid_type_errors() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: err
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer:
      content:
        - type: video
          url: "https://example.com"
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "unknown content type should fail");
        let err = result.unwrap_err();
        assert!(err.message.contains("unknown content part type"));
    }

    #[test]
    fn parse_infer_content_empty_sequence_errors() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: err
provider: claude
model: claude-sonnet-4-6
tasks:
  - id: t
    infer:
      content: []
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_err(), "empty content should fail");
    }

    #[test]
    fn parse_infer_content_image_url_part() {
        let yaml = r#"
schema: "nika/workflow@0.12"
workflow: url
provider: openai
model: gpt-4o
tasks:
  - id: t
    infer:
      content:
        - type: image_url
          url: "https://example.com/photo.jpg"
          detail: low
        - type: text
          text: "What is in this photo?"
"#;
        let result = parse(yaml, FileId(0));
        assert!(result.is_ok(), "image_url should parse: {:?}", result.err());
    }

    #[test]
    fn test_parse_infer_with_guardrails() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: summarize
    infer:
      prompt: "Summarize this article"
      guardrails:
        - type: length
          min_words: 50
          max_words: 200
        - type: regex
          pattern: "^Summary:"
          message: "Output must start with 'Summary:'"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("summarize").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Infer(action)) => {
                assert_eq!(action.value.prompt.value, "Summarize this article");
                assert_eq!(action.value.guardrails.len(), 2);
                assert_eq!(action.value.guardrails[0].guardrail_type(), "length");
                assert_eq!(action.value.guardrails[1].guardrail_type(), "regex");
            }
            _ => panic!("Expected Infer action"),
        }
    }

    #[test]
    fn test_parse_infer_shorthand_no_guardrails() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: quick
    infer: "Generate a headline"
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("quick").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Infer(action)) => {
                assert!(
                    action.value.guardrails.is_empty(),
                    "Shorthand infer should have no guardrails"
                );
            }
            _ => panic!("Expected Infer action"),
        }
    }

    #[test]
    fn test_parse_infer_guardrails_on_failure_fail() {
        let yaml = r#"
schema: "nika/workflow@0.12"
tasks:
  - id: strict
    infer:
      prompt: "Generate strict output"
      guardrails:
        - type: length
          min_words: 10
          on_failure: fail
"#;
        let workflow = parse(yaml, FileId(0)).unwrap();
        let task = workflow.get_task("strict").unwrap();

        match &task.value.action {
            Some(RawTaskAction::Infer(action)) => {
                assert_eq!(action.value.guardrails.len(), 1);
                assert_eq!(
                    action.value.guardrails[0].on_failure(),
                    crate::ast::guardrails::OnFailure::Fail
                );
            }
            _ => panic!("Expected Infer action"),
        }
    }
}