camel-integration-test 0.46.0

Scenario document model, parser, and integration-tier test harness for rust-camel
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
//! Partner scripting end to end (ADR-0069 sections 5, 8, 9).
//!
//! The first file-run proof of the shipped address/bindVar stack: a
//! YAML string loads through the crate's document path, partners bind
//! (scripted where the document declares a `partners:` entry,
//! permissive otherwise), `fill_bind_vars` writes the bound authority
//! into the scenario variables, and the whole document runs through
//! [`run_scenario_document`]. The assertions inspect the partner's
//! recorder — a literal `:0` dial cannot produce a recorded arrival,
//! so a recording is the proof the send reached the bound address.
//!
//! The helper mirrors the CLI driver's partner mapping (status
//! default 200, headers default empty, body through the client send
//! path's `value_to_wire` encoding) at the library level. The
//! scenarios exercise the client-role wire path
//! only — except the two-layer test, which boots one route the same
//! way the CLI driver does, to prove the env-tier binding form.

#![cfg(feature = "http")]

mod common;

use std::collections::BTreeMap;
use std::sync::Arc;

use camel_api::Value;
use camel_integration_test::runner::fill_bind_vars;
use camel_integration_test::{
    DirectStimulus, DocumentOutcome, HttpPartner, HttpRecorder, LayeredEnv, PartnerAdapter,
    PartnerRouter, ScenarioFailure, ScenarioVars, ScenarioVerdict, TransportError, ambient_std,
    boot_scenario, parse_scenario_document, partner_scripts_for, run_scenario_document,
};

/// The endpoint URI every document here declares for its partner. The
/// `:0` port is the router key; the wire target is the bound address.
const ORDERS: &str = "http://127.0.0.1:0/orders";

/// Partner-direct document: a PUT send to the harness-declared `:0`
/// endpoint, a receive extracting the response status, and two
/// validations — the extracted status is 200 and the last received
/// body is the scripted `put-ok`. The `partners:` entry is keyed by
/// the declared URI; its JSON body needs the JSON content type to
/// round-trip as the `put-ok` string.
const PUT_PUT_OK_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 200
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: put-ok
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    response:
      status: 200
      headers:
        content-type: application/json
      body: put-ok
"#;

/// Escape document: a POST whose only body leaf is the escaped
/// `$${not_a_var}`; the partner is permissive (no `partners:` entry),
/// so the recorded wire body is the whole proof.
const ESCAPE_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: POST
    body: '$${not_a_var}'
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
"#;

/// Unmatched-script document: the partner scripts only POST /orders,
/// the scenario sends DELETE. The receive extracts the served status,
/// a validation proves it is exactly the unmatched 500, and the final
/// body validation mismatches on the empty body — the failure under
/// assertion.
const DELETE_UNMATCHED_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: DELETE
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 500
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: 200
partners:
  http://127.0.0.1:0/orders:
  - method: POST
    path: /orders
    response:
      status: 200
      body: nope
"#;

/// Declared-but-empty-partners document: the harness reference is
/// declared but its `partners:` entry is an empty sequence, so the
/// partner binds non-permissively (scripted with nothing) and every
/// request is unmatched. The receive extracts the served status, the
/// status validation proves it is exactly the unmatched 500, and the
/// final body validation mismatches on the empty body — the failure
/// under assertion.
const EMPTY_PARTNERS_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: GET
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 500
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: 200
partners:
  http://127.0.0.1:0/orders: []
"#;

/// Unset-variable document: a send to a dynamic URI whose `missing`
/// variable nothing ever sets. No partner binds (the reference is a
/// plain string), and the send must fail at interpolation, before any
/// dial.
const UNSET_VAR_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: http://${missing}/orders
    method: POST
"#;

/// CRUD-chain document: a POST whose scripted 201 body carries the
/// extracted `orderId`, then a GET whose URI interpolates both
/// `${PARTNER}` and `${orderId}` in string form. The GET script
/// matches the exact path `/orders/ord-7`, so a broken interpolation
/// (the literal `${orderId}` on the wire) misses the script and the
/// final body validation fails.
const CRUD_CHAIN_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: POST
    body:
      sku: abc
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      orderId: body.id
- send:
    to: 'http://${PARTNER}/orders/${orderId}'
    method: GET
- receive:
    from: 'http://${PARTNER}/orders/${orderId}'
    deadline: 5s
- validate:
    target:
      lastReceived: 'http://${PARTNER}/orders/${orderId}'
    expectation:
      contains: ord-7
partners:
  http://127.0.0.1:0/orders:
  - method: POST
    path: /orders
    response:
      status: 201
      headers:
        content-type: application/json
      body:
        id: ord-7
  - method: GET
    path: /orders/ord-7
    response:
      status: 200
      headers:
        content-type: application/json
      body:
        id: ord-7
"#;

/// Roundtrip-by-interpolated-receive document: the send goes through
/// the map-form reference, but the `receive` is declared as the plain
/// string `http://${PARTNER}/orders`. The pass proves the receive
/// found the parked roundtrip: `lane_key_for` resolves the
/// interpolated authority to the registered map-ref key, and a miss
/// would be an unbound endpoint or a receive timeout instead.
const RECEIVE_INTERPOLATED_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: POST
- receive:
    from: 'http://${PARTNER}/orders'
    deadline: 5s
partners:
  http://127.0.0.1:0/orders:
  - method: POST
    path: /orders
    response:
      status: 200
      body: parked-ok
"#;

