How to Avoid Accidental File Deletion in AI Coding: Git, Permissions, and Recovery Workflow

A practical checklist for preventing accidental file deletion in AI coding: use Git, workspace isolation, dangerous-command confirmation, read-only review, ignore rules, and recovery procedures to reduce risks in Codex, Claude Code, Cursor, and other Agent tools.

The scariest AI coding accident is not always wrong code. Sometimes it is deleted files.

Tools such as Codex, Claude Code, and Cursor can read and write project files, run commands, refactor in batches, and move directories. If the context is misunderstood or permissions are too broad, they can delete files, overwrite config, clear generated output, or remove uncommitted work.

So the first safety rule is not “make the AI smarter.” It is: do not give it the chance to do destructive work in the wrong scope.

This article gives a practical workflow for reducing accidental deletion risk and recovering quickly when it still happens.

Quick Answer: Use Layers of Protection

Do not rely on one sentence such as “do not delete files.” Use multiple layers:

Layer What to do Problem solved
Git workspace Check git status before edits; commit at important points Recovery after deletion
Directory isolation Let AI operate only in the current project or temporary branch Avoid unrelated files
Dangerous-command confirmation Human confirmation before delete, overwrite, or mass move Prevent automatic destructive commands
Read-only review Ask AI to analyze impact before editing Reduce broad mistakes
Ignore rules Exclude caches, build output, secrets, data directories Avoid touching wrong files
Recovery flow Prepare git restore, recycle bin, backups, snapshots Stay calm after accidents

Most important: before AI can edit files, the project must be recoverable.

Common Deletion Traps

1. “Clean up the project”

This phrase is risky. AI may interpret it as deleting unused files, old components, duplicate scripts, old Markdown, tmp, dist, build, or public.

But “looks unused” and “is unused” are different. Some files are referenced by CI, deployment scripts, dynamic imports, plugin systems, or documentation.

Safer prompt:

1
First list the files you think can be cleaned up and explain why. Do not delete anything until I confirm.

2. “Refactor the directory structure”

Moving files affects imports, static assets, framework conventions, CI/CD, docs links, multilingual content, and deployment output.

Safer flow:

  1. Generate a migration plan.
  2. List files to move.
  3. List references to update.
  4. Execute in small batches.
  5. Check after each batch.
  6. Delete old paths only after confirmation.

3. “Delete everything unused”

“Unused” needs evidence. Otherwise AI may guess from filenames, timestamps, or search results.

Use:

1
Only identify candidate files without static references. Rank them by risk. Do not delete.

Then ask:

1
Could these files be loaded dynamically, referenced by config, CI, deployment scripts, or docs?

Step 1: Check Git Status Before Editing

Before AI edits, run:

1
git status --short

If the workspace already has many uncommitted changes, risk is higher. You may not know what AI deleted versus what already existed.

Rules:

  • Clean workspace: safer for AI edits.
  • Few known changes: continue, but mark files AI must not touch.
  • Many uncommitted changes: commit, stash, or back up first.
  • Important untracked files: add them to Git or back them up.

Untracked files are especially risky:

1
2
3
?? notes.md
?? scripts/new-tool.ps1
?? content/post/2026/07/41/

If deleted, git restore cannot bring them back.

Step 2: Create Small Recovery Points

Before a large AI change, make a safety commit:

1
2
git add .
git commit -m "chore: save working state before ai changes"

Or stash including untracked files:

1
git stash push -u -m "before ai changes"

The -u matters because it includes untracked files. In daily work, small commits are often clearer than long-lived stash entries.

Step 3: Limit AI to the Right Directory

Do not run AI coding tools from your home directory, Downloads, or Desktop root.

Use the project root:

1
cd C:\Work\my-project

Then say:

1
Only modify files inside the current repository. Do not read or modify paths outside the repo.

For temporary files:

1
Put all temporary files under tmp/ai-work/. Do not create or delete temp files elsewhere.

For high-risk changes, use a Git worktree or temporary clone:

1
git worktree add ../my-project-ai-test -b ai-test

Step 4: Confirm Dangerous Commands

Be careful with:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
rm -rf
del /s
Remove-Item -Recurse
git clean -fd
git reset --hard
git checkout -- .
mv
move
robocopy /MIR
rsync --delete

They are not always forbidden, but the target path, impact, and recovery path must be clear.

In Windows PowerShell, this is especially dangerous:

1
Remove-Item -Recurse -Force

Safer rule:

1
Before delete, overwrite, mass move, git reset, git clean, or rsync --delete, stop and explain the exact target paths and impact. Wait for my confirmation.

Step 5: Review Before Deleting

AI is good at finding deletion candidates. It should not decide alone.

Ask for a table:

File AI reason Risk Delete?
old-script.js No static reference Medium Needs confirmation
dist/ Build output Low Can delete if rebuildable
legacy-config.json Looks old High Do not delete directly

Then ask it to check whether files may be used by config, CI, deployment scripts, dynamic imports, or docs.

If you use Claude Code subagents, a read-only cleanup-reviewer can list candidates without editing. See: /en/2026/07/10/claude-code-subagent-project-fit-guide/.

