Semicolons denote the end of a query.
If you have multiple lines and some of them have semicolons, then you are executing multiple queries, not just one.
Variables only retain their references within the context of a single query.
There are two queries being executed here.
The first query includes the MATCH on line 1 and the MERGE on line 2 because of the semicolon at the end of line 2.
The second query only includes the MERGE at line 3, and because it is a separate query, a and p5 are not bound to the variables you matched upon from the first query.
Instead, they would be seen as brand new variables, not bound to anything, and your MERGE would create the entire pattern: two brand new nodes (freshly binding them to the variables) and the relationship between them.
It's also important to note that even if you removed the semicolon at the end of line 2, there would still be issues, as you are reusing the rel variable for two different MERGEs. That will not work, as the relationship properties are different between these. You would need to either drop the rel variable from your query entirely (which is the best thing to do when you are not reusing the same variable later) or use a new variable for the second relationship.