Skip to content

Codex Environment & Debugging Playbook

Download this guide (PDF)

Codex runs your code in a locked-down cloud container. Get three things right (the network allowlist, the setup script, and the written rules in AGENTS.md) and it behaves like a tireless pair-programmer. Add a master prompt and worker prompts and it can audit, fix and re-test a whole codebase while you watch the gates turn green.

Docs checked December 1, 2026. OpenAI documents two experiences, current Codex Cloud and Codex Cloud (Legacy); setting names can change, so treat labels as a guide.

The six artifacts

# Artifact What it does
1 Network fix Stops pypi.org: via pip install from being blocked: allowlist, republish, or vendor wheels.
2 Setup script Builds the virtualenv and installs every dependency and tool while the internet is still on.
3 AGENTS.md Standing instructions: commands, quality bar, guardrails.
4 Debug workflow The gate ladder, single vs. parallel sessions, CI and pre-commit guardrails.
5 Master prompt Full audit, debug and fix loop with a dashboard report.
6 Worker prompt One module, task to sub-task decomposition, Tree-of-Thoughts ranking, YAML patch output.

Beyond the post: what changed from the original ChatGPT export

  • Custom Instructions became AGENTS.md. Codex reads AGENTS.md files from your repo. Do not rely on ChatGPT profile settings to steer Codex.
  • Setup script fixed. Removed pip flags that poetry install does not accept, and the venv now persists into the agent phase (setup runs in a separate shell).
  • Ruff E999 dropped. It was removed in Ruff 0.8.0; syntax errors are always reported now.
  • Coverage gate and benchmark command repaired. The original XML check could not run, and --benchmark-only skips normal tests.
  • Both Codex experiences covered: current Codex Cloud and Codex Cloud (Legacy).

1. Fix "Network access blocked"

The error

Network access: Some requests were blocked due to network access restrictions. Consider granting access in environment settings. pypi.org: via pip install

Nothing is broken. A Codex task has two phases: the setup script runs with internet access, then the agent runs with internet off by default. A pip install run by the agent hits that wall. You fix it in the environment settings, not in your code.

flowchart LR
    A["1 Start: container created, repo checked out"] --> B["2 Setup script: pip / poetry install, internet ON"]
    B --> C["3 Snapshot cached, Legacy up to 12 h"]
    C --> D["4 Maintenance script on resume, optional"]
    D --> E["5 Agent runs tests, ruff, mypy, internet OFF by default"]
    E --> F{"pypi.org allowlisted?"}
    F -- yes --> G["pip install works"]
    F -- no --> H["Blocked: network access restrictions"]
    H --> I["Fix: enable internet, allowlist, republish, test in a NEW task"]

Fix it in four steps

  1. Open the environment. Open Codex settings and edit the environment attached to your repository.
  2. Turn on internet access for the agent. The switch is labelled Allow Codex to access internet in current Codex Cloud (Legacy: agent internet access).
  3. Choose the narrowest policy that works (table below). For Python packages, Package managers already includes PyPI.
  4. Save and republish, then test in a NEW task. Existing tasks keep their old policy. Re-run pip install <package> there.

Pick a policy

Policy What it allows Use it when
Package managers (Legacy: "Common dependencies") A preset of registries and download hosts: PyPI (pypi.org, pythonhosted.org), npm, crates.io, the Go proxy, Maven/Gradle, Ubuntu/Debian archives, GitHub source and releases. The agent only needs to install dependencies. Recommended default.
Custom domains only (Legacy: "None" + your list) Only the hosts you list under Additional allowed domains. Add exact hostnames: pypi.org and files.pythonhosted.org. Other subdomains need their own entries. Tighter control, or a private index plus PyPI.
All (unrestricted) Everything on the public internet. Rarely. Raises prompt-injection and exfiltration risk.

Security note

Agent internet access increases risk: prompt injection from untrusted web pages, code or secret exfiltration, malware or vulnerable dependencies, and license-restricted content. Allow only the domains you need, review the work log, and keep a no-internet environment for sensitive repos. Legacy environments can also restrict requests to GET, HEAD and OPTIONS. An allowed domain opens the network path only; it does not supply credentials.