/// Plain-string-body document: the scripted body is a JSON string and
/// the response declares no content type, so the receive decodes the
/// wire bytes as plain text. The validation proves the string serves
/// verbatim: quoted wire bytes (a body serialized as JSON) would
/// mismatch under the text decode.
const PLAIN_STRING_BODY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: exact text
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    response:
      status: 200
      body: "exact text"
"#;

/// Null-body document: the scripted body is an explicit null and the
/// response declares no content type, so the received body is the
/// empty string — a null body never decodes to null, and a stale
/// literal `null` on the wire would fail the validation.
const NULL_BODY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: ''
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    response:
      status: 200
      body: null
"#;

/// Delay document: one entry with `delay: 100ms` serving a 200 with
/// body `slow-ok`. The scenario sends, receives (which parks the
/// delayed roundtrip), and validates status 200 plus the body. The
/// timing itself is proven at adapter level in Task 1.2; this e2e
/// proves the delayed response still reaches the scenario's receive.
const DELAY_RESPONSE_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 200
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: slow-ok
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    delay: 100ms
    response:
      status: 200
      headers:
        content-type: application/json
      body: slow-ok
"#;

/// Elapsed-bound document, passing side: the scripted `delay: 300ms`
/// puts the response's wire arrival ~300ms after the scenario start,
/// past the 200ms `elapsedAtLeast` bound on the `lastReceived` validate.
const ELAPSED_WAITED_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation:
      equals:
        ok: true
    elapsedAtLeast: 200ms
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    delay: 300ms
    response:
      status: 200
      headers:
        content-type: application/json
      body: {"ok": true}
"#;

/// Elapsed-bound document, early-arrival side: the response arrives
/// ~immediately (no script delay) but the scenario consumes it only
/// after a 1s `sleep`. The 500ms `elapsedAtLeast` bound must judge the
/// WIRE arrival, not the consumption time — consumed late is still
/// arrived early, so the validate must fail.
const ELAPSED_EARLY_ARRIVAL_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- sleep:
    duration: 1s
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation:
      equals:
        ok: true
    elapsedAtLeast: 500ms
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    response:
      status: 200
      headers:
        content-type: application/json
      body: {"ok": true}
"#;

/// Elapsed-bound document, unreachable bound: an immediate arrival
/// against a 10s `elapsedAtLeast` bound must fail naming the endpoint,
/// the bound, and the actual elapsed time.
const ELAPSED_TOO_EARLY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation:
      equals:
        ok: true
    elapsedAtLeast: 10s
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    response:
      status: 200
      headers:
        content-type: application/json
      body: {"ok": true}
"#;

/// Fault document: the partner scripted `fault: close` records the
/// request and then aborts the connection with no response bytes. The
/// send dials and parks the failing roundtrip; the receive consumes
/// it and surfaces the transport-class failure.
const FAULT_CLOSE_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    fault: close
"#;

/// Delay-before-fault document: the connection is held for `delay:
/// 100ms` and then aborted, so the receive's parked roundtrip fails
/// after the delay. The failure is the same transport-class
/// `ActionTransport` as a bare fault; the delay ordering is proven at
/// adapter level in Task 1.2.
const DELAY_BEFORE_FAULT_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    delay: 100ms
    fault: close
"#;

/// Times document: an entry served `times: 2` (201, body `A`) then a
/// fallback entry (200, body `B`), both matching the same PUT. The
/// scenario sends and receives three times, validating status and
/// body in order: 201/A, 201/A, 200/B — the third exchange proves the
/// `times` entry spent itself and the fallback served.
const TIMES_TWO_FALLBACK_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 201
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: A
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 201
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: A
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: PUT
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    deadline: 5s
    extract:
      status: status
- validate:
    target: {variable: status}
    expectation: 200
- validate:
    target:
      lastReceived: http://127.0.0.1:0/orders
    expectation: B
partners:
  http://127.0.0.1:0/orders:
  - method: PUT
    path: /orders
    times: 2
    response:
      status: 201
      headers:
        content-type: application/json
      body: A
  - method: PUT
    path: /orders
    response:
      status: 200
      headers:
        content-type: application/json
      body: B
"#;

/// Two-layer document: the same variable name `PARTNER` must be
/// visible on both tiers of one run. The scenario tier carries the
/// bare authority (`host:port`, no scheme — proven by the
/// `http://${PARTNER}/orders` send dialing), and the route env tier
/// carries the `http://host:port` form — the booted route's producer
/// target is exactly `${env:PARTNER}`, so only the full form dials.
/// The direct send is the route stimulus; the third wire arrival, on
/// path `/`, is the producer's env-tier dial.
const TWO_LAYER_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: PARTNER
    method: POST
- send:
    to: 'http://${PARTNER}/orders'
    method: GET
- send:
    to: direct:start
    body: env-tier-probe
"#;

/// The partner-direct path end to end: the send addresses the
/// harness-declared `:0` URI, `fill_bind_vars` supplies the bound
/// authority, and the scripted PUT is served. The recorder saw
/// exactly one arrival on `/orders` as PUT — only the bound address
/// can produce a recording.
#[tokio::test]
async fn partner_direct_send_reaches_bound_address() {
    let (outcome, recorders) = common::run_doc(PUT_PUT_OK_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "every action must pass: {outcome:?}"
    );

    let recorded = recorders[ORDERS].recorded_requests();
    assert_eq!(recorded.len(), 1, "exactly one request must reach the wire");
    assert_eq!(recorded[0].method, "PUT");
    assert_eq!(recorded[0].path, "/orders");
}

