truefix-at 0.1.5

TrueFix acceptance-test (AT) conformance suite.
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
//! Authored acceptance-test scenarios (black-box behaviour contracts).
//!
//! These reproduce the *behaviour* of the classic QuickFIX server AT scenarios from the FIX
//! specification — independently scripted, with no source or test data copied (Constitution
//! Principle III). Coverage spans logon/sequencing, admin handling, resend/gap-fill, out-of-order
//! queueing, the field-validation reject family (across FIX.4.2 and FIX.4.4), and the special
//! suites (789/369, CheckLatency, garbled/checksum, resend chunking). The corpus is grown by
//! adding permutations on top of this runner.

use truefix_core::{Field, Message};

use crate::runner::{ExpectMsg, Scenario, SessionTweaks, Step, client_message};

/// The FIX versions the server suite is exercised against (FR-002; US9 adds `FIX.Latest`, the
/// tenth dictionary — the whole version-agnostic core (logon/sequencing/resend/admin) runs
/// against it exactly as it does the other nine, since `start_acceptor`'s session-layer protocol
/// logic never depends on a per-version dictionary being loaded — dictionary-backed field
/// validation scenarios remain separately authored for FIX.4.2/FIX.4.4 only, unaffected).
pub const SUITE_VERSIONS: &[&str] = &[
    "FIX.4.0",
    "FIX.4.1",
    "FIX.4.2",
    "FIX.4.3",
    "FIX.4.4",
    "FIX.5.0",
    "FIX.5.0SP1",
    "FIX.5.0SP2",
    "FIX.Latest",
];

fn logon(version: &str, seq: i64, reset: bool) -> Message {
    let mut m = client_message(version, "A", seq);
    m.body.set(Field::int(98, 0));
    m.body.set(Field::int(108, 30));
    // T129 (feature 009): FIX.4.0 predates ResetSeqNumFlag(141) (introduced in FIX.4.1) — the
    // field doesn't exist in that dictionary at all, so sending it now that FIX.4.0 has a bundled
    // validator (`runner::dictionary_for_version`) would draw a TagNotDefinedForMessage reject on
    // every scenario using this shared helper with `reset: true`.
    if reset && version != "FIX.4.0" {
        m.body.set(Field::string(141, "Y"));
    }
    m
}

fn scenario(name: &str, version: &str, steps: Vec<Step>) -> Scenario {
    scenario_with(name, version, steps, SessionTweaks::default())
}

fn scenario_with(name: &str, version: &str, steps: Vec<Step>, tweaks: SessionTweaks) -> Scenario {
    Scenario {
        name: name.to_owned(),
        versions: vec![version.to_owned()],
        steps,
        tweaks,
    }
}

/// 1a — a valid Logon with the correct MsgSeqNum is answered with a Logon.
fn valid_logon(v: &str) -> Scenario {
    scenario(
        "1a_ValidLogonWithCorrectMsgSeqNum",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
        ],
    )
}

/// 1a — a Logon whose MsgSeqNum is too high requests the missing range before the acceptor
/// transitions to LoggedOn.
fn logon_seq_too_high(v: &str) -> Scenario {
    scenario(
        "1a_ValidLogonMsgSeqNumTooHigh",
        v,
        vec![
            Step::Send(logon(v, 10, false)), // no reset; expected is 1
            Step::Expect(ExpectMsg::of("2").field(7, "1")), // ResendRequest BeginSeqNo=1
        ],
    )
}

/// 2b — an application/admin message with MsgSeqNum too high triggers a ResendRequest.
fn msgseqnum_too_high(v: &str) -> Scenario {
    scenario(
        "2b_MsgSeqNumTooHigh",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 10)), // Heartbeat, seq too high
            Step::Expect(ExpectMsg::of("2").field(7, "2")), // ResendRequest BeginSeqNo=2
        ],
    )
}

/// 2c — a message with MsgSeqNum too low (no PossDup) draws a Logout and disconnect.
fn msgseqnum_too_low(v: &str) -> Scenario {
    scenario(
        "2c_MsgSeqNumTooLow",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 1)), // Heartbeat, seq too low
            Step::Expect(ExpectMsg::of("5")),      // Logout
            Step::ExpectDisconnect,
        ],
    )
}

/// 4b — a received TestRequest is answered with a Heartbeat echoing the TestReqID.
fn received_test_request(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.body.set(Field::string(112, "HELLO"));
    scenario(
        "4b_ReceivedTestRequest",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "HELLO")),
        ],
    )
}

/// ReverseRoute — a reply to a message carrying OnBehalfOf* routing fields reverses them onto
/// DeliverTo* on the reply.
fn reverse_route(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.body.set(Field::string(112, "ROUTE-ME"));
    tr.header.set(Field::string(115, "BROKER")); // OnBehalfOfCompID
    scenario(
        "ReverseRoute",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            Step::Expect(
                ExpectMsg::of("0")
                    .field(112, "ROUTE-ME")
                    .field(128, "BROKER"),
            ), // DeliverToCompID
        ],
    )
}

/// ReverseRouteWithEmptyRoutingTags — a routing tag present but empty still reverses.
fn reverse_route_empty_tags(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.body.set(Field::string(112, "ROUTE-EMPTY"));
    tr.header.set(Field::string(115, "")); // OnBehalfOfCompID, present but empty
    scenario(
        "ReverseRouteWithEmptyRoutingTags",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "ROUTE-EMPTY").field(128, "")),
        ],
    )
}

/// 13b — an unsolicited Logout is answered with a Logout and disconnect.
fn unsolicited_logout(v: &str) -> Scenario {
    scenario(
        "13b_UnsolicitedLogoutMessage",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "5", 2)), // Logout
            Step::Expect(ExpectMsg::of("5")),
            Step::ExpectDisconnect,
        ],
    )
}

/// NEW-85/FR-049 (009/US2) — Logout is terminal even when its MsgSeqNum is above the expected
/// value. It is answered immediately instead of being queued behind a ResendRequest.
fn too_high_logout_processed_immediately(v: &str) -> Scenario {
    scenario(
        "NEW85_TooHighLogoutProcessedImmediately",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "5", 5)),
            Step::Expect(ExpectMsg::of("5")),
            Step::ExpectDisconnect,
        ],
    )
}

/// 2f — a ResendRequest for already-sent admin traffic is answered with a SequenceReset-GapFill.
fn resend_request_gap_fill(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(7, 1)); // BeginSeqNo
    rr.body.set(Field::int(16, 0)); // EndSeqNo=0 → "until end"
    scenario(
        "2f_ResendRequestGapFill",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            // Only the admin Logon was sent, so the resend collapses to a GapFill.
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(
                ExpectMsg::of("4")
                    .field(123, "Y")
                    .field(36, "2")
                    .field(34, "1"),
            ),
        ],
    )
}

/// 2g — a SequenceReset-Reset advances the expected inbound sequence number.
fn sequence_reset_reset(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 99); // MsgSeqNum ignored for SequenceReset-Reset
    sr.body.set(Field::int(36, 5)); // NewSeqNo=5 (no GapFillFlag → Reset)
    let mut tr = client_message(v, "1", 5); // now-expected sequence
    tr.body.set(Field::string(112, "AFTER-RESET"));
    scenario(
        "2g_SequenceResetReset",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Send(tr),
            // Heartbeat (not ResendRequest) proves the server now expects seq 5.
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "AFTER-RESET").field(34, "2")),
        ],
    )
}

/// 2m — a message with MsgSeqNum too low but PossDupFlag=Y is ignored, not a Logout.
fn poss_dup_too_low(v: &str) -> Scenario {
    let mut dup = client_message(v, "0", 1); // Heartbeat, seq too low
    dup.header.set(Field::string(43, "Y")); // PossDupFlag
    let mut tr = client_message(v, "1", 2);
    tr.body.set(Field::string(112, "STILL-UP"));
    scenario(
        "2m_PossDupMsgSeqNumTooLow",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(dup),
            Step::Send(tr),
            // A Heartbeat (not Logout/disconnect) proves the dup was silently ignored.
            Step::Expect(ExpectMsg::of("0").field(112, "STILL-UP")),
        ],
    )
}

/// GAP-08 (US3, feature 005) — a PossDup message whose OrigSendingTime is later than its
/// SendingTime (an anti-replay violation — the message claims to have originally been sent
/// *after* the resend that is carrying it) draws a Logout and disconnect, not the silent ignore
/// that `poss_dup_too_low` above exercises for a legitimate low-seq PossDup.
fn poss_dup_orig_sending_time_after_sending_time(v: &str) -> Scenario {
    let mut dup = client_message(v, "0", 1); // Heartbeat, seq too low
    dup.header.set(Field::string(43, "Y")); // PossDupFlag
    dup.header.set(Field::string(122, "20240101-00:00:05")); // OrigSendingTime > SendingTime(52)
    scenario(
        "GAP08_PossDupOrigSendingTimeAfterSendingTime",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(dup),
            // NEW-87 (feature 009): a session Reject precedes the Logout for this non-Logon
            // anti-replay violation, matching QFJ's two-message shape (SessionRejectReason=5,
            // version-filtered like every other session Reject -- see reject_field_correctness.rs
            // for the per-version detail already covered at the unit level).
            Step::Expect(ExpectMsg::of("3")),
            Step::Expect(ExpectMsg::of("5")), // Logout: anti-replay violation
            Step::ExpectDisconnect,
        ],
    )
}

/// GAP-18a (US3, feature 005) — a second Logon received on an already-logged-on session is
/// rejected (Logout + disconnect), not silently reprocessed as if it were the first.
fn duplicate_logon_rejected(v: &str) -> Scenario {
    scenario(
        "GAP18a_DuplicateLogonRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(logon(v, 2, false)),
            Step::Expect(ExpectMsg::of("5")), // Logout: duplicate Logon
            Step::ExpectDisconnect,
        ],
    )
}

/// BUG-59/FR-023 (feature 007): FIX.4.0/4.1 never carry `SessionRejectReason(373)` at all (QFJ
/// omits the field entirely below FIX.4.2) — every scenario asserting a specific 373 value needs
/// to instead assert its *absence* for these two versions.
fn expect_session_reject_reason(v: &str, msg_type: &str, code: &str) -> ExpectMsg {
    let e = ExpectMsg::of(msg_type);
    if v == "FIX.4.0" || v == "FIX.4.1" {
        e.without_field(373)
    } else {
        e.field(373, code)
    }
}

