OpenAI Codex and AGENTS.md — Hierarchical Loading, Sandbox Isolation, and Multi-Repo Delegation
AI coding agents ignoring team commit conventions, scattering any types everywhere, and trying to run heavy E2E tests locally. This usually isn't a problem of missing rules — it's a problem of having no channel to deliver the rules. Copy-pasting rules into system prompts every session doesn't scale, and switching one tool means starting from scratch.
AGENTS.md formalizes that channel into a single file. It's a README for agents placed in the project directory, automatically read when an agent starts a session so team rules are included in context. Originating from OpenAI Codex, this format is gradually being adopted by various coding agent tools — but since each tool handles priority and default rule files differently (e.g., Cursor uses .cursor/rules, Windsurf uses .windsurfrules), the same file may not be interpreted in exactly the same way across tools. In this article, we use Codex's behavior as the reference within verifiable bounds.
Three topics are covered: how the file loading hierarchy is actually merged, why the cloud agent's two-phase sandbox execution model is security-significant, and the pattern for delegating team rules to parallel agents in monorepo and multi-repo environments.
File Loading Hierarchy: From Global to Subdirectory
Codex reads AGENTS.md from three scopes and concatenates them into a single context. Each scope has a different coverage area.
- Global:
~/.codex/AGENTS.md— Machine-wide defaults for each individual. May vary per team member; team rules should not go here. - Repository Root:
<git-root>/AGENTS.md— Team-wide rules committed to Git. - Subdirectory: All AGENTS.md files found along the agent's working path. Files closer to the CWD take higher precedence.
The three scopes are concatenated, not overwritten. When instructions conflict, the content from the more specific file (closer to the current directory) takes precedence. The merged context has a size limit (conventionally around 32 KiB); content pushed beyond that limit may be truncated, so keeping each file short and dense is the safer approach.
Two-Phase Sandbox Execution Model
Cloud Codex agents receive an isolated container per task. The key security point is that execution inside that container is split into two phases.
During the Setup phase, the network is open, allowing preparatory tasks such as pnpm install and pip install to complete. When transitioning to the Agent phase, the network is blocked and CODEX_SANDBOX_NETWORK_DISABLED=1 is set in the environment. From this point on, the agent operates offline and only performs code editing, test execution, and result returning.
The separation yields two practical benefits. First, it eliminates the vector by which an agent could exfiltrate data to external servers or arbitrarily download additional packages during execution. Second, pre-warming the cache during Setup shortens Agent phase time, reducing costs for repeated tasks. The base image codex-universal comes pre-loaded with major runtimes including Python, Node.js, Go, and Rust.
Approval Modes: Balancing Autonomy and Safety
Codex CLI divides agent autonomy into three levels.
| Mode | File Edits | Shell Commands | Recommended For |
|---|---|---|---|
suggest |
Requires approval | Requires approval | Initial adoption, sensitive repositories |
auto-edit |
Auto-allowed | Requires approval | General team development |
full-auto |
Auto-allowed | Auto-allowed | CI, validated repetitive tasks |
full-auto is not a mode to enable from day one. It's safer to have the team learn the agent's behavioral patterns with auto-edit first and gradually expand. In particular, avoid full-auto in repositories that accept PRs from external contributors (see the prompt injection section below).
Pre-Adoption Review: Benefits and Trade-offs
Before moving to practical application, here is a summary of what teams gain and what they must accept.
| Item | Benefits | Trade-offs |
|---|---|---|
| Cross-tool compatibility | Deliver rules to multiple tools with a single file | Priority and interpretation differ per tool. One file cannot perfectly unify all tools |
| Hierarchical flexibility | Manage team-specific rules independently in a monorepo | More layers increase the cost of tracking which rules are actually applied |
| Always-on | Auto-loaded every session. Reduces repeated mistakes by new agents | Longer rules consume more context budget |
| Parallel execution | Delegate tasks to multiple repositories simultaneously | Conflicts between parallel PRs and duplicate review burden fall on humans |
| Sandbox isolation | Two-phase model blocks external communication during execution | Source code is transmitted to OpenAI infrastructure during cloud execution (risk compared to self-hosting) |
A checklist helps judge readiness: Is the codebase mature enough for the team to document rules?, Can source code be uploaded for cloud execution?, Does the PR review pipeline have capacity to handle parallel tasks? If all three are yes, adoption delivers substantial value.
Structuring Hierarchy in a Monorepo
In large repositories, keeping only common rules at the root and layering team-specific rules per subdirectory makes management easier.
<repo-root>/
├── AGENTS.md ← Common: commit conventions, security rules
├── packages/
│ └── web/
│ └── AGENTS.md ← Frontend: React patterns, CSS rules
└── services/
└── api/
└── AGENTS.md ← Backend: API design, DB rulesWhen an agent works inside packages/web/, the root file and packages/web/AGENTS.md are loaded together. The frontend team only needs to manage their own rules; the root automatically covers common rules.
Here is a practical example of a root AGENTS.md. Keeping the file itself in English is the recommended default, considering multilingual contributors.
# AGENTS.md
## Build & Test
- Before commit: `pnpm lint && pnpm test`
- E2E: `pnpm test:e2e` (CI only, do not run locally)
- Type check: `pnpm typecheck`
## Commit Convention
- Format: `feat:`, `fix:`, `chore:`, `docs:`
- Subject in imperative mood (e.g., "add user auth endpoint")
## Code Style
- Functional components only (no class components)
- No `any` types
- Remove `console.log` before committing
## Do Not
- Disable the sandbox network guard in test fixtures
(do not stub or override `CODEX_SANDBOX_NETWORK_DISABLED`)
- Commit real secrets — use `.env.example` templates
- Edit files under `node_modules/` directlyThe key is actionable commands and explicit prohibitions. Do not include things that can be inferred by browsing the repository (language used, directory structure).
It's easier to manage Setup scripts by specifying only the path in AGENTS.md and keeping them in a separate file.
## Setup
Environment bootstrap is performed by `./setup.sh`.
All network-dependent downloads must complete in this phase.#!/bin/bash
# setup.sh — runs in the Setup phase (network allowed)
set -euo pipefail
pnpm install --frozen-lockfile
pnpm build:depsFor a mixed Python/Node stack, add pip install inside setup.sh, and in that case also list Python-related commands (pytest, ruff, etc.) in the root AGENTS.md to ensure stack consistency and prevent agent confusion.
Multi-Repo Parallel Delegation Pattern
Codex supports a sub-agent configuration where a manager agent coordinates multiple worker agents. When an engineering lead submits a ticket, the manager decomposes the task by repository and each worker proceeds in an independent sandbox.
Since each repository has its team's AGENTS.md, a worker running in the api repository automatically follows the backend team's rules. Using tickets from issue trackers like Linear or Jira as triggers, you can build a workflow where a single specification propagates asynchronously into PRs across multiple repositories. However, the interdependencies between parallel PRs and review order must still be managed by humans.
Common Pitfalls in Practice
Having an LLM write AGENTS.md for you. The value of AGENTS.md lies in non-obvious information that cannot be inferred by browsing the codebase. LLMs tend to scan the codebase and summarize obvious facts into the file, consuming context budget while lowering signal-to-noise ratio. The curation of the file is better done by humans.
Including secrets in the file. AGENTS.md is committed to Git. API keys and production tokens must be injected via environment variables or a secret manager during the Setup phase.
Assuming "the agent must follow the rules because we wrote them." AGENTS.md is just text fed into model context; it has no enforcement power. It reduces the frequency of violations but cannot eliminate them, so approval modes and code review remain the last line of defense.
Underestimating prompt injection. As long as the agent executes a shell, malicious scripts mixed into the repository (postinstall hooks, typosquatted packages, instructions inside READMEs, etc.) can become injection vectors. Activating full-auto is safer only after review, and only in internal trusted repositories that do not receive PRs from external contributors.
Ignoring context budget. Pushing a very large monorepo into a single task saturates the context and causes the agent to miss rules. Splitting tasks by subdirectory and narrowing scope with hierarchical AGENTS.md produces more stable results.
Summary
The practical value of AGENTS.md can be compressed into one sentence: If team rules are written into a file, the rules stay in place no matter how many tools and repositories multiply. Even if the tool switches from Codex to another agent, the file continues to work; even with multiple repositories, each has its own living hierarchy.
Here are the key points to remember.
- AGENTS.md from three scopes is concatenated; files closer to the current directory take precedence.
- The network is only open during the Setup phase. All work requiring downloads must finish here.
- AGENTS.md is guidance, not enforcement. Approval modes and code review are the last line of defense.
- Humans curate the file. Delegating to an LLM fills it with obvious information that only consumes context.
The lowest-friction starting point is to commit a single root AGENTS.md containing only two or three rules the team frequently breaks and the commit convention, run it for a few days in suggest mode, and observe how the agent responds. Add hierarchy afterward, only where needed.
References
- OpenAI Codex Official AGENTS.md (GitHub)
- Sandbox Concepts Official Documentation — OpenAI Developers
- Cloud Environments Official Documentation — OpenAI Developers
- Agent Approvals & Security — OpenAI Developers
- Introducing Codex — OpenAI Official Blog
- Run Long Horizon Tasks with Codex — OpenAI Developers Blog
- Running Codex Safely at OpenAI — OpenAI Official Blog
- AGENTS.md Official Format Site
- AGENTS.md Spec 2026: Recommended Sections — morphllm.com
- AGENTS.md for OpenAI Codex: Rules, Loading, and Templates — eastondev.com
- Codex CLI Guide 2026: Setup, Sandbox, AGENTS.md & MCP — blakecrosley.com
- Shipyard: Codex CLI Cheatsheet — shipyard.build
- OpenAI Codex Security Risks and Best Practices — cybedefend.com
- Codex Cloud Environments: Setup Scripts and Caching — codex.danielvaughan.com
- AGENTS.md Advanced Patterns: Nested Hierarchies — codex.danielvaughan.com