Verify the fix

In a new task, ask Codex to run these three probes. If any fails, the host is not on the allowlist yet.

# In a NEW task after republishing: can the agent reach PyPI?
curl -sSI https://pypi.org/simple/ | head -n 1                         # expect HTTP/2 200
pip download --no-deps --dest /tmp/probe requests                     # expect "Saved ..."
curl -sSI https://files.pythonhosted.org/ | head -n 1                  # file host reachable?

If you cannot (or should not) enable internet

Vendor the wheels:

# on your machine
pip download -r requirements.txt -d wheels/
# upload wheels/ with the repo, then in the setup script:
pip install --no-index --find-links wheels/ \
    -r requirements.txt

Or point pip at a private index with pip.conf or --index-url, and add only that host to the allowlist.

  • Secrets in Legacy environments exist only during setup; they are removed before the agent runs.
  • Legacy caches the container for up to 12 hours. Changing the script, variables or secrets resets the cache; otherwise use Reset cache.

2. The setup script

Every task starts in a fresh container. The setup script is your one chance, with the internet on, to build the virtualenv and download every dependency and tool. Paste this into the Setup script field (Legacy), or hand it to Codex as the install script to test and record (current Codex Cloud).

#!/usr/bin/env bash
# Codex setup script: Python / Django / Poetry.  Runs WITH internet access.
set -Eeuo pipefail

POETRY_VERSION="${POETRY_VERSION:-}"   # empty = latest; pin it once your lockfile needs a specific version
PY_TOOLS="${PY_TOOLS:-ruff mypy pytest pytest-cov pytest-xdist pytest-benchmark pre-commit}"

cd "${REPO_DIR:-$PWD}"                 # setup runs from the repo checkout
python --version                       # choose the version in Environment > Set package versions

# 1. In-project virtualenv: same paths in every session
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip wheel setuptools

# 2. Poetry (it will use the active .venv)
python -m pip install "poetry${POETRY_VERSION:+==$POETRY_VERSION}"
poetry config virtualenvs.in-project true

# 3. Download EVERYTHING now, while the network is open
poetry install --no-interaction --all-extras --with dev,test
python -m pip install $PY_TOOLS        # better: add these to the dev group in pyproject.toml
# python -m pip install opentelemetry-distro opentelemetry-instrumentation-django   # optional tracing

# 4. Pre-build the git-hook environments so they work offline later
pre-commit install --install-hooks || true

# 5. Setup runs in a SEPARATE bash session: persist what the agent phase needs
{
  echo "source \"$PWD/.venv/bin/activate\""
  echo "export PIP_NO_INPUT=1 PIP_DISABLE_PIP_VERSION_CHECK=1 COVERAGE_FILE=\"$PWD/.coverage\""
} >> ~/.bashrc

# 6. Smoke test: surface problems now, but do not fail setup on red tests
pytest -q || true
ruff --version && mypy --version
echo "Environment ready."

Before you paste

  • Drop any Poetry group you do not have from --with dev,test; Poetry errors on unknown groups.
  • Pick the Python version in the environment's Set package versions (or CODEX_ENV_PYTHON_VERSION in the reference image), then confirm with the python --version line.
  • Uncomment the OpenTelemetry line only for Django projects you want traced.

What each block does, and why

Block Why it matters
1. In-project .venv Stable paths between sessions. Poetry reuses the active venv.
2. Poetry, pinned on demand Pin POETRY_VERSION once your lockfile needs it; otherwise stay current. (The original pinned 1.8.2.)
3. Install everything now The agent phase has no internet by default, so test and lint tools (pytest-cov, pytest-xdist, mypy, ruff) must already be there.
4. Pre-build hook environments pre-commit downloads each hook's environment on first use; doing it here avoids a network error later.
5. Persist to ~/.bashrc Setup runs in a separate Bash session, so source and export do not carry over. Without this, the agent would not see your venv.
6. Smoke test Tracebacks show up in the setup log. || true keeps red tests from failing the whole setup.

Creative ways to use the sandbox