/// The `$${` escape survives to the wire: the recorded request body
/// is the literal `${not_a_var}`, with no variable lookup attempted.
#[tokio::test]
async fn escape_reaches_wire() {
    let (outcome, recorders) = common::run_doc(ESCAPE_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "every action must pass: {outcome:?}"
    );

    let recorded = recorders[ORDERS].recorded_requests();
    assert_eq!(recorded.len(), 1);
    assert_eq!(
        String::from_utf8_lossy(&recorded[0].body),
        "${not_a_var}",
        "the escaped leaf must reach the wire as the literal: {:?}",
        recorded[0].body
    );
}

/// A request no script matches gets the unmatched 500 with an empty
/// body: the status validation passes (the received status is exactly
/// 500), and the final body validation is the asserted mismatch whose
/// detail shows the empty body.
#[tokio::test]
async fn unmatched_script_serves_500_empty() {
    let (outcome, _recorders) = common::run_doc(DELETE_UNMATCHED_DOC).await;
    assert_eq!(outcome.verdict, None, "the last validate must fail");

    assert!(
        matches!(&outcome.per_action[2], Ok(ScenarioVerdict::Pass)),
        "the status validate must pass, proving the received status is 500: {outcome:?}"
    );
    let failure = outcome
        .per_action
        .last()
        .and_then(|result| result.as_ref().err())
        .expect("the last action must have failed");
    let ScenarioFailure::ValidationMismatch { detail, .. } = failure else {
        panic!("expected ValidationMismatch, got {failure:?}");
    };
    assert!(
        detail.contains("got \"\""),
        "the mismatch detail must show the empty body: {detail}"
    );
}

/// A harness reference whose `partners:` entry is an explicitly empty
/// sequence is non-permissive: the partner binds scripted-with-nothing,
/// so every request is unmatched and gets the 500 with an empty body.
/// The status validation passes (received status is exactly 500), and
/// the final body validation is the asserted mismatch whose detail
/// shows the empty body.
#[tokio::test]
async fn declared_empty_partners_serves_unmatched_500() {
    let (outcome, _recorders) = common::run_doc(EMPTY_PARTNERS_DOC).await;
    assert_eq!(outcome.verdict, None, "the last validate must fail");

    assert!(
        matches!(&outcome.per_action[2], Ok(ScenarioVerdict::Pass)),
        "the status validate must pass, proving the received status is 500: {outcome:?}"
    );
    let failure = outcome
        .per_action
        .last()
        .and_then(|result| result.as_ref().err())
        .expect("the last action must have failed");
    let ScenarioFailure::ValidationMismatch { detail, .. } = failure else {
        panic!("expected ValidationMismatch, got {failure:?}");
    };
    assert!(
        detail.contains("got \"\""),
        "the mismatch detail must show the empty body: {detail}"
    );
}

/// A send referencing a variable nothing sets fails the action with
/// the apparatus class `VarUnresolved` (rc-whof), before any dial.
#[tokio::test]
async fn unset_variable_fails_apparatus() {
    let (outcome, _recorders) = common::run_doc(UNSET_VAR_DOC).await;
    assert_eq!(outcome.verdict, None);

    let failure = outcome
        .per_action
        .last()
        .and_then(|result| result.as_ref().err())
        .expect("the send must fail");
    assert!(
        matches!(&failure, ScenarioFailure::VarUnresolved { name } if name == "missing"),
        "expected VarUnresolved {{ name: \"missing\" }}, got {failure:?}"
    );
}

/// The CRUD chain end to end: the extracted `orderId` interpolates
/// into the GET's string-form URI, which reaches the scripted
/// exact-path matcher and round-trips through the string-form
/// receive. A non-interpolated `${orderId}` path would miss the
/// `/orders/ord-7` script, serve the unmatched 500 with an empty
/// body, and fail the final `contains` validation.
#[tokio::test]
async fn crud_chain_interpolates_extracted_id() {
    let (outcome, recorders) = common::run_doc(CRUD_CHAIN_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the whole chain must pass: {outcome:?}"
    );

    let recorded = recorders[ORDERS].recorded_requests();
    assert_eq!(recorded.len(), 2, "POST then GET on the same partner");
    assert_eq!(recorded[0].method, "POST");
    assert_eq!(recorded[1].method, "GET");
    assert_eq!(
        recorded[1].path, "/orders/ord-7",
        "the extracted id must be on the wire path"
    );
}

/// The `receive` declared as the interpolated string
/// `http://${PARTNER}/orders` finds the roundtrip the map-form send
/// parked: `lane_key_for` resolves the interpolated authority to the
/// registered map-ref key. A miss here is an unbound-endpoint
/// transport failure or a receive timeout, never a pass.
#[tokio::test]
async fn receive_endpoint_interpolates() {
    let (outcome, _recorders) = common::run_doc(RECEIVE_INTERPOLATED_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the interpolated receive must find the parked roundtrip: {outcome:?}"
    );
}

/// The delayed response serves end to end: the scripted `delay` holds
/// the 200, and the receive validates the scripted status and body.
/// Timing itself is proven at adapter level (Task 1.2); here the
/// delayed response is proven to reach the scenario's receive.
#[tokio::test]
async fn delay_response_serves_e2e() {
    let (outcome, recorders) = common::run_doc(DELAY_RESPONSE_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the delayed response must serve: {outcome:?}"
    );

    let recorded = recorders[ORDERS].recorded_requests();
    assert_eq!(recorded.len(), 1, "exactly one request must reach the wire");
    assert_eq!(recorded[0].method, "PUT");
    assert_eq!(recorded[0].path, "/orders");
}

