How can I recover from an accidental git push -f?

Try this:

  1. Connect to the remote over SSH.

  2. Make a backup of the entire remote repository.

    tar cvzf project-backup.tgz /path/to/project.git
    
  3. If you know at least the first few characters of bbbbbbb, use git show bbbbbb and/or git log bbbbbb to find out the full commit hash. (If you need only the hash, git rev-parse bbbbbb will also work, but it's always better to check.)

    If you don't know the value at all, run git fsck and you should get a list of "dangling commits". Examine each commit using git show <hash> and git log <hash> until you find the correct one.

  4. Update the branch references:

    echo aaaaaaaaaaaaaaa.... > refs/heads/master
    echo bbbbbbbbbbbbbbb.... > refs/heads/foo
    
  5. Use git log master and git log foo to ensure that you restored the correct branches.