Capability Try this Payoff
Inline test runs "Run pytest -q and list the failing lines." TDD loop without leaving the task.
AI-assisted review pre-commit run --all-files, then "fix Ruff E501 only". Mechanical style work delegated.
Profiling Add django-silk; hit a view; inspect SQL timing at /silk/. Finds N+1 queries before CI.
Trace visualisation Export OTLP JSON to a file during tests, then "plot span durations". Performance dashboard in the task.
Mutation testing Add mutmut; run mutmut run --paths-to-mutate app/. Shows tests that pass but prove nothing.

Easy-to-forget checklist

  • Internet policy allows pypi.org and files.pythonhosted.org if the agent must install anything (Part 1).
  • PIP_NO_INPUT=1 so nothing hangs on a y/n prompt (set in step 5).
  • COVERAGE_FILE points to a stable path so runs merge their results.
  • Secrets go in the Secrets or Network secrets settings, never in the repo. In Legacy they are setup-only.
  • Commit a .devcontainer.json that calls the same script so local VS Code matches Codex.
  • The same script works in CI (ubuntu-latest or python:3.x); add a make test target.
  • Republish the environment after dependency changes; new tasks start from the published snapshot.

3. AGENTS.md: your rules, in the repo

The original session built a two-box "Custom Instructions" block. The reliable place for those rules in Codex is a file named AGENTS.md. It travels with the repo, applies to every task and every teammate, and is how Codex learns your lint and test commands.

Why not ChatGPT Custom Instructions?

Those are profile settings for ChatGPT conversations. Codex documents AGENTS.md as its instruction mechanism, so put anything you need enforced there.

Template: copy to the repo root

# AGENTS.md

## Project
Python 3.x, Django, Poetry. The virtualenv is `.venv` (created by the setup script and
auto-activated). Source in `src/`, tests in `tests/`.

## Commands: run in this order
- Tests:       `pytest -q`            (`-n auto` when a path has more than 5 tests; `--maxfail=1` while fixing)
- Lint + fix:  `ruff check --fix` then `ruff format`
- Types:       `mypy src/`
- Coverage:    `coverage run -m pytest && coverage report --fail-under=85`
- Hooks:       `pre-commit run --all-files`

## Rules
- Assume the network is OFF. Never pip install / poetry add during a task; if a
  dependency is missing, say so and stop.
- Never weaken, skip, xfail or delete a test to make it pass. Fix the code.
- No `# noqa` or `# type: ignore` without a one-line reason.
- Secrets come from environment variables (`os.getenv`). Never hard-code or print them.
- Smallest correct diff. Every bug fix ships with a pytest test that fails before the fix.
- Type-hint new functions; Google-style docstrings; flag un-instrumented views and jobs.
- Ask ONE clarifying question only if truly blocked; otherwise ship runnable code.

## Reporting
Start with a one-sentence TL;DR, then steps taken, then how to re-run the checks and the
coverage change.

## Definition of done
All commands above exit 0, coverage >= 85 %, no new warnings, diff reviewed.

How Codex finds and merges AGENTS.md

  1. Global: one file from ~/.codex (AGENTS.override.md first, else AGENTS.md).
  2. Project: from the repo root down to your working directory, one file per folder (AGENTS.override.md, then AGENTS.md, then any configured fallback names).
  3. Merge: files are joined root-first, so the closest file wins. Combined size is capped by project_doc_max_bytes (32 KiB by default); split rules into nested folders if you hit it.

Monorepo? Nest a closer file

# services/payments/AGENTS.md   (closest file wins; keep it short)
- Money is `Decimal`, never `float`. Currency codes are ISO 4217 strings.
- Run only this package's tests while iterating:  `pytest services/payments -q`
- Any change to a public function needs a contract test in `tests/contracts/`.

Then prove it loaded: start a task and ask "Summarise the instructions you loaded, in order." You should see the root rules followed by the folder rules.

Directive to reason

