Безопасное восстановление в git

Восстанавливает работу после ошибок в git без потерь: reflog, revert против reset, случайно удалённая ветка, откат неудачного merge или rebase, потерянный stash; сначала бэкап, перед разрушительными шагами – вопрос пользователю. Используйте, когда в git что-то сломали или потеряли.

Git и PRПак: Работа с Git104 строкиsafe-git-recovery

Установка

Выполните одну команду — она сохранит SKILL.md в папку скиллов агента. Перезапустите агента, и он подхватит скилл сам.

Claude Code — macOS, Linux
mkdir -p ~/.claude/skills/safe-git-recovery && curl -fsSL https://anymodel.org/en/skills/git-workflow/safe-git-recovery/SKILL.md -o ~/.claude/skills/safe-git-recovery/SKILL.md
Codex, Cursor — macOS, Linux
mkdir -p ~/.agents/skills/safe-git-recovery && curl -fsSL https://anymodel.org/en/skills/git-workflow/safe-git-recovery/SKILL.md -o ~/.agents/skills/safe-git-recovery/SKILL.md
Claude Code — Windows PowerShell
New-Item -ItemType Directory -Force "$HOME\.claude\skills\safe-git-recovery" | Out-Null; Invoke-WebRequest https://anymodel.org/en/skills/git-workflow/safe-git-recovery/SKILL.md -UseBasicParsing -OutFile "$HOME\.claude\skills\safe-git-recovery\SKILL.md"
Codex, Cursor — Windows PowerShell
New-Item -ItemType Directory -Force "$HOME\.agents\skills\safe-git-recovery" | Out-Null; Invoke-WebRequest https://anymodel.org/en/skills/git-workflow/safe-git-recovery/SKILL.md -UseBasicParsing -OutFile "$HOME\.agents\skills\safe-git-recovery\SKILL.md"

Другой агент: сохраните файл в его папку скиллов или дайте ему ссылку на файл: https://anymodel.org/en/skills/git-workflow/safe-git-recovery/SKILL.md

SKILL.md

Исходник

Safe Git Recovery

Most git mistakes are recoverable because git keeps old commits around for a while. Your job is to find the lost state, secure it, and only then fix things. Speed is not the goal; not losing work is.

1. Stop and look

Do not run anything that rewrites history or discards changes yet. Gather the facts:

git status
git branch -vv
git log --oneline --graph --decorate -20
git reflog -30
git stash list

Ask the user what they were doing and what they expect to see. Establish whether the commits involved were pushed (git branch -r --contains <sha>), because pushed history is shared and needs a different approach.

2. Make a backup before touching anything

Create a safety ref at the current state so every later step can be undone:

git branch backup/before-recovery-$(date +%Y%m%d-%H%M%S)

If there are uncommitted changes you want to preserve, do not clean them away. Copy them out first (git stash push -u -m "backup" is acceptable only if the user agrees, as it moves their files) or tell the user to copy the folder.

3. Pick the right tool

Undo a commit that is already pushed or shared:

git revert <sha>              # adds a new commit that cancels it; safe for shared history
git revert -m 1 <merge-sha>   # undo a merge commit, keeping mainline as parent 1

Undo local, unpushed commits (history rewrite, ask first):

git reset --soft HEAD~1       # undo the commit, keep changes staged
git reset --mixed HEAD~1      # undo the commit, keep changes unstaged

git reset --hard throws away uncommitted work; run it only with the user's explicit approval and after the backup branch exists.

Recover a deleted branch or a commit that "disappeared":

git reflog                                # find the last sha the branch pointed at
git branch restored-feature <sha>         # recreate it under a safe name

Recover after a bad rebase or reset: git reflog shows entries such as rebase (finish) and reset: moving to .... Find the entry just before the mistake (HEAD@{n}), then inspect it with git log --oneline HEAD@{n} and recreate a branch from it before moving anything.

Undo a bad merge that is not pushed: look at the reflog for the pre-merge head and create a branch there. If the merge is still in progress, git merge --abort is the way out.

Recover a dropped stash or a stash lost after a reset:

git fsck --no-reflogs --lost-found | grep commit    # dangling commits (stashes show up here)
git show <sha>                                      # inspect candidates
git stash apply <sha>                               # apply a recovered stash commit

Recover a single file from an older commit. This overwrites the working-tree file. If it has uncommitted edits, ask first or inspect without touching it: git show <sha>:path/to/file > /tmp/file.old.

git restore --source=<sha> -- path/to/file

Lost uncommitted work that was never added or stashed cannot be recovered by git; check editor local history and the OS trash instead.

4. Verify before declaring success

  • Compare the recovered state with what the user expects: git diff backup/... restored-branch, git log --stat.
  • Run the build and tests if the recovery touched code.
  • Only now move the real branch (git switch main, git branch -f or git reset), and show the user the exact command first.

5. Report

What happened: <one or two lines, based on the reflog>
Backup: <branch/tag name and sha>
Recovered: <branch name, sha, what it contains>
Commands run: <list>
Needs your decision: <e.g. force-push to fix the remote, delete the backup later>

Pitfalls

  • Do not force-push (--force, --force-with-lease) to repair a remote without asking; it rewrites what others have pulled.
  • Do not run git gc --prune=now, git reflog expire or git clean -fd during recovery; they delete the very data you need.
  • Do not reset --hard to "get back to a clean state" before looking at the reflog.
  • Do not use revert on a shared branch when the goal is to hide a leaked secret; rotate the secret instead, and discuss history rewriting with the user.
  • Reflog entries expire (typically 90 days for reachable, 30 for unreachable) and are local to each clone; act promptly.
  • Do not delete the backup branch yourself; leave that to the user.

Source: AnyModel skills catalog · License: CC BY 4.0

Подключить через AnyModel API

Скилл работает на той модели, которую использует агент. Подключите Claude Code, Codex или Cursor к AnyModel и запускайте его на Claude, GPT, Gemini и других моделях по одному ключу — оплата за токены, без подписки.

Ещё из пака Работа с Git

Сообщения коммитов

Пишет сообщение коммита по staged diff: короткая тема в повелительном наклонении, в теле – зачем, одно логическое изменение на коммит, в стиле, принятом в репозитории. Используйте, когда просят закоммитить или написать сообщение коммита.

Описание PR

Пишет описание PR по diff и коммитам: что и зачем изменилось, как проверено, риски и выкатка, скриншоты для UI – без выдуманных утверждений. Используйте, когда просят описание PR или вы собираетесь его открыть.

Разрешение merge-конфликтов

Разрешает конфликты merge и rebase, разбираясь в намерениях обеих сторон и их коммитов, без слепого выбора ours или theirs, затем собирает проект и гоняет тесты; при настоящем конфликте намерений спрашивает пользователя. Используйте, когда merge или rebase остановился на конфликтах.

Changelog и release notes

Готовит changelog или release notes для пользователей по коммитам и PR с последнего тега: Added, Changed, Fixed, Removed, без внутреннего шума. Используйте, когда просят release notes, запись в changelog или что изменилось с прошлого релиза.