On May 9, 2012, the executives of Fannie Mae, the beleaguered mortgage finance company, finally went public with good news: After three and a half years as a ward of the state, it was profitable again.

Since being bailed out by the government at the height of the financial crisis, Fannie had drawn $116 billion from the Treasury. But it had been clear for months inside the company that things were looking up. In fact, when Susan McFarland, chief financial officer of Fannie, announced the earnings, she said, “We expect our financial results for 2012 to be significantly better than 2011.”

But even as Fannie’s profit report brought hope to shareholders, it also stirred government officials to action. The day after Fannie’s announcement, court documents show, a high-level official at the agency that regulates the lender sent an email to a colleague. In it, the official asked for legal advice regarding a proposed change to the repayment terms of the government’s bailout of Fannie Mae and its brother mortgage backer, Freddie Mac.

Three months later, on a quiet Friday in August, that change came: The Treasury Department would take all of the companies’ profits for its general-purpose fund, helping to finance government operations and reduce debt. The shift would better protect taxpayers, the government said.