Directive Why it is there
Assume the network is off The agent phase blocks egress unless you allowlisted it, so ad-hoc installs fail. Missing dependencies belong in the setup script.
Never weaken tests The fastest way for an agent to turn a gate green is to skip the test. This rule closes that door.
ruff check --fix then ruff format One tool for lint and format; fixes first, formatting last.
coverage report --fail-under=85 Turns "enough coverage" into an exit code the agent cannot argue with.
Secrets via os.getenv Keeps keys out of diffs and logs.
One clarifying question Keeps momentum without endless back-and-forth.
TL;DR first Makes review of long runs fast.

Boosters

  • Add "generate Google-style docstrings for new functions" and docs grow with the code.
  • Add "when you add an endpoint, add a span and a test" to keep observability honest.
  • Point new teammates at this file; the task logs become an onboarding guide for your stack.

4. Debug with gates, not guesses

Strive for accuracy by letting tools find the bugs: tests first, cheap automatic fixes next, interactive debugging only for what is left. When a rung is red, fix it and restart from rung 1.

The ladder in commands

# Command What it tells you
1 pytest -q --maxfail=1 A red test is the fastest bug locator. Reproduce it here before reading stack traces.
2 ruff check --fix and pre-commit run --all-files Unused imports, many PEP 8 problems and other safe issues fixed in milliseconds.
3 mypy src/ Interface mismatches caught before they become runtime surprises.
4 pytest -q --cov=src, coverage html, then pytest --benchmark-only Un-exercised branches, then slow paths. Run benchmarks as a separate command: --benchmark-only skips non-benchmark tests.
5 pytest tests/test_bad.py -x --pdb Drops into pdb at the failure for the stubborn cases.
6 opentelemetry-instrument --traces_exporter console python manage.py runserver Console spans expose slow queries and circular imports.

One Codex session, or several?

Strategy Best for Watch out for
One container + pytest -n auto Many small or I/O-bound tests. Fewest moving parts and simplest coverage. Tests that share global state fail in parallel; audit fixtures first.
One session, serial tests CPU-bound suites or heavy Django DB fixtures. Slower wall-clock time.
Several Codex tasks Large refactor plus new-test writing, or independent modules (Parts 5 and 6). Merge conflicts and duplicated context. Give each task its own branch and a clear remit.

Rule of thumb

Optimise tests in-process (-n auto) before starting extra Codex tasks. You avoid context duplication and keep one virtualenv cache. Use a second task only when two streams of work touch different files, and let the tests arbitrate truth.

Put it on autopilot

Hooks, .pre-commit-config.yaml:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: <latest tag>            # run `pre-commit autoupdate` to pin the current release
    hooks:
      - id: ruff                 # keep the linter BEFORE the formatter
        args: [--fix]
      - id: ruff-format
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: <latest tag>
    hooks:
      - id: mypy
        additional_dependencies: []   # e.g. django-stubs

CI gate on coverage:

# .github/workflows/test.yml (steps only)
- run: pip install poetry && poetry install --with dev,test
- run: poetry run pytest -q -n auto --cov=src
- run: poetry run coverage report --fail-under=85     # fails the job below 85 %

Profile like production: add django-silk to a dev settings module and read SQL timings at /silk/.

Done means done

  • pytest -q passes and coverage is at least 85 %.
  • ruff check --fix reports 0 remaining issues.
  • mypy prints "Success: no issues found".
  • OpenTelemetry console spans appear for key views and background jobs.
  • CI is green and parallel test time is acceptable.

5. The master prompt

Paste this into a fresh Codex task once the environment and AGENTS.md are in place. It runs the gates, classifies every failure, fixes what it can, re-runs, and reports on a dashboard. It stops after three loops so it cannot spin forever.

ROLE
You are a senior Python code auditor working inside this Codex sandbox. Follow AGENTS.md.

GOAL
Run a full audit -> debug -> fix cycle until every quality gate is green (max 3 loops).

QUALITY GATES (run exactly these)
G1  pytest -q
G2  ruff check --fix && ruff format
G3  mypy src/
G4  coverage run -m pytest && coverage report --fail-under=85
G5  (optional) pytest --benchmark-only        G6  (optional) python manage.py check --deploy

PROCEDURE
1. BASELINE   Run G1-G4 without editing anything. Record every result.
2. CLASSIFY   List every failure (test break, lint, type, coverage < 85 %, missing OTel spans)
              as syntax/logic, style, type, performance or observability. Group by module.