/// The wire-arrival bound, passing side: the delayed response's wire
/// arrival lands ~300ms after the scenario start, past the 200ms
/// `elapsedAtLeast` bound — the not-before-X control `run.sh`
/// expressed with `awk t>=X`.
#[tokio::test]
async fn waited_arrival_passes_elapsed_bound() {
    let (outcome, _recorders) = common::run_doc(ELAPSED_WAITED_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the delayed arrival must satisfy the elapsed bound: {outcome:?}"
    );
}

/// THE regression pin: the response arrives ~immediately but the
/// scenario consumes it only after a 1s `sleep`. The assertion must
/// measure the WIRE arrival (~tens of ms, well under the 500ms bound),
/// never the consumption time (~1s): consumed late is still arrived
/// early, so the validate fails naming the endpoint and the bound.
#[tokio::test]
async fn early_arrival_fails_even_when_consumed_late() {
    let (outcome, _recorders) = common::run_doc(ELAPSED_EARLY_ARRIVAL_DOC).await;
    assert_eq!(
        outcome.verdict, None,
        "the early arrival must fail the 500ms bound: {outcome:?}"
    );
    let failure = outcome
        .per_action
        .get(3)
        .and_then(|result| result.as_ref().err())
        .expect("the final validate must fail");
    let ScenarioFailure::ValidationMismatch { action, detail } = failure else {
        panic!("expected ValidationMismatch, got {failure:?}");
    };
    assert_eq!(*action, 3, "the final validate is the failing action");
    assert!(
        detail.contains(ORDERS),
        "detail must name the redacted endpoint subject: {detail}"
    );
    assert!(
        detail.contains("500ms"),
        "detail must name the elapsed bound: {detail}"
    );
    assert!(
        detail.contains("after the scenario started"),
        "detail must name the actual elapsed (humantime, any unit) \
         between `arrived` and `after the scenario started`: {detail}"
    );
}

/// An unreachable bound fails an immediate arrival, naming the
/// endpoint, the `10s` bound, and the actual elapsed time.
#[tokio::test]
async fn too_early_arrival_fails_naming_actual() {
    let (outcome, _recorders) = common::run_doc(ELAPSED_TOO_EARLY_DOC).await;
    assert_eq!(
        outcome.verdict, None,
        "the 10s bound must fail an immediate arrival: {outcome:?}"
    );
    let failure = outcome
        .per_action
        .get(2)
        .and_then(|result| result.as_ref().err())
        .expect("the final validate must fail");
    let ScenarioFailure::ValidationMismatch { action, detail } = failure else {
        panic!("expected ValidationMismatch, got {failure:?}");
    };
    assert_eq!(*action, 2, "the final validate is the failing action");
    assert!(
        detail.contains(ORDERS),
        "detail must name the redacted endpoint subject: {detail}"
    );
    assert!(
        detail.contains("10s"),
        "detail must name the bound: {detail}"
    );
    assert!(
        detail.contains("after the scenario started"),
        "detail must name the actual elapsed (humantime, any unit) \
         between `arrived` and `after the scenario started`: {detail}"
    );
}

/// A scripted JSON-string body with no content type serves verbatim:
/// the received body is `exact text` exactly — no surrounding quotes,
/// no escaping — because the partner body encoding mirrors the client
/// send path (`value_to_wire`).
#[tokio::test]
async fn plain_string_body_served_verbatim() {
    let (outcome, _recorders) = common::run_doc(PLAIN_STRING_BODY_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the string body must serve verbatim: {outcome:?}"
    );
}

/// A scripted null body serves empty: the received body decodes to
/// the empty string (never to null, never to the literal `null`
/// text), because the partner body encoding mirrors the client send
/// path (`value_to_wire`).
#[tokio::test]
async fn null_body_serves_empty() {
    let (outcome, _recorders) = common::run_doc(NULL_BODY_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the null body must serve empty: {outcome:?}"
    );
}

/// Asserts a faulted roundtrip surfaced on the receive as the
/// transport-class failure naming its own action index: the send
/// passed and the partner recorded exactly one PUT on `/orders` (the
/// request reached the wire before the abort), the receive failed with
/// `ActionTransport` on action 1, and the transport message names the
/// connection closure.
fn assert_receive_transport_failure(outcome: &DocumentOutcome, recorder: &HttpRecorder) {
    assert_eq!(outcome.verdict, None, "the receive must fail");

    assert!(
        matches!(&outcome.per_action[0], Ok(ScenarioVerdict::Pass)),
        "the send must dial and park the roundtrip: {outcome:?}"
    );
    let recorded = recorder.recorded_requests();
    assert_eq!(recorded.len(), 1, "exactly one request must reach the wire");
    assert_eq!(recorded[0].method, "PUT");
    assert_eq!(recorded[0].path, "/orders");

    let failure = outcome
        .per_action
        .get(1)
        .and_then(|result| result.as_ref().err())
        .expect("the receive must fail");
    let ScenarioFailure::ActionTransport { action, source } = failure else {
        panic!("expected ActionTransport, got {failure:?}");
    };
    assert_eq!(*action, 1, "the receive is the failing action");
    let TransportError::Other { message } = source else {
        panic!("expected a transport failure, got {source:?}");
    };
    assert!(
        message.contains("connection closed"),
        "the transport message should name the connection closure: {message}"
    );
}

/// A `fault: close` partner aborts the connection with no response
/// bytes. The send dials and parks the failing roundtrip, so the
/// scenario observes the fault on the receive: the roundtrip of the
/// send fails, and the receive surfaces the transport-class failure
/// naming its own action index.
#[tokio::test]
async fn fault_close_fails_receive_e2e() {
    let (outcome, recorders) = common::run_doc(FAULT_CLOSE_DOC).await;
    assert_receive_transport_failure(&outcome, &recorders[ORDERS]);
}

