Codex Ignores Your Project Structure: The AGENTS.md Fix

New files land in /src/ when your repo uses /app/; deps go to the root package.json in a monorepo; tests use a framework you don't have. Fix it with a root AGENTS.md, nested overrides, and canonical-example pointers — verified against Codex behavior, June 2026.

You asked Codex to add a feature module. The PR puts it in /src/features/billing/. Your repo uses /app/(dashboard)/billing/ (Next.js App Router). The diff is plausible — it just doesn’t match your codebase at all. Or: Codex adds vitest deps to the root package.json of a pnpm workspace where each package keeps its own package.json. Or: it writes tests with jest when the rest of the repo runs vitest.

Codex isn’t guessing maliciously. It defaults to generic patterns when your repo’s conventions aren’t visible to the model in the conversation it builds. The durable fix is an AGENTS.md file at the repo root with a directory map and pointers to canonical examples, plus naming target paths explicitly in each task. As of June 2026, Codex CLI runs on OpenAI’s gpt-5.5 by default for ChatGPT-authenticated sessions, and it has been trained to read and follow AGENTS.md closely (OpenAI Codex docs).

TL;DR

  • Why it happens: No AGENTS.md, so Codex generalizes structure from whatever files it reads first. The first directory it lands in becomes its mental model of “the project layout.”
  • The 80% fix: Put an AGENTS.md at your git root with a directory map, a “Canonical examples” section pointing at real folders, and a “Do not” list. Codex auto-loads it on every task.
  • The other 20%: Name the exact target path in the prompt (apps/web/src/features/billing/), point at one real example to copy, and for monorepos pin the working package. Reject wrong structure immediately and re-prompt rather than hand-fixing.
  • Scale lever: Add per-package AGENTS.md files. Codex merges every file from your git root down to the current directory; the closest one wins on conflicts.

How Codex actually loads instructions (June 2026)

This is the mechanism the fixes below rely on, so it’s worth getting exact. Codex builds an instruction chain by concatenating, in this order (OpenAI docs):

StepSourceNotes
1~/.codex/AGENTS.override.md, then ~/.codex/AGENTS.mdYour global, cross-project rules; Codex uses only the first non-empty file at this level
2Each directory from git root → current directoryChecks AGENTS.override.md, then AGENTS.md, then any project_doc_fallback_filenames; at most one file per directory
MergeClosest file winsCodex concatenates files from the root down, joined by blank lines; files nearer your working directory appear later, so they override earlier guidance
Cap32 KiB combinedproject_doc_max_bytes (default 32 KiB, set in ~/.codex/config.toml); Codex skips empty files and stops once the limit is hit

AGENTS.md is plain Markdown — no required fields, no mandatory schema. It is an open standard (agents.md) that Codex, and most other coding agents, parse. OpenAI’s own Codex repository ships dozens of nested AGENTS.md files, one per package, which is the model behavior you are leaning on.

Which model is reading it matters less than you’d think: gpt-5.5 is the default for ChatGPT-authenticated Codex (CLI, app, and IDE extension), with gpt-5.4 as a fallback and gpt-5.2-codex for API-key workflows (Codex models). All of them honor AGENTS.md; none of them can honor conventions you never wrote down.

Common causes

Ordered by hit rate, highest first.

1. No AGENTS.md (or it’s stale)

Without AGENTS.md at the repo root, Codex reads a sample of files and generalizes — but it can’t reconstruct structural conventions from a few reads. The first directory it lands in becomes “the project layout.” This is the single highest-hit cause.

How to spot it: ls AGENTS.md at the repo root — missing means the agent is guessing structure from file samples. If it exists, check git log -1 --format=%cr AGENTS.md. Last update older than 6 months while many features have shipped since usually means the directory map no longer matches reality, and Codex follows the stale map.

2. Task didn’t name target paths

“Add a billing feature” lets Codex pick. “Add a billing feature in apps/web/src/features/, following the layout of apps/web/src/features/auth/” pins it. The first is a coin flip; the second is determinate.

How to spot it: Re-read your prompt. If no specific directory is named, Codex chose its own.

3. Codex generalized from the wrong example file

It read legacy/v1/UserService.ts first because it appears earlier in alphabetical traversal, decided “this is the project style,” and ignored your modern src/services/UserService.ts. Both exist; Codex picked the wrong canonical.

How to spot it: The new code matches a deprecated/legacy area in style/imports/structure. Codex was reading the wrong subtree.

