WASHINGTON — Year after year, both in his messy personal life and his brazen theft of classified documents from the National Security Agency, Harold T. Martin III put to the test the government’s costly system for protecting secrets.

And year after year, the system failed.

Mr. Martin got and kept a top-secret security clearance despite a record that included drinking problems, a drunken-driving arrest, two divorces, unpaid tax bills, a charge of computer harassment and a bizarre episode in which he posed as a police officer in a traffic dispute. Under clearance rules, such events should have triggered closer scrutiny by the security agencies where he worked as a contractor.

Yet even after extensive leaks by Pfc. Bradley Manning in 2010 and Edward Snowden in 2013 prompted new layers of safeguards, Mr. Martin was able to walk out of the N.S.A. with highly classified material, adding it to the jumbled piles in his house, shed and car.

A federal judge in Baltimore ruled on Friday that Mr. Martin, 51, must remain jailed on charges of stealing government documents and mishandling classified information over two decades. Prosecutors say they will add new charges under the Espionage Act. Mr. Martin, whose arrest in August was disclosed by The New York Times this month, has admitted to taking the material but denies giving secrets to anyone else.