Bone rotation during IK animation

Hello community. I was trying to create an animation to scale a wall procedurally, using the On animator IK function and starting from a T-position.
As seen in the video, that’s fine, as long as one of the feet is not resting on the wall. When this happens, the leg no longer follows the foot naturally, but rotates senselessly.
I then tried to straighten the rotation of the leg by calling the bone via script and it works, but the foot is no longer able to go to the position that I indicate with animator.GoalIK because the leg remains constrained in the position via script and does not follow the foot.
I don’t know how I should fix it … I wonder if there is a way to fix the rotation of the leg by making it subject to foot movements anyway like when the standard animation is running and the leg bone is not called via script.

link video: File upload & sharing. Send large photos and videos. Online cloud storage.

Can someone help me? As seen in the video, the legs when they reach the top of the wall have a strange rotation.
If I call with “LateUpdate ()” the leg bone when it comes over the wall and straighten it, then it remains bound to that rotation and the leg is not affected by the position of the feet called on “OnAnimatorIK ()” (if instead I deactivate the rotation the leg returns to be twisted).
I tried to change avatar too but the defect remains so it is not that.
I would like to understand if I am wrong something or these are not feasible movements using only “OnAnimatorIK ()” and if you need to insert an animation when you get to the top of the wall or there is a way to fix the leg by keeping it under the effect of calls on “OnAnimatorIK ()”.

that’s the knee IK.
try setIKHintPosition