4. Monorepo treated as one package

Codex didn’t realize your repo is a pnpm/yarn workspace. Adds dependencies to root package.json, imports across packages without using the workspace alias, runs pnpm install at the wrong level.

How to spot it: New imports cross package boundaries directly (relative paths or top-level package names). Check pnpm-workspace.yaml / lerna.json / nx.json — if any exists, Codex must respect the workspace.

5. Test framework / linter mismatch

Repo uses vitest; Codex writes jest-style tests because jest is the more common pattern in its training data. The tests look correct but never run, because the framework isn’t installed.

How to spot it: A new test file imports a framework not in package.json. Run pnpm test path/to/new-file.test.tsCannot find module 'jest' (or vi is not defined in the reverse case) confirms it.

6. Codex created a folder where one already existed under a different name

Your repo has src/Components/ (capital C). Codex made src/components/ (lowercase). On case-insensitive filesystems (macOS default) this is a confusing duplicate. On case-sensitive (Linux CI) it breaks imports unexpectedly.

How to spot it: Two directories differing only in case. ls -la src/ | sort reveals.

Shortest path to fix

Ordered by ROI. Step 1 alone eliminates the large majority of structure mismatches in practice, because it removes the guessing entirely.

Step 1: Create AGENTS.md with a directory map

In your repo root:

# AGENTS.md

## Directory map

- `apps/web/` — Next.js App Router (NOT pages router)
  - `apps/web/src/features/` — feature modules, one folder per feature
  - `apps/web/src/components/` — shared UI primitives (lowercase!)
  - `apps/web/app/` — routes, group folders use `(name)` syntax
- `packages/ui/` — shared component library, build with tsup
- `packages/db/` — Prisma client + migrations
- `scripts/` — Node CLI utilities

## Canonical examples

- Feature module layout: see `apps/web/src/features/auth/`
- Shared component pattern: see `packages/ui/src/button/`
- API route convention: see `apps/web/app/api/users/route.ts`

## Conventions

- Package manager: **pnpm** (workspace). Never use `npm` or `yarn`.
- Test framework: **vitest** with `@testing-library/react`. Never use jest.
- Linter: ESLint config in `packages/eslint-config-acme/`.
- Imports: use workspace aliases (`@acme/ui`), not relative `../../`.

## Do not

- Create folders in `src/` — features go in `apps/web/src/features/`.
- Add dependencies to root `package.json` — add to the package that uses them.
- Mix `Components/` (capital) with `components/` (lowercase) — we use lowercase.

Codex auto-loads this on every task — no flag needed. Keep the whole instruction chain under the 32 KiB cap (project_doc_max_bytes); if a root file balloons past that, split rules into per-package files (Step 6) rather than one giant document, or Codex will silently stop reading once the limit is hit.

Step 2: Point at a canonical example in the task

For new features:

Add the billing feature. Follow the structure of `apps/web/src/features/auth/`:
- index.ts (public API)
- types.ts
- components/
- hooks/
- billing.test.tsx (vitest, not jest)

Place new files at `apps/web/src/features/billing/`.

A pointer to a specific real example beats any amount of prose convention.

Step 3: Tell Codex which package to work in (monorepo)

Working directory: apps/web

- All file paths in this task are relative to apps/web.
- Add dependencies via `pnpm --filter=@acme/web add <pkg>`.
- Use the workspace alias `@acme/ui` when importing shared components.
- Do not touch root `package.json` or other packages.

Step 4: Reject mismatched structure early, re-prompt

If Codex creates the wrong directory, don’t fix it manually — delete the wrong location, re-prompt:

Your previous patch created `src/billing/`. That's wrong — see AGENTS.md.
Correct path: `apps/web/src/features/billing/`.

Delete `src/billing/`. Re-implement under the correct path, following
`apps/web/src/features/auth/` as the canonical example.

This trains the session, not just fixes one mistake.

Step 5: For large repos, narrow Codex’s “starting view”

In repos with many top-level dirs, Codex’s first reads dominate its mental model. Pin the read:

Before writing any code, read these three files:
1. apps/web/src/features/auth/index.ts
2. apps/web/src/features/auth/billing.test.tsx
3. apps/web/src/features/auth/components/LoginForm.tsx

These are the canonical patterns for this codebase. Apply them to the new feature.

Step 6: Per-package AGENTS.md (and overrides) for big monorepos