/// The `delay` applies before the `fault`: the connection is held then
/// aborted, and the receive's parked roundtrip fails with the same
/// transport-class failure. The delay ordering itself is proven at
/// adapter level (Task 1.2).
#[tokio::test]
async fn delay_before_fault_fails_receive_e2e() {
    let (outcome, recorders) = common::run_doc(DELAY_BEFORE_FAULT_DOC).await;
    assert_receive_transport_failure(&outcome, &recorders[ORDERS]);
}

/// The `times: 2` entry serves two matching requests then spends
/// itself, and the fallback entry answers the third: the scenario
/// receives and validates 201/A, 201/A, then 200/B in order — the
/// third exchange proves the times entry was spent.
#[tokio::test]
async fn times_two_then_fallback_e2e() {
    let (outcome, recorders) = common::run_doc(TIMES_TWO_FALLBACK_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the times-then-fallback chain must pass: {outcome:?}"
    );

    let recorded = recorders[ORDERS].recorded_requests();
    assert_eq!(recorded.len(), 3, "three sends must reach the wire");
    for request in &recorded {
        assert_eq!(request.method, "PUT");
        assert_eq!(request.path, "/orders");
    }
}

/// One run, one partner, one variable name on two tiers: the scenario
/// variable `PARTNER` carries the bare `host:port` authority — proven
/// by the `http://${PARTNER}/orders` send dialing successfully (a
/// scheme-bearing value would double the scheme and fail the dial) —
/// while the route env tier carries `http://host:port` — proven by the
/// booted route whose producer target is exactly `${env:PARTNER}`
/// arriving on the partner recorder at path `/`, the only wire arrival
/// no scenario send can produce.
#[tokio::test]
async fn two_layer_bindvar_both_visible() {
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path();
    // The http producer's SSRF guard rejects loopback targets unless
    // the project allows them — the same opt-in the outbound fixture
    // declares.
    std::fs::write(
        root.join("Camel.toml"),
        "log_level = \"info\"\n\n[components.http]\nallow_internal = true\n",
    )
    .expect("write Camel.toml");
    std::fs::write(
        root.join("routes.yaml"),
        "routes:\n  - id: env-tier-probe\n    from: direct:start\n    steps:\n      - to: ${env:PARTNER}\n",
    )
    .expect("write routes.yaml");
    let path = root.join("case.test.yaml");
    std::fs::write(&path, TWO_LAYER_DOC).expect("write case file");
    let doc = parse_scenario_document(&path).expect("document must load");

    let partner = HttpPartner::start_permissive(200)
        .await
        .expect("partner must bind 127.0.0.1:0");
    let recorder = partner.recorder();

    // The CLI driver's env-tier wiring: the harness tier keeps the
    // `http://host:port` form route files interpolate, while
    // `fill_bind_vars` below keeps the scenario tier at bare
    // `host:port`. Same name, two layers, two forms.
    let harness_provisioned = BTreeMap::from([(
        "PARTNER".to_string(),
        format!("http://{}", partner.bound_addr()),
    )]);
    let env = LayeredEnv::new(
        doc.env.clone().unwrap_or_default(),
        harness_provisioned,
        doc.env_passthrough.clone().unwrap_or_default(),
        ambient_std(),
    );
    let run = boot_scenario(&doc, root, &env)
        .await
        .expect("the full boot must succeed");
    let ctx = Arc::new(tokio::sync::Mutex::new(run.ctx));

    let mut adapters: BTreeMap<String, Box<dyn PartnerAdapter>> = BTreeMap::new();
    adapters.insert(
        "direct:start".to_string(),
        Box::new(DirectStimulus::new(Arc::clone(&ctx))),
    );
    adapters.insert(ORDERS.to_string(), Box::new(partner));
    let router = PartnerRouter::new(adapters);

    let mut vars = ScenarioVars::new();
    fill_bind_vars(&common::wired_refs(&doc), &router, &mut vars);
    let outcome = run_scenario_document(&doc, &router, &mut vars, None).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "both layers must be visible under one name: {outcome:?}"
    );

    let recorded = recorder.recorded_requests();
    assert_eq!(recorded.len(), 3, "two scenario sends plus the route dial");
    assert_eq!(recorded[0].method, "POST");
    assert_eq!(recorded[0].path, "/orders");
    assert_eq!(recorded[1].method, "GET");
    assert_eq!(recorded[1].path, "/orders");
    assert_eq!(
        recorded[2].path, "/",
        "only the env-tier producer dial arrives with no path: {:?}",
        recorded[2]
    );

    let mut guard = ctx.lock().await;
    run.boot
        .shutdown(&mut guard)
        .await
        .expect("clean shutdown must complete");
}

// --- Server-role receive lanes (rc-ps97b) --------------------------------
//
// The server-role receive derives its lane path from the receive's
// own interpolated reference (path and query), never from the
// registered key's path. The fixtures bind ONE partner under
// [`RECEIVE_LANE_ORDERS`]; plain-string references resolve to it by
// interpolated authority alone.

/// The declared endpoint the receive-lane fixtures register: the
/// partner binds under this raw `:0` URI, and `MOCK` interpolates to
/// its bound bare authority on the scenario tier.
const RECEIVE_LANE_ORDERS: &str = "http://127.0.0.1:0/orders";

