Fix variable scope and heredoc escaping issue in completion hook