Step 6: Put File Safety Rules in AI Memory Files

Add rules to AGENTS.md, CLAUDE.md, or another project instruction file:

1
2
3
4
5
6
7
8
# File Safety Rules

- Do not delete files unless the user explicitly asks for deletion.
- Before deleting, moving, or overwriting files, list the exact paths and wait for confirmation.
- Never run git reset --hard, git clean -fd, rm -rf, Remove-Item -Recurse, rsync --delete, or robocopy /MIR without explicit confirmation.
- Do not modify files outside the repository root.
- Treat untracked files as user-created files, not disposable temporary files.
- Prefer small edits and small commits.

Chinese projects can use Chinese rules:

1
2
3
4
5
6
7
# 文件安全规则

- 不要主动删除文件。
- 删除、移动、覆盖前,必须先列出完整路径和原因。
- 未跟踪文件默认视为用户文件,不要当成临时文件处理。
- 不要执行 `git reset --hard``git clean -fd``Remove-Item -Recurse` 等破坏性命令,除非用户明确确认。
- 不要修改仓库外的文件。

This is not perfect protection, but it reduces unilateral action.

If you maintain project memory, store “directories not to touch,” “commands requiring confirmation,” and “generated files” there. Related: /en/2026/07/08/claude-code-multi-project-memory-team-workflow/.

Step 7: Separate Source, Generated Files, and User Data

Many deletions come from unclear file identity.

Type Examples Can AI delete?
Source src/, app/, content/ Not directly
Config .env.example, config/, package.json High risk
Generated dist/, build/, public/ Only if rebuildable
Cache .cache/, .next/cache/ Usually yes
User data uploads/, data/, notes/ Default no
Local secrets .env, *.key, secrets/ Do not read or modify

Write directory notes:

1
2
3
4
5
6
## Directory Notes

- `content/` is source content. Do not delete posts.
- `public/` is generated by Hugo and can be rebuilt.
- `.env` and `secrets/` must not be read or modified.
- `tmp/ai-work/` is the only allowed temporary workspace.

Step 8: Know the Recovery Flow

If files are deleted, stop broad AI edits first.

Restore Tracked Files

1
2
3
4
git status --short
git restore path/to/file
git restore path/to/directory
git restore --source HEAD~1 path/to/file

Restore From History

1
2
git log -- path/to/file
git restore --source <commit> path/to/file

If the File Was Untracked

Check, in order:

  1. editor local history;
  2. Windows Recycle Bin;
  3. OneDrive, Dropbox, Syncthing version history;
  4. NAS snapshots or backups;
  5. file recovery tools;
  6. AI conversation history.

This is why git stash push -u or a small commit matters before big changes.

Step 9: Require a Diff Before Deletion

Before deleting, ask AI to show:

1
2
git diff --stat
git status --short

It should explain:

  • which files will be deleted;
  • which files will be moved;
  • which files are only modified;
  • which files are untracked;
  • how to recover after deletion.

Be careful with:

1
2
3
D  src/important.ts
 D content/post/2026/07/old/index.zh-cn.md
?? backup/

D means tracked deletion. ?? means untracked; Git cannot restore it automatically.

After AI edits, check status again.

Step 10: Tool-Specific Notes

Codex

  • Check git status first.
  • Explicitly forbid deleting untracked files.
  • Ask for a plan before large changes.
  • Stop before Remove-Item, rm -rf, git clean, or git reset.
  • Ask for a final list of actual changed files.

Claude Code

  • Put file safety rules in CLAUDE.md.
  • Use read-only subagents for review.
  • Avoid destructive scripts in hooks.
  • Mark commands requiring human confirmation.

Cursor and IDE Tools

  • Do not accept broad deletions at once.
  • Inspect file tree changes.
  • Confirm deleted files one by one.
  • Trust Git more than IDE undo for important projects.

Safe Prompt Template

For cleanup, refactor, or migration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
请先分析,不要修改文件。

目标:找出这次任务可能需要修改、移动或删除的文件。

要求:
1. 不要删除任何文件。
2. 不要执行 git reset、git clean、rm -rf、Remove-Item -Recurse、rsync --delete、robocopy /MIR。
3. 未跟踪文件默认视为用户文件,不要当作临时文件处理。
4. 先输出计划、影响范围和风险点。
5. 如果确实建议删除文件,列出完整路径、原因、风险等级和恢复方式,等待我确认。

When executing:

1
2
3
只执行我确认过的这些文件操作。
每次删除或移动前,再输出目标路径。
完成后运行 git status --short,并汇报新增、修改、删除的文件。

Final Thought

AI coding does not mean never deleting files. Projects do need cleanup.

The rule is that deletion should be evidence-based, listed, confirmed, verified, and recoverable. Git, small commits, read-only review, permission confirmation, project rules, backups, and recovery procedures turn accidental deletion from a disaster into a recoverable incident.

If your AI Agent often runs long tasks, also record the state, changed scope, and recovery point for each phase. That reduces the chance of repeating dangerous commands after interruption. See: /en/2026/07/10/ai-agent-long-task-resume-guide/.

记录并分享
Built with Hugo
Theme Stack designed by Jimmy