3. FIX        Smallest correct change per issue; add a regression test with each logic fix.
              If one module has 3+ failures, hand it to a worker (WORKER PROMPT) on its own branch.
4. RE-RUN     Re-run G1-G4. Anything red -> back to step 2. Stop after 3 loops and report.
5. REPORT     Produce the output below.

CONSTRAINTS
- No network calls, no installs.
- Never delete, skip or xfail tests. Never hard-code secrets (use os.getenv).
- Do not edit generated files, migrations already applied, or files outside the repo.
- Ask exactly ONE clarifying question if requirements are ambiguous; otherwise proceed.
- Keep prose short; accurate diffs and passing tests matter most.

OUTPUT FORMAT
### RESULTS   one row per gate (PASS/FAIL), last 30 lines of each failing gate
### CHANGES   files touched + one-line git-style commit message each
### SUMMARY   green/red dashboard, coverage %, benchmark delta, remaining TODOs

Begin now.

What a finished run looks like

Illustrative SUMMARY block; numbers are made up.

Gate Result Detail
G1 pytest -q PASS 412 passed in 38 s (loop 2 of 3)
G2 ruff PASS 0 remaining; 31 safe fixes applied
G3 mypy PASS Success: no issues found in 87 source files
G4 coverage PASS 88.4 % (+6.1 %), threshold 85 %
G5 benchmark WATCH one endpoint 12 % slower; recorded as a TODO

Why it works

Pattern Effect
Role prompt "Senior Python code auditor" keeps tone and priorities consistent.
Baseline before edits You can diff results and prove each fix helped.
Loop with a cap Iterates to green, but three loops bound cost and runaway edits.
Exit-code gates --fail-under and tool exit codes leave no room for "looks fine".
Anti-cheat constraints No skipped or deleted tests, no secrets in code, no edits outside scope.
One clarifying question Keeps momentum without endless replies.

Usage tips

  1. Run on a clean branch. Let Codex commit; squash-merge later.
  2. Single tab + pytest -n auto is usually faster and avoids merge pain. If you open two tabs, give them separate branches (for example audit/fixes and audit/tests) and let CI reconcile.
  3. Timeout guard. Huge diffs can exceed limits; split the prompt by directory.
  4. Persist artefacts. Keep .coverage, coverage.xml and any Silk profiles for later diffs.

Customise it

Goal Change
Raise the bar Swap 85 for your threshold in G4 and in AGENTS.md.
Performance gate Add G5 with an agreed tolerance for pytest --benchmark-only.
Security pass Insert bandit -r src and pip-audit after Ruff (install them in setup).
Django production settings Keep G6: python manage.py check --deploy.

Edits, not paste-backs

The original asked for full-file replacements in a code block, which suits plain chat. Inside a Codex task the agent edits files directly, so this version asks for a change list and commit messages. If you do paste into plain chat, add: "output each changed file as one full replacement block."

6. The worker prompt

The master orchestrates. The worker specialises: it takes one module and its failing output, breaks it into sub-tasks, tries several fixes per sub-task, and returns a patch the master can merge. Paste it into a second task, or let the master fill the two placeholders and launch it.

ROLE
You are a specialised "debug worker" inside the Codex sandbox. Your only boss is the master
prompt. You receive ONE module path ({MODULE_PATH}) and its failing-gate output ({FAILURE_LOG})
and must return a pass-ready patch. Follow AGENTS.md.

TASK-DECOMPOSE
1. Parse {FAILURE_LOG}; list each distinct error as a sub-task.
2. Order sub-tasks by dependency: lint -> type -> logic -> coverage -> performance.
3. For each sub-task:
   a. Generate up to three candidate fixes ("thoughts"), at least two different approaches.
   b. Rank them by likelihood of success and code stability; pick the best.
   c. Apply it, then run the localised tests:  pytest {MODULE_PATH} -q
      (add -n auto when the path has more than 5 tests).
4. When every sub-task passes: ruff check {MODULE_PATH} --fix, then mypy {MODULE_PATH}.
   Use `ruff --unsafe-fixes` only after ALL safe fixes succeed, and review each unsafe diff.
