Judge almost shut down surveillance program, documents show