Virginia Gov. Terry McAuliffe speaks to the media about the new state budget, which he will get from the General Assembly next week and will have seven days to accept or amend it. (Steve Helber/AP)

Virginia seemed hopelessly locked in a partisan budget and Medicaid standoff, careening toward its first-ever government shutdown. Yet for weeks behind the scenes, a handful of lawmakers were hammering out a deal.

They were wrapping up that work when a Democratic state senator suddenly resigned, giving one side in the stalemate a convenient — if numerically unsound — excuse to cave. The budget drama was over. For about a day.

Then an obscure bit of budget language that has been on the books for a year incited fear among rank-and-file Republicans that they were about to get snookered — by Gov. Terry McAuliffe (D) and maybe even members of their own party.

Conservative Republicans revolted. The deal so painstakingly hashed out between House and Senate leaders began to crumble. After hours of frenzied closed-door negotiations in the Capitol, Republicans finally united to pass a budget one minute before midnight Thursday — but with an anti-Medicaid amendment that GOP leaders insisted was unnecessary.

Those twists and turns do not end the budget saga; McAuliffe still can amend or veto the spending plan. But they spotlight Richmond’s volatile political mood, newly rattled by the stunning primary loss last week by House Majority Leader Eric Cantor (R-Va.) to an underfunded tea party-backed challenger.

Even as the GOP took full control of the legislature, thwarting Medicaid expansion and dimming the legislative prospects for McAuliffe’s entire term, the Republican Party’s insecurities and internal fractures were on vivid display. Conservative Republicans, already suspicious that McAuliffe will attempt through executive order what he cannot win through the legislature, made it clear that they also distrust the GOP pragmatists in their midst.

“I respect people who want Medicaid expansion. I don’t have any problem with bringing that thing forward and battling it out and having a debate on the idea,” said Sen. Richard H. Black (R-Loudoun), who led the revolt and inspired the Twitter hashtag #blackorbust. “What I have a problem with is the kind of politician that tells the people you’re doing one thing and then does the opposite through the back door. To me, that’s sleazy politics.”

Black was speaking not only about Democrats, but also Republicans who tried in vain to assure him that the budget language he objected to was not, in fact, a loophole that McAuliffe could exploit to expand Medicaid on his own.

“I find it difficult to believe that the leadership of both parties were not keenly aware of the impact of that language,” Black said.

The language that set off the uproar reads: “There is hereby appropriated sum sufficient nongeneral funds for such costs as may be incurred to implement coverage for newly eligible individuals pursuant to . . . the Patient Protection and Affordable Care Act.”

It was carried over from budget language adopted last year, under then-Gov. Robert F. McDonnell (R). Its ostensible purpose is to authorize additional Medicaid spending if the state Medicaid commission certifies that certain reforms, which the legislature insisted must come before expansion, have been accomplished.

But rank-and-file Republicans are worried that McAuliffe might try to use that language to argue that the money has already been appropriated for him to expand Medicaid to 400,000 uninsured Virginians without the legislature’s authority. The federal government has promised to pay most of the $2 billion-a-year cost, but Virginia’s constitution requires legislative approval of all spending — even with pass-through money from Washington.

The budget language drew little notice until Steve Albertson, a Republican activist from Stafford and a member of the party’s state central committee, raised questions about it last week on his blog, the Bull Elephant.

“Folks, if Republicans are serious about stopping Medicaid expansion, and about keeping this lawless executive Terry McAuliffe from doing it on his own, then Republican legislators must act,” he wrote. “If conservatives in the Senate vote for the House budget without fixing this backdoor for the governor, then they will be held responsible for allowing Terry McAuliffe to get away with expansion.”

His blog post concluded with: “We’re watching.”

If those words were worrisome to GOP legislators when they appeared online Tuesday morning, they were positively ominous by Tuesday night, when Cantor lost to economist Dave Brat, an anti-establishment upstart. Cantor’s spectacular comeuppance had Republicans in Richmond looking over their shoulders at a time when they should have been celebrating a coup.

Just a day earlier, a conservative Democratic senator from Southwest Virginia resigned, handing Republicans a 20-to-19 advantage in what had been an evenly split chamber. With the House of Delegates already dominated by the GOP, the party suddenly had full control of the General Assembly.

