The original loophole was built to let things out and keep things in. It was a slit in a castle wall.

In medieval English the opening was a loupe, a narrow vertical gap for keeping watch and shooting arrows. Grammarphobia cites the *Oxford English Dictionary*'s first example from Piers Plowman, written in the second half of the 14th century. It warns against light leaping in "at louer ne at loupe."

The slit was clever engineering. Wikipedia's article on arrowslits says the walls behind it were splayed, giving the archer a wide field of fire while the outside showed almost nothing to aim at. Some were cut in a cross, to suit both longbow and crossbow.

The "loop" has nothing to do with a loop of string. World Wide Words says one 19th-century scholar thought the openings were loop-shaped, but experts favour a Dutch source. Grammarphobia says the OED points to a Middle Dutch word meaning "lie in wait, watch, or peer." World Wide Words names lupen, "to watch or peer," and glupen, "to spy or lurk." Either way, a loupe was a watching hole.

The longer form came later. World Wide Words says "loop" was stretched to "loophole" in the 16th century, to tell it apart from the other loop. The OED's first example of "loop hole" is from William Garrard's Art of Warre in 1591. It describes townspeople not showing themselves at their "defences or loop holes."

Then the word escaped the castle. By about the middle of the 17th century it was used figuratively for a means of escape. By 1700, World Wide Words says, it had its modern sense: a gap in a law or rule that lets someone slip past it. Grammarphobia quotes Thomas Jefferson in 1807, unsure "what loop-hole they will find in the case."

The military meaning outlived the bow. Wikipedia says that after gunpowder arrived, the loophole for firearms became the arrowslit's successor.