/// BUG-06 (006/US1) — a plain-mode SequenceReset missing NewSeqNo(36) entirely is rejected as a
/// required-tag-missing violation, not silently skipped while still draining the queue.
fn sequence_reset_reset_missing_new_seq_no_rejected(v: &str) -> Scenario {
    let sr = client_message(v, "4", 2); // no NewSeqNo at all, no GapFillFlag
    scenario(
        "BUG06_SequenceResetMissingNewSeqNoRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — this Reject is the server's
            // 2nd message (after the Logon ack).
            Step::Expect(expect_session_reject_reason(v, "3", "1").field(34, "2")), // RequiredTagMissing
        ],
    )
}

/// NEW-70/FR-040 (009/US2) — gap-fill mode also requires NewSeqNo(36). A malformed gap-fill must
/// draw a required-tag-missing Reject rather than being silently accepted without advancing.
fn sequence_reset_gap_fill_missing_new_seq_no_rejected(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 2);
    sr.body.set(Field::string(123, "Y")); // GapFillFlag, but no NewSeqNo
    scenario(
        "NEW70_GapFillMissingNewSeqNoRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Expect(
                expect_session_reject_reason(v, "3", "1") // RequiredTagMissing
                    .field(371, "36") // RefTagID = NewSeqNo
                    .field(34, "2"), // T138 (feature 009, NEW-51): outbound MsgSeqNum
            ),
        ],
    )
}

/// BUG-22 (006/US1) — a ResendRequest missing BeginSeqNo(7) entirely draws a required-tag-missing
/// Reject instead of a silent non-response.
fn resend_request_missing_begin_seq_no_rejected(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(16, 5)); // EndSeqNo present; BeginSeqNo entirely absent
    scenario(
        "BUG22_ResendRequestMissingBeginSeqNoRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            Step::Expect(
                expect_session_reject_reason(v, "3", "1") // RequiredTagMissing
                    .field(371, "7") // RefTagID = BeginSeqNo
                    .field(34, "2"), // T138 (feature 009, NEW-51): outbound MsgSeqNum
            ),
        ],
    )
}

/// BUG-22 (006/US1) — a ResendRequest missing EndSeqNo(16) entirely draws a required-tag-missing
/// Reject instead of a silent non-response.
fn resend_request_missing_end_seq_no_rejected(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(7, 1)); // BeginSeqNo present; EndSeqNo entirely absent
    scenario(
        "BUG22_ResendRequestMissingEndSeqNoRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            Step::Expect(
                expect_session_reject_reason(v, "3", "1") // RequiredTagMissing
                    .field(371, "16") // RefTagID = EndSeqNo
                    .field(34, "2"), // T138 (feature 009, NEW-51): outbound MsgSeqNum
            ),
        ],
    )
}

/// B3 (006/US1) — an invalid application message enqueued behind a gap is validated (and
/// rejected) exactly like an in-order one when the gap is later filled and it's drained, instead
/// of bypassing dictionary validation.
fn gap_fill_drained_message_is_validated(v: &str) -> Scenario {
    let mut invalid_order = new_order_single(3); // seq 3, arrives first -> queued (gap)
    invalid_order.body.set(Field::string(54, "Z")); // invalid Side enum
    scenario(
        "B3_GapFillDrainedMessageIsValidated",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(invalid_order),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) on both server responses.
            Step::Expect(ExpectMsg::of("2").field(7, "2").field(34, "2")), // ResendRequest for the gap at seq 2
            Step::Send(client_message(v, "0", 2)), // fills the gap, drains queued seq 3
            Step::Expect(ExpectMsg::of("3").field(373, "5").field(34, "3")), // the drained seq-3 message is rejected
        ],
    )
}

/// B5 (006/US1) — a dictionary-validation failure with `DisconnectOnError` sends a Logout before
/// disconnecting, matching the identity/latency disconnect paths, instead of dropping the
/// connection with only a Reject sent.
fn dictionary_failure_disconnect_sends_logout(v: &str) -> Scenario {
    let mut invalid_order = new_order_single(2);
    invalid_order.body.set(Field::string(54, "Z")); // invalid Side enum
    scenario_with(
        "B5_DictionaryFailureDisconnectSendsLogout",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(invalid_order),
            Step::Expect(ExpectMsg::of("3").field(373, "5")), // session Reject
            Step::Expect(ExpectMsg::of("5")),                 // Logout, before disconnecting
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            disconnect_on_error: true,
            ..SessionTweaks::default()
        },
    )
}

/// NEW-63 (feature 009): a dictionary-invalid Logon (missing the required EncryptMethod(98)
/// field) sends a Logout and disconnects even with `DisconnectOnError=N` -- previously that
/// config left only a bare session Reject sent, stranding the session in `AwaitingLogon`.
fn dict_invalid_logon_disconnects_without_disconnect_on_error(v: &str) -> Scenario {
    let mut bad_logon = client_message(v, "A", 1);
    bad_logon.body.set(Field::int(108, 30)); // HeartBtInt present, EncryptMethod(98) deliberately absent
    scenario_with(
        "NEW63_DictInvalidLogonDisconnectsWithoutDisconnectOnError",
        v,
        vec![
            Step::Send(bad_logon),
            Step::Expect(ExpectMsg::of("3")), // session Reject (dictionary-validation failure)
            Step::Expect(ExpectMsg::of("5")), // Logout, not left stranded in AwaitingLogon
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            disconnect_on_error: false,
            ..SessionTweaks::default()
        },
    )
}

/// B7 (006/US1) — an inbound message (here, the Logon itself) with an unparseable SendingTime
/// fails the CheckLatency check, instead of silently bypassing it, and is aborted like any other
/// latency failure (Logout + disconnect).
fn unparseable_sending_time_fails_latency(v: &str) -> Scenario {
    let mut bad_logon = logon(v, 1, true);
    bad_logon.header.set(Field::string(52, "not-a-timestamp"));
    scenario_with(
        "B7_UnparseableSendingTimeFailsLatency",
        v,
        vec![
            Step::Send(bad_logon),
            // T130 (feature 009, NEW-29): assert the actual reject reason, not just "a Logout
            // occurred".
            Step::Expect(ExpectMsg::of("5").field(58, "SendingTime accuracy problem")),
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            check_latency: true,
            ..SessionTweaks::default()
        },
    )
}

/// 1d — with ResetOnLogon (default), the acceptor's Logon response carries ResetSeqNumFlag=Y.
/// FIX.4.0 predates the field entirely (see `logon`'s doc comment) — `logon()` never sets it on
/// that version's inbound Logon, so (per BUG-28/FR-005's "echo only what the inbound Logon itself
/// carried" rule) the response correctly omits it too, rather than echoing a fabricated `Y`.
fn logon_response_carries_reset_flag(v: &str) -> Scenario {
    let expect = if v == "FIX.4.0" {
        ExpectMsg::of("A").without_field(141)
    } else {
        ExpectMsg::of("A").field(141, "Y")
    };
    scenario(
        "1d_LogonResponseResetFlag",
        v,
        vec![Step::Send(logon(v, 1, true)), Step::Expect(expect)],
    )
}

/// T015 (US1, feature 007): BUG-28/FR-005 — the acceptor's Logon response must echo the INBOUND
/// Logon's own `ResetSeqNumFlag`, not `config.reset_on_logon` (which defaults to `true` for every
/// AT-suite acceptor session, per `runner.rs`'s `start_acceptor`). Previously the response always
/// echoed `Y` regardless of what the inbound Logon carried — this scenario sends a Logon WITHOUT
/// the flag and confirms the response correctly omits it too.
fn logon_response_does_not_echo_reset_flag_when_inbound_lacks_it(v: &str) -> Scenario {
    scenario(
        "BUG28_LogonResponseDoesNotEchoAbsentResetFlag",
        v,
        vec![
            Step::Send(logon(v, 1, false)), // no ResetSeqNumFlag on the inbound Logon
            Step::Expect(ExpectMsg::of("A").without_field(141)),
        ],
    )
}

/// T036 (US1, feature 007): BUG-89/FR-011 — a dictionary-invalid *admin* message (a TestRequest
/// carrying a tag the dictionary doesn't define) draws a plain session-level Reject (35=3), not
/// silent pass-through. Previously `validate_app` returned `None` unconditionally for every
/// admin-typed message, so this would have gone unvalidated regardless of the dictionary.
fn admin_message_dictionary_invalid_is_rejected(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2); // TestRequest
    tr.body.set(Field::string(112, "TESTREQID"));
    tr.body.set(Field::string(4321, "not-a-real-tag")); // unknown tag, below the UDF range (5000+)
    scenario(
        "BUG89_AdminMessageDictionaryInvalidIsRejected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("3")), // plain Reject, not BusinessMessageReject (35=j)
        ],
    )
}

/// 2_noseq — a post-logon message with no MsgSeqNum(34) draws a session-level Reject.
fn missing_msg_seq_num(v: &str) -> Scenario {
    let mut m = Message::new();
    m.header
        .set(Field::string(8, crate::runner::wire_begin_string(v)));
    m.header.set(Field::string(35, "1")); // TestRequest, but without MsgSeqNum
    m.header.set(Field::string(49, "CLIENT"));
    m.header.set(Field::string(56, "SERVER"));
    m.header.set(Field::string(52, "20240101-00:00:00"));
    m.body.set(Field::string(112, "NOSEQ"));
    scenario(
        "2_MissingMsgSeqNum",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(m),
            Step::Expect(ExpectMsg::of("3")), // Reject: missing/invalid MsgSeqNum
        ],
    )
}

/// 0_idle — after the negotiated heartbeat interval of silence, the acceptor emits a Heartbeat.
///
/// NEW-103 (audit 006): `TestRequestDelayMultiplier` defaults to `0.5` (QFJ parity), strictly
/// less than the idle-heartbeat-send threshold's `1.0`, so a totally silent peer now draws the
/// liveness-probing TestRequest *before* the next idle Heartbeat, on every tick after the first
/// — not after it, as the previous (non-parity) `1.0` default happened to produce. Sending the
/// TestRequest also resets this session's own "time since last sent" clock (`send_stored`), which
/// is why the Heartbeat that follows lands a full tick later rather than on the same tick.
fn idle_heartbeat_emitted(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.body.set(Field::int(108, 1)); // 1-second heartbeat so the timer fires quickly
    scenario(
        "0_IdleHeartbeatEmitted",
        v,
        vec![
            Step::Send(lo),
            Step::Expect(ExpectMsg::of("A")),
            Step::Expect(ExpectMsg::of("1").field(112, "TEST")), // silent-peer probe fires first
            Step::Expect(ExpectMsg::of("0")), // unprompted Heartbeat from the idle-send timer
        ],
    )
}

