How the fired F.B.I. director’s greatest asset proved his undoing.

On Tuesday, when Donald Trump abruptly dismissed the F.B.I. director, James Comey, his Administration insisted that he was merely following the recommendation of his Attorney General and Deputy Attorney General, the two most senior officials in the Justice Department.

In a three-page memorandum attached to Comey’s termination letter, the Deputy Attorney General, Rod J. Rosenstein, cited concern for the F.B.I.’s “reputation and credibility.” He said that the director had defied Justice Department policies and traditions and overstepped his authority in the way he handled the Hillary Clinton e-mail investigation.

This was a puzzling assertion from the Trump Administration, not least because Trump is widely acknowledged to have reaped the benefits of Comey’s actions on Election Day. After the F.B.I. director sent his letter to Congress, on October 28th, about the discovery of new Clinton e-mails and the Bureau’s plans to assess them, Trump praised Comey for his “guts” and called the news “bigger than Watergate.”

In the aftermath of Comey’s firing, Democrats and some Republicans in Congress have proposed a far more credible explanation for Trump’s action, accusing the President of trying to halt the F.B.I.’s investigation into Russian interference in the election and possible collusion with his campaign. Some of those legislators, as well as many critics in the press, have said that Trump has ignited a constitutional crisis, and they called for the appointment of an independent prosecutor to carry out the Russia investigation.

Comey’s dismissal came just as his Russia probe appeared to be widening. Just last week, the F.B.I. director went to Rosenstein, who had been in his job only for a few days, to ask for significantly more resources in order to accelerate the investigation, according to the Times. Tensions between the Trump Administration and Comey had been escalating already, and Trump’s fury over the F.B.I.’s Russia probe remained full-throated. On Monday, Trump tweeted that the inquiry was a “taxpayer funded charade.”

It is now clear that the aim of Rosenstein’s memo was simply to provide a pretext for Comey’s firing. White House officials may have thought it would be a persuasive rationale because Comey has come in for criticism from leaders of both political parties. Trump had been harboring a long list of grievances against the F.B.I. director, including his continued pursuit of the Russia probe. On Thursday, Trump confirmed in an interview with NBC News’s Lester Holt that, even before he received the Deputy Attorney General’s memo, he had already made up his mind to dismiss Comey. In the end, Comey’s conspicuous independence—for so long, his greatest asset—proved his undoing, making him too grave a threat to Trump but also giving the President a plausible excuse to fire him.

Rosenstein’s memo reflects genuine frustration inside the Justice Department about the F.B.I.’s handling of the Clinton e-mails, and betrays long-standing fissures between the two institutions, which are headquartered across from each other on Pennsylvania Avenue. Rosenstein, a Trump appointee who was previously the U.S. Attorney in Maryland, titled his memo “Restoring Public Confidence in the F.B.I.” In the wake of Comey’s ouster, the F.B.I.’s impartiality and competence remains an essential issue, making understanding what actually happened in the Clinton e-mail inquiry urgent as well.

Comey’s announcement about the discovery of the new Clinton e-mails did break with written and unwritten Justice Department guidelines against interfering with elections. Last week, during testimony before Congress, Comey cast the move as a singularly difficult decision and an act of principled self-sacrifice, driven by events far beyond his control­­. “I knew this would be disastrous for me personally,” he said. “But I thought this is the best way to protect these institutions that we care so much about.’’

A close examination, however, of the F.B.I.’s handling of the Clinton e-mails reveals a very different narrative, one that was not nearly so clear-cut or inevitable. It is one that places previously undisclosed judgments and misjudgments by the Bureau at the very heart of what unfolded.

“I could see two doors and they were both actions,” Comey recounted in testimony before the Senate Judiciary Committee. “One was labelled ‘speak’; the other was labelled ‘conceal.’ . . . I stared at ‘speak’ and ‘conceal.’ ‘Speak’ would be really bad. There’s an election in eleven days—lordy, that would be really bad. Concealing, in my view, would be catastrophic, not just to the F.B.I. but well beyond. And, honestly, as between really bad and catastrophic, I said to my team, ‘We got to walk into the world of really bad.’ I’ve got to tell Congress that we’re restarting this, not in some frivolous way—in a hugely significant way.”

But by the time Comey elected, on October 28th, to speak, rather than conceal, he and his senior aides had actually known for more than three weeks that agents sifting through files on a laptop belonging to the former congressman Anthony Weiner, as part of a sex-crimes investigation, had stumbled across e-mails sent by Clinton when she was Secretary of State. The agents had been unable, legally, to open the e-mails, because they fell outside the bounds of their investigation of Weiner.

F.B.I. officials kept the discovery to themselves. Without consulting or even informing the Justice Department lawyers who had worked on the e-mail inquiry, F.B.I. officials concluded that they lacked the evidence to seek a search warrant to examine the e-mails right away. Several legal experts and Justice Department officials I spoke to now say that this conclusion was unnecessarily cautious. F.B.I. officials also ruled out asking Weiner or his wife, Huma Abedin, one of Clinton’s closest aides, to allow access to the laptop—permission their lawyers told me they would have granted.

Instead, New York agents working the Weiner investigation, which centered on allegations of an explicit online relationship with a fifteen-year-old girl, were told to continue their search of his laptop as before but to take note of any additional Clinton e-mails they came across.

In the days that followed, investigators slowly sorted through the laptop’s contents, following standard protocols in a case that was anything but standard, and moving with surprisingly little dispatch to assess the significance of the e-mails.

After weeks of work, the agents concluded that the laptop contained thousands of Clinton messages, a fact they waited at least three more days to share with Comey. Finally, as Comey recounted before Congress last week, the F.B.I. director convened his top aides in his conference room at Bureau headquarters to weigh the political and institutional consequences of what to do next.

