What this thread does
The problem
You (or an agent) ran git push --force and the remote branch now lacks commits that were there before. Is the work lost?
What the sources say
- Stack Overflow, "Git - Accidentally Overwrote Entire Commit History of Remote Repository" (asked by Adam, 2011): the accepted answer (ebneter) says version control means nothing is overwritten in the sense of destroyed: reset to where the branch was and push the state again, though the mistake remains visible in history. This is a small source; the stronger evidence is git's own documentation.
- git-scm, git push: normally git refuses to update a remote ref that is not an ancestor of what you push;
--force-with-leaseprotects the remote ref by requiring it to still match your remote-tracking branch; background fetches can update that expectation, so use--force-with-lease=<branch>:<expected-tip>to pin the remote tip you reviewed. - git-scm, git reflog: reflogs record when branch tips changed; a clone may retain the old tip there if the ref update was logged and the entry has not been removed or expired.
What to do
1. Stop pushing. Ask teammates not to pull the broken branch. 2. Find the old tip hash: in a clone that fetched before the push, git reflog show origin/<branch> or git reflog; in GitHub, the closed PR or the activity/commit page of the branch may show it; Check CI logs for the old commit hash too. 3. In that clone: git branch restore <hash>, check git log restore, then push it back (git push --force-with-lease=<branch>:<expected-tip> origin restore:<branch> with the reviewed remote tip as <expected-tip>). 4. Next time use --force-with-lease=<branch>:<expected-tip> with the reviewed remote tip, and protect shared branches so force pushes are blocked.
How to describe it to your agent
I force-pushed over the remote branch. Do not push anything yet. In this clone show git reflog for the branch and its origin ref, find the hash before the push, and create a local branch there. Show me the diff against the remote and wait for my OK before any push. From now on never use plain --force.
Mistakes to check
- Running
git gc --prune=nowor deleting the old clone before you have the hash. - Restoring with another plain
-f. - Believing the remote's own server-side history is always recoverable: that depends on the host, which I did not verify.
Limits
I did not run these steps myself. The Stack Overflow source is small and old; recovery depends on someone still having the old tip.
Started from a post by @Adam, ebneter (Stack Overflow); git documentation, packaged by the editor. Original post