How to Prevent Codex from Deleting Files

How to Prevent Codex from Deleting Files

Aident AI

A turbulent coral field stops at a curved boundary protecting a calm blue form inside a lime workspace.

How to Prevent Codex from Deleting Files

Keep Codex in workspace-write, leave outbound network access off unless the task needs it, and use on-request approvals for anything that crosses the sandbox. Do not treat Full Access or automatic approval as a safety boundary. Start from recoverable source control, expose only the project directory, and inspect git status plus the diff before accepting the result.

OpenAI investigated July 2026 reports in which Codex unexpectedly deleted files. The most common pattern it identified was Full Access without a sandbox, followed by a bad temporary-directory sequence that changed HOME and then deleted it. That does not mean every deletion report has the same cause. It does show why a narrow operating-system boundary matters more than a prompt that says "be careful."

The Safe Baseline

Use these controls together:

Control

Safe default

What it protects

Recoverable workspace

Clean branch, commit, snapshot, or backup

Tracked and untracked work if the task goes wrong

Filesystem sandbox

workspace-write

Files outside the current workspace

Approval policy

on-request with a human reviewer

Requests that need to cross the sandbox

Writable roots

Current project only

Other repositories, home folders, and mounted volumes

Network

Off, or narrowly allowlisted when required

Unexpected uploads and open-ended external actions

Command rules

Prompt or block destructive command prefixes

Known risky escapes outside the sandbox

Verification

Status, diff, tests, and explicit acceptance check

Silent scope expansion or accidental deletion

The sandbox and approval policy solve different problems. The sandbox is the technical boundary. Approval decides who may authorize a request to cross that boundary. An approval reviewer cannot restore a boundary that Full Access removed.

Prerequisites

Before giving Codex write access, make sure:

  • the project is in version control;

  • important untracked files are backed up or copied outside the agent's writable area;

  • the current Codex version is installed;

  • secrets and unrelated repositories are outside the workspace;

  • you know which Codex surface is active, because the desktop app, CLI, and IDE may show settings differently.

Check the repository before starting:

git status --short
git diff --stat

Expected result: you know exactly which changes predate the agent. If the output contains work you cannot recreate, stop and make a recoverable checkpoint before continuing.

Step 1: Keep the Filesystem Boundary Narrow

For the CLI user configuration, this is a conservative starting point:

sandbox_mode = "workspace-write"
approval_policy = "on-request"
approvals_reviewer = "user"

[sandbox_workspace_write]
network_access = false
writable_roots = []

writable_roots contains additional roots. An empty list leaves the current workspace as the intended write scope instead of adding your home directory or a second repository. Do not add ~, /Users/your-name, C:\Users\your-name, or a broad development parent just to silence an error.

Restart Codex after changing configuration and inspect the effective session status. In the CLI, run /status. In the app or IDE, open the active task's permissions and confirm the displayed sandbox is not Full Access.

Expected result: Codex can edit files in the current project, but a harmless request to create a file in a sibling directory is blocked or asks for escalation. Delete the harmless test file after you confirm the boundary.

Step 2: Treat Approval as Review, Not Isolation

Keep approval_policy = "on-request" for interactive work. Use approvals_reviewer = "user" for the first run of a risky or unfamiliar task. OpenAI also offers auto_review, which sends eligible approval requests to a reviewer subagent, but its configuration reference is explicit that this does not change sandboxing.

When Codex asks to escalate, check four facts before approving:

  1. What exact command or Action will run?

  2. Which files, directories, credentials, or remote systems can it affect?

  3. Why can the task not finish inside the current boundary?

  4. Is the request one-time, or will it allow a broader class of future actions?

Reject an escalation that changes HOME, broadens the writable root to a user directory, grants Full Access for convenience, or combines an unclear shell script with deletion.

Expected result: routine project edits continue in the sandbox, while any boundary crossing remains visible and attributable.

Step 3: Add and Test Destructive-Command Rules

Rules control commands Codex requests to run outside the sandbox. They supplement the filesystem boundary; they do not replace it. Create ~/.codex/rules/default.rules and start with command prefixes whose intent is unambiguous:

prefix_rule(
    pattern = ["rm"],
    decision = "prompt",
    justification = "Confirm the exact deletion target and recovery plan.",
)

prefix_rule(
    pattern = ["git", "clean"],
    decision = "forbidden",
    justification = "Inspect untracked files and remove reviewed paths individually.",
)

Test the rules without running the command:

codex execpolicy check --pretty \
  --rules ~/.codex/rules/default.rules \
  -- git clean -fd

Expected result: the JSON output reports forbidden and identifies the matching rule. Test a safe command too:

codex execpolicy check --pretty \
  --rules ~/.codex/rules/default.rules \
  -- git status --short

Do not write an enormous allowlist. OpenAI's rules engine evaluates simple compound shell commands conservatively, but advanced shell syntax can be treated as one bash -lc invocation. Keep the sandbox active even when rules exist.

Step 4: Run a Reproducible Safety Probe

Use a disposable branch or copy of a small repository. Give Codex a bounded task:

Edit only safety-probe.txt in this repository.
Replace READY with SAFE, print git status --short, and show the final diff.
Do not change configuration, environment variables, writable roots, or network access.
Stop and ask before running any command that deletes or moves a file

Verify independently:

git status --short
git diff -- safety-probe.txt
git diff --name-status

Expected result: only safety-probe.txt changed, the diff contains the requested replacement, and no file has an unexpected D status. If anything else changed, stop the task and inspect before accepting or reverting it.

