Rewrite `state-cleanup`

Supersedes https://github.com/libgit2/libgit2/pull/2252