At this point, Comey and his deputies were venturing far beyond their typical purview as criminal investigators. Under normal circumstances, department policies discouraged public discussion of developments in ongoing cases of any kind; with the election fast approaching, there was the added sensitivity of avoiding even the perception of interference with the political process. But F.B.I. officials worried that agents in New York who disliked Clinton would leak news of the e-mails’ existence. Like nearly everyone in Washington, senior F.B.I. officials assumed that Clinton would win the election, and were evaluating their options with that in mind. The prospect of oversight hearings, led by restive Republicans investigating an F.B.I. “coverup,” made everyone uneasy.

One more misjudgment informed Comey’s decision. F.B.I. officials estimated that it would take months to review the e-mails. Agents wound up completing their work in just a few days. (Most of the e-mails turned out to be duplicates of messages collected in the previous phase of the Clinton investigation.) Had F.B.I. officials known that the review could be completed before the election, Comey likely wouldn’t have said anything before examining the e-mails. Instead, he announced that nothing had changed in the Clinton case—on November 6th, just two days before the election, and after many millions had already cast their ballots in early voting.

The debate over Comey’s effect on the 2016 election and, now, his historic dismissal, is likely to persist for years. In the months since Donald Trump became the nation’s forty-fifth President, a number of media organizations—most recently, the Times—have scrutinized Comey’s handling of the Clinton e-mails. They have also examined Comey’s accompanying silence about the Bureau’s investigation of possible ties between the Trump campaign and Russia, an inquiry that began in July of 2016.

Clinton traces her loss directly to Comey; she asserted recently that if the election had been held on October 27th, “I would be your President.” Trump retorted, in a tweet, that the F.B.I. director was “the best thing that ever happened to Hillary Clinton in that he gave her a free pass for many bad deeds!’’

This account is based on interviews with dozens of participants in the events leading up to the election. They include current and former officials from the F.B.I. and the Justice Department who were eager to have their actions understood but unwilling to be quoted by name. Comey himself declined my requests for an interview. Back in early January, however, he replied politely to a written interview request, acknowledging that he was aware of my “ongoing work.” He wrote from an e-mail address whose whimsical name, he said, “the Russians may have a harder time guessing.”

Comey added a note of intrigue, suggesting that there were unappreciated complexities to the story that hadn’t yet become known: “You are right there is a clear story to tell—one that folks willing to actually listen will readily grasp—but I’m not ready to tell it just yet for a variety of reasons.”

During his testimony before Congress last week, Comey said that the possibility that he’d influenced the outcome of the Presidential election made him “mildly nauseous.” Previously, over two decades of public service, Comey had made independence from partisan politics the foundation of his political identity. Comey, who is fifty-six years old, had been the rarest of creatures in Washington: a Republican even Democrats could love.

A registered Republican for most of his adult life, Comey had made a point of telling a congressional committee last July that he was no longer affiliated with either party. (His distance from partisan politics extends to the voting booth; records show that Comey hasn’t voted in a primary or general election in the past decade.)

Comey rose to prominence through the Justice Department, first as a federal prosecutor in New York and Virginia, and then as the United States Attorney in Manhattan, and the Deputy Attorney General under President George W. Bush. From early on, colleagues say, Comey carefully cultivated a reputation for integrity and nonpartisanship. Until the events of the past year, it had always served him well. “He knew what was the right thing to do,” a former federal prosecutor who worked with Comey told me. “But he figured out how to execute it in a way that, whatever the result, Jim Comey would be protected. I say that respectfully. He has an exceptional gift for that.”

Comey liked to map out the ramifications of major decisions, often in lengthy meetings with deputies. At critical moments in his career, Comey showcased his independence—too eagerly, in the view of some who accuse him of “moral vanity.” “I think he has a bit of a God complex—that he’s the last honest man in Washington,” a former Justice Department official who has worked with him told me. “And I think that’s dangerous.”

Daniel Richman, a Columbia law professor and close friend of Comey who has served as his unofficial media surrogate, acknowledged Comey’s penchant for public righteousness. “He certainly does love the idea of being a protector of the Constitution,” Richman said. “The idea of doing messy stuff and taking your lumps in the press.” But Richman, who worked with Comey as a federal prosecutor in Manhattan, insisted that Comey’s motivations were sincere. “More than most people, he thinks that when it comes to making really difficult decisions, transparency and accountability have incredible value,” Richman said.

Among scores of people I interviewed, not even Comey’s harshest critics believe that he acted out of a desire to elect a Republican President. Comey built his reputation by taking on powerful figures of both parties. Most famously, while serving as acting Attorney General under George W. Bush, he’d raced to the hospital bedside of the ailing Attorney General, John Ashcroft, to confront Administration officials seeking Ashcroft’s reauthorization for a domestic-surveillance program that the Justice Department considered illegal. Comey’s congressional testimony, in 2007, about the confrontation raised his public profile, earning him encomiums from both parties. In 2013, after Comey completed a seven-year interlude in the private sector, Barack Obama chose the Republican lawyer as the director of the F.B.I. “To know Jim Comey is also to know his fierce independence and his deep integrity,” the President declared, in a Rose Garden ceremony. The Senate confirmed him ninety-three to one.

The F.B.I. is a division of the United States Department of Justice, and its director reports to the Attorney General. But, from the start of his ten-year term at the F.B.I., Comey asserted a belief in the agency’s right to chart its own course. “The F.B.I. is in the executive branch,” Comey likes to say, “but not of the executive branch.”

The investigation of Clinton’s e-mails was exactly the sort of challenge Comey seemed to have spent his career preparing for. The F.B.I. formally opened its probe on July 10, 2015, just three months after Clinton announced her candidacy for President. “We all recognized it was a no-win situation,” the former F.B.I. executive assistant director John Giacalone, who helped oversee the investigation’s first seven months, said. At the outset, the goal was to finish the investigation by the end of 2015—before the first primary votes were cast. It took twice that long, barely ending before the party conventions in July, 2016.

