– Weeks after the militants seized the city, as fighters roamed the streets and religious extremists rewrote the laws, an order rang out from the loudspeakers of local mosques. Public servants, the speakers blared, were to report to their former offices.

To make sure every government worker got the message, the militants followed up with phone calls to supervisors.

The phone call reached Muhammad Nasser Hamoud, a 19-year-veteran of the Iraqi Directorate of Agriculture, behind the locked gate of his home, where he was hiding with his family. Terrified but unsure what else to do, he and his colleagues trudged back to their six-story office complex. They arrived to find chairs lined up in neat rows.

The commander who strode in sat facing the room, his leg splayed out so that everyone could see the pistol holstered to his thigh. For a moment, the only sounds were the hurried prayers of the civil servants mumbling under their breath.

Their fears proved unfounded. The commander had a tame request: Resume your jobs immediately. A sign-in sheet would be placed at the entrance to each department. Those who failed to show up would be punished.

Meetings like this one occurred throughout the territory controlled by the Islamic State of Iraq and Syria in 2014. Soon municipal employees were back fixing potholes, painting crosswalks, repairing power lines and overseeing payroll. “We had no choice but to go back to work,” said Hamoud. “We did the same job as before. Except we were now serving a terrorist group.”

The disheveled fighters who burst out of the desert more than three years ago founded a state that was acknowledged by no one except themselves. And yet for nearly three years, ISIS controlled a stretch of land that at one point was the size of Britain, with a population estimated at 12 million people. At its peak, it included a 100-mile coastline in Libya, a section of Nigeria’s lawless forests and a city in the Philippines, as well as colonies in at least 13 other countries. By far the largest city under their rule was Mosul.

Nearly all of that territory has now been lost, but what the militants left behind helps answer the troubling question of their longevity: How did a group whose spectacles of violence galvanized the world against it hold onto so much land for so long? Part of the answer can be found in more than 15,000 pages of internal ISIS documents I recovered during five trips to Iraq over more than a year.

ISIS built a state of administrative efficiency that collected taxes and picked up the garbage. It ran a marriage office that oversaw medical examinations to ensure that couples could have children. It issued birth certificates — printed on ISIS stationery. It ran its own department of motor vehicles.

Militants monetized every inch of territory

The documents and interviews with dozens of people who lived under their rule show that the group at times offered better services and proved itself more capable than the government it had replaced.

They also suggest that the militants learned from mistakes that the United States made in 2003 after it invaded Iraq, including the decision to purge members of Saddam Hussein’s ruling party from their positions and bar them from employment. That decree succeeded in erasing the Baathist state, but also gutted civil institutions, creating the power vacuum that groups like ISIS rushed to fill.

A little more than a decade later, after seizing huge tracts of Iraq and Syria, the militants tried a different tactic. They built their state on the back of the one that existed before, absorbing the know-how of its hundreds of government cadres.

One of the keys to their success was their diversified revenue stream. The group drew its income from so many strands of the economy that airstrikes alone were not enough to cripple it. Ledgers, receipt books and monthly budgets describe how the militants monetized every inch of territory they conquered, taxing every bushel of wheat, every liter of sheep’s milk and every watermelon sold at markets they controlled. From agriculture alone, they reaped hundreds of millions of dollars. Contrary to popular perception, the group was self-financed, not dependent on external donors.

More surprisingly, the documents provide further evidence that the tax revenue ISIS earned far outstripped income from oil sales. The U.S.-led coalition, trying to eject ISIS, tried in vain to strangle the group by bombing its oil installations. It’s much harder to bomb a barley field. It was not until last summer that the militants abandoned Mosul, after a battle so intense that it was compared to the worst combat of World War II.

The Ministry of War Spoils

“We dismiss the Islamic State as savage. It is savage. We dismiss it as barbaric. It is barbaric. But at the same time these people realized the need to maintain institutions,” said Fawaz A. Gerges, author of “ISIS: A History.” “The Islamic State’s capacity to govern is really as dangerous as their combatants.”

The day after the meeting, Hamoud, a Sunni, returned to work and found that his department was now staffed 100 percent by Sunnis, the sect of Islam practiced by the militants. His former Shia and Christian colleagues had all fled.

The militants sent female employees home and closed the day care center. They shuttered the legal department, saying disputes would now be handled according to God’s law alone.

But the biggest change came five months into the group’s rule. The change involved the very department Hamoud headed, which was responsible for renting government-owned land to farmers. A 27-page manual outlined the group’s plans for seizing property from the religious groups it had expelled and using it as the seed capital of the caliphate. “Confiscation,” the manual says, will be applied to the property of every single “Shia, apostate, Christian, Nusayri and Yazidi based on a lawful order issued directly by the Ministry of the Judiciary.”

Hamoud’s office was instructed to make a list of the properties owned by non-Sunnis — and to seize them. A ministry was set up to collect and reallocate beds, tables, bookshelves — even the forks the militants took from the houses they seized. They called it the Ministry of War Spoils.

ISIS’ promise of taking care of its own, including free housing for foreign recruits, was one of the draws of the caliphate. As 2014 blurred into 2015, ISIS soldiers set out to remake every aspect of life — starting with the role of women. The militants commandeered a textile factory, which began manufacturing bales of regulation-length female clothing.

Hamoud began taking side streets to and from work to dodge the frequent executions that were being carried out in traffic circles and public squares. In one, a teenage girl accused of adultery was forced to her knees and a stone slab was dropped onto her head. On a bridge, the bodies of people accused of being spies swung from the railing.

But on the same thoroughfares, Hamoud noticed the streets were visibly cleaner than they had been when the Iraqi government was in charge. The street sweepers had not changed. What had was that the militants imposed a new discipline, said a half-dozen employees who worked under ISIS.

Residents also said that their taps were less likely to run dry, the sewers less likely to overflow and potholes fixed more quickly under the militants, even though there were now near-daily airstrikes.

On the western banks of the Tigris River, in a pulverized building, I found an abandoned briefcase that belonged to Yasir Issa Hassan, a young administrator of the Trade Division inside ISIS’ Ministry of Agriculture. The briefcase shed light on the scope of the organization’s revenue machine and offered a blueprint for how it worked.

The financial reports tallied over $19 million in transactions involving agriculture alone.

But perhaps the most lucrative tax was a religious tax known as emzakat/em, which is considered one of the five pillars of Islam. It is calculated at 2.5 percent of an individual’s assets, and up to 10 percent for agricultural production.

It all added up to as much as $800 million in annual tax revenue, said a study by the Paris-based Center for the Analysis of Terrorism.

Though the militants are gone, reminders of ISIS and their style of governance remain. In Tel Kaif, for example, residents recalled how the militants conscripted a committee of electrical engineers to fix an overloaded power grid. They installed new circuit breakers, and for the first time, residents who had been accustomed to at most six hours of electricity a day could now reliably turn on lights.