/// 4_silence — continued silence past the initial TestRequest probe draws further idle
/// Heartbeats (on this session's own send cadence, unrelated to the now-outstanding probe) until
/// `HeartBeatTimeoutMultiplier` disconnects the unresponsive peer (see
/// [`idle_heartbeat_emitted`]'s doc for why the probe itself now fires first under NEW-103's
/// parity default).
fn test_request_on_silence(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.body.set(Field::int(108, 1));
    scenario(
        "4_TestRequestOnSilence",
        v,
        vec![
            Step::Send(lo),
            Step::Expect(ExpectMsg::of("A")),
            Step::Expect(ExpectMsg::of("1").field(112, "TEST")), // liveness probe
            Step::Expect(ExpectMsg::of("0")), // idle Heartbeat, still on its own cadence
            Step::Expect(ExpectMsg::of("0")), // another idle Heartbeat tick later
            Step::ExpectDisconnect,           // peer never answers -> heartbeat-timeout disconnect
        ],
    )
}

/// 5_initiated — an acceptor-initiated Logout (graceful): the server sends Logout, the client acks,
/// and the server disconnects.
fn acceptor_initiated_logout(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(11, "LOGOUT")); // sentinel: triggers monitor.force_logout
    scenario_with(
        "5_AcceptorInitiatedLogout",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("5")), // acceptor-initiated Logout
            Step::Send(client_message(v, "5", 3)), // client acknowledges
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// 1c — the acceptor adopts the HeartBtInt from the inbound Logon and echoes it in its response.
fn logon_adopts_heartbeat_interval(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.body.set(Field::int(108, 45)); // override the helper's default of 30
    scenario(
        "1c_LogonAdoptsHeartBtInt",
        v,
        vec![
            Step::Send(lo),
            Step::Expect(ExpectMsg::of("A").field(108, "45")),
        ],
    )
}

/// 2x — out-of-order delivery: a too-high message is queued and a ResendRequest is issued; once the
/// gap is filled the queued message is processed in order.
fn out_of_order_queued_then_drained(v: &str) -> Scenario {
    let mut tr3 = client_message(v, "1", 3);
    tr3.body.set(Field::string(112, "THREE"));
    let mut tr2 = client_message(v, "1", 2);
    tr2.body.set(Field::string(112, "TWO"));
    scenario(
        "2x_OutOfOrderQueuedThenDrained",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr3), // seq 3 arrives before 2 → queued
            Step::Expect(ExpectMsg::of("2").field(7, "2")), // ResendRequest BeginSeqNo=2
            Step::Send(tr2), // fills the gap
            Step::Expect(ExpectMsg::of("0").field(112, "TWO")), // seq 2 processed
            Step::Expect(ExpectMsg::of("0").field(112, "THREE")), // queued seq 3 drained in order
        ],
    )
}

/// 2_dedup — once a gap has triggered a ResendRequest, further too-high messages are queued
/// without emitting a second ResendRequest (the resend-pending guard).
fn resend_request_not_duplicated(v: &str) -> Scenario {
    let mut tr2 = client_message(v, "1", 2);
    tr2.body.set(Field::string(112, "TWO"));
    scenario(
        "2_ResendRequestNotDuplicated",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 4)), // seq 4: gap → one ResendRequest
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) on both server responses.
            Step::Expect(ExpectMsg::of("2").field(7, "2").field(34, "2")),
            Step::Send(client_message(v, "0", 5)), // seq 5: still too high → no second request
            Step::Send(tr2),                       // fills seq 2
            // The next message must be the Heartbeat for seq 2, not a duplicate ResendRequest.
            Step::Expect(ExpectMsg::of("0").field(112, "TWO").field(34, "3")),
        ],
    )
}

/// 2_begin0 — `NEW-02` (feature 009): a ResendRequest with `BeginSeqNo=0` is treated as "from
/// sequence 1" and answered (here, with only the admin Logon sent, that collapses to a GapFill
/// covering seq 1), not silently dropped. Previously this scenario asserted the (buggy) opposite
/// -- that `BeginSeqNo=0` was ignored -- locking in `NEW-02`'s defect as "correct" until this fix.
fn resend_request_begin_zero_treated_as_one(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(7, 0)); // BeginSeqNo=0 -> treated as 1
    rr.body.set(Field::int(16, 0));
    scenario(
        "2_ResendRequestBeginZeroTreatedAsOne",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            // Only the admin Logon was sent, so the resend collapses to a GapFill -- same
            // response `resend_request_gap_fill`'s explicit BeginSeqNo=1 case gets.
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(
                ExpectMsg::of("4")
                    .field(123, "Y")
                    .field(36, "2")
                    .field(34, "1"),
            ),
        ],
    )
}

/// 2f3 — a ResendRequest with an explicit (bounded) EndSeqNo still collapses admin traffic to a
/// GapFill.
fn resend_request_bounded_end(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(7, 1)); // BeginSeqNo
    rr.body.set(Field::int(16, 1)); // EndSeqNo explicit, not 0
    scenario(
        "2f3_ResendRequestBoundedEnd",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(
                ExpectMsg::of("4")
                    .field(123, "Y")
                    .field(36, "2")
                    .field(34, "1"),
            ),
        ],
    )
}

/// T018 (US1, feature 007): BUG-29/FR-007 — a `ResendRequest` for a sequence range higher than
/// what's expected is answered immediately (a GapFill here, since only admin traffic has been
/// sent), not deferred until our own gap toward the counterparty resolves. Previously this would
/// be silently queued behind our own outstanding `ResendRequest`, which is exactly the shape of a
/// `ResendRequest`-vs-`ResendRequest` deadlock when both sides are in this state simultaneously.
fn resend_request_too_high_answered_immediately(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 5); // too-high: server expects seq 2
    rr.body.set(Field::int(7, 1)); // BeginSeqNo
    rr.body.set(Field::int(16, 1)); // EndSeqNo
    let mut after_gap = client_message(v, "1", 6);
    after_gap
        .body
        .set(Field::string(112, "NO-DUPLICATE-RESEND"));
    scenario(
        "BUG29_ResendRequestTooHighAnsweredImmediately",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            // Their too-high ResendRequest is answered right away...
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) on all 3 server responses. The
            // GapFill answering a ResendRequest carries the MsgSeqNum of the slot it fills (1,
            // the Logon's own outbound slot), not a freshly-incremented live sequence number —
            // resending/gap-filling replays historical positions rather than consuming new ones.
            Step::Expect(ExpectMsg::of("4").field(34, "1")),
            // ...and we still separately request our own gap (seq 2..4).
            Step::Expect(ExpectMsg::of("2").field(7, "2").field(34, "2")),
            Step::Send(client_message(v, "0", 2)),
            Step::Send(client_message(v, "0", 3)),
            Step::Send(client_message(v, "0", 4)),
            Step::Send(after_gap),
            // NEW-86: draining the queued seq-5 ResendRequest only advances sequence accounting;
            // it must not emit the already-sent GapFill a second time. A duplicate would arrive
            // before this Heartbeat and fail the expectation.
            Step::Expect(
                ExpectMsg::of("0")
                    .field(112, "NO-DUPLICATE-RESEND")
                    .field(34, "3"),
            ),
        ],
    )
}

/// 2d — a SequenceReset-GapFill advances the expected inbound sequence number.
fn sequence_reset_gap_fill_advances(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 2);
    sr.body.set(Field::string(123, "Y")); // GapFillFlag
    sr.body.set(Field::int(36, 5)); // NewSeqNo
    let mut tr = client_message(v, "1", 5);
    tr.body.set(Field::string(112, "GAP-FILLED"));
    scenario(
        "2d_SequenceResetGapFillAdvances",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "GAP-FILLED").field(34, "2")),
        ],
    )
}

/// 2e — a SequenceReset-GapFill whose NewSeqNo is behind the expected number is ignored.
fn sequence_reset_gap_fill_backward_ignored(v: &str) -> Scenario {
    // After logon the server expects seq 2; a GapFill to NewSeqNo=1 must not rewind it.
    let mut sr = client_message(v, "4", 2);
    sr.body.set(Field::string(123, "Y"));
    sr.body.set(Field::int(36, 1)); // backward NewSeqNo
    let mut tr = client_message(v, "1", 2); // still the expected sequence
    tr.body.set(Field::string(112, "NO-REWIND"));
    scenario(
        "2e_SequenceResetGapFillBackwardIgnored",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "NO-REWIND").field(34, "2")),
        ],
    )
}

/// 2h — a ResendRequest for messages that were never sent yields no response (session continues).
fn resend_request_nothing_to_resend(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 2);
    rr.body.set(Field::int(7, 5)); // BeginSeqNo beyond anything sent
    rr.body.set(Field::int(16, 0));
    let mut tr = client_message(v, "1", 3); // ResendRequest consumed seq 2
    tr.body.set(Field::string(112, "ALIVE"));
    scenario(
        "2h_ResendRequestNothingToResend",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rr),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "ALIVE").field(34, "2")),
        ],
    )
}

/// 3a — a received Reject is consumed (no reply) and the sequence number advances.
fn reject_message_consumed(v: &str) -> Scenario {
    let mut rej = client_message(v, "3", 2);
    rej.body.set(Field::int(45, 1)); // RefSeqNum
    let mut tr = client_message(v, "1", 3); // Reject consumed seq 2
    tr.body.set(Field::string(112, "AFTER-REJECT"));
    scenario(
        "3a_ReceivedRejectConsumed",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(rej),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "AFTER-REJECT")),
        ],
    )
}

/// 0a — a received Heartbeat is consumed (no reply) and the sequence number advances.
fn heartbeat_consumed(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 3); // Heartbeat consumed seq 2
    tr.body.set(Field::string(112, "AFTER-HB"));
    scenario(
        "0a_ReceivedHeartbeatConsumed",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 2)), // Heartbeat at the expected sequence
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "AFTER-HB")),
        ],
    )
}

/// A valid FIX.4.4 NewOrderSingle (all required fields present).
fn new_order_single(seq: i64) -> Message {
    let mut m = client_message("FIX.4.4", "D", seq);
    m.body.set(Field::string(11, "ORDER-1")); // ClOrdID
    m.body.set(Field::string(21, "1")); // HandlInst
    m.body.set(Field::string(55, "AAPL")); // Symbol
    m.body.set(Field::string(54, "1")); // Side
    m.body.set(Field::string(60, "20240101-00:00:00")); // TransactTime
    m.body.set(Field::string(40, "2")); // OrdType
    m
}

/// A valid FIX.4.2 NewOrderSingle (req:11,55,54,38,40 — note no HandlInst/TransactTime, Side {1,2}).
fn new_order_single_42(seq: i64) -> Message {
    let mut m = client_message("FIX.4.2", "D", seq);
    m.body.set(Field::string(11, "ORDER-42")); // ClOrdID
    m.body.set(Field::string(21, "1")); // HandlInst
    m.body.set(Field::string(55, "AAPL")); // Symbol
    m.body.set(Field::string(54, "1")); // Side
    m.body.set(Field::string(60, "20240101-00:00:00")); // TransactTime
    m.body.set(Field::int(38, 100)); // OrderQty
    m.body.set(Field::string(40, "2")); // OrdType
    m
}