Sen. Phillip P. Puckett’s exit ignited controversy, with some Democrats claiming that the GOP had “bribed” him to leave with a job offer for him and a judicial appointment for his daughter. Puckett said there was no quid pro quo but quickly withdrew his bid for a top tobacco commission post.

Even amid that firestorm, the anti-expansion forces basked in what looked like a sudden win.

Momentum had actually turned their way starting in late May, when state budget forecasters announced a projected $1 billion shortfall, a figure that grew last week to $1.5 billion. McAuliffe used that news to beat the drum for expansion, saying the state needed the federal Medicaid money more than ever.

But the shortfall convinced House and Senate budget leaders that it was time to set aside Medicaid and nail down a budget. House Appropriations Committee Chairman S. Chris Jones (R-Suffolk), who opposes Medicaid expansion, and Senate Finance Committee Co-chairman Walter A. Stosch (R-Henrico), who supports it, started talking almost daily.

Working with state budget staffers, they cooked up what they thought was the most painless way to make the diminished financial projections line up with expenses. They were nearing completion when Puckett’s resignation last Monday thrust everything into overdrive.

As a matter of pure numerical strength, Puckett’s exit was no reason for pro-expansion forces to fold. Because three moderate Republican senators support a form of Medicaid expansion, pro-expansion senators were still up 22 to 17 after he left.

But his resignation Monday shook everything loose.

“Everybody’s been looking for an exit,” said Sen. William M. Stanley Jr. (R-Franklin). “It’s like a fire in a movie house.”

Before the day was up, the newly empowered Senate Republicans had ordered members to return to Richmond on Thursday. And by Monday night, news was leaking that Senate budget negotiators had agreed to pass a budget without Medicaid expansion.

There was little time for Republicans to savor the surrender.

By Tuesday morning, the Bull Elephant’s provocative blog post had hit. That prompted Black to start working on a budget amendment that would prohibit expansion of Medicaid without the legislature’s approval.

Republican leaders in the House and Senate said there was no need for the amendment — and feared that it would scuttle the budget deal that the three pro-expansion Republican senators had signed on to only reluctantly.

Black was not convinced. Nor were conservative legislators, who threatened to vote against the deal without the amendment.

Sen. Thomas A. Garrett (R-Louisa) tweeted, “#blackorbust I WON’T vote for a budget that lacks #dickblack amendment” and, “The full GA should vote up or down on #medicaidexpansion. No tricks” during a long night of closed-door Senate negotiations Thursday.

Conservative Republicans worried that the three moderate Republican senators opposed the amendment to keep an avenue open for McAuliffe or the Medicaid commission to expand without the General Assembly’s approval. There were suspicions about House leadership, too, even though Republican opposition to expansion has been led all year by House Speaker William J. Howell (R-Stafford) and other House GOP leaders.

Some tea party activists contend that the conservative but pragmatic speaker secretly wanted to slip McAuliffe the keys to expansion. Howell’s office dismissed that theory, as did many Republican legislators. But some of those legislators feared that Howell and other House leaders were so bent on getting a budget that they were ignoring the risks posed by the budget language.

Those fears turned a bit of Capitol Medicaid lore on its head. Lobbyists for expansion had been whispering all year that some GOP delegates secretly favored expansion but feared crossing the powerful speaker. Ultimately, the GOP rank-and-file pushed Howell to the right, not the other way around, as it eventually persuaded him to insist on an anti-expansion budget amendment.

“The speaker has never thought there was language in the budget that gave the governor the authority to expand Medicaid unilaterally. But, based on reports that he may try to do so, a lot of members were rightly concerned about the language,” Howell spokesman Matthew Moran said. “House leadership expressed to the Senate in the strongest possible terms that it would be very difficult to secure passage in the House without an amendment.”

Eventually, the three Senate moderates gave in to that pressure, convinced that the budget deal would sink and the state could face a shutdown and the loss of its stellar bond rating if they did not go along.

The Senate passed the budget, and so did the House, sending it on its way to McAuliffe’s desk and whatever new twists and turns Richmond can muster.