The focus of the inquiry, run out of F.B.I. headquarters because of its sensitivity, was whether Clinton’s use of an unclassified e-mail system housed on private servers in the basement of her Chappaqua home violated any laws or allowed hackers and foreign governments to access government secrets. It was staffed by a core team of a dozen F.B.I. agents and analysts, along with two prosecutors from the Justice Department’s National Security Division and two from the Eastern District of Virginia.

Much of their time was taken up trying to find and examine all of the roughly sixty-two thousand messages from Clinton’s four years as Secretary of State, which began in January, 2009; two of Clinton’s lawyers had deleted about half of the e-mails, deeming them purely personal. This had sent the F.B.I. on an often-frustrating hunt for the missing e-mails. Agents fanned out to locate, examine, and reconstruct scattered hardware and data-backup systems from Clinton’s private network, as well as all the BlackBerrys, iPads, computers, and storage drives that Clinton, her aides, and her lawyers had used. Forensic recovery would eventually help the F.B.I. to find 17,448 deleted e-mails, including thousands that agents deemed work-related.

Even as thousands of messages remained elusive, the investigators ultimately reached consensus that the evidence didn’t warrant criminal charges, which required proof of intentional misconduct, gross negligence, or efforts to obstruct justice. After nearly a year and more than ninety interviews, they had identified eighty-one message chains deemed to be classified that passed through her private server. Clinton’s practices were sloppy, irresponsible, and in defiance of State Department policies, but investigators found no proof of criminal conduct—just a misguided effort by Clinton to maintain control over what the public, and her opponents, could learn about her.

As the inquiry neared its end, Comey, who had closely monitored it from the start, requested summaries of more than thirty government prosecutions involving mishandling of classified information. He waded through the records, seeking to understand the cases’ rationale and how they had been resolved. In the end, he agreed with the investigators’ unanimous conclusion: Clinton should not face criminal charges.

By June, 2016, the F.B.I. and the Justice Department were jointly weighing the question of how to reveal their decision in the midst of the Presidential campaign. F.B.I. and Justice officials had been discussing for weeks a major departure from the usual handling of a criminal inquiry that ended without charges.

The final interview, with Clinton herself, was scheduled for Saturday, July 2nd, at F.B.I. headquarters. Agents planned to spend the next week completing a confidential memo detailing their findings, assuming nothing new materialized. Then, in accord with standard Justice Department procedure, the supervising prosecutors and agents, along with top officials from both the Justice Department and the F.B.I., would privately brief the Attorney General, Loretta Lynch, on their recommendation against bringing charges. She would accept, closing the case.

Lynch was a widely respected seventeen-year Justice Department veteran who had previously served as the United States Attorney for the Eastern District of New York, under President Bill Clinton and, then, President Obama. In April, 2015, a Republican-controlled Senate confirmed her to replace Eric Holder as Attorney General. The first African-American woman to serve as Attorney General, Lynch was a graduate of Harvard Law School, the daughter of a librarian and a Baptist preacher and the sister of a Navy SEAL. She’d prosecuted corrupt politicians from both parties and was viewed as a career prosecutor, not a political figure. But the Trump campaign and conservative Web sites called her integrity into question. Any exoneration of Clinton, they said, would be tainted because Lynch was an Obama appointee.

So the Justice Department and the F.B.I. together plotted an unusual strategy. Over weeks of meetings, they discussed a plan in which Comey and Lynch would appear together at a news conference. After announcing the F.B.I.’s recommendation and the Attorney General’s acceptance of it, they would affirm their mutual confidence in the thoroughness and integrity of the investigation. Given the public appetite for more information, officials also considered sending a limited summary of their findings to the inspector general for the intelligence community. He had referred the matter for investigation in the first place, and could choose to make the summary public.

“It hadn’t all been sketched out,” a former Justice Department official familiar with the matter told me. “But there were conversations about how it could go. There were these discussions between the buildings, leadership to leadership. Everyone knew how this rolled out was really important.”

Comey had his own ideas. Unbeknownst to his Justice Department colleagues, Comey had resolved to proceed alone with the announcement. Since May, he had been holding a parallel series of meetings with top F.B.I. confidants to thrash through his plan. He would publicly announce—and explain—the Clinton decision without Lynch at his side. “We had discussions for months about what this looked like,” Michael Steinbach, who retired as the F.B.I.’s executive assistant director for national security in February, 2017, said. “This, for us, was the best course of action, given the political situation that we were in—for us to do it independently.”

As Comey saw it, according to Steinbach and others familiar with his thinking, the public doubted Lynch’s independence and would be less likely to accept the decision if she were involved in announcing it.

Comey and his aides had another motivation for acting alone. In their view, the American people were entitled to hear the investigators’ views of Clinton’s conduct, something they believed Lynch would not allow. Justice Department policies frown upon officials commenting on investigations, especially if they are making subjective remarks about people whom prosecutors have declined to charge. But with Election Day just four months away, F.B.I. officials felt that it was essential to provide a fuller accounting “that allowed the American people to make an informed decision,” Steinbach said. “Our concern, as we got closer to the election, was to make sure that the American people understood we found no evidence of a crime but we did find evidence of misconduct.’’

F.B.I. officials began drafting a lengthy statement that explained their recommendation not to prosecute but was, nevertheless, harshly critical of Clinton. “For the director to get that out, he’s either doing it alone or he’s not doing it,” Steinbach told me. “D.O.J.’s not going to let it happen.”