/// Sibling-path document: the routes dial `/orders` AND `/billing` on
/// the one partner (each through its own `direct:` stimulus, so no
/// response body ever feeds a second dial). A declared-key receive
/// first drains the `/orders` lane (its path is the registered key's
/// path under both parse sources), then the receive
/// `from: http://${MOCK}/billing` must drain the BILLING arrival off
/// its own lane. A server-role arrival carries the inbound request,
/// so the discrimination is structural: draining the emptied
/// `/orders` lane instead is a receive-timeout.
const SIBLING_PATH_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: direct:orders
- send:
    to: direct:billing
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: MOCK
    deadline: 2s
- receive:
    from: 'http://${MOCK}/billing'
    deadline: 2s
"#;

/// Bare-authority document: the receive addresses `http://${MOCK}`
/// with no path. The parse must reject it as an apparatus error
/// naming the declaration, never a silent `/` lane and never a
/// receive-timeout.
const BARE_AUTHORITY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- receive:
    from: 'http://${MOCK}'
    deadline: 300ms
"#;

/// Query-matching document: the wire lane is `/api?x=1` (two route
/// dials through one `direct:` stimulus), a receive on the exact
/// path-and-query drains it, and a receive on `?x=2` times out naming
/// the arrived wire lane.
const QUERY_MATCH_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: direct:probe
- send:
    to: direct:probe
- receive:
    from: 'http://${MOCK}/api?x=1'
    deadline: 2s
- receive:
    from: 'http://${MOCK}/api?x=2'
    deadline: 300ms
"#;

/// Declared-key regression document: a receive by the registered
/// map-form endpoint (no roundtrip parked — the only prior send
/// stimulates the route) drains the route-dialed `/orders` arrival
/// off its lane. A server-role arrival carries the inbound request,
/// so the drain itself is the whole proof.
const DECLARED_KEY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: direct:probe
- receive:
    from:
      endpoint: http://127.0.0.1:0/orders
      provisioning: harness
      bindVar: MOCK
    deadline: 2s
"#;

/// Secret-query document: the receive addresses
/// `http://${MOCK}?authPassword=x` (no path). The apparatus error
/// names the declaration with the secret value masked (ADR-0051).
const SECRET_QUERY_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- receive:
    from: 'http://${MOCK}?authPassword=x'
    deadline: 300ms
"#;

/// Standalone-roundtrip document: a dynamic-ref send parks a
/// roundtrip and a standalone receive by the same reference drains it
/// — the client-role-first dispatch is unchanged by the lane-path fix.
const ROUNDTRIP_STANDALONE_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: 'http://${MOCK}/orders'
    method: POST
- receive:
    from: 'http://${MOCK}/orders'
    deadline: 2s
- validate:
    target:
      lastReceived: 'http://${MOCK}/orders'
    expectation:
      contains: parked-ok
- validate:
    target:
      partner:
        endpoint: http://127.0.0.1:0/orders
        provisioning: harness
    expectation:
      count: 1
partners:
  http://127.0.0.1:0/orders:
  - method: POST
    path: /orders
    response:
      status: 200
      body: parked-ok
"#;

/// Path-aware characterization document (bd rc-cr5yf): two
/// dynamic-ref sends park their roundtrips `/a` (a-ok) then `/b`
/// (b-ok) — no reply expectation, the roundtrips stay parked, each
/// under its own path's lane key. The receives are CROSSED against
/// the parking order: the first receive names `http://${MOCK}/b` and
/// must drain the `/b` roundtrip (b-ok), the second names
/// `http://${MOCK}/a` and gets a-ok. An oldest-first path-blind
/// implementation would hand the first receive the older `/a`
/// roundtrip and fail both validates. This pins the path-aware
/// parking contract.
const PATH_AWARE_DOC: &str = r#"
routeFiles: [routes.yaml]
scenario:
- send:
    to: 'http://${MOCK}/a'
    method: POST
- send:
    to: 'http://${MOCK}/b'
    method: POST
- receive:
    from: 'http://${MOCK}/b'
    deadline: 2s
- receive:
    from: 'http://${MOCK}/a'
    deadline: 2s
- validate:
    target:
      lastReceived: 'http://${MOCK}/b'
    expectation:
      contains: b-ok
- validate:
    target:
      lastReceived: 'http://${MOCK}/a'
    expectation:
      contains: a-ok
- validate:
    target:
      partner:
        endpoint: http://127.0.0.1:0/orders
        provisioning: harness
    expectation:
      count: 2
partners:
  http://127.0.0.1:0/orders:
  - method: POST
    path: /a
    response:
      status: 200
      body: a-ok
  - method: POST
    path: /b
    response:
      status: 200
      body: b-ok
"#;

/// The `routes.yaml` one-dial-per-stimulus routes: each route dials
/// exactly one env-tier target, so no dial's response body can feed
/// the next dial's method choice.
fn single_dial_routes(dials: &[(&str, &str)]) -> String {
    let routes: Vec<String> = dials
        .iter()
        .map(|(stimulus, target)| {
            format!(
                "  - id: dial-{stimulus}\n    from: direct:{stimulus}\n    steps:\n      - to: ${{env:{target}}}\n"
            )
        })
        .collect();
    format!("routes:\n{}", routes.join(""))
}

