Chief Gallagher was turned in by his own platoon last spring. Several fellow SEALs reported that he had shot civilians and killed a captive Islamic State fighter with a custom hunting knife during a deployment in Iraq in 2017. He was also charged with obstruction of justice for threatening to kill SEALs who reported him.

At trial he was acquitted of all charges except one, for which he was demoted: bringing discredit to the armed forces by posing for photos with the teenage captive’s dead body.

Mr. Trump reversed that demotion, and also announced that he was ordering the pardons of Clint Lorance, a former Army lieutenant who was serving a 19-year sentence for the murder of two civilians, and Maj. Mathew L. Golsteyn, an Army Special Forces officer who was facing murder charges for killing an unarmed Afghan he believed was a Taliban bomb maker.

While the Army carried out the president’s orders and dropped the matter, the Navy did so but also began disciplinary proceedings to strip Chief Gallagher of his Trident pin and oust him from the elite SEAL commando unit.

Mr. Trump was having none of it. On Thursday, he wrote on Twitter that “the Navy will NOT be taking away Warfighter and Navy Seal Eddie Gallagher’s Trident Pin.” He added: “This case was handled very badly from the beginning. Get back to business!”

The president’s tweet further infuriated top Navy and SEALs leaders, and Mr. Spencer threatened to resign, Defense Department officials said. He told a number of Pentagon officials that he was willing to go to the mat over this, and it was under that belief that Mr. Esper and Gen. Mark A. Milley, the chairman of the Joint Chiefs of Staff, then went to Mr. Trump to ask him to allow the disciplinary process to go through.

A senior Defense Department official said Mr. Spencer was also pursuing the side deal with the White House, unbeknown to either Mr. Esper or General Milley. Mr. Spencer, the official said, told White House officials that if Mr. Trump allowed the disciplinary process to go forward, Mr. Spencer would see to it that Chief Gallagher was not ousted from the Navy SEALs in the end.