Then, on the evening of June 27th, former President Bill Clinton and Lynch both happened to be on the tarmac at the Phoenix Sky Harbor International Airport, and the ex-President strode aboard her government plane. When news of the visit inevitably spilled out, both Lynch and Clinton insisted that they’d merely discussed golf and family matters during a thirty-minute conversation.

For those who felt that the Obama Administration was doing everything it could to help Hillary Clinton win, the encounter was conclusive proof. “SNAKES ON A PLANE,” the New York Post screamed. “Bill’s shady meeting taints probe.” Lynch declined to recuse herself from the case but said that she fully expected to accept whatever recommendation the F.B.I. agents and career prosecutors made.

The tarmac episode reinforced Comey’s conviction to act on his own. The F.B.I. interviewed Clinton the following Saturday, July 2nd. Justice Department officials settled in to wait for a draft of the F.B.I.’s report.

Instead, at about 10:30 A.M. on July 5th, Justice Department officials received an informal heads-up: in thirty minutes, Comey was going to hold a live-televised press briefing at F.B.I. headquarters. Before stepping in front of cameras, Comey sent an e-mail to all F.B.I. employees with a copy of his prepared remarks, and an explanation of why he was speaking so freely and on his own. “I am doing that,” Comey wrote, “because I think the confidence of the American people in the FBI is a precious thing, and I want them to understand that we did this investigation in a competent, honest, and independent way.”

Moments later, Comey delivered what he called “an update on the F.B.I.’s investigation.” He told reporters, “This is going to be an unusual statement in at least a couple of ways. First, I’m going to include more detail about our process than I ordinarily would, because I think the American people deserve those details in a case of intense public interest. And, second, I have not coördinated this statement or reviewed it in any way with the Department of Justice or any other part of the government. They do not know what I’m about to say.”

Comey then described Clinton as “extremely careless” in handling “very sensitive, highly classified information.” As “any reasonable person” in her position “should have known,” Comey declared, a private, unclassified e-mail server “was no place for that conversation.” Despite these statements, Comey concluded that, because there was no evidence of intentional misconduct or efforts to obstruct justice, “no reasonable prosecutor would bring such a case.”

Late the following afternoon, Lynch met with the F.B.I. director, agents, and prosecutors for their formal briefing. In a two-sentence statement, the Justice Department announced that the Attorney General had accepted their “unanimous recommendation.”

Partisan outrage was immediate. Conservative media and Trump surrogates accused Comey of protecting Clinton and preventing rank-and-file F.B.I. agents from pursuing the truth. During nine hours of congressional hearings in which Comey elaborated further on his opinions of Clinton’s conduct, Republicans repeatedly questioned his reasoning for ending the investigation without charges.

Perhaps more worrisome to Comey was the rising discontent within the F.B.I. The retired assistant director James Kallstrom, a Trump backer who had run the New York field office from 1995 to 1997, became a fixture on Fox News and Fox Business, where he attacked Comey’s “nonsensical conclusion” in the Clinton probe and highlighted the “disgust” of “hundreds” of active and retired agents, including some “involved in this thing” who “feel like they’ve been stabbed in the back.” Kallstrom said, “I think we’re going to see a lot more of the facts come out in the course of the next few months. That’s my prediction.”

For their part, Justice Department officials were incredulous at Comey’s decision to proceed without them. On Tuesday, in his Comey memo, Rosenstein said that the F.B.I. director was “wrong to usurp the Attorney General’s authority” by announcing “his own conclusions about the nation’s most sensitive criminal investigation.” He added, “It is not the function of the Director to make such an announcement,” and “the Director ignored another longstanding principle: we do not hold press conferences to release derogatory information about the subject of a declined criminal investigation.”

A recent report in the Times raised the prospect of another factor in Comey’s calculations. Early last year, another F.B.I. investigative team had found a memo or e-mail hacked by the Russians in which a Democratic operative expressed confidence that Lynch would protect Clinton. According to the Times, Comey worried that if Lynch were involved in the Clinton announcement and the Russians leaked the document, then voters would not trust the inquiry.

But Comey did not confront Lynch, demand that she recuse herself, or raise the matter with the Deputy Attorney General, Sally Yates, former Justice Department officials told me. Instead, he sent an aide to confer with David Margolis, a respected senior Justice Department official, who has since died. Margolis never raised the issue with department leadership. Two former officials who have seen the document told me that it was never a real concern. Comey and his defenders, they insisted to me, are now engaged in “revisionist history.”

In May, 2016, just as the F.B.I.’s investigation into the Clinton e-mails was nearing its final stages, a young woman in Indiana named Sydney Leathers received a Facebook message from someone she did not know.

Three years earlier, Leathers had earned notoriety as Anthony Weiner’s most famous sexting partner. Leathers, then a twenty-three-year-old college student, had come forward, at first anonymously, with details about her online relationship with the disgraced former congressman, who had gone by the screen name Carlos Danger. Leathers’s story inspired countless tabloid headlines and ended Weiner’s political comeback as a candidate for mayor of New York City. Leathers quickly cashed in, selling her story to tabloid media, letting “Inside Edition” record her cosmetic-surgery makeover, starring in porn films, and charging for phone sex and Webcam services.

The messages Leathers received in 2016 were from someone who identified herself as a fifteen-year-old in North Carolina. The sender said she had been sexting with Weiner, but Leathers was skeptical. “I just thought it was a crazy person,” she told me.

Leathers changed her mind after the girl sent screen shots from months of exchanges with the former congressman. The teen-ager wanted to go public, but Leathers urged her to call the police instead. “I don’t claim to be a morality queen,” Leathers said. “I don’t care if he was sexting another adult. But, if it’s a child, it’s another story. I felt a little protective of her.”

After it became clear that the teen-ager was determined to tell her story, Leathers said she shifted to “damage control.”