/// Loads `yaml`, binds ONE partner under [`RECEIVE_LANE_ORDERS`]
/// (scripted where the document declares the matching `partners:`
/// entry, permissive otherwise), marks `authPassword` a secret query
/// key (ADR-0051), seeds the scenario tier's `MOCK` with the bound
/// bare authority, and runs the document without booting routes. The
/// shape for pure roundtrip scenarios: plain-string send/receive
/// references resolve to the partner by interpolated authority alone.
async fn run_doc_one_partner(yaml: &str) -> (DocumentOutcome, HttpRecorder) {
    let dir = tempfile::tempdir().expect("temp dir");
    let path = dir.path().join("case.test.yaml");
    std::fs::write(&path, yaml).expect("write case file");
    let doc = parse_scenario_document(&path).expect("document must load");

    let scripts = partner_scripts_for(&doc, RECEIVE_LANE_ORDERS);
    let partner = match scripts {
        Some(scripts) => HttpPartner::start(scripts).await,
        None => HttpPartner::start_permissive(200).await,
    }
    .expect("partner must bind 127.0.0.1:0");
    let bound = partner.bound_addr().to_string();
    let recorder = partner.recorder();

    let mut adapters: BTreeMap<String, Box<dyn PartnerAdapter>> = BTreeMap::new();
    adapters.insert(RECEIVE_LANE_ORDERS.to_string(), Box::new(partner));
    let router = PartnerRouter::new(adapters);
    router.set_secret_query_keys(vec!["authPassword".to_string()]);

    let mut vars = ScenarioVars::new();
    vars.set("MOCK", Value::String(bound));
    let outcome = run_scenario_document(&doc, &router, &mut vars, None).await;
    (outcome, recorder)
}

/// Boots the document's routes and runs the document: one partner
/// binds under [`RECEIVE_LANE_ORDERS`], each `dial_paths` entry gets
/// an env-tier variable `MOCK_DIAL_N` carrying the full dial URI
/// (`http://{bound}{path}`) for the routes file to produce against,
/// the scenario tier's `MOCK` carries the bound bare authority, and
/// the `direct:` stimuli the document names trigger the dials.
/// Mirrors the two-layer fixture's env-tier wiring; the route-dialed
/// arrivals park on the partner's server-role lanes with no roundtrip
/// in the way.
async fn run_doc_route_dialed(
    yaml: &str,
    routes_yaml: &str,
    dial_paths: &[&str],
) -> (DocumentOutcome, HttpRecorder) {
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path();
    // The http producer's SSRF guard rejects loopback targets unless
    // the project allows them — the same opt-in the outbound fixture
    // declares.
    std::fs::write(
        root.join("Camel.toml"),
        "log_level = \"info\"\n\n[components.http]\nallow_internal = true\n",
    )
    .expect("write Camel.toml");
    std::fs::write(root.join("routes.yaml"), routes_yaml).expect("write routes.yaml");
    let path = root.join("case.test.yaml");
    std::fs::write(&path, yaml).expect("write case file");
    let doc = parse_scenario_document(&path).expect("document must load");

    let scripts = partner_scripts_for(&doc, RECEIVE_LANE_ORDERS);
    let partner = match scripts {
        Some(scripts) => HttpPartner::start(scripts).await,
        None => HttpPartner::start_permissive(200).await,
    }
    .expect("partner must bind 127.0.0.1:0");
    let bound = partner.bound_addr().to_string();
    let recorder = partner.recorder();

    let harness_provisioned: BTreeMap<String, String> = dial_paths
        .iter()
        .enumerate()
        .map(|(n, suffix)| (format!("MOCK_DIAL_{n}"), format!("http://{bound}{suffix}")))
        .collect();
    let env = LayeredEnv::new(
        doc.env.clone().unwrap_or_default(),
        harness_provisioned,
        doc.env_passthrough.clone().unwrap_or_default(),
        ambient_std(),
    );
    let run = boot_scenario(&doc, root, &env)
        .await
        .expect("the full boot must succeed");
    let ctx = Arc::new(tokio::sync::Mutex::new(run.ctx));

    let mut adapters: BTreeMap<String, Box<dyn PartnerAdapter>> = BTreeMap::new();
    for stimulus in ["direct:orders", "direct:billing", "direct:probe"] {
        adapters.insert(
            stimulus.to_string(),
            Box::new(DirectStimulus::new(Arc::clone(&ctx))),
        );
    }
    adapters.insert(RECEIVE_LANE_ORDERS.to_string(), Box::new(partner));
    let router = PartnerRouter::new(adapters);
    router.set_secret_query_keys(vec!["authPassword".to_string()]);

    let mut vars = ScenarioVars::new();
    fill_bind_vars(&common::wired_refs(&doc), &router, &mut vars);
    vars.set("MOCK", Value::String(bound));
    let outcome = run_scenario_document(&doc, &router, &mut vars, None).await;

    let mut guard = ctx.lock().await;
    run.boot
        .shutdown(&mut guard)
        .await
        .expect("clean shutdown must complete");
    (outcome, recorder)
}

/// One partner, two dialed sibling paths, two receives: after the
/// declared-key receive empties the `/orders` lane, the receive
/// `from: http://${MOCK}/billing` must drain the BILLING arrival. The
/// registered key's path is `/orders`; the receive's own reference
/// names `/billing`, and only the reference counts.
#[tokio::test]
async fn dynamic_receive_sibling_path_drains_own_lane() {
    let routes = single_dial_routes(&[("orders", "MOCK_DIAL_0"), ("billing", "MOCK_DIAL_1")]);
    let (outcome, recorders) =
        run_doc_route_dialed(SIBLING_PATH_DOC, &routes, &["/orders", "/billing"]).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the billing receive must drain the billing lane: {outcome:?}"
    );

    let recorded = recorders.recorded_requests();
    assert_eq!(
        recorded.len(),
        2,
        "both route dials must reach the wire: {recorded:?}"
    );
    assert_eq!(recorded[0].path, "/orders");
    assert_eq!(recorded[1].path, "/billing");
}