5. If a fix depends on another module, decompose recursively: fix the dependency first,
   but only inside {MODULE_PATH}; report anything outside it instead of touching it.
6. If any gate still fails, loop back to step 3 (max 3 loops), then set passes: false.
7. Emit exactly this YAML:

module: <MODULE_PATH>
passes: true            # or false after 3 loops
patches:
  - file: <relative path>
    content: |-
      # full replacement of the file
summary: |
  - tests passed in X s
  - coverage delta +Y %
  - remaining TODOs: none

CONSTRAINTS
- No network calls or installs.  Never delete, skip or xfail tests.
- Do not touch anything outside {MODULE_PATH}.
- Ask ONE clarifying question if the log is ambiguous; otherwise start immediately.

Begin on the supplied module now.

Why this structure is accurate

Technique What it buys you
Task to sub-task List errors first, solve them one by one: factored decomposition improves LLM accuracy on complex tasks.
Tree-of-Thoughts candidates Generate and rank several fixes before choosing; reported to beat single-shot reasoning on coding tasks.
Safe-then-unsafe linting --fix applies safe fixes only; --unsafe-fixes can change behaviour, so apply it last and review.

Also: localised runs (pytest {path}, plus -n auto past five tests) cut iteration time and isolate side effects, and Codex tasks run in separate containers that merge through Git, which is the pattern this prompt uses.

Master + worker, end to end

flowchart TD
    M1["Master: run gates, pytest ruff mypy coverage"] --> M2["Master: triage failing modules and logs"]
    M2 --> W1["Worker 1: src/services/payments"]
    M2 --> W2["Worker 2: src/api"]
    M2 --> W3["Worker 3: tests/unit/models"]
    W1 -- YAML patch --> M3["Master: apply patches, rerun global gates"]
    W2 -- YAML patch --> M3
    W3 -- YAML patch --> M3
    M3 --> D{"All gates green?"}
    D -- yes --> Z["Done: PR plus dashboard summary"]
    D -- no, max 3 passes --> M2
  1. Master task: run the master prompt. It finds the failing modules and launches one worker per module with {MODULE_PATH} and {FAILURE_LOG} filled in (new Codex tasks, or chained calls).
  2. Worker tasks: each follows the script and returns a YAML patch. Keep one branch per worker.
  3. Master again: merge the patches, re-run the global gates, and close the loop only when everything is green or three passes are used.

Guardrails for multi-agent runs

  • Give every worker its own branch and forbid edits outside its module; overlapping files cause merge pain.
  • Treat passes: true as a claim. The master must re-run the global gates before believing it.
  • Review any --unsafe-fixes diff and any change to a test file by hand.

Quick reference and troubleshooting

Symptom Likely cause Fix
pypi.org: via pip install blocked Agent internet is off or the host is not allowlisted. Part 1: enable internet, Package managers or custom domains, republish, new task.
Allowed pypi.org but still blocked on a download Custom list is missing the file host. Add files.pythonhosted.org; subdomains need their own entries.
Tools "not found" in the agent phase Setup's source / export did not persist. Append them to ~/.bashrc (script step 5).
Setup change has no effect Cached container or unpublished environment. Republish; Legacy: Reset cache.
poetry install fails on groups --with names a group that does not exist. Drop unknown groups from the command.
pre-commit tries to download hooks Hook environments were not built in setup. pre-commit install --install-hooks in setup.
Tests pass alone, fail with -n auto Shared global state or fixtures. Audit fixtures; run serially for that path.
Agent ignores your rules Rules are in a ChatGPT profile, or AGENTS.md exceeds the size cap. Move them to AGENTS.md; keep it under 32 KiB or split by folder.
A noqa: E999 comment lingers The rule was removed in Ruff 0.8.0. Delete it; enable RUF100 to find other stale noqa comments.

Sources

Verified December 1, 2026.


Generals of Chaos · Order the chaos. Rebuilt from an exported ChatGPT working session: conversational Q&A flattened into an engineering playbook, citation placeholders removed, commands corrected and re-verified.