“How can I at least make you some money?” she said she asked the teen-ager. “I basically said, ‘The only way you should do this is if they pay you.’ Certain outlets will pay you to talk, and I had made deals with a lot of them.” Leathers’s agent alerted dailymail.com, the online version of a British tabloid with which she’d previously done business. Both Leathers and the girl received a sizable fee; the teen’s father, an attorney, helped negotiate her payment.

On July 30th, Leathers took another step. She had not communicated with Weiner for years, but she decided to send him a private Facebook message that amounted to a half-warning, half-scold:

This is super awkward but you need to know something. There’s a 15-year-old girl named [redacted] messaging me and she’s claiming you guys sext and skyped. And that you know how old she is. For once I’m keeping my mouth shut. I want nothing to do with this. Frankly, I hope it isn’t true. But she showed me a screenshot that looks legit to me. How have you not learned your lesson? This is another level of fucked up. I suggested to her not to talk to the press so you’re welcome but you may want to refrain from messaging anyone under 18 for gods sake. If she is really someone you’ve been talking to, you better cut that off quickly. She’s talking about potentially messing with Hillary’s campaign. I am kind of pissed to be put in this situation to be honest.

The Daily Mail story appeared on September 21st. The twenty-two-hundred-word article was accompanied by dozens of screen captures, displaying half-clad photos and suggestive texts that Weiner had sent the teen-ager, a high-school sophomore whose name was withheld. She told the Daily Mail that she had contacted Weiner, then fifty-one, in late January, 2016. During online video chats, she said, Weiner had invited her to undress and masturbate. She said he’d urged her to engage in “rape fantasies.” The girl’s father said that he’d learned of the relationship in April but did not alert the police because his child believed the relationship was “consensual” and “I didn’t want to exacerbate anything that she has mentally going on.” The article included four pictures of Weiner’s wife, Huma Abedin, including one of her with Hillary Clinton.

Abedin was perhaps Clinton’s closest aide, often described as a surrogate daughter. She had met Clinton in 1996, while she was a White House intern, and spent her entire adult life working for her. When Abedin married Weiner, in 2010, Bill Clinton officiated at the ceremony; the couple had a son a year later.

When the F.B.I. began investigating the Clinton e-mails, in 2015, agents had taken special interest in Abedin because she was one of the four aides who served as conduits for most of Clinton’s State Department messages, screening them, forwarding them, and printing them out for her boss. When agents interviewed Abedin on April 5, 2016, she told them that she had used Yahoo and state.gov accounts while working in the State Department, as well as an e-mail address on Clinton’s private basement server, huma@clintonemail.com.

They asked Abedin what devices she used for e-mail, at work and home, and whether she’d kept any archive. According to F.B.I. notes of the interview, Abedin said that she had already turned over everything she had to the State Department. The agents did not ask to inspect any personal computers at her Manhattan apartment, where she lived with Weiner and their son. Her lawyer would later publicly insist that Abedin had no idea that her exchanges with Clinton were on his laptop. The couple has since separated.

The Daily Mail story raised the possibility of serious criminal charges for Weiner. If he had encouraged an underage female to take explicit photos or video of herself, he could be charged with producing child pornography, a felony that carries a minimum prison term of fifteen years. F.B.I. agents in New York immediately began investigating.

On September 26th, after federal prosecutors in New York obtained a search warrant, and the F.B.I. collected Weiner’s iPhone, iPad, and laptop. Agents began examining the computer—a silver, 15.6-inch 2015 Dell Inspiron 7000—for any pictures, videos, or other evidence involving Weiner’s teen-age sexting partner. An agent sorting through the contents of the hard drive came across a jolting find: a State Department memo and some e-mails between Abedin and Hillary Clinton. The documents were not covered by the sex-crimes warrant, which meant that the F.B.I. had no legal right to examine them.

The Presidential election was five weeks away.

The agent went to the office of the U.S. Attorney for the Southern District of New York for guidance. Prosecutors there wanted no part of the e-mail case, which had been staffed by a special team of agents, F.B.I. analysts, and Justice Department lawyers working out of F.B.I. headquarters, in Washington. The New York prosecutors told the agent to seek advice from that team. They said nothing to their own bosses at Justice Department headquarters.

By October 3rd, senior officials at the F.B.I.—including Comey—had been alerted that the Weiner laptop contained an unknown number of Clinton e-mails. By this point, the e-mail controversy had receded as an issue in the Presidential race. Any news of the discovery would surely have profound consequences for the Clinton campaign, especially as the election drew ever closer. Yet, over the following three weeks, F.B.I. agents proceeded unhurriedly with their investigation, on the premise that what they knew of the discovery was not, as one official put it to me, “investigatively significant.”

F.B.I. officials decided not to share news of the new e-mails on the laptop with the Justice Department prosecutors who had worked with them on the Clinton case. A former high-ranking Justice Department official, who dealt frequently with the F.B.I., blamed the failure on institutional distrust. “There is a general tendency, with everything at the Bureau, to keep things inside the Bureau until they figure out what to do,” he told me.

Without the involvement of their Justice Department colleagues, the F.B.I. eschewed options that might have expedited matters. Former Justice Department officials familiar with the case told me that the F.B.I.’s failure to move more quickly in this phase of the investigation represented a serious blunder. “It probably would have helped to have the prosecutors on the investigation involved at the earliest moment,” the former high-ranking official told me.

A crucial question was whether the discovery of the first few e-mails and a State Department document was sufficient to obtain a new search warrant to locate and examine all the Clinton messages right away. The former federal magistrate judge John Facciola, now an adjunct law professor at Georgetown University, told me that he would have granted such a warrant request, even after the discovery of just a “handful” of Clinton e-mails. The F.B.I.’s earlier investigation had revealed that some messages from the Clinton server contained improperly stored classified information, Facciola noted. “If the headers show transmittal from Clinton to Abedin, it follows as night to day that others bearing that header may also be classified, and we have a right to search. What more you need than that, I don’t know.”

