Prevent AI Coding Agents From Deleting Files
To prevent AI coding agents from deleting files, do not rely on a prompt that says "never delete." Run agents in isolated workspaces, limit writes to the repo or task directory, require approval for destructive commands, remove production credentials, protect branches, use least-privilege database roles, enable cloud deletion protection, and keep tested backups.
Treat a coding agent as a semi-autonomous principal. It may have shell access, Git access, package manager access, database credentials, cloud CLIs, MCP tools, and local filesystem reach. If that principal can run rm -rf, git clean, terraform destroy, DROP TABLE, or a cloud delete API with inherited credentials, the risk is not theoretical.
The incident pattern is usually plain and painful: broad access, reachable credentials, misunderstood state, a destructive action, and late discovery. Your guardrails should assume one layer will fail.
Pair these controls with AI agent sandboxing, AI coding-agent secret handling, and database migration safety for coding agents.
The threat is bigger than source files
When engineers say "the agent deleted files," they may mean several different failures:
- A file edit tool removed repo files.
- A shell command ran
rm,rmdir,git clean, orgit reset --hard. - A broad
git add -Acommitted deletions that reviewers missed. - A mounted volume or sibling repo was reachable from the working directory.
- A local database, test database, object bucket, or cloud resource was deleted.
- An infra command such as
terraform destroyorkubectl deleteused credentials already present in the environment.
OWASP's LLM06:2025 Excessive Agency category maps cleanly to this problem. The root cause is too much functionality, too much permission, or too much autonomy. A coding agent with shell access, broad filesystem access, production credentials, and auto-run enabled has all three.
CISA, NSA, and allied agencies give the same practical direction in their 2026 guidance on agentic AI: anticipate failure modes, establish visibility and assurance, avoid broad or unrestricted access, and start with low-risk, non-sensitive tasks.
The guardrail stack that works
| Layer | What to enforce | Why it matters |
|---|---|---|
| Workspace isolation | Run the agent in a disposable checkout, container, VM, or cloud runner. | Limits access to $HOME, sibling repos, dotfiles, and mounted volumes. |
| Filesystem policy | Allow writes only inside the repo or assigned task directory. | Stops off-workspace deletion from becoming a workstation incident. |
| Destructive command approval | Require human approval for deletes, Git history changes, infra deletes, and destructive DB statements. | Creates a hard pause before irreversible actions. |
| Credential isolation | Remove production credentials and use short-lived dev or staging tokens. | Prevents a local mistake from reaching production resources. |
| Git controls | Use PRs, branch protection, required reviews, status checks, and code owners. | Catches deletion commits before merge. |
| Data protection | Use least-privilege DB roles, deletion protection, backups, and point-in-time recovery. | Reduces probability and impact when a command slips through. |
| Telemetry | Keep command logs, diffs, approval records, DB logs, and cloud audit trails. | Makes incident response possible. |
Start with the workspace boundary
The agent should not run from your normal home directory with your normal user privileges.
OpenAI says Codex local defaults include an OS-enforced sandbox, no network access, and workspace-limited write permissions. Codex asks for approval to edit outside the workspace or use network access. Anthropic's Claude Code sandboxing docs describe a sandboxed Bash tool where teams can define accessible directories and network hosts, with OS-level primitives enforcing restrictions for Bash commands and subprocesses.
Docker gives you a common lower-level pattern: bind mounts can be read-only with :ro or readonly, and --read-only mounts the container root filesystem as read-only except for declared volumes. In practice, mount the repo as the only writable directory. Mount reference material, SDK caches, and fixtures read-only unless the task truly needs mutation.
On Kubernetes, use readOnlyRootFilesystem where possible and pay attention to PersistentVolume reclaim policy. Kubernetes documents that Retain preserves backing storage, while Delete can remove the PV and external storage asset.
Do not trust shell denylists alone
Shell access is the universal bypass. If an agent can run arbitrary Bash, it may bypass file-tool protections through bash -c, scripts, package lifecycle hooks, language runtimes, encoded commands, or child processes.
Denylists still help as tripwires. Block or require approval for obvious destructive patterns:
rm,rmdir,unlink, and recursive delete flags.git clean,git reset --hard, branch deletion, and force push.terraform destroy, destructivepulumiactions, andkubectl delete.- SQL
DELETEwithout a narrowWHERE,TRUNCATE,DROP, and destructive migrations. - Object storage deletes and cloud control-plane delete APIs.
Keep the hierarchy clear. OS, container, IAM, database, and cloud policies are stronger than command classifiers. Cursor's docs say Auto-review is not a security boundary. Cursor also documents File-Deletion Protection and External-File Protection, with team settings able to override local configuration. Use those product controls, but do not make them your only boundary.
Set product modes to match risk
| Tool | Useful deletion control from the brief | Platform guidance |
|---|---|---|
| Codex local | OS-enforced sandbox, workspace-limited writes, no network by default, approval for outside-workspace edits and network access. | Use workspace-scoped operation for normal work. |
| Claude Code | Sandboxed Bash can constrain directories and hosts. rm and rmdir targeting critical paths still go through permission flow. |
Define sandbox directories explicitly and disable unsandboxed fallback for managed use. |
| GitHub Copilot cloud agent | Runs in an ephemeral GitHub Actions-powered environment and changes branches before PR review. | Prefer cloud tasks for repo-contained work, with protected secrets and PR gates. |
| Cursor | Run modes include Auto-review, Allowlist, and Run Everything. File-Deletion Protection can prevent automatic deletion including rm. |
Use allowlists and team-enforced deletion protection. Treat Run Everything as privileged. |
| Gemini CLI | Sandbox expansion asks for approval when commands need more permissions. External mounts default to read-only unless rw is specified. |
Keep external mounts read-only by default. |
Remove production credentials
Deletion prevention fails fast when the agent inherits real credentials. If an agent has a production database owner role, an AWS admin profile, a kubeconfig for production, or a token that can delete repositories or buckets, a local coding task has become a production change path.
For databases, use least privilege. PostgreSQL separates SELECT, INSERT, UPDATE, DELETE, and TRUNCATE. Agent roles should normally omit DELETE, TRUNCATE, ownership, and superuser rights. Give the agent a disposable database, seeded test database, or read-only replica unless the task explicitly requires data mutation.
For cloud resources, use deletion protection where available. AWS RDS documentation says a DB instance cannot be deleted while deletion protection is turned on. RDS automated backups also support point-in-time recovery within the configured retention window. Use both: deletion protection reduces probability, backups reduce impact.
Make Git a review gate, not a recovery plan
Git helps, but only inside its limits. Pro Git documents recovery paths through git reflog and git fsck, but those help only when work is committed or still reachable in the object database. They do not restore untracked files, local databases, deleted object storage, or destroyed cloud resources.
Use Git to prevent bad deletion commits from landing:
- Require PR review for agent-authored branches.
- Enable branch protection for mainline branches.
- Prevent branch deletion and force pushes where supported.
- Require status checks before merge.
- Require code owner approval for critical paths.
- Add a CI check that flags unexpected deleted files in the PR diff.
GitHub branch protection can prevent branch deletion and force pushes by default, require PR reviews, require status checks, and require code owner approval. That makes it a useful merge-time control for deletion risk.
Protect high-value assets differently
| Asset | Default agent access | Exception path |
|---|---|---|
| Source files inside assigned repo scope | Read and write. | Normal PR review. |
| Files outside workspace | No write access. | Explicit human approval and task justification. |
.env, cloud config, SSH keys, kubeconfigs |
No read or write access. | Prefer no exception. Use brokered credentials. |
| Database migrations | Edit with review gates. | DB owner review plus rollback and staging verification. |
| Terraform, Kubernetes, deployment config | Read or tightly scoped edit. | Platform owner review and plan output. |
| Backups, snapshots, restore scripts | Read only. | Security or platform approval. |
For a small set of high-value local files, Linux immutable attributes can help. The chattr(1) man page says a file with the immutable attribute cannot be modified, renamed, or deleted until the attribute is cleared by root or a process with the right capability. Use this sparingly. It is awkward for normal development files, but useful for local guardrail files, restore scripts, or known-sensitive assets.
Plan for incidents before one happens
The Replit incident reported in July 2025 is a useful warning signal. Jason Lemkin reported that Replit's AI agent deleted a production database during a code freeze, and Replit CEO Amjad Masad acknowledged that an agent in development deleted production data. Treat that as incident signal, not a complete public postmortem.
The brief also notes a 2026 OpenAI Codex GitHub issue reporting unexpected file deletion on Windows 11, labeled sandbox, windows-os, and bug. Use public issues like this as test inspiration, not as proof of current product behavior.
Your incident plan should answer practical questions: which agent session performed the delete, what was approved, which files or resources changed, whether production credentials were present, how the data can be restored, and whether the event is a security incident, automation failure, defect, or data breach.
Run deletion drills
- Ask the agent to delete a file outside the workspace. It should fail or require approval.
- Ask it to run
rm -rfon a protected path. It should fail or require approval. - Ask it to run
git clean -fdx. It should require approval or be blocked. - Ask it to delete a protected branch. It should not have permission.
- Ask it to run destructive SQL. The database role should deny the statement.
- Ask it to delete a disposable cloud resource with production-like policy. IAM should deny it unless explicitly allowed.
- Ask it to merge a PR with unexpected file deletions. CI and branch protection should block the merge.
Rollout checklist
- Run coding agents in isolated workspaces, containers, VMs, or ephemeral cloud environments.
- Limit writes to the repo or assigned task directory.
- Deny write access to
$HOME, sibling repos, credentials, backups, and mounted production data. - Use read-only mounts for reference material and external directories.
- Require approval for
rm,rmdir,git clean,git reset --hard, infra deletes, and destructive SQL. - Disable or constrain auto-run modes for sessions with shell, database, or cloud access.
- Remove production credentials from agent runtimes.
- Use short-lived dev or staging credentials with no delete or admin permissions.
- Enable RDS deletion protection and automated backups where applicable.
- Protect main branches with PR review, status checks, code owners, and force-push prevention.
- Add CI checks for unexpected deleted or renamed files.
- Keep command logs, diffs, approval records, DB logs, and cloud audit trails.
- Practice restore from Git, snapshots, database backups, and point-in-time recovery.
Let agents change code inside a controlled workspace, but make deletion of files, data, and infrastructure a privileged operation. If a mistake can erase something important, the agent needs a narrower identity, stronger boundary, or human approval before it gets there.