The scenario doesn’t surprise me an @PaulWalters is spot on in the answer above about testing small and working out. The issue here is that historically action code was less powerful and rock-solid escaping wasn’t a big deal. A result is some functions may not handle escaping as well as others. If you have nested/chained functions a good triage is to try each discrete function from start/inner and pass the result to an attribute to check in which part(s) the escaping passes or fails.
I hear you on the AppleScript - it is as I guessed. Still, be aware of it as a backstop option. Should it be needed there is some expertise here in the forum.
For now, I think following the testing advice above is the best way ahead.
Tip: If you want to be able to noodle around with action code in a bigger space such as a note’s $Text space without quote types being converted etc., apply the build-in ‘Code’ prototype to your TBX and than assign that to a new note (before you add any code).