Codex Leaves Files in /tmp: A Step-by-Step Guide to Automatic Cleanup
Codex finishes a task, but the helper scripts, downloaded files, and test logs it created under /tmp remain. After enough runs, it becomes difficult to tell which files are safe to remove.
The practical fix is to give each task its own temporary directory, tell Codex when to remove it, and use a cleanup mechanism in the code that creates it. For local Codex CLI runs, a launcher can also remove the session directory when the foreground command exits.
This guide targets Linux and WSL users with basic terminal experience. It covers files created for your tasks. Codex’s own runtime files, persistent state, and tool caches can have different lifetimes.
Choose the cleanup method
| Method | Cleanup point | Best use |
|---|---|---|
AGENTS.md rule |
When Codex completes a task | Persistent project or user instructions |
Bash EXIT trap |
When the owning shell exits | One shell operation, including command failures |
Python TemporaryDirectory |
When the with block exits |
Python scripts, including ordinary exceptions |
| CLI launcher | When its local foreground Codex command exits | A session-level fallback |
Start with the instruction rule, then add automatic cleanup to temporary scripts. Use the launcher if you also want cleanup when the CLI session ends. Instructions guide the agent; they cannot guarantee cleanup after a crash, SIGKILL, or a machine shutdown.
Step 1: Inspect the files without deleting them
Run these commands in the Linux environment where Codex executes:
codex --version
du -sh /tmp
if [ -d /tmp/codex-work ]; then
du -sh /tmp/codex-work
find /tmp/codex-work -mindepth 1 -maxdepth 1 -type d -print
fi
This is an inventory. Existing files elsewhere in /tmp are not automatically Codex task files. Leave unidentified files alone; the steps below give new files a clear owner and cleanup boundary.
The CLI flags below were checked against local Codex CLI 0.162.1 and the official CLI reference. Check codex --help if your version differs.
Step 2: Add a permanent rule to AGENTS.md
For this project only, open AGENTS.md in the repository root:
nano AGENTS.md
For a default across projects, open the instructions in your Codex home:
mkdir -p "${CODEX_HOME:-$HOME/.codex}"
nano "${CODEX_HOME:-$HOME/.codex}/AGENTS.md"
Append this section to the existing file, keeping the other instructions:
## Temporary files
- Create a unique directory for each task under /tmp/codex-work/.
- If TMPDIR points to a dedicated Codex session directory, create task
directories inside that directory instead.
- Put temporary scripts, downloads, logs, and intermediate files there.
- Record the exact task directory you created.
- Save final deliverables in the workspace before cleanup.
- Wait for processes using task files to finish before deleting them.
- Use a Bash EXIT trap or Python TemporaryDirectory when practical.
- Before finishing, delete only your task directory, verify it is gone,
and report any cleanup failure.
- Never clear all of /tmp, delete other tasks' files, or remove persistent
Codex state and caches as part of task cleanup.
- The session directory supplied through TMPDIR belongs to the launcher;
delete your task subdirectory, not the launcher's session directory.
Codex loads global and project guidance at startup. Same-level AGENTS.override.md files take precedence over AGENTS.md; deeper project guidance can override earlier rules. Restart after editing and check the effective instruction file. Official AGENTS.md documentation
In the new session, ask:
Summarize the temporary-file rules you loaded. For this task, record the
temporary directory, save deliverables in the workspace, then delete your
task directory and verify it is gone.
This makes cleanup part of task completion. The next two steps put cleanup into executable code so it also runs when an ordinary command fails.
Step 3: Use a Bash EXIT trap for shell work
Run this complete example from your project root:
bash <<'BASH'
set -euo pipefail
task_base="${TMPDIR:-/tmp/codex-work}"
mkdir -p "$task_base"
task_tmp=$(mktemp -d "$task_base/task-XXXXXXXX")
trap 'rm -rf -- "$task_tmp"' EXIT
printf 'Task directory: %s\n' "$task_tmp"
mkdir -p artifacts
printf 'temporary input\n' > "$task_tmp/input.txt"
tr '[:lower:]' '[:upper:]' < "$task_tmp/input.txt" > "$task_tmp/result.txt"
cp -- "$task_tmp/result.txt" artifacts/cleanup-result.txt
cat artifacts/cleanup-result.txt
BASH
Expected output includes a unique task path and:
TEMPORARY INPUT
The deliverable remains at artifacts/cleanup-result.txt. The temporary directory is removed when this Bash process exits, including when a failing command causes set -e to exit the shell.
Keep creation, work, and cleanup in the same shell script. A trap registered in one tool invocation cannot clean files created in a later, separate shell. For work spanning several calls, let the agent track its task directory and explicitly clean it at the end.
The quoted variable and -- restrict removal to the exact directory returned by mktemp. Do not replace that path with a wildcard over /tmp. This example uses foreground commands; wait for child processes before letting the owning shell exit. Check the cleanup result as shown in Step 6 rather than assuming deletion always succeeds.
Step 4: Use TemporaryDirectory for Python work
Save this as cleanup_demo.py, or download the complete example:
#!/usr/bin/env python3
import os
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
base = Path(os.environ.get("TMPDIR", "/tmp/codex-work"))
base.mkdir(parents=True, exist_ok=True)
output = Path("artifacts/cleanup-result-python.txt")
output.parent.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(prefix="task-", dir=base) as directory:
task_tmp = Path(directory)
print(f"Task directory: {task_tmp}")
intermediate = task_tmp / "result.txt"
intermediate.write_text("temporary input\n".upper(), encoding="utf-8")
shutil.copyfile(intermediate, output)
print(f"Temporary directory exists: {task_tmp.exists()}")
print(f"Deliverable exists: {output.exists()}")
Run it with Python 3; no third-party package is needed:
python3 cleanup_demo.py
Expected final lines:
Temporary directory exists: False
Deliverable exists: True
Python removes the directory when the context exits, including ordinary exception unwinding. mkdtemp() alone requires manual cleanup. See the Python tempfile documentation.
Keep every temporary file inside that directory and copy the final output before leaving the block. Close file handles and wait for subprocesses first. Abrupt termination can bypass context cleanup.
Step 5: Add cleanup around local Codex CLI runs
For an additional fallback, use a launcher. It creates a fresh session directory, sets TMPDIR, waits for the foreground CLI command, and removes that directory on exit. It also preserves a failing CLI exit status.
Create the project’s scripts/ directory, then save this as scripts/codex-clean. You can also download the launcher:
#!/usr/bin/env bash
set -euo pipefail
command -v codex >/dev/null 2>&1 || {
printf 'codex is not on PATH\n' >&2
exit 127
}
run_root=/tmp/codex-work
mkdir -p "$run_root"
run_tmp=$(mktemp -d "$run_root/session-XXXXXXXX")
readonly run_tmp
cleanup() {
run_status=$?
trap - EXIT
if rm -rf -- "$run_tmp"; then
printf 'Cleaned session directory: %s\n' "$run_tmp" >&2
else
printf 'Cleanup failed: %s\n' "$run_tmp" >&2
if [ "$run_status" -eq 0 ]; then
run_status=1
fi
fi
exit "$run_status"
}
trap cleanup EXIT
export TMPDIR="$run_tmp"
printf 'Session directory: %s\n' "$run_tmp" >&2
codex --no-daemon --sandbox workspace-write \
--add-dir "$run_tmp" \
-c "shell_environment_policy.set.TMPDIR=\"$run_tmp\"" \
"$@"
Then run:
mkdir -p scripts
# Save the launcher above as scripts/codex-clean before running:
chmod +x scripts/codex-clean
./scripts/codex-clean
Inside the session, ask Codex to create task subdirectories within $TMPDIR and follow Step 2’s rule. When finished, exit the CLI to trigger session cleanup. A completed response in an open interactive session does not trigger the launcher’s trap.
For a single noninteractive task, run:
./scripts/codex-clean exec \
'Use a unique task directory inside TMPDIR for scratch files. Save a short cleanup test report as artifacts/codex-cleanup-report.txt, then remove your task directory and verify it is gone.'
Use this from a repository you trust. If execution stops at a repository check, resolve that prerequisite before judging cleanup behavior.
The launcher grants write access to its session directory, explicitly sets the tool-shell TMPDIR, and uses --no-daemon for a local foreground run. See the CLI reference and environment configuration reference.
TMPDIR is a convention, not filesystem isolation. A command with a hard-coded /tmp/example path can still write outside the session directory. The launcher only deletes its own directory. Remote sessions, detached jobs, and shared background servers need cleanup tied to their actual lifetime. Finish or stop processes using its files before exiting. Keep data needed across session resumes in the workspace.
Step 6: Verify cleanup and saved output
The launcher prints paths like these:
Session directory: /tmp/codex-work/session-Ab12Cd34
Cleaned session directory: /tmp/codex-work/session-Ab12Cd34
Check the actual path printed by your run. This command asks for the path instead of guessing a directory:
bash <<'BASH'
read -r -p 'Paste the session directory printed by the launcher: ' checked_tmp < /dev/tty
if [ -e "$checked_tmp" ]; then
printf 'Still exists: %s\n' "$checked_tmp"
else
printf 'Removed: %s\n' "$checked_tmp"
fi
test -f artifacts/codex-cleanup-report.txt
BASH
After the noninteractive example, expect Removed: ... and a successful deliverable check. Confirm the report content too. A cleanup sentence in the model’s answer is weaker evidence than a filesystem check. For the Bash example, check its printed task path and artifacts/cleanup-result.txt instead.
You can list remaining session directories without deleting them:
find /tmp/codex-work -mindepth 1 -maxdepth 1 -type d -name 'session-*' -print
Other directories may belong to active sessions. A nonempty parent directory does not establish that your own run failed to clean up.
Step 7: Troubleshoot common failures
Codex still writes directly into /tmp
Ask it to print $TMPDIR from an actual tool shell, then use that directory explicitly in mktemp -d "$TMPDIR/task-XXXXXXXX" or TemporaryDirectory(dir=...). Some tools ignore TMPDIR. If your environment policy uses an allowlist, ensure it permits TMPDIR; do not disable the whole policy. Environment policy reference
The AGENTS.md rule is ignored
Restart Codex in the intended project and check same-level AGENTS.override.md files. If CODEX_HOME is set, edit the instructions there. Ask Codex to summarize the active cleanup rule. Instruction discovery
Permission denied or an unsupported launcher flag
Check that your user can create /tmp/codex-work directories and inspect codex --help. If a shared server’s parent directory belongs to another user, choose a user-owned writable task root and adjust the rule and launcher together. --add-dir adds write access in workspace-write mode, subject to organization policies. Keep the sandbox enabled. Older CLIs without --no-daemon need an updated CLI or the script-level methods above.
The directory survives a crash
Neither instructions nor an EXIT trap can run after SIGKILL or power loss. Once you have confirmed the exact directory belongs to a stopped run and contains no needed output, remove that directory only. Do not schedule an age-only deletion job: a long-running task can still use old files. Automated crash recovery needs ownership and liveness checks appropriate to your scheduler.
Cleanup succeeds but disk space is still missing
Another process may hold a deleted file open. Follow the related Linux deleted-file disk-space guide. Deleting additional unrelated temporary files does not diagnose that condition.
Summary
Add a clear temporary-file rule to AGENTS.md, create a unique directory for each task, and save deliverables before cleanup. Use Bash traps or Python context managers to remove temporary files on ordinary completion and failure. For local CLI sessions, the launcher adds cleanup at command exit; verify the exact directory is gone and keep persistent output in the workspace.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/codex-tmp-auto-clean.html
- 版权声明:本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。
相关文章
- Fix Delayed Python Logs with -u, flush, and Bash pipefail
- Stream gzip Logs with Python and Detect Truncation and CRC Errors
- Back Up SQLite with Python: WAL Snapshots and Restore Checks
- Python SIGTERM Shutdown: Finish the Current Record Before Stopping
- Debug a Stuck Python Script with faulthandler Thread Dumps