/// 14a (FIX.4.2) — a tag not defined in the 4.2 dictionary draws a session-level Reject.
fn invalid_tag_number_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::string(999, "X")); // 999 undefined, below the UDF range
    scenario(
        "14a_InvalidTagNumber_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "0")), // InvalidTagNumber
        ],
    )
}

/// 14c (FIX.4.2) — a defined tag (TestReqID 112) not valid for NewOrderSingle draws a Reject.
fn tag_not_defined_for_msg_type_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::string(112, "X")); // defined in 4.2, but not a NewOrderSingle field
    scenario(
        "14c_TagNotDefinedForMsgType_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "2")), // TagNotDefinedForMessageType
        ],
    )
}

/// 14d (FIX.4.2) — a present-but-empty ClOrdID(11) draws a Reject (TagSpecifiedWithoutValue).
fn tag_specified_without_value_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::new(11, Vec::new())); // ClOrdID present but empty
    scenario(
        "14d_TagSpecifiedWithoutValue_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "4")), // TagSpecifiedWithoutValue
        ],
    )
}

/// 14f (FIX.4.2) — a non-numeric OrderQty(38) draws a session-level Reject (IncorrectDataFormat).
fn incorrect_data_format_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::string(38, "abc")); // OrderQty is a QTY; "abc" is not numeric
    scenario(
        "14f_IncorrectDataFormat_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "6")), // IncorrectDataFormat
        ],
    )
}

/// 14_valid (FIX.4.2) — a fully-valid NewOrderSingle passes the 4.2 dictionary: no Reject.
fn valid_new_order_accepted_42() -> Scenario {
    let mut tr = client_message("FIX.4.2", "1", 3);
    tr.body.set(Field::string(112, "ORDER42-OK"));
    scenario(
        "14_valid_NewOrderSingleAccepted_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single_42(2)),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "ORDER42-OK")),
        ],
    )
}

/// 14b (FIX.4.2) — a NewOrderSingle missing required HandlInst(21) draws a session-level Reject
/// (US9, feature 005, FR-031: OrderQty(38) is optional in the real bundled FIX.4.2 dictionary —
/// HandlInst/Side/TransactTime/OrdType are NewOrderSingle's actual directly-required fields).
fn required_field_missing_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body = {
        let mut b = truefix_core::FieldMap::new();
        for f in new_order_single_42(2).body.fields() {
            if f.tag() != 21 {
                b.set(Field::new(f.tag(), f.value_bytes().to_vec()));
            }
        }
        b
    };
    scenario(
        "14b_RequiredFieldMissing_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "1")), // RequiredTagMissing
        ],
    )
}

/// 14e (FIX.4.2) — an out-of-enumeration Side value draws a session-level Reject.
fn incorrect_enum_value_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::string(54, "Z")); // not a real Side value
    scenario(
        "14e_IncorrectEnumValue_42",
        "FIX.4.2",
        vec![
            Step::Send(logon("FIX.4.2", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "5")), // ValueIsIncorrect
        ],
    )
}

/// 14_valid — a fully-valid NewOrderSingle passes validation: no Reject, sequence advances.
fn valid_new_order_accepted(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 3); // order consumed seq 2
    tr.body.set(Field::string(112, "ORDER-OK"));
    scenario(
        "14_valid_NewOrderSingleAccepted",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Send(tr),
            // A Heartbeat (not a Reject) proves the order was accepted and seq advanced.
            Step::Expect(ExpectMsg::of("0").field(112, "ORDER-OK")),
        ],
    )
}

/// T084 (US9, feature 006): `MinQty` (tag 110) on a NewOrderSingle is accepted, not rejected as an
/// undefined tag — `001.md` originally flagged tag 110 as absent from every bundled dictionary;
/// 005's dictionary-coverage work resolved that, but the AT suite never grew a scenario actually
/// exercising it (`docs/todo/003.md`'s own follow-up note). Confirmed via `dict-src/normalized/
/// FIX44.fixdict`/`FIX42.fixdict`: tag 110 is `opt:` on NewOrderSingle (`message D`) in both.
fn min_qty_field_accepted(name: &str, v: &str, order: Message) -> Scenario {
    let mut tr = client_message(v, "1", 3); // order consumed seq 2
    tr.body.set(Field::string(112, "MINQTY-OK"));
    scenario(
        name,
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Send(tr),
            // A Heartbeat (not a Reject) proves MinQty was accepted as a recognized field.
            Step::Expect(ExpectMsg::of("0").field(112, "MINQTY-OK")),
        ],
    )
}

fn min_qty_field_accepted_44() -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::int(110, 100)); // MinQty
    min_qty_field_accepted("MinQty_FieldAccepted_44", "FIX.4.4", order)
}

fn min_qty_field_accepted_42() -> Scenario {
    let mut order = new_order_single_42(2);
    order.body.set(Field::int(110, 50)); // MinQty
    min_qty_field_accepted("MinQty_FieldAccepted_42", "FIX.4.2", order)
}

/// A FIX.4.4 NewOrderSingle with the given repeating-group fields appended in wire order.
fn nos_with_group(seq: i64, group: &[(u32, &str)]) -> Message {
    let mut m = new_order_single(seq);
    for (t, v) in group {
        m.body.set(Field::string(*t, v));
    }
    m
}

/// 14i — a NoXxx count that does not match the number of group entries draws a session Reject.
fn group_count_mismatch(v: &str) -> Scenario {
    let order = nos_with_group(2, &[(453, "2"), (448, "A"), (447, "1"), (452, "1")]);
    scenario(
        "14i_RepeatingGroupCountNotEqual",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "16")), // IncorrectNumInGroupCount
        ],
    )
}

/// NEW-69/FR-039 (009/US2) — an empty value inside a repeating-group entry is subject to the
/// same TagSpecifiedWithoutValue validation as a top-level field.
fn empty_value_inside_group(v: &str) -> Scenario {
    let order = nos_with_group(2, &[(453, "1"), (448, ""), (447, "1"), (452, "1")]);
    scenario(
        "NEW69_EmptyValueInsideRepeatingGroup",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(
                ExpectMsg::of("3")
                    .field(371, "448") // RefTagID = PartyID
                    .field(373, "4"), // TagSpecifiedWithoutValue
            ),
        ],
    )
}

/// 14j — out-of-order repeating-group members draw a session Reject.
fn group_out_of_order(v: &str) -> Scenario {
    // Entry: delimiter 448, then 452 (PartyRole), then 447 (PartyIDSource) — out of order.
    let order = nos_with_group(2, &[(453, "1"), (448, "A"), (452, "1"), (447, "1")]);
    scenario(
        "14j_OutOfOrderRepeatingGroupMembers",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "15")), // RepeatingGroupFieldsOutOfOrder (15)
        ],
    )
}

/// QFJ934 — a nested group whose entry omits its delimiter draws a session Reject.
fn nested_group_missing_delimiter(v: &str) -> Scenario {
    // NoPartySubIDs entry starts with 803 instead of the delimiter 523.
    let order = nos_with_group(
        2,
        &[
            (453, "1"),
            (448, "A"),
            (447, "1"),
            (452, "1"),
            (802, "1"),
            (803, "1"),
            (523, "S"),
        ],
    );
    scenario(
        "QFJ934_MissingDelimiterNestedRepeatingGroup",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "15")),
        ],
    )
}

/// 21 — a repeating-group count of zero is accepted as an empty group.
fn group_zero_count(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 3);
    tr.body.set(Field::string(112, "ZERO-GRP-OK"));
    let order = nos_with_group(2, &[(453, "0")]);
    scenario(
        "21_RepeatingGroupSpecifierWithValueOfZero",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Send(tr),
            // A Heartbeat (not a Reject) proves the zero-count group was accepted.
            Step::Expect(ExpectMsg::of("0").field(112, "ZERO-GRP-OK")),
        ],
    )
}

/// app1 — an active acceptor fills each NewOrderSingle with an ExecutionReport (35=8).
fn app_order_executed(v: &str) -> Scenario {
    scenario_with(
        "app_NewOrderSingleExecuted",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            // ExecutionReport echoing ClOrdID with ExecType=New.
            Step::Expect(ExpectMsg::of("8").field(11, "ORDER-1").field(150, "0")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// app2 — successive application responses carry increasing outbound MsgSeqNum.
fn app_orders_sequenced(v: &str) -> Scenario {
    scenario_with(
        "app_OrdersOutboundSequenced",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Expect(ExpectMsg::of("8").field(34, "2")), // first ExecutionReport: outbound seq 2
            Step::Send(new_order_single(3)),
            Step::Expect(ExpectMsg::of("8").field(34, "3")), // second ExecutionReport: outbound seq 3
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// app3 — a ResendRequest for a stored application message replays it as a PossDup (43=Y), not a
/// GapFill (this is the application-resend path, distinct from admin gap-fill).
fn app_message_resent_as_poss_dup(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 3); // after logon(1) + order(2), this is seq 3
    rr.body.set(Field::int(7, 2)); // BeginSeqNo = the ExecutionReport's outbound seq
    rr.body.set(Field::int(16, 2)); // EndSeqNo = 2
    scenario_with(
        "app_MessageResentAsPossDup",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Expect(ExpectMsg::of("8").field(34, "2")), // ExecutionReport at outbound seq 2
            Step::Send(rr),
            // Replayed application message: same MsgSeqNum, now flagged PossDup.
            Step::Expect(ExpectMsg::of("8").field(34, "2").field(43, "Y")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// app4 — a ResendRequest spanning admin + application traffic yields a GapFill for the admin
/// Logon followed by a PossDup replay of the ExecutionReport.
fn app_mixed_resend_gapfill_then_possdup(v: &str) -> Scenario {
    let mut rr = client_message(v, "2", 3);
    rr.body.set(Field::int(7, 1)); // BeginSeqNo = 1 (the admin Logon)
    rr.body.set(Field::int(16, 2)); // EndSeqNo = 2 (the ExecutionReport)
    scenario_with(
        "app_MixedResendGapFillThenPossDup",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Expect(ExpectMsg::of("8").field(34, "2")),
            Step::Send(rr),
            // Admin Logon(1) collapses to a GapFill up to seq 2 ...
            Step::Expect(ExpectMsg::of("4").field(123, "Y").field(36, "2")),
            // ... then the application ExecutionReport(2) is replayed as a PossDup.
            Step::Expect(ExpectMsg::of("8").field(34, "2").field(43, "Y")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// GAP-07 (US3, feature 005) — an application-vetoed resend is replaced by a
/// SequenceReset-GapFill on the wire (FR-007), not replayed as a PossDup. Contrast with
/// `app_message_resent_as_poss_dup` above: identical shape, except the executor app's
/// "VETO-RESEND" sentinel ClOrdID (`runner::AtApp::to_app`) vetoes the resend specifically (the
/// original live send, seq 2, still goes out and is acknowledged normally).
fn app_resend_veto_produces_gap_fill(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(11, "VETO-RESEND"));
    let mut rr = client_message(v, "2", 3); // after logon(1) + order(2), this is seq 3
    rr.body.set(Field::int(7, 2)); // BeginSeqNo = the ExecutionReport's outbound seq
    rr.body.set(Field::int(16, 2)); // EndSeqNo = 2
    scenario_with(
        "GAP07_AppResendVetoProducesGapFill",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("8").field(34, "2")), // live send: not vetoed
            Step::Send(rr),
            // Vetoed resend: a GapFill covering exactly the vetoed sequence number, not a
            // PossDup replay of the ExecutionReport.
            Step::Expect(ExpectMsg::of("4").field(123, "Y").field(36, "3")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// 14b — a NewOrderSingle missing required Side(54) draws a session-level Reject (US9, feature
/// 005, FR-031: HandlInst(21) is optional in the real bundled FIX.4.4 dictionary — Side, along
/// with ClOrdID/TransactTime/OrdType, is NewOrderSingle's actual directly-required field).
fn required_field_missing(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body = {
        let mut b = truefix_core::FieldMap::new();
        for f in new_order_single(2).body.fields() {
            if f.tag() != 54 {
                b.set(Field::new(f.tag(), f.value_bytes().to_vec()));
            }
        }
        b
    };
    scenario(
        "14b_RequiredFieldMissing",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "1")), // Reject: RequiredTagMissing
        ],
    )
}

/// 14e — a field with an out-of-range enumerated value draws a session-level Reject.
fn incorrect_enum_value(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(54, "Z")); // not a real Side value
    scenario(
        "14e_IncorrectEnumValue",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "5")), // Reject: ValueIsIncorrect
        ],
    )
}

/// 14a — a field whose tag is not defined in the dictionary draws a session-level Reject.
fn invalid_tag_number(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(999, "X")); // 999 undefined, below the UDF range
    scenario(
        "14a_InvalidTagNumber",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "0")), // Reject: InvalidTagNumber
        ],
    )
}