For a 30-package repo, one root AGENTS.md can’t cover everyone’s conventions — and a sprawling root file risks the 32 KiB cap. Add apps/web/AGENTS.md, packages/ui/AGENTS.md, each with package-specific rules. Codex walks from the git root down to the file being edited and merges every AGENTS.md it finds; the closest one wins on conflicts because it appears last in the prompt.

apps/web/AGENTS.md
└── "This package uses App Router, Server Components by default."

packages/ui/AGENTS.md
└── "All components are client components; put 'use client' at the top of each file."

When one package needs to override an inherited rule rather than add to it, use AGENTS.override.md in that directory. At a given level, if AGENTS.override.md exists Codex loads it and ignores the regular AGENTS.md at that same level — but it still merges files from parent directories above it, so an override swaps out one level’s file, not the whole chain (OpenAI docs). The same lookup applies to your global ~/.codex/AGENTS.md, which is the right place for personal, cross-project preferences rather than repo conventions.

How to confirm it’s fixed

After adding AGENTS.md, run one real task and check three things before you trust the session:

  1. Codex actually loaded the file. In the Codex CLI, run /status (or /context) — the instruction files it pulled in are listed there. If your root AGENTS.md isn’t listed, you’re not at the git root, the file is empty, or you blew past the 32 KiB cap. Confirm the path with git rev-parse --show-toplevel and make sure AGENTS.md sits at that exact directory.
  2. The next patch lands in the right place. Ask for a small new module and inspect the diff before applying it — git diff --stat should show files under the path your map declares (apps/web/src/features/<name>/), not a fresh src/ folder.
  3. The new tests run. If the task added tests, run them (pnpm test path/to/new-file.test.ts). A clean run means Codex used your installed framework; Cannot find module 'jest' means it ignored the convention and you need to tighten the “Conventions” / “Do not” sections.

If all three pass on a throwaway task, the durable fix is in place and you can stop hand-correcting paths.

Prevention

  • Maintain AGENTS.md as a living doc — refresh it whenever the architecture changes, not just at project start.
  • Always include a “Canonical examples” section pointing at real folders Codex can read.
  • In task prompts, name the target path explicitly; “in the right place” never works.
  • For monorepos, set the working directory or --filter in every prompt.
  • Per-package AGENTS.md files for big repos; reach for AGENTS.override.md only when a child must contradict the root.
  • Keep the merged instruction chain under 32 KiB so nothing gets silently dropped.
  • Audit duplicate-case folders (Components/ vs components/) quarterly and consolidate.

FAQ

Do I have to point Codex at AGENTS.md, or does it find the file on its own? It finds it on its own. Codex automatically enumerates AGENTS.md files from ~/.codex plus every directory from your git root down to the working directory and injects them into the conversation — no flag or @-mention required. You only name files when you want to point at a canonical example inside a task.

Where does Codex look, and which file wins if two conflict? Lookup order is ~/.codex/AGENTS.override.md~/.codex/AGENTS.md (only the first non-empty one at the global level), then each directory from git root to your current directory (AGENTS.override.md, then AGENTS.md, then any project_doc_fallback_filenames), one file per directory. Codex concatenates them root-first, so files closer to your working directory appear later and win on conflicts. An AGENTS.override.md only displaces the regular AGENTS.md at its own level — it doesn’t discard what parent directories contributed.

Is there a size limit on AGENTS.md? Yes. Codex stops adding files once the combined size hits project_doc_max_bytes, which defaults to 32 KiB. Empty files are skipped. Past that limit, additional AGENTS.md files are silently ignored — another reason to split rules into per-package files instead of one huge root document.

Which model reads AGENTS.md, and does the version change anything? As of June 2026, ChatGPT-authenticated Codex (CLI, app, IDE extension) defaults to gpt-5.5, with gpt-5.4 as a fallback and gpt-5.2-codex for API-key workflows. All of them are trained to follow AGENTS.md. The model version affects code quality, not whether your conventions are honored — that depends entirely on whether you wrote them down.

Codex put files in the wrong folder anyway. Should I just move them? No. Delete the wrong location and re-prompt with the correct path plus a canonical example to copy. Moving files by hand fixes one PR but leaves the session’s mental model wrong, so the next task repeats the mistake.

Does AGENTS.md work outside Codex? Yes. AGENTS.md is an open standard that most coding agents read, so the same file generally guides other tools too. The lookup order and size cap described here are Codex-specific, but the directory map and canonical-examples approach is portable.

Tags: #Codex #Coding agent #Troubleshooting #Debug #Project structure