KABUL—On a day when Taliban and U.S. officials met in the Gulf state of Qatar for another round of talks to end the Afghan war, insurgents detonated a captured Humvee loaded with explosives at the gate of a base operated by the country’s intelligence agency and stormed the compound, spraying gunfire.

By the time the Taliban assault in Maidan Wardak province was over on Monday, dozens of agency personnel lay dead in what even by the war’s gruesome standards was a stunning loss of life and a deep embarrassment to the country’s...