/// 14c — a defined field that is not valid for this message type draws a session-level Reject.
fn tag_not_defined_for_msg_type(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(112, "X")); // TestReqID is defined but not part of NewOrderSingle
    scenario(
        "14c_TagNotDefinedForMsgType",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "2")), // Reject: TagNotDefinedForMessageType
        ],
    )
}

/// 14d — a field present with no value draws a session-level Reject.
fn tag_specified_without_value(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::new(11, Vec::new())); // ClOrdID present but empty
    scenario(
        "14d_TagSpecifiedWithoutValue",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "4")), // Reject: TagSpecifiedWithoutValue
        ],
    )
}

/// 14f — a field whose value has the wrong data format draws a session-level Reject.
fn incorrect_data_format(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.set(Field::string(38, "abc")); // OrderQty is a QTY; "abc" is not numeric
    scenario(
        "14f_IncorrectDataFormat",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "6")), // Reject: IncorrectDataFormat
        ],
    )
}

/// 14h — a tag appearing more than once outside a repeating group draws a session-level Reject.
fn repeated_tag(v: &str) -> Scenario {
    let mut order = new_order_single(2);
    order.body.add_field(Field::string(11, "ORDER-1-DUP")); // ClOrdID(11) repeated
    scenario(
        "14h_RepeatedTag",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "13")), // Reject: TagAppearsMoreThanOnce
        ],
    )
}

/// 2r — an unregistered (unknown) MsgType draws a Business Message Reject.
fn unregistered_msg_type(v: &str) -> Scenario {
    scenario(
        "2r_UnregisteredMsgType",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "UU", 2)), // unknown application MsgType
            Step::Expect(ExpectMsg::of("j")),       // BusinessMessageReject
        ],
    )
}

/// Special suite — NextExpectedMsgSeqNum (789): a peer reporting it is behind our outbound
/// counter triggers an immediate resend (which, for admin-only traffic, is a GapFill).
fn next_expected_msg_seq_num(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.body.set(Field::int(789, 1)); // peer next-expects our seq 1, but we will have sent the Logon
    scenario_with(
        "special_NextExpectedMsgSeqNum",
        v,
        vec![
            Step::Send(lo),
            // Having consumed inbound Logon seq 1, the server reports it next expects seq 2.
            Step::Expect(ExpectMsg::of("A").field(789, "2")),
            // The server's Logon already consumed outbound seq 1, so it fills the gap to 2.
            Step::Expect(ExpectMsg::of("4").field(123, "Y").field(36, "2")),
        ],
        SessionTweaks {
            enable_next_expected: true,
            ..SessionTweaks::default()
        },
    )
}

/// Special suite — LastMsgSeqNumProcessed (369): the server stamps the sequence number of the
/// last inbound message it processed, reflecting the just-consumed Logon.
fn last_msg_seq_num_processed(v: &str) -> Scenario {
    scenario_with(
        "special_LastMsgSeqNumProcessed",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            // After processing inbound Logon seq 1, LastMsgSeqNumProcessed is 1.
            Step::Expect(ExpectMsg::of("A").field(369, "1")),
        ],
        SessionTweaks {
            enable_last_processed: true,
            ..SessionTweaks::default()
        },
    )
}

/// Special suite — CheckLatency/timestamps: a Logon with a stale SendingTime is rejected with a
/// Logout citing a SendingTime accuracy problem, then the session is disconnected.
fn check_latency_timestamps(v: &str) -> Scenario {
    // client_message stamps a fixed 2024 SendingTime, far outside MaxLatency relative to "now".
    scenario_with(
        "special_CheckLatencyStaleSendingTime",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            // T130 (feature 009, NEW-29): assert the actual reject reason (Text/58), not just
            // that some Logout occurred — a Logout for the wrong reason would previously still
            // pass this scenario.
            Step::Expect(ExpectMsg::of("5").field(58, "SendingTime accuracy problem")),
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            check_latency: true,
            ..SessionTweaks::default()
        },
    )
}

/// Encode `msg` and corrupt its CheckSum digits, keeping BodyLength (and thus framing) intact so
/// the frame is delivered whole but fails checksum validation on decode.
fn garble_checksum(msg: &Message) -> Vec<u8> {
    let mut raw = msg.encode();
    // The trailer is always `10=DDD<SOH>`: the three checksum digits sit at len-4..len-1, and the
    // literal `10=` occupies the three bytes before them. Overwrite the digits with (real+1) mod
    // 256 so the frame stays well-formed (BodyLength intact) but fails checksum validation.
    let digits_at = match raw.len().checked_sub(4) {
        Some(p) => p,
        None => return raw,
    };
    let Some(cs_field_start) = digits_at.checked_sub(3) else {
        return raw;
    };
    let computed: u32 = raw
        .get(..cs_field_start)
        .map(|pre| pre.iter().map(|&b| u32::from(b)).sum::<u32>() & 0xFF)
        .unwrap_or(0);
    let wrong = format!("{:03}", (computed + 1) & 0xFF);
    if let Some(slot) = raw.get_mut(digits_at..digits_at + 3) {
        slot.copy_from_slice(wrong.as_bytes());
    }
    raw
}

/// Special suite — validateChecksum / rejectGarbledMessages (default N): a frame with a bad
/// CheckSum is silently dropped (no Reject, no disconnect, sequence counter untouched), so the
/// next correctly-sequenced message is still processed.
fn garbled_message_dropped(v: &str) -> Scenario {
    let garbled = garble_checksum(&client_message(v, "0", 2)); // Heartbeat with a broken CheckSum
    let mut tr = client_message(v, "1", 2); // reuses seq 2: the garbled frame was never counted
    tr.body.set(Field::string(112, "AFTER-GARBLE"));
    scenario(
        "special_GarbledMessageDropped",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::SendRaw(garbled),
            Step::Send(tr),
            // A Heartbeat at seq 2 proves the garbled frame was dropped without advancing state.
            Step::Expect(ExpectMsg::of("0").field(112, "AFTER-GARBLE")),
        ],
    )
}

/// Special suite — RejectGarbledMessage=Y: a garbled frame draws a session-level Reject (35=3,
/// SessionRejectReason=0) instead of a silent drop, and the sequence counter is untouched.
fn garbled_message_rejected(v: &str) -> Scenario {
    let garbled = garble_checksum(&client_message(v, "0", 2));
    let mut tr = client_message(v, "1", 2); // reuses seq 2: the garbled frame was never counted
    tr.body.set(Field::string(112, "AFTER-GARBLE-REJECT"));
    scenario_with(
        "special_RejectGarbledMessage",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::SendRaw(garbled),
            Step::Expect(ExpectMsg::of("3").field(373, "0")), // session Reject
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "AFTER-GARBLE-REJECT")),
        ],
        SessionTweaks {
            reject_garbled: true,
            ..SessionTweaks::default()
        },
    )
}

/// Special suite — resendRequestChunkSize: when a gap is detected, the ResendRequest is bounded to
/// one chunk (EndSeqNo = BeginSeqNo + chunk - 1) instead of an open-ended range.
fn resend_request_chunk_size(v: &str) -> Scenario {
    scenario_with(
        "special_ResendRequestChunkSize",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 10)), // gap: expected 2, received 10
            // chunk=5 → request only 2..=6 rather than 2..0 (open-ended).
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(
                ExpectMsg::of("2")
                    .field(7, "2")
                    .field(16, "6")
                    .field(34, "2"),
            ),
        ],
        SessionTweaks {
            resend_chunk_size: 5,
            ..SessionTweaks::default()
        },
    )
}