Former Justice Department officials told me that they also could have sought consent from Weiner and Abedin to examine the e-mails without a warrant. Lawyers for both told me that they were never asked and would have readily acceded. F.B.I. officials, who were not fond of consent agreements, reportedly did not do this because they worried that Weiner would have sought concessions on any sex-crime charges; lawyers familiar with the matter dismiss the notion that he had any bargaining leverage.

Officials at F.B.I. headquarters instructed the New York agent examining Weiner’s hard drive for evidence of sex crimes to continue his work as before, and to keep a log of any further Clinton e-mails he came across.

By all accounts, this phase of the process went slowly. The software that the Bureau used to inventory the contents of Weiner’s laptop kept crashing. It would take about ten days before agents were able to retrieve a complete record of the messages saved on the laptop, showing dates, senders, and recipients. But, even then, the F.B.I. did not immediately seek a warrant.

By mid-October, inside the U.S. Attorney’s office in Manhattan, the handful of officials who knew about the discovery of the Clinton e-mails were openly wondering what was going on. Any effort to obtain a second warrant would have to go through their office, and they had heard nothing.

On Friday, October 21st, Joon Kim, the Deputy U.S. Attorney for the Southern District, called an official in the Deputy Attorney General’s office at Justice Department headquarters to ask what was being done about the Clinton e-mails on Weiner’s laptop. Recognizing the importance of the call, Kim wrote a memo noting it.

For Justice Department officials, the call was the first they’d heard of the e-mails. The following Monday, F.B.I. and Justice Department lawyers finally gathered in Washington to discuss what to do. The New York agents had finished tabulating the e-mails between Abedin and Clinton, and they numbered in the thousands. F.B.I. investigators who had been part of the Clinton inquiry decided that they were eager to examine the new e-mails.

Throughout their yearlong investigation, F.B.I. investigators had been frustrated by their inability to locate all of Clinton’s e-mails, especially those sent during the first eight weeks of her tenure as Secretary of State, a troubling gap in their records. Some of those now appeared to be on Weiner’s laptop, and they might reveal incriminating information about Clinton’s motivation in setting up the private server in the first place. Investigators recognized that, in all likelihood, the new e-mails would not change the decision to close the case without charges. Most were probably duplicates of what the F.B.I. had already seen. It seemed improbable that agents would find written proof that Clinton intended to violate the law. Still, it seemed foolish not to examine the e-mails. The Justice Department lawyers readily agreed to seek a court order, leading Comey’s deputies to schedule a meeting with their boss on the morning of October 27th.

More than three weeks had passed from the time that Comey and his top deputies had been alerted to the initial discovery of Clinton e-mails on Weiner’s laptop. Yet, in his congressional testimony, Comey described what he heard in his briefing that Thursday morning as a startling new development. “The Anthony Weiner thing landed on me on October 27 and there was a huge—this is what people forget—new step to be taken,” he said. “We may be finding the golden missing e-mails that would change this case. If I were not to speak about that, it would be a disastrous, catastrophic concealment.”

Comey immediately approved plans to seek a new warrant. Such warrants are typically obtained in secret before a magistrate judge and not made public, but Comey told his deputies that he wanted to send a letter to congressional leaders the next day.

Justice Department policies bar employees from interfering with elections and discourage taking any action that might be perceived as interference in the weeks before votes are cast. Election Day 2016 was less than two weeks off; early voting had already begun in thirty-six states.

Comey would justify his October 28th disclosure as a matter of moral obligation: he’d told two congressional committees that the investigation was complete, and plans to review the new material meant that that was no longer true. Before Congress last week, he characterized his decision as a choice between “speak” and “conceal.”

In his memo released on Tuesday, Rosenstein scorned this characterization. “ ‘Conceal’ is a loaded term that misstates the issue,” he wrote. “When federal agents quietly open a criminal investigation, we are not concealing anything; we are simply following the longstanding policy that we refrain from publicizing non-public information. In that context, silence is not concealment.”

There was another motivation for Comey’s decision to “speak”: F.B.I. officials feared that news of the new e-mails would leak out, damaging the Bureau and its director. The primary source of anxiety was the F.B.I.’s own New York field office, which was handling the Weiner case and harbored deep pockets of anti-Clinton sentiment. New York agents had already been griping to the media about headquarters’ curbs on their investigation of the Clinton Foundation. Two prominent Trump surrogates with close local F.B.I. ties—Kallstrom and Rudy Giuliani, a former U.S. Attorney and New York mayor—had for weeks been warning about agent fury over Comey’s decision in the e-mail case. Lately, Giuliani had been chortling on Fox News about the Trump campaign’s plans for “some pretty big surprises” that “you’re going to hear about in the next few days.” (He would later claim that he had advance knowledge of the new e-mails.)

Comey and his aides had considered saying nothing about the discovery until agents could assess its significance, but only if their task would be completed by the election. “If we were of the belief we’d get through it before the election, we wouldn’t have said anything,” Steinbach said. But, given the number of Clinton-related messages on Weiner’s laptop (the F.B.I. had identified forty-nine thousand as “potentially relevant”), no one felt confident promising the F.B.I. director that they could be examined in time. “I was thinking, I hope we can get this done in a couple of months,” Steinbach told me.

Mark Pollitt, a Syracuse University information-studies professor who ran the F.B.I.’s national computer-forensics lab program during his career as a special agent, said that this mistaken judgment was likely born of excessive bureaucratic caution. “If you know this one’s going to go to the director and Attorney General and maybe the President of the United States, we’re going to give them the worst-case scenario so we don’t get yelled at for dragging our feet,” he said. “I’m not going to say I can get it done in a particular time frame and then not make that deadline.”