/// A receive `from: http://${MOCK}` (no path) is an apparatus-class
/// transport error naming the declaration — never a silent `/` lane
/// and never a receive-timeout.
#[tokio::test]
async fn dynamic_receive_bare_authority_is_apparatus() {
    let (outcome, _recorders) = run_doc_one_partner(BARE_AUTHORITY_DOC).await;
    assert_eq!(outcome.verdict, None, "the receive must fail");

    let failure = outcome
        .per_action
        .first()
        .and_then(|result| result.as_ref().err())
        .expect("the receive must have failed");
    let ScenarioFailure::ActionTransport { action, source } = failure else {
        panic!("expected an apparatus transport failure, got {failure:?}");
    };
    assert_eq!(*action, 0, "the receive is the failing action");
    let TransportError::Other { message } = source else {
        panic!("expected a transport failure, got {source:?}");
    };
    assert!(
        message.contains("empty or absent path"),
        "the error must name the empty path: {message}"
    );
    assert!(
        message.contains("http://127.0.0.1:"),
        "the error must name the declaration: {message}"
    );
}

/// The wire lane is `/api?x=1`: the matching receive drains it, and
/// the `?x=2` receive times out listing the arrived wire path.
#[tokio::test]
async fn dynamic_receive_query_matches_wire_path_and_query() {
    let routes = single_dial_routes(&[("probe", "MOCK_DIAL_0")]);
    let (outcome, _recorders) = run_doc_route_dialed(QUERY_MATCH_DOC, &routes, &["/api?x=1"]).await;
    assert_eq!(outcome.verdict, None, "the ?x=2 receive must time out");

    assert!(
        matches!(&outcome.per_action[2], Ok(ScenarioVerdict::Pass)),
        "the exact path-and-query receive must drain its lane: {outcome:?}"
    );
    let failure = outcome
        .per_action
        .get(3)
        .and_then(|result| result.as_ref().err())
        .expect("the ?x=2 receive must have timed out");
    let ScenarioFailure::ReceiveTimeout { lanes, .. } = failure else {
        panic!("expected a receive-timeout, got {failure:?}");
    };
    assert!(
        lanes.contains("/api?x=1"),
        "the timeout must list the arrived wire lane: {lanes}"
    );
}

/// Regression: a receive by the registered declared key (no roundtrip
/// parked) drains its route-dialed arrival off the lane — the
/// declared-key path is unchanged.
#[tokio::test]
async fn declared_key_receive_unchanged() {
    let routes = single_dial_routes(&[("probe", "MOCK_DIAL_0")]);
    let (outcome, _recorders) = run_doc_route_dialed(DECLARED_KEY_DOC, &routes, &["/orders"]).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the declared-key receive must drain its lane: {outcome:?}"
    );
}

/// A receive `from: http://${MOCK}?authPassword=x` fails as an
/// apparatus error whose declaration echo masks the secret value
/// (ADR-0051): the raw pair never prints.
#[tokio::test]
async fn bare_authority_secret_query_redacted() {
    let (outcome, _recorders) = run_doc_one_partner(SECRET_QUERY_DOC).await;
    assert_eq!(outcome.verdict, None, "the receive must fail");

    let failure = outcome
        .per_action
        .first()
        .and_then(|result| result.as_ref().err())
        .expect("the receive must have failed");
    let ScenarioFailure::ActionTransport { source, .. } = failure else {
        panic!("expected an apparatus transport failure, got {failure:?}");
    };
    let TransportError::Other { message } = source else {
        panic!("expected a transport failure, got {source:?}");
    };
    assert!(
        message.contains("empty or absent path"),
        "the error must name the empty path: {message}"
    );
    assert!(
        !message.contains("authPassword=x"),
        "the raw secret value must never print: {message}"
    );
    assert!(
        message.contains("authPassword=***"),
        "the secret value must render masked: {message}"
    );
}

/// Regression: a dynamic-ref standalone send parks a roundtrip and a
/// standalone receive by the same reference drains it — the
/// client-role-first dispatch is unchanged.
#[tokio::test]
async fn roundtrip_receive_first_then_take_still_works() {
    let (outcome, recorders) = run_doc_one_partner(ROUNDTRIP_STANDALONE_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "the standalone receive must drain the parked roundtrip: {outcome:?}"
    );

    let recorded = recorders.recorded_requests();
    assert_eq!(recorded.len(), 1, "exactly one request must reach the wire");
    assert_eq!(recorded[0].path, "/orders");
}

/// Characterization (bd rc-cr5yf): two dynamic-ref sends park their
/// roundtrips under their own path's lane keys, and the receives are
/// CROSSED against the parking order — the receive naming `/b`
/// drains the `/b` roundtrip (`b-ok`) and the receive naming `/a`
/// gets `a-ok`, both witnessed by the document's `lastReceived`
/// validates. An oldest-first path-blind implementation drains the
/// older `/a` roundtrip into the `/b` receive and fails both. This
/// pins the path-aware parking contract: no cross-match between
/// paths, oldest-first within one path.
#[tokio::test]
async fn standalone_roundtrip_receives_drain_their_own_path() {
    let (outcome, recorders) = run_doc_one_partner(PATH_AWARE_DOC).await;
    assert_eq!(
        outcome.verdict,
        Some(ScenarioVerdict::Pass),
        "each receive must drain its own path's parked roundtrip: {outcome:?}"
    );

    let recorded = recorders.recorded_requests();
    assert_eq!(recorded.len(), 2, "both sends must reach the wire");
    assert_eq!(recorded[0].path, "/a");
    assert_eq!(recorded[1].path, "/b");
}