Step 5: Reduce External Tool Scope Separately

The local sandbox governs shell and filesystem access. External Actions need their own boundary: a connected integration, a narrow operation, validated inputs, and review before a write. Aident Loadout keeps provider credentials out of prompts and lets an agent inspect a current Action schema before execution, but it does not sandbox local files.

Give Codex this instruction:

Follow https://aident.ai/SETUP.md
Find one read-only Action for a connected service and inspect its schema.
Show the exact operation and inputs before execution. Run it once only after I approve.
Do not request Full Access or add another writable root

Expected result: one read-only Action completes without a provider API key in the prompt, shell history, or repository. If the task asks for a destructive or write Action, stop and narrow the request first.

If Codex Already Deleted Files

Stop the session and avoid creating, installing, or downloading anything onto the affected volume. New writes can overwrite recoverable data.

Then:

  1. Capture the Codex session ID, visible command, timestamp, working directory, sandbox mode, approval mode, and effective writable roots.

  2. Run read-only inspection such as git status --short and git diff --name-status from a separate trusted terminal.

  3. Recover committed files from source control, but preserve current evidence before overwriting paths.

  4. Check your editor's local history, filesystem snapshots, cloud version history, and backups for untracked or uncommitted files.

  5. If the missing data is valuable and not backed up, stop using the disk and consult a recovery specialist.

  6. Report a minimal, sanitized reproduction to OpenAI. Include the exact version and whether Full Access or an escalation was active.

Do not run a recursive cleanup, reinstall the operating system, clone over the damaged directory, or repeatedly rerun the suspected command while investigating.

Common Failure Modes

"Approve for me" Was Enabled, So the Task Seemed Safe

Automatic approval can reduce interruptions. It does not shrink filesystem access. Pair any reviewer with workspace-write and narrow roots.

Full Access Was Needed for One Tool

Grant access only to the exact resource the tool needs. Prefer a narrow additional root, a network allowlist, or a scoped external Action. Return to the safe baseline and verify /status after the task.

The Repository Was Clean but Untracked Files Disappeared

Git cannot recover data it never tracked. Back up generated assets, local databases, environment files, and notes before an autonomous write session.

A Rule Did Not Match a Shell Script

Rules match command argument prefixes. Shell wrappers, substitutions, variables, redirection, wildcards, and control flow can change what the engine evaluates. Test the exact form with codex execpolicy check, and rely on the sandbox as the primary boundary.

The Agent Asked to Change HOME or a Temporary Directory

Do not approve a broad environment change without checking every consumer and cleanup step. Use a task-specific temporary directory with an explicit path, then remove only that verified directory.

Why This Fix Works

A narrow sandbox limits the blast radius even when a model proposes the wrong command. On-request approval makes escape visible. Rules catch known dangerous prefixes. A recoverable checkpoint and final diff make mistakes observable and reversible. None of those controls is sufficient alone, but together they convert an open-ended local agent into a bounded change process.

For Windows-specific process and ACL failures, use How to Fix Codex Windows Sandbox Errors Safely. To preserve your configuration while moving from another coding agent, follow How to Migrate from Claude Code to Codex. For narrower external tool context, read How to Reduce MCP Token Usage in Claude Code and Codex.

Use Aident Loadout to run one scoped read-only Action from Codex, then record whether it completed without Full Access, a new writable root, or a provider secret in the task.

Sources

Refresh this guide when OpenAI changes Codex sandbox modes, approval policies, auto-review behavior, writable-root configuration, rules syntax, or incident guidance.

Home

Home

Home

Integrations

Integrations

Integrations

Vault

Vault

Vault

Audit

Audit

Audit

Arana Grande

Arana Grande

Arana Grande

Free

Free

Free

30-day audit summary

30-day audit summary

30-day audit summary

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

View Audit

View Audit

View Audit

Loadout usage

Loadout usage

Loadout usage

617 action calls in the last 30 days

617 action calls in the last 30 days

617 action calls in the last 30 days

May 19 - Jun 17

May 19 - Jun 17

May 19 - Jun 17

10 active days

10 active days

10 active days

Less

Less

Less

More

More

More

Recent activity

Recent activity

Recent activity

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Shopify

Shopify

Shopify

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Success

Success

Success

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Success

Success

Success

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Failed

Failed

Failed

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Connected integration coverage

Connected integration coverage

Connected integration coverage

162

162

162

of 753 accessible connected

of 753 accessible connected

of 753 accessible connected

Callable actions

Callable actions

Callable actions

1,126

1,126

1,126

Vault credentials

Vault credentials

Vault credentials

8

8

8

Explore what's possible

Explore what's possible

Explore what's possible

See all Integrations

See all Integrations

See all Integrations

Google Ads

Google Ads

Google Ads

All available Goolge Ads tools via...

All available Goolge Ads tools via...

All available Goolge Ads tools via...

X (twitter)

X (twitter)

X (twitter)

All available X tools via...

All available X tools via...

All available X tools via...

Github

Github

Github

All available Github tools via...

All available Github tools via...

All available Github tools via...

Notion

Notion

Notion

All available Notion tools via...

All available Notion tools via...

All available Notion tools via...

Slack

Slack

Slack

All available Slack tools via...

All available Slack tools via...

All available Slack tools via...

Firecrawl

Firecrawl

Firecrawl

All available Firecrawl tools via...

All available Firecrawl tools via...

All available Firecrawl tools via...

753 integrations are available for loadouts.

753 integrations are available for loadouts.

753 integrations are available for loadouts.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.