warn "Launching [[$cmd]]";
I don't see the output of that anywhere in your output, yet this is the thing that is giving you problems.
If you don't see what is wrong in your local output, maybe share that output with us?
Also, when you run the commands manually, why do you do:
sed -i "s#.*$h#$k#gI" test.txt
when the command you are having trouble with is something else?
sed -i "s#.*HOSTA#ssh-rsa AAAAB3NzaC1yc2 root@HOSTA#gI" /tmp/test.txt
Try to bring your manual interaction as close to the scripted interaction as possible. Only then you can see where the difference is between the two things that makes one fail and one succeed.