This is my interpretation of the rules & what I coded:
At the very start of the round, if any unit has the attachment canDefensiveRetreat = true, the defender gets a prompt if they want to retreat, and to which territory. They may only retreat to friendly/neutral territories, not an enemy territory, and they can't retreat to a territory with enemy units in it, unless only enemy air is present, which is non-blocking.
If the defender chooses not to retreat, then the battle proceeds as normal. If the defender chooses a territory to retreat to, then that territory is saved and stored for later. The attackers fire at all of the defending units. Any units that are doing a defensive retreat do not fire back. Casualties are removed, and then any retreating units retreat to the destination we stored earlier. Any defender units not capable of retreating remain and must fight to the end/get captured/get removed, whatever happens normally
EDIT: I was originally going to have a property that applies to all land units, but it turns out that in A&A North Africa not all land units can defensive retreat (the truck and the supply token can't) so it pretty much needs to be a unit attachment. This offers some variation as the mapmaker can select what units they want to be able to do a defender retreat