If you're doing any sort of UI/GUI manipulation, either with AppleScript or Keyboard Maestro, then yes, it does need to be unlocked to work.
You could use a
pause until in Keyboard Maestro macro to wait until "the calculation" "SCREENSAVER()" returns "false" and then the macro would wait until the next time the screen is unlocked. (See The Wiki for more details.)
Alternatively, if your Mac is in a secure location, you could turn off the password requirement to wake from sleep or screensaver, if you understand and accept the associated potential risks.
I have an older Mac that I do this with. It basically just does a few simple automations, but they require the Mac to be "ok" so I turned off the screensaver password. I also have turned off iCloud Keychain on that Mac, and it does not have access to anything I consider "vital" so if someone did manage to access it, I don't think they would get access to anything meaningful. (Most everything is in 1Password anyway, which remains separately encrypted.)
(Considering that would require physical access to a computer in my home, someone using it would indicate I could have bigger issues to worry about.)
But each person would have to make their own risk assessment and determine their own comfort level.