This time, Comey decided to alert the Justice Department of his plans. Officials there tried vigorously to dissuade him from sending the letter. Heated discussions took place between a Comey deputy and an official in the Deputy Attorney General’s office, acting as surrogates for their bosses. The Justice official retrieved a transcript of Comey’s congressional testimony to point out that the director had never explicitly promised an update of every development in the case. Comey’s deputy acknowledged that this was the case but said the director’s view was that it didn’t matter; he had a “duty” to correct the “impression” he’d left that the F.B.I.’s work was done. According to the former Justice official, Comey’s deputy also made clear that the F.B.I. director was “very concerned” about a leak—that the news “was coming out anyway.”

The Justice official reminded Comey’s deputy about department policy regarding overt investigative steps before an election. Criticism was inevitable, he argued; the best defense was to consistently follow the normal process. The F.B.I.’s response: “This one’s different.”

“This wasn’t a policy-position disagreement,’’ the former Justice Department official told me. “Comey felt this was his credibility on the line. He was the one who had testified before Congress. Their view is, ‘We get the policy and procedures. But he’s the one who had to personally suffer the fallout if he doesn’t update the Hill. It’s his ass in the sling.’ ”

Lynch and Yates had the power to order Comey not to send the letter. But Comey’s high-minded characterization of his “obligation” made that option seem perilous to senior Justice Department officials. If they gave Comey such an order, it wasn’t clear that he would comply. And if he did, there was a chance that it could be portrayed as the Attorney General ordering the F.B.I. director to hide information from Congress. None of that would play well, especially in the aftermath of the tarmac incident. So the Justice Department officials stuck to pleading through staff.

Comey deliberated with his deputies into Thursday night about exactly what to say, generating multiple drafts of his letter. The first ran just two sentences; later versions offered far more detail, then somewhat less, as Comey and his staff struggled to find the right balance. Steinbach joined a conference call about the language while shopping for Halloween pumpkins in Virginia with his daughter. “The intention was to write a statement that was as politically neutral as possible—that did not allow for incorrect inference,” one person familiar with the situation told me. Predictably, that would prove impossible.

During a conference call the next morning with a half-dozen participants, F.B.I. officials read portions of their draft to their Justice Department counterparts, who argued that the letter was certain to be used to political advantage by Trump. They urged Comey to add language that made clear that the director was making the disclosure because of the obligation he felt from his testimony, not because of the gravity of the discovery—and that the e-mails had been found on the laptop of an aide’s husband, not in Clinton’s possession.

Comey declined to make any changes. He dispatched his three-paragraph letter to sixteen congressional leaders shortly before noon on Friday, October 28th. It disclosed the discovery of new Clinton e-mails “that appear to be pertinent,” as well as plans to “assess their importance,” before noting, “The FBI cannot yet assess whether or not this material may be significant, and I cannot predict how long it will take us to complete this additional work.”

Comey explained his actions more fully in an e-mail to F.B.I. staff:

Of course, we don’t ordinarily tell Congress about ongoing investigations, but here I feel an obligation to do so given that I testified repeatedly in recent months that our investigation was completed. I also think it would be misleading to the American people were we not to supplement the record. At the same time, however, given that we don’t know the significance of this newly discovered collection of emails, I don’t want to create a misleading impression. In trying to strike that balance, in a brief letter and in the middle of an election season, there is significant risk of being misunderstood.

Within hours, “law-enforcement officials” disclosed to the press that the “unrelated case” was the Weiner sexting investigation. Trump, who’d previously been bashing Comey, celebrated the news at a New Hampshire rally. Clinton’s “corruption is on a scale we have never seen before,” he declared, amid chants of “Lock her up!” “We must not let her take her criminal scheme into the Oval Office.” Democrats, who had praised Comey since July, were outraged. A Clinton spokesman blamed Comey for “unleashing a wildfire of innuendo.”

Clinton’s campaign set up a war room at its Brooklyn headquarters to respond to the news. The campaign highlighted an open letter signed by ninety-nine former Justice Department officials from both parties who declared that they were “astonished and perplexed” by Comey’s actions. “The strategy was not to debate what Comey had done,” the Clinton pollster Joel Benenson told me. “The strategy was to aggressively discredit his actions with these bipartisan prosecutors.”

As the campaign—and debate over Comey’s actions—churned on, the F.B.I. faced enormous pressure to complete its review of the new e-mails before Election Day, on November 8th. The government obtained its search warrant on Sunday, October 30th, two days after Comey’s letter, and agents immediately began scouring a copy of Weiner’s hard drive, which an agent had already carried to Washington from New York.

Exactly how thousands of Clinton e-mails ended up on Weiner’s laptop remains somewhat mysterious. In his testimony last week, Comey said that Abedin had forwarded “hundreds and thousands” of e-mails—including some containing classified information—to her husband’s e-mail account, so that Weiner could print out the messages for delivery to Clinton. But two sources familiar with the matter told me that Abedin forwarded only a handful of Clinton e-mails to her husband for printing. Most of the old Clinton messages found on the laptop trace to backups of Abedin’s BlackBerry, which might have been first stored on a desktop computer at the couple’s home before ending up on Weiner’s laptop inadvertently, as part of a bulk transfer of old files. After Abedin’s lawyer pressed the F.B.I. to clarify the matter, and I wrote an article about it, the Bureau released a letter correcting Comey’s testimony.

F.B.I. agents had told their bosses that reviewing the new e-mails would take them well past Election Day. But, as the ten-member team began working around the clock, the process quickly accelerated. The F.B.I. agents rapidly ruled out huge batches of messages that weren’t work-related, “de-duped” thousands of e-mails they’d seen before, and isolated the relative few—about six thousand, according to Comey—that required individual scrutiny. Potentially classified e-mails went to analysts for review.

