# Codex cloud environments: setup, caching, network, and best-of-N

URL: https://developertoolkit.ai/en/codex/automate/cloud-environments/
Description: Architect Codex cloud environments: setup vs maintenance scripts, setup-only secrets, default-off egress, best-of-N trade-offs, and objective diff gates.

A Codex cloud environment defines the isolated hosted container where unattended Codex cloud tasks execute: repository checkout, setup and maintenance phases, setup-only secrets, container caching, and a default-off agent internet policy. Developers and tech leads architect these boundaries so background tasks stay fast, reproducible, safe against prompt injection, and verifiable through CI.

Your first cloud task burns most of its runtime reinstalling packages, the second fails offline against a private registry, and the third opens a pull request whose tests never ran because browser binaries were missing. Every one of those failures stems from environment architecture rather than model quality.

## Understand the six-phase cloud task lifecycle

Every cloud task—whether triggered from the web, CLI, GitHub, or workspace chat integrations—moves through strict phase boundaries that explain almost every runtime failure:

1. **Container start:** Codex launches a container from its base image (or resumes a cached snapshot) and checks out your pushed remote branch.
2. **Setup phase:** Setup runs with internet access and is the **only phase where secrets exist**.
3. **Maintenance phase:** On cached resumes, Codex skips full setup and runs the fast maintenance script to catch up with recent branch changes.
4. **Lockdown:** Secrets are purged from the container and the agent-phase internet policy engages (default: completely offline).
5. **Agent loop:** Codex reads committed `AGENTS.md` instructions, edits files, and runs build, lint, and test commands inside the prepared filesystem.
6. **Result:** The task returns a summary and one diff per attempt, ready for inspection, local application, or pull-request review.