/// GAP-09 (US4, feature 005) — a chunked inbound resend spanning more than one chunk
/// auto-continues without an external re-request: each GapFill that closes one chunk but not the
/// full known gap immediately draws the next chunk's `ResendRequest` from TrueFix itself, since a
/// well-behaved reference-engine counterparty never re-requests the remainder unprompted.
fn chunked_resend_auto_continues(v: &str) -> Scenario {
    // NEW-84 (feature 009): each chunk's GapFill now must carry its OWN MsgSeqNum matching the
    // start of the gap segment it fills (2, 5, 8) -- previously (before NEW-84's fix made a
    // gap-fill's own MsgSeqNum meaningful) this scenario used sequentially-incrementing but
    // protocol-incorrect values (2, 3, 4), which happened to "work" only because the prior code
    // never checked a gap-fill's own MsgSeqNum against `next_in_seq` at all.
    let mut gf1 = client_message(v, "4", 2);
    gf1.body.set(Field::string(123, "Y")); // GapFillFlag
    gf1.body.set(Field::int(36, 5)); // NewSeqNo: closes chunk 1 (2..4)
    let mut gf2 = client_message(v, "4", 5);
    gf2.body.set(Field::string(123, "Y"));
    gf2.body.set(Field::int(36, 8)); // closes chunk 2 (5..7)
    let mut gf3 = client_message(v, "4", 8);
    gf3.body.set(Field::string(123, "Y"));
    gf3.body.set(Field::int(36, 11)); // closes chunk 3 (8..10); the full gap (target=10) is done
    let mut tr = client_message(v, "1", 11); // matches next_in_seq after gf3's NewSeqNo=11
    tr.body.set(Field::string(112, "SETTLED"));
    scenario_with(
        "GAP09_ChunkedResendAutoContinues",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(client_message(v, "0", 10)), // gap: expected 2, got 10
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) on all 4 server responses.
            Step::Expect(
                ExpectMsg::of("2")
                    .field(7, "2")
                    .field(16, "4")
                    .field(34, "2"),
            ), // chunk 1: 2..4
            Step::Send(gf1),
            // No external nudge: the next chunk's ResendRequest is auto-issued.
            Step::Expect(
                ExpectMsg::of("2")
                    .field(7, "5")
                    .field(16, "7")
                    .field(34, "3"),
            ), // chunk 2: 5..7
            Step::Send(gf2),
            Step::Expect(
                ExpectMsg::of("2")
                    .field(7, "8")
                    .field(16, "10")
                    .field(34, "4"),
            ), // chunk 3: 8..10
            Step::Send(gf3),
            Step::Send(tr),
            // A Heartbeat (not a fourth ResendRequest) proves the gap is now fully closed.
            Step::Expect(ExpectMsg::of("0").field(112, "SETTLED").field(34, "5")),
        ],
        SessionTweaks {
            resend_chunk_size: 3,
            ..SessionTweaks::default()
        },
    )
}

// --- 003 US1: identity/CompID/logon-integrity class (T012) ---
//
// `1c_InvalidSenderCompID`/`1c_InvalidTargetCompID`/`1d_InvalidLogonWrongBeginString` (a mismatch
// on the *Logon itself*) previously couldn't be represented against this harness's dynamic-template
// acceptor (`start_acceptor`): the template adopts whatever CompIDs/BeginString the first Logon
// claims, rather than checking them against a pre-existing fixed identity, so there was nothing to
// "mismatch" on a first connection. `identity_problem`'s CheckCompID/BeginString logic is proven
// mid-session elsewhere, where a fixed identity already exists from an earlier Logon — see
// `begin_string_value_unexpected` / `comp_id_does_not_match_profile` below. T133/T134 (feature 009,
// NEW-83) added `start_fixed_identity_acceptor` (a `SessionTweaks::fixed_identity`-gated,
// `AcceptorBuilder::with_session`-based mode) specifically to cover the Logon-time variant: a
// mismatched first Logon never resolves to the registered session (no dynamic-template fallback),
// so the connection is simply dropped rather than answered.

/// 1c — a Logon whose SenderCompID doesn't match the acceptor's configured counterparty identity
/// is refused: the connection is dropped without a reply (`route_and_run`'s static-session lookup
/// fails with no template to fall back to).
fn invalid_sender_comp_id(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.header.set(Field::string(49, "WRONG-SENDER"));
    scenario_with(
        "1c_InvalidSenderCompID",
        v,
        vec![Step::Send(lo), Step::ExpectDisconnect],
        SessionTweaks {
            fixed_identity: Some(("SERVER".to_owned(), "CLIENT".to_owned())),
            ..SessionTweaks::default()
        },
    )
}

/// 1c — same as `invalid_sender_comp_id`, but the mismatch is on TargetCompID instead.
fn invalid_target_comp_id(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.header.set(Field::string(56, "WRONG-TARGET"));
    scenario_with(
        "1c_InvalidTargetCompID",
        v,
        vec![Step::Send(lo), Step::ExpectDisconnect],
        SessionTweaks {
            fixed_identity: Some(("SERVER".to_owned(), "CLIENT".to_owned())),
            ..SessionTweaks::default()
        },
    )
}

/// 1d — a Logon whose BeginString doesn't match the acceptor's configured version is refused the
/// same way: the static-session lookup keys on BeginString too, so this never resolves either.
fn invalid_logon_wrong_begin_string(v: &str) -> Scenario {
    // FIX.4.2 differs from every other `SUITE_VERSIONS` entry, so it's always a mismatch here.
    let wrong_begin = if v == "FIX.4.2" { "FIX.4.4" } else { "FIX.4.2" };
    let lo = logon(wrong_begin, 1, true);
    scenario_with(
        "1d_InvalidLogonWrongBeginString",
        v,
        vec![Step::Send(lo), Step::ExpectDisconnect],
        SessionTweaks {
            fixed_identity: Some(("SERVER".to_owned(), "CLIENT".to_owned())),
            ..SessionTweaks::default()
        },
    )
}

/// 1d — a Logon carrying a stale SendingTime (outside MaxLatency) draws a Logout and disconnect.
/// Same underlying `CheckLatency` mechanism as the `special_CheckLatencyStaleSendingTime` suite,
/// exposed here under its Appendix B name and run across the full version matrix.
fn invalid_logon_bad_sending_time(v: &str) -> Scenario {
    scenario_with(
        "1d_InvalidLogonBadSendingTime",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            // T130 (feature 009, NEW-29): assert the actual reject reason, not just "a Logout
            // occurred".
            Step::Expect(ExpectMsg::of("5").field(58, "SendingTime accuracy problem")),
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            check_latency: true,
            ..SessionTweaks::default()
        },
    )
}

/// QFJ648/BUG-95/FR-019 (feature 007) — a Logon with a negative HeartBtInt is rejected
/// (Logout + disconnect), matching QuickFIX/J's actual QFJ-648 fix: contrary to this scenario's
/// previous assumption (that the invalid value was silently ignored, keeping the acceptor's
/// configured default, and the session logged on normally), QFJ-648 is precisely the issue that
/// *added* this rejection to QuickFIX/J's `Session.next()` (`RejectLogon("HeartBtInt must not be
/// negative")`) — confirmed via QuickFIX/J's own source/issue history. The previous version of
/// this scenario had it backwards.
fn qfj648_negative_heart_bt_int(v: &str) -> Scenario {
    let mut lo = logon(v, 1, true);
    lo.body.set(Field::int(108, -1)); // HeartBtInt, invalid
    scenario(
        "QFJ648_NegativeHeartBtInt",
        v,
        vec![
            Step::Send(lo),
            Step::Expect(ExpectMsg::of("5")), // Logout: HeartBtInt must not be negative
            Step::ExpectDisconnect,
        ],
    )
}

// --- 003 US1: sequence/PossDup class (T013) ---

/// 2a — a message whose MsgSeqNum exactly matches the expected inbound sequence number is
/// processed normally (the baseline case every other sequencing scenario builds on).
fn msgseqnum_correct(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2); // TestRequest at exactly the expected seq
    tr.body.set(Field::string(112, "INSEQ"));
    scenario(
        "2a_MsgSeqNumCorrect",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "INSEQ").field(34, "2")), // Heartbeat echo, not a reject
        ],
    )
}

/// 2e — a message carrying PossDupFlag=Y at exactly the expected sequence number is not actually
/// a duplicate (the flag doesn't match reality); it is processed normally rather than specially
/// rejected or ignored — only `Ordering::Less` PossDup traffic gets the "already received" pass.
fn poss_dup_not_received(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.header.set(Field::string(43, "Y")); // PossDupFlag, but this seq was never actually sent before
    tr.body.set(Field::string(112, "NOTADUP"));
    scenario(
        "2e_PossDupNotReceived",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "NOTADUP").field(34, "2")),
        ],
    )
}

/// 10 — a SequenceReset-Reset (not GapFill) with NewSeqNo equal to the current expected sequence
/// is accepted (a no-op re-affirmation), unlike GapFill's backward case.
fn seq_reset_new_seq_no_equal(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 99);
    sr.body.set(Field::int(36, 2)); // NewSeqNo == current expected (2), no GapFillFlag → Reset
    let mut tr = client_message(v, "1", 2);
    tr.body.set(Field::string(112, "STILL-2"));
    scenario(
        "10_MsgSeqNumEqual",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "STILL-2").field(34, "2")),
        ],
    )
}

/// 10 — a SequenceReset-Reset (not GapFill) with NewSeqNo *behind* the current expected sequence
/// is rejected (BUG-06/FR-002, feature 006), not honored — corrected from this scenario's prior
/// (incorrect) assumption that Reset has no backward guard at all; a rewind here is exactly the
/// anti-replay hole BUG-06 closed, reopening the window to replay/re-accept previously-processed
/// sequence numbers.
fn seq_reset_new_seq_no_less(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 99);
    sr.body.set(Field::int(36, 1)); // NewSeqNo=1, behind the current expected (2)
    scenario(
        "10_MsgSeqNumLess",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(expect_session_reject_reason(v, "3", "5").field(34, "2")), // ValueIsIncorrect
        ],
    )
}

// --- 003 US1: resend/reset class (T014) ---

/// 11b — a SequenceReset-GapFill with NewSeqNo equal to the current expected sequence is accepted
/// (the `>=` guard passes; distinct from `11a`/`11c`, already covered by the existing
/// `sequence_reset_gap_fill_advances`/`sequence_reset_gap_fill_backward_ignored` scenarios).
fn seq_reset_gap_fill_new_seq_no_equal(v: &str) -> Scenario {
    let mut sr = client_message(v, "4", 2); // GapFill's own MsgSeqNum is consumed as usual
    sr.body.set(Field::string(123, "Y")); // GapFillFlag
    sr.body.set(Field::int(36, 3)); // NewSeqNo == the seq the GapFill message itself would advance to
    let mut tr = client_message(v, "1", 3);
    tr.body.set(Field::string(112, "GAPFILL-EQ"));
    scenario(
        "11b_NewSeqNoEqual",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(sr),
            Step::Send(tr),
            // T138 (feature 009, NEW-51): outbound MsgSeqNum(34) — the server's 2nd message.
            Step::Expect(ExpectMsg::of("0").field(112, "GAPFILL-EQ").field(34, "2")),
        ],
    )
}

