If you cannot use a specif agent as @Savio Moreira suggested the only option that I found is to duplicate some steps.
In my case have a similar pipeline with 2 stage:
- Build (To validate PR)
- Visual Studio build
- Visual Studio Test
- VS test
- Publish (To publish the Artifact after merge into master)
- Visual Studio build
- Copy file
- Publish build artifacts
The Build part is trigger only when a PR is created using a condition in the YAML Stage and Enable Branch policies.
The Publish part is trigger only when there is merge into master.
It's a bit annoying that some steps need to be duplicated but the execution is unique, and with the same pipeline I can execute validation before merge and then create the artifact once the code is into master.
The checkout option doesn't help since in my case each stage is executed on a completely different container.