OpenAI offers both **published reusable cloud environments** (prepared, tested, and shared across a workspace for interactive and chat delegation) and **script-configured cloud environments** (used for custom setup/maintenance pipelines and repository integrations). Follow the [official OpenAI Codex documentation](https://developers.openai.com/codex) for current UI workflows, `codex cloud` CLI subcommands, and plan availability.

## Design setup, caching, and secret boundaries deliberately

### Split expensive setup from fast maintenance

Start with automatic dependency installation for standard ecosystems, and write an explicit setup script once tasks need system packages, code generators, browser binaries, or shared workspace builds. Keep three invariants in every setup script:

- **Fail loudly (`set -euo pipefail`):** Silent install failures let the agent waste turns diagnosing "command not found" errors.
- **Pin lockfile installs (`--frozen-lockfile`, `npm ci`):** Guarantee every container resolves the exact dependency graph CI tests.
- **End with a smoke gate (such as `typecheck`):** A broken environment should fail during setup with a clear log rather than tempting the agent to edit application code around missing tools.

Because container snapshots stay warm across tasks for hours, split work by change frequency:

- **Setup script (expensive, rare changes):** OS packages, Playwright/browser binaries, base toolchain, initial lockfile install.
- **Maintenance script (cheap, runs on every cached resume):** Frozen lockfile sync and codegen so cached containers never test today's branch against yesterday's schemas or dependencies.

Remember two practical traps: setup runs in a separate shell from the agent (persist required runtime variables through environment settings rather than transient `export`), and resetting a shared environment's cache forces every teammate's next task to pay full setup time. Rehearse setup scripts locally using OpenAI's `codex-universal` reference container before saving changes to a shared environment.

### Enforce the secrets vs environment variables split

| Store | Available during | Appropriate contents | Never store here |
| --- | --- | --- | --- |
| Environment variable | Setup and agent phases | `NODE_ENV=test`, local test DB URLs, test flags | Anything unsafe to expose in a pull request or log |
| Secret | Setup phase only (removed before agent loop) | Private npm/PyPI registry tokens, container pull tokens | Credentials required during runtime test execution |

Removing secrets at lockdown ensures a prompt-injected dependency or web page cannot exfiltrate registry tokens during the agent loop. Whenever tests require a runtime credential, supply an isolated test-only dummy key or stub the external service.

## Lock down agent internet access

Setup always has network access; the agent loop has **none by default**. That default blocks three major risks at once: prompt injection from external pages, code exfiltration, and unreviewed package installs.

Turn agent internet on only when tasks genuinely cannot run offline, combining the tightest domain allowlist with read-only HTTP methods:

| Egress posture | Policy shape | When to use |
| --- | --- | --- |
| Off (default) | Zero agent internet | All packages and fixtures install during setup. Start here. |
| Locked down | Common dependencies preset + explicit named domains · `GET`, `HEAD`, `OPTIONS` only | Agent must query public registries or read-only test APIs |
| Hand-built allowlist | Empty preset + manually justified domains · read-only methods | Regulated codebases requiring written justification per host |
| Unrestricted | All domains allowed | Disposable sandboxes holding zero proprietary code or secrets. Avoid on real repos. |

Restricting methods to `GET`, `HEAD`, and `OPTIONS` prevents `POST`/`PUT` exfiltration, yet query parameters in `GET` URLs can still leak data to an allowlisted domain—keep the domain list minimal.

**Network access turns external text into untrusted instructions**

Any GitHub issue, documentation page, or API response fetched during the agent loop can embed hostile prompt-injection instructions. Narrow domain allowlists and read-only HTTP methods enforce protection mechanically; reading the agent's summary afterwards cannot. See [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/).

## Use best-of-N and monorepo fan-out selectively

Codex cloud supports running multiple independent attempts (`--attempts`, best-of-N) on the same prompt and fanning identical scoped prompts across monorepo packages. Because each attempt consumes a full agent run, spend extra runs only where ambiguity makes a single first pass expensive:

- **Good fits for best-of-N:** Race conditions, subtle caching bugs, refactors with genuinely competing designs, or performance trade-offs. Name distinct candidate approaches explicitly if attempts keep converging on identical diffs.
- **Skip best-of-N for mechanical edits:** Three identical diffs waste compute without improving confidence.
- **Monorepo fan-out discipline:** Submit one narrow task per package against a pushed branch using an identical prompt template so diffs remain directly comparable, and forbid cross-package edits in each task.

## Verify cloud task diffs without reading every line

Treat every cloud diff as an untrusted proposal filtered through five objective gates:

1. **Require CI-equivalent command output.** Your setup script makes every `AGENTS.md` check runnable; reject any cloud task whose summary omits the exact lint, typecheck, and test commands and exit statuses.

2. **Check blast radius from task metadata first.** Inspect changed-file and line counts before reading diffs—a single-endpoint fix touching 40 files goes back with tighter scope immediately.

3. **Re-run verification outside the agent.** Apply the diff inside a clean local [Git worktree](/en/codex/automate/worktrees/) or open a pull request and let CI run on a clean runner. CI is the authority, never the agent's summary.

4. **Run automated review and protect the oracle.** Trigger `@codex review` ([code review with Codex](/en/codex/ship/code-review/)) and explicitly inspect any edits to test assertions, snapshots, CI files, or lockfiles ([protecting the oracle](/en/workflows/test/protect-the-oracle/)).

5. **Keep named human merge ownership.** Best-of-N and fan-out scale proposal generation while the submitting engineer retains full merge accountability.

Before enabling team-wide cloud delegation, run `npx @wondelai/harness-audit` ([Harness Audit](/en/harness-audit/)) to confirm your repository's `AGENTS.md` and CI checks align cleanly.

## When Codex cloud environments break

| Symptom | Root cause | Recovery |
| --- | --- | --- |
| "Command not found" during agent loop | Setup failed silently or exported `PATH` only inside setup shell | Add `set -euo pipefail`, persist variables via environment settings, and rehearse in `codex-universal` |
| Tests pass in cloud but fail in CI | Warm container cache holds stale dependencies or codegen | Move frozen lockfile sync and codegen into maintenance script; reset cache once |
| Every task pays full cold-start time | Frequent edits to setup script, vars, or secrets invalidate cache | Batch environment changes and keep volatile refresh steps in maintenance |
| Agent cannot fetch a package mid-task | Agent internet is disabled by default | Install the dependency during setup, or allowlist its registry read-only |
| Private registry fails during agent loop | Secret token was purged at lockdown | Move private package installs into setup; never copy secrets into env vars |
| Task ran against outdated code | Local commits were not pushed or wrong branch targeted | Push the branch first and pass branch identifiers explicitly in scripts |
| Applying a cloud diff fails locally | Local working tree diverged from task base | Apply into a clean worktree checked out at the task's base branch |

## Official docs and next steps

Refer to [developers.openai.com/codex](https://developers.openai.com/codex) for current published-environment flows, `codex cloud` CLI commands, and Slack, Linear, and GitHub integration setup.

- Cross-tool comparison of hosted sandboxes: [ephemeral environments](/en/workflows/harness/ephemeral-environments/)
- Unattended automation patterns: [background agents](/en/workflows/automate/background-agents/) · [issue-to-PR pipeline](/en/workflows/automate/issue-to-pr-pipeline/)
- Local isolation and context hygiene: [isolated Git worktrees](/en/codex/automate/worktrees/) · [optimize `AGENTS.md` and skills](/en/codex/build/agents-md-optimization/)
- Govern cloud access alongside laptops: [Codex enterprise governance](/en/codex/team/enterprise-governance/)