Midway through a final all-night push, on Saturday, November 5th, two agents left F.B.I. headquarters for a pizza-and-soda run. Outside, they found lime-green spray-painted graffiti near the building’s main entrance, some of it covering the F.B.I. seal. It read “ASSHOLE” and “CORRUPT.”

At about 2:30 A.M. on Sunday, the F.B.I. agents finished their work, and the team’s leader dispatched a message to their bosses. They had found new State Department messages but none, after all, from the missing period at the start of Clinton’s term, and nothing that suggested a criminal motive. Twelve e-mail threads contained classified information; none of them were new.

That afternoon, Comey wrote to Congress again, revealing that the F.B.I. had completed its review without finding anything to change the conclusions that he had announced back in July.

The days after Comey’s revelation had been devastating to Clinton’s campaign. “Comey put a hole through the wall, and Trump drove a Mack truck through it,” Benenson told me. The news dominated the home-stretch coverage; even the announcement that the review was over didn’t help. “You are in no good position at that point,” Benenson said. “Any discussion of e-mails and investigations is going to be a losing proposition.”

Trump’s campaign made the most of the Comey letter. “Decades of lies, coverups, and scandal have finally caught up with Hillary Clinton,” a new Trump TV ad intoned. “Hillary Clinton is under F.B.I. investigation again, after her e-mails were found on pervert Anthony Weiner’s laptop. Think about that! America’s most sensitive secrets, unlawfully sent, received, and exposed by Hillary Clinton, her staff, and Anthony Weiner. Hillary cannot lead a nation while crippled by a criminal investigation!”

“The Trump campaign was using it to the hilt,” Benenson said. “They took Comey’s statement, and they drove it. The most effective thing they did with it is to say, ‘This will never end. If she’s President, it will never end.’ ”

The “Comey effect” set in quickly. In a uniquely volatile electorate, enamored of neither candidate, weighing Trump’s temperament versus Clinton’s ethics, many of those who had finally been ready to vote for the Democrat fled. Her numbers slipped in key states. “It was enough of a lingering concern that at the end they said, ‘Screw it. I’m not going to vote for her,’ ” Benenson said. “They went with the third-party candidate or stayed home.”

Many analysts concluded that Comey’s actions tilted the Presidency to Trump. Nate Silver, the polling guru at the Web site FiveThirtyEight, said that Comey’s letter produced a swing of about three points in the popular vote in the handful of states that won Trump the Presidency. In a post-campaign interview, the Trump pollster Tony Fabrizio put it this way: “When you really drill down on this election, if you change the vote in five counties, four in Florida, one in Michigan, we’d be having a totally opposite conversation right now.”

F.B.I. officials remain bitter at how Clinton and her supporters have blamed them for Trump’s election. “I don’t find it credible,” Steinbach said. “It’s a mess she helped create from start to finish, with start being when she elected to use a private server. Even if you were to assume the investigation influenced the election, her actions created the environment. You can second-guess how it played out. But our guiding principle was to protect the American people and the Constitution of the United States.”

In January, the Justice Department’s inspector general announced that he would review charges that Comey’s public disclosures about the Clinton investigation violated department policies. Comey issued a statement saying that he welcomed “thoughtful evaluation and transparency” on the matter. Some of Comey’s friends and colleagues had weighed making public a letter of support for him, before eventually deciding against it. In conversations with reporters, they began seeking to explain his actions.

Some of the most withering criticism of Comey focussed on his refusal, before the election, to disclose the F.B.I.’s investigation into the possibility of collusion between the Russian government and Trump associates—even as he spoke at length about Clinton’s e-mails. In late March, quoting two anonymous sources, Newsweek reported that Comey had actually wanted to talk about the Russian political meddling, through a personal, bylined newspaper column, but the White House had blocked him from doing so. People familiar with the matter told me that the Obama Administration had wanted to respond in a more direct way, through an official finding. That came on October 7th, through a statement about Russian hacking from the secretary of Homeland Security and the director of National Intelligence. Comey declined to be included on the statement, telling Administration officials that he believed it was too close to the election.

During conversations I had with Richman, he began to hint at something in the Russian e-mail hack that had influenced Comey’s decision to go it alone with his July 5th announcement on the Clinton inquiry. “It’s not just the stupid tarmac visit,” he told me in late February, 2017. “You don’t get to always defend yourself when you’re in his position.” Two months later, the Times disclosed the existence of the document claiming that Lynch would protect Clinton.

Last week, Comey finally got his chance to defend himself. Called before the Senate Judiciary Committee, he offered an emotional account of his handling of the e-mail investigation but then made his misstatement about Abedin forwarding “hundreds and thousands” of e-mails to Weiner. This week, after F.B.I. officials clarified the issue, I asked the Bureau another question: Why hadn’t agents, who had access to Abedin’s e-mails and could, presumably, see that she had forwarded two classified messages to her husband, taken the opportunity to examine his laptop much earlier, as part of the original e-mail inquiry? If they had done so, what ensued in October might never have happened. The F.B.I. declined to comment.

On Wednesday, in a farewell letter e-mailed to Bureau employees, Comey said he was not dwelling on his firing and urged his former colleagues not to, either. “I have long believed that a President can fire an FBI Director for any reason, or for no reason at all,” Comey wrote. “I have said to you before that, in times of turbulence, the American people should see the FBI as a rock of competence, honesty, and independence.”

This piece is a collaboration between The New Yorker and ProPublica.

Peter Elkind is an investigative reporter based in Texas. He is the co-author of “The Smartest Guys in the Room: The Amazing Rise and Scandalous Fall of Enron.”