/// RejectResentMessage — a replayed (PossDupFlag=Y) message that itself fails dictionary
/// validation still draws a session-level Reject; PossDup does not exempt a message from
/// validation (requires the FIX.4.4 dictionary; scoped to that version like the other
/// dictionary-validation scenarios).
fn reject_resent_message() -> Scenario {
    let mut order = new_order_single(2);
    order.body = {
        // rebuild body without Side(54), the same required field `required_field_missing`
        // demonstrates, so this exercises validation rather than a fresh failure mode.
        let mut b = truefix_core::FieldMap::new();
        for f in new_order_single(2).body.fields() {
            if f.tag() != 54 {
                b.set(Field::new(f.tag(), f.value_bytes().to_vec()));
            }
        }
        b
    };
    order.header.set(Field::string(43, "Y")); // PossDupFlag
    order.header.set(Field::string(122, "20240101-00:00:00")); // OrigSendingTime, required with PossDup
    scenario(
        "RejectResentMessage",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(order),
            Step::Expect(ExpectMsg::of("3").field(373, "1")), // Reject: RequiredTagMissing
        ],
    )
}

// --- 003 US1: message-type/admin-app class (T015) ---

/// 2i — a BeginString mismatch on a *post-logon* message (not the Logon itself) draws a Logout
/// and disconnect, proving `CheckCompID`'s BeginString guard applies to every inbound message.
fn begin_string_value_unexpected(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.header.set(Field::string(8, "FIX.9.9"));
    scenario(
        "2i_BeginStringValueUnexpected",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("5")), // Logout: Incorrect BeginString
            Step::ExpectDisconnect,
        ],
    )
}

/// 2k — a post-logon message whose CompIDs don't match the session profile draws a Logout and
/// disconnect (the same `CheckCompID` guard as `1c_Invalid*CompID`, exercised mid-session).
fn comp_id_does_not_match_profile(v: &str) -> Scenario {
    let mut tr = client_message(v, "1", 2);
    tr.header.set(Field::string(49, "IMPOSTER"));
    scenario(
        "2k_CompIDDoesNotMatchProfile",
        v,
        vec![
            Step::Send(logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            // NEW-87 (feature 009): a session Reject precedes the Logout for this non-Logon CompID
            // mismatch, matching QFJ's `doBadCompID` two-message shape.
            Step::Expect(ExpectMsg::of("3")),
            Step::Expect(ExpectMsg::of("5")), // Logout: CompID problem
            Step::ExpectDisconnect,
        ],
    )
}

/// A Logon with SendingTime stamped to the real current time (rather than `client_message`'s fixed
/// 2024 timestamp), so a `CheckLatency`-enabled session accepts it.
fn fresh_logon(version: &str, seq: i64, reset: bool) -> Message {
    let mut m = logon(version, seq, reset);
    m.header
        .set(Field::utc_timestamp(52, time::OffsetDateTime::now_utc()));
    m
}

/// 2o — a post-logon message with a stale SendingTime (outside MaxLatency) draws a Logout and
/// disconnect, the same `CheckLatency` guard as `1d_InvalidLogonBadSendingTime` exercised
/// mid-session (after a Logon whose own SendingTime is fresh) rather than at logon.
fn sending_time_value_out_of_range(v: &str) -> Scenario {
    let tr = client_message(v, "1", 2); // fixed 2024 SendingTime, stale relative to "now"
    // BUG-59/FR-023 (feature 007): FIX.4.0/4.1 omit SessionRejectReason(373) entirely, so this
    // reject-reason assertion (T130, NEW-29) is version-filtered like `reject_field_correctness.rs`'s
    // existing unit coverage of the same rule.
    let reject_expect = if matches!(v, "FIX.4.0" | "FIX.4.1") {
        ExpectMsg::of("3").field(58, "SendingTime accuracy problem")
    } else {
        ExpectMsg::of("3")
            .field(373, "10")
            .field(58, "SendingTime accuracy problem")
    };
    scenario_with(
        "2o_SendingTimeValueOutOfRange",
        v,
        vec![
            Step::Send(fresh_logon(v, 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr),
            // NEW-87 (feature 009): a session Reject precedes the Logout for this non-Logon
            // latency failure, matching QFJ's `doBadTime` two-message shape.
            // T130 (feature 009, NEW-29): assert the actual reject reason on both messages, not
            // just "a Logout occurred".
            Step::Expect(reject_expect),
            Step::Expect(ExpectMsg::of("5").field(58, "SendingTime accuracy problem")),
            Step::ExpectDisconnect,
        ],
        SessionTweaks {
            check_latency: true,
            ..SessionTweaks::default()
        },
    )
}

/// 8 — a stream of only admin (session-level) messages is processed in sequence with no
/// application-layer involvement.
fn only_admin_messages() -> Scenario {
    let mut tr1 = client_message("FIX.4.4", "1", 2);
    tr1.body.set(Field::string(112, "A1"));
    let mut tr2 = client_message("FIX.4.4", "1", 3);
    tr2.body.set(Field::string(112, "A2"));
    scenario(
        "8_OnlyAdminMessages",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(tr1),
            Step::Expect(ExpectMsg::of("0").field(112, "A1")),
            Step::Send(tr2),
            Step::Expect(ExpectMsg::of("0").field(112, "A2")),
        ],
    )
}

/// 8 — a stream of only application messages (no admin traffic beyond the Logon) is processed in
/// sequence, each acknowledged by the executor app.
fn only_application_messages() -> Scenario {
    scenario_with(
        "8_OnlyApplicationMessages",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Expect(ExpectMsg::of("8")),
            Step::Send(new_order_single(3)),
            Step::Expect(ExpectMsg::of("8")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

/// 8 — admin and application messages interleaved in the same stream are each dispatched to the
/// correct layer, in order, without cross-contamination.
fn admin_and_application_messages() -> Scenario {
    let mut tr = client_message("FIX.4.4", "1", 3);
    tr.body.set(Field::string(112, "MIXED"));
    scenario_with(
        "8_AdminAndApplicationMessages",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::Send(new_order_single(2)),
            Step::Expect(ExpectMsg::of("8")),
            Step::Send(tr),
            Step::Expect(ExpectMsg::of("0").field(112, "MIXED")),
            Step::Send(new_order_single(4)),
            Step::Expect(ExpectMsg::of("8")),
        ],
        SessionTweaks {
            executor_app: true,
            ..SessionTweaks::default()
        },
    )
}

// --- 003 US3: field-order validation (T022) ---
//
// These require `ValidateFieldsOutOfOrder` enabled on the acceptor's validator (the
// `validate_fields_out_of_order` `SessionTweaks` field), and a non-admin application message —
// `Session::validate_app` skips admin-type messages (including Logon) entirely, so the Logon
// itself is never a vehicle for this check. Raw bytes are sent directly (`Step::SendRaw`) since
// `Message::encode()` always re-emits the canonical header/body/trailer order, which would erase
// the very out-of-order-ness under test.

/// Build a well-formed FIX.4.4 NewOrderSingle frame from `rest` (every field after BeginString/
/// BodyLength), computing BodyLength/CheckSum correctly regardless of `rest`'s order.
fn raw_new_order_single(rest: &[(u32, &str)]) -> Vec<u8> {
    let body: String = rest.iter().map(|(t, v)| format!("{t}={v}\x01")).collect();
    let prefix = format!("8=FIX.4.4\x019={}\x01", body.len());
    let pre_checksum = format!("{prefix}{body}");
    let checksum: u32 = pre_checksum.bytes().map(u32::from).sum::<u32>() & 0xFF;
    format!("{pre_checksum}10={checksum:03}\x01").into_bytes()
}

/// 2t — the third field on the wire must be MsgType(35); here SenderCompID(49) usurps that slot.
fn first_three_fields_out_of_order() -> Scenario {
    let raw = raw_new_order_single(&[
        (49, "CLIENT"),
        (35, "D"),
        (56, "SERVER"),
        (34, "2"),
        (52, "20240101-00:00:00"),
        (11, "O1"),
        (21, "1"),
        (55, "AAPL"),
        (54, "1"),
        (60, "20240101-00:00:00"),
        (40, "2"),
    ]);
    scenario_with(
        "2t_FirstThreeFieldsOutOfOrder",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::SendRaw(raw),
            Step::Expect(ExpectMsg::of("3").field(373, "14")), // Reject: TagOutOfRequiredOrder
        ],
        SessionTweaks {
            validate_fields_out_of_order: true,
            ..SessionTweaks::default()
        },
    )
}

/// 14g — a trailer-classified field (CheckSum aside) arriving before the body section is done, or
/// a header field arriving after body fields have started, violates header/body/trailer
/// sectioning.
fn header_body_trailer_fields_out_of_order() -> Scenario {
    let raw = raw_new_order_single(&[
        (35, "D"),
        (55, "AAPL"),   // body field
        (49, "CLIENT"), // header field, arriving after a body field already appeared
        (56, "SERVER"),
        (34, "2"),
        (52, "20240101-00:00:00"),
        (11, "O1"),
        (21, "1"),
        (54, "1"),
        (60, "20240101-00:00:00"),
        (40, "2"),
    ]);
    scenario_with(
        "14g_HeaderBodyTrailerFieldsOutOfOrder",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::SendRaw(raw),
            Step::Expect(ExpectMsg::of("3").field(373, "14")), // Reject: TagOutOfRequiredOrder
        ],
        SessionTweaks {
            validate_fields_out_of_order: true,
            ..SessionTweaks::default()
        },
    )
}

/// 15 — header and body fields interleaved throughout the message (not just one field out of
/// place), still caught by the same sectioning check.
fn header_and_body_fields_ordered_differently() -> Scenario {
    let raw = raw_new_order_single(&[
        (35, "D"),
        (49, "CLIENT"),
        (55, "AAPL"),   // body field
        (56, "SERVER"), // header field, after a body field already appeared
        (11, "O1"),
        (34, "2"),
        (52, "20240101-00:00:00"),
        (21, "1"),
        (54, "1"),
        (60, "20240101-00:00:00"),
        (40, "2"),
    ]);
    scenario_with(
        "15_HeaderAndBodyFieldsOrderedDifferently",
        "FIX.4.4",
        vec![
            Step::Send(logon("FIX.4.4", 1, true)),
            Step::Expect(ExpectMsg::of("A")),
            Step::SendRaw(raw),
            Step::Expect(ExpectMsg::of("3").field(373, "14")), // Reject: TagOutOfRequiredOrder
        ],
        SessionTweaks {
            validate_fields_out_of_order: true,
            ..SessionTweaks::default()
        },
    )
}

/// Special suite — validateChecksum: TrueFix validates the wire checksum unconditionally at
/// decode time (a documented design decision — see `ValidationOptions::validate_checksum`'s doc
/// comment — checksum enforcement is not an optional safety property), so a bad-checksum frame is
/// always caught via the garbled-message path regardless of any validation toggle. Reuses the
/// existing `garbled_message_dropped`/`garbled_message_rejected` scenarios as this suite's content.
pub fn validate_checksum_suite() -> Vec<Scenario> {
    vec![
        garbled_message_dropped("FIX.4.4"),
        garbled_message_rejected("FIX.4.4"),
    ]
}

/// Special suite — timestamps: SendingTime-accuracy (CheckLatency) validation, the representative
/// timestamp-handling behavior class this harness can assert today (exact wire-format-precision
/// assertions on *outbound* SendingTime — e.g. millisecond vs. second precision on a non-fixed,
/// "now"-derived value — would need `ExpectMsg` to support predicate/format matching rather than
/// only exact-value matching; a disclosed harness-capability gap, not a protocol gap, tracked in
/// `docs/todo/001.md`'s TODO-01). Reuses `check_latency_timestamps` as this suite's content.
pub fn timestamps_suite() -> Vec<Scenario> {
    vec![
        check_latency_timestamps("FIX.4.4"),
        unparseable_sending_time_fails_latency("FIX.4.4"),
    ]
}

/// Special suite — resynch: session resynchronization behavior (ResendRequest gap recovery,
/// SequenceReset Reset/GapFill in both directions, out-of-order queueing/draining, and chunked
/// resend) — QuickFIX/J's `resynch` AT category. Reuses the existing resend/reset scenarios as
/// this suite's content (the same scenarios already run per-version inside `server_suite()`; this
/// function groups them as their own discoverable, independently-runnable suite).
pub fn resynch_suite() -> Vec<Scenario> {
    vec![
        resend_request_gap_fill("FIX.4.4"),
        resend_request_bounded_end("FIX.4.4"),
        resend_request_not_duplicated("FIX.4.4"),
        resend_request_begin_zero_treated_as_one("FIX.4.4"),
        resend_request_nothing_to_resend("FIX.4.4"),
        out_of_order_queued_then_drained("FIX.4.4"),
        sequence_reset_reset("FIX.4.4"),
        sequence_reset_gap_fill_advances("FIX.4.4"),
        sequence_reset_gap_fill_backward_ignored("FIX.4.4"),
        sequence_reset_gap_fill_missing_new_seq_no_rejected("FIX.4.4"),
        resend_request_chunk_size("FIX.4.4"),
        chunked_resend_auto_continues("FIX.4.4"),
    ]
}

/// The (representative) server acceptance-test suite across [`SUITE_VERSIONS`].
pub fn server_suite() -> Vec<Scenario> {
    let mut out = Vec::new();
    for &v in SUITE_VERSIONS {
        out.push(valid_logon(v));
        out.push(logon_seq_too_high(v));
        out.push(msgseqnum_too_high(v));
        out.push(msgseqnum_too_low(v));
        out.push(received_test_request(v));
        out.push(reverse_route(v));
        out.push(reverse_route_empty_tags(v));
        out.push(unsolicited_logout(v));
        out.push(too_high_logout_processed_immediately(v));
        out.push(logon_response_carries_reset_flag(v));
        out.push(logon_response_does_not_echo_reset_flag_when_inbound_lacks_it(v));
        out.push(logon_adopts_heartbeat_interval(v));
        out.push(resend_request_gap_fill(v));
        out.push(resend_request_bounded_end(v));
        out.push(resend_request_too_high_answered_immediately(v));
        out.push(resend_request_not_duplicated(v));
        out.push(resend_request_begin_zero_treated_as_one(v));
        out.push(out_of_order_queued_then_drained(v));
        out.push(sequence_reset_reset(v));
        out.push(sequence_reset_gap_fill_advances(v));
        out.push(sequence_reset_gap_fill_backward_ignored(v));
        out.push(sequence_reset_gap_fill_missing_new_seq_no_rejected(v));
        out.push(resend_request_nothing_to_resend(v));
        out.push(reject_message_consumed(v));
        out.push(heartbeat_consumed(v));
        out.push(missing_msg_seq_num(v));
        out.push(idle_heartbeat_emitted(v));
        out.push(test_request_on_silence(v));
        out.push(poss_dup_too_low(v));
        // 005 US3: session-state-machine protocol-correctness safeguards (T021).
        out.push(poss_dup_orig_sending_time_after_sending_time(v));
        out.push(duplicate_logon_rejected(v));
        // 003 US1: identity/CompID/logon-integrity + sequence/PossDup classes (T012/T013).
        out.push(invalid_logon_bad_sending_time(v));
        out.push(qfj648_negative_heart_bt_int(v));
        out.push(msgseqnum_correct(v));
        out.push(poss_dup_not_received(v));
        out.push(seq_reset_new_seq_no_equal(v));
        out.push(seq_reset_new_seq_no_less(v));
        out.push(seq_reset_gap_fill_new_seq_no_equal(v));
        out.push(begin_string_value_unexpected(v));
        out.push(comp_id_does_not_match_profile(v));
        out.push(sending_time_value_out_of_range(v));
        // 006 US1: session protocol-correctness fixes (T021). The decreasing-NewSeqNo case is
        // covered by the corrected `10_MsgSeqNumLess` (`seq_reset_new_seq_no_less`) above, not a
        // separate scenario.
        out.push(sequence_reset_reset_missing_new_seq_no_rejected(v));
        out.push(resend_request_missing_begin_seq_no_rejected(v));
        out.push(resend_request_missing_end_seq_no_rejected(v));
        // T135 (feature 009, NEW-83): Logon-time identity-mismatch scenarios, using the new
        // fixed-identity acceptor mode (T133/T134).
        out.push(invalid_sender_comp_id(v));
        out.push(invalid_target_comp_id(v));
        out.push(invalid_logon_wrong_begin_string(v));
    }
    // Field-validation scenarios for FIX.4.2 (its NewOrderSingle subset differs from 4.4).
    out.push(valid_new_order_accepted_42());
    out.push(required_field_missing_42());
    out.push(incorrect_enum_value_42());
    out.push(invalid_tag_number_42());
    out.push(tag_not_defined_for_msg_type_42());
    out.push(tag_specified_without_value_42());
    out.push(incorrect_data_format_42());
    // Field-validation scenarios require the dictionary; authored for FIX.4.4.
    out.push(valid_new_order_accepted("FIX.4.4"));
    out.push(group_count_mismatch("FIX.4.4"));
    out.push(empty_value_inside_group("FIX.4.4"));
    out.push(group_out_of_order("FIX.4.4"));
    out.push(nested_group_missing_delimiter("FIX.4.4"));
    out.push(group_zero_count("FIX.4.4"));
    out.push(app_order_executed("FIX.4.4"));
    out.push(app_orders_sequenced("FIX.4.4"));
    out.push(app_message_resent_as_poss_dup("FIX.4.4"));
    out.push(app_mixed_resend_gapfill_then_possdup("FIX.4.4"));
    out.push(acceptor_initiated_logout("FIX.4.4"));
    // 005 US3: resend-veto → GapFill (T021), single-version since it uses new_order_single.
    out.push(app_resend_veto_produces_gap_fill("FIX.4.4"));
    out.push(required_field_missing("FIX.4.4"));
    out.push(incorrect_enum_value("FIX.4.4"));
    out.push(invalid_tag_number("FIX.4.4"));
    out.push(tag_not_defined_for_msg_type("FIX.4.4"));
    out.push(tag_specified_without_value("FIX.4.4"));
    out.push(incorrect_data_format("FIX.4.4"));
    out.push(repeated_tag("FIX.4.4"));
    // T129 (feature 009, NEW-28): now that every `FLAT_DICTIONARY_VERSIONS` entry has a bundled
    // dictionary (`runner::dictionary_for_version`), these two dictionary-validation scenarios —
    // which build their probe message directly via `client_message`/`logon` rather than the
    // FIX.4.4-hardcoded `new_order_single` helper — run across that matrix instead of FIX.4.4
    // alone. FIX.5.0/SP1/SP2/Latest are deliberately excluded: they have no flat validator (see
    // `dictionary_for_version`'s doc comment), so these scenarios' expected Reject would never
    // arrive for those four.
    for &v in crate::runner::FLAT_DICTIONARY_VERSIONS {
        out.push(unregistered_msg_type(v));
        out.push(admin_message_dictionary_invalid_is_rejected(v));
    }
    // Special-category suites (T086) requiring per-acceptor session-feature toggles.
    out.push(next_expected_msg_seq_num("FIX.4.4"));
    out.push(last_msg_seq_num_processed("FIX.4.4"));
    out.push(check_latency_timestamps("FIX.4.4"));
    out.push(garbled_message_dropped("FIX.4.4"));
    out.push(garbled_message_rejected("FIX.4.4"));
    out.push(resend_request_chunk_size("FIX.4.4"));
    // 005 US4: chunked-resend auto-continuation (T031, GAP-09/FR-011).
    out.push(chunked_resend_auto_continues("FIX.4.4"));
    // 003 US3: field-order validation (T022).
    out.push(first_three_fields_out_of_order());
    out.push(header_body_trailer_fields_out_of_order());
    out.push(header_and_body_fields_ordered_differently());
    // 003 US1: resend/reset + message-type/admin-app classes (T014/T015), dictionary/app-dependent.
    out.push(reject_resent_message());
    out.push(only_admin_messages());
    out.push(only_application_messages());
    out.push(admin_and_application_messages());
    // 006 US1: dictionary/tweak-dependent session protocol-correctness fixes (T021).
    // Single-version: both build their probe order via the FIX.4.4-hardcoded `new_order_single`
    // helper, so extending them to the full matrix would need a per-version order builder —
    // out of this item's scope (NEW-28 is about the validator being present, not every scenario's
    // fixture being version-generic).
    out.push(gap_fill_drained_message_is_validated("FIX.4.4"));
    out.push(dictionary_failure_disconnect_sends_logout("FIX.4.4"));
    // T129: version-safe (builds its Logon via `client_message` directly, no `new_order_single`),
    // but only meaningful where a validator exists to reject the missing EncryptMethod(98).
    for &v in crate::runner::FLAT_DICTIONARY_VERSIONS {
        out.push(dict_invalid_logon_disconnects_without_disconnect_on_error(
            v,
        ));
    }
    out.push(unparseable_sending_time_fails_latency("FIX.4.4"));
    // 006 US9 (T084): MinQty (tag 110) is a recognized, accepted field (BUG-17 MinQty follow-up).
    out.push(min_qty_field_accepted_44());
    out.push(min_qty_field_accepted_42());
    out
}