Skip to content

Best Practices: Beyond Obvious Platitudes, a Few That Actually Work

📚 Series Navigation: The previous article 35 Command and Configuration Cheatsheet laid out commands, configuration keys, and shortcuts into a cheatsheet that you can stick on your wall. This article moves to a different level—instead of explaining "what features are available," it talks about "how to combine these features to make Codex truly save you trouble." The next article 37 Troubleshooting Common Issues will talk about "what to do when things go wrong."

To be honest, when I first got Codex, I did something pretty stupid: I read the official best-practices page from beginning to end, thought every single point made perfect sense, and then... closed the page without improving my own usage by even a single bit.

The problem wasn't me—it is that the vast majority of so-called best practices are just obvious platitudes: "write clear prompts," "remember to test," "iterate in small steps"—they all sound correct, but they don't tell you how clear is clear enough, what to test, or how small a step is. You nod in agreement like a woodpecker, but go back to using it exactly the same way. This kind of cure-all advice essentially kicks the responsibility back to you.

So in this article, I don't plan to repeat those grand theories that anyone can say. I chewed through the official best-practices document and picked out a few points that truly changed my usage and that I have verified myself. For each, I will give you "Why to do this + How to do it specifically + What pitfalls you will run into if you don't." Only those that actually work are kept; those that sound high-end but cannot be put into practice are all cut.

To tell the truth, for most of the items below, I had to make mistakes and suffer the consequences first before coming back to fix them.

After reading this article, you will get:

  • A mindset of configuring Codex as a "teammate" rather than a "disposable tool"
  • What exactly to write in AGENTS.md (project instruction manual) and how long it should be to be useful
  • A prompt four-piece set of "Goal + Context + Constraints + Verification"—just fill in the blanks
  • How to divide permissions into several tiers based on scenarios, and which tier beginners should start with
  • Why you should let it generate a plan first for complex tasks before taking action
  • How to let Codex test and review by itself instead of you watching every single step
  • How to handle online/production tasks by first obtaining a chain of evidence, sanitizing records, and then confirming the fix
  • A comparison table of "Pitfall ❌ / Correct Practice ✅" to copy directly

⚠️ Commands, configuration keys, and default behaviors are subject to Codex official documentation; model names and availability vary with versions and plans, and are subject to your local codex --help, the /model panel, and ~/.codex/config.toml.


01 Change Your Mindset First: Codex Is a Teammate You Train, Not a Disposable Tool

Let's start with the conclusion: When using Codex, the quality of the results depends mostly on what you treat it as.

Many people (including my early self) treat it as a "question-and-answer" search box: toss a problem at it, grab the answer and leave, and start from scratch next time. Using it this way, it can only ever show 30% of its power.

Analogy: Codex is like a new colleague you just hired who is highly capable but knows absolutely nothing about your project. You wouldn't expect him to understand everything on day one—you have to give him an onboarding manual (AGENTS.md), tell him how to run and test the code, and correct him when he makes a mistake so he remembers it. The longer you train him, the smoother it gets. Conversely, if you hire a different temp worker who doesn't know you every single time, you will forever be repeating the same explanations.

There is a sentence in the official documentation that I strongly agree with, roughly meaning: Instead of treating Codex as a disposable assistant, treat it as a teammate you will continuously configure and polish. All the practices in the rest of this article are essentially built around this single sentence—turning temporary, repetitive tasks into persistent configurations.

My own turning point was early 2026. Before that, every time I opened a new session, I had to type "this project uses pnpm instead of npm", "run tests with pnpm test", and "commit messages must be in Chinese" all over again, seven or eight times a day. Until one day I got tired of it and stuffed them into AGENTS.md, and the world instantly became peaceful—only then did I realize I had been using a very smart tool in the dumbest way possible.

💡 Summary in one sentence: Treating Codex as a teammate to be continuously trained, rather than a disposable tool, is the foundation of all best practices.


02 Write AGENTS.md Properly: Let It Work "With Context" Automatically

Why do this. This is the antidote to the pain point mentioned in the previous section. AGENTS.md is an instruction manual placed inside the project. Codex will automatically read it into context every time it comes in, without you needing to @ it manually. Things that need to be explained repeatedly in a project are written once and take effect permanently.

Analogy: AGENTS.md is a README for AI. A regular README is written for humans, telling them what the project is and how to run it; AGENTS.md is written for Codex, telling it your rules, landmines, and "standards for completion."

How to do it. The official recommendation is that a good AGENTS.md should cover these sections, which you can just list accordingly:

  • Project structure and where important directories are
  • How to run the project
  • What commands to use for build, test, and lint respectively
  • Engineering conventions and PR submission requirements
  • Constraints and red lines of "absolutely do not do"
  • What the "completion standard" is and how to verify it

The fastest way to start is to run /init in the CLI, which will scaffold an initial AGENTS.md in the current directory. But don't use it straight out of the box—what it generates is a template, and you must modify it to match the actual state of your project.

AGENTS.md can also be layered: the one in ~/.codex/ is your personal default; the one in the project root is the team's shared standard; the one in a subdirectory represents local rules. The closer it is to the current directory, the higher its priority.

Counter-example (one I actually ran into). My problem at the beginning was doing the exact opposite: writing a bunch of one-time instructions like "don't touch the database this time" or "only modify this file this time" into AGENTS.md. As a result, the file kept growing longer and was full of outdated rules, which ended up misleading Codex. Only later did I learn my lesson—

Put one-time requirements in prompts, and write persistent rules in AGENTS.md. Short and precise is better than long and vague.

The official guide has a particularly practical little habit worth copying: When Codex makes the same mistake for the second time, have it do a retrospective and add the lesson to AGENTS.md. This way, your instruction manual is grown from real friction, rather than written out of thin air.

💡 Summary in one sentence: Consolidate "persistent rules" into AGENTS.md; being short, precise, and realistic is far more useful than writing a long piece of empty talk.


03 Prompts Shouldn't Rely on Inspiration: Goal + Context + Constraints + Verification, a Four-Piece Set to Fill in the Blanks

Why do this. We talked about prompts in the previous cheatsheet article; here I will just add a structure you can copy directly. Codex is very powerful now, and it can manage to give you a result even if your prompt is rough. However, on large projects or high-risk tasks, if the prompt is fuzzy, it will have to guess more, and if it guesses wrong, you will have to rework it.

The "good prompt default recipe" provided officially is a four-piece set, which I use like a fill-in-the-blank question:

ElementWhat it answersWhat happens if left blank
GoalWhat exactly you want to modify or buildIt fails to capture the main point and does a bunch of things you didn't ask for
ContextWhich files, errors, or examples are related (you can @ reference files)It searches blindly in the wrong places, taking detours
ConstraintsWhat specifications, architecture, or security requirements to followIt follows its own habits, messing up the entire style
Verification (Done when)What conditions must be met to be considered completeIt thinks "it runs" is enough to deliver, leaving the bugs to you

How to do it. You don't need to write every sentence like a contract. For anything slightly complex, or tasks where you don't want to do rework, quickly go through these four blocks in your mind (or just type them out) before submitting: what do I want it to do, where is the related material, what is off-limits, and how do I know it's done.

Analogy: This four-piece set is like giving instructions to a renovation team. You wouldn't just say "make the kitchen look nicer" and let them start working—you have to specify what style you want (Goal), where the floor plans and utility diagrams are (Context), that load-bearing walls must not be touched (Constraints), and that during verification the lights must work, water must run, and cabinets must not wobble (Verification). The clearer the instruction, the less the rework.

The section I forget most often is Verification. Earlier, I asked Codex to modify a form validation, only saying "add a mobile number format validation," but didn't say "after adding it, the existing email validation must not break, and related tests must pass." It quickly added the mobile number validation and accidentally broke the email logic. I didn't notice it until I ran the tests before going live. Since then, the "Done when" section is a must-fill for me.

💡 Summary in one sentence: Don't rely on inspiration for prompts. Fill in the blanks according to the four sections of "Goal + Context + Constraints + Verification," and especially don't leave out verification.


04 Generate a Plan First for Complex Tasks Before Taking Action

Why do this. When a task is complex or vague, asking it to write code directly forces it to guess your intentions while typing. You will only find out that the direction went wrong very late. Letting it generate a plan first is equivalent to giving you a cheap "course correction opportunity" before taking action.

Analogy: This is like looking at blueprints before building a house. No one would let a construction crew lay bricks without a drawing—tearing down crooked walls hurts your liver. A plan is that drawing; it is just a few lines of text, which is much cheaper than reworking an entire block of code.

How to do it. The official guide provides several approaches, ranked by ease of adoption:

  • Use Plan mode (Most Recommended): Use /plan in the CLI, or press Shift+Tab to switch. It will first gather context, ask you clarifying questions, and provide a more reliable plan. Once you nod, it will take action.
  • Let it interview you in reverse: If you haven't thought it through yourself, tell it: "Don't write yet. Challenge me first, and ask questions to turn this vague idea into a concrete solution."
  • Use the PLANS.md template: A more advanced approach where multi-step, long-running tasks follow an execution plan template (subject to the official execution plans guide).

Counter-example. The official guide explicitly lists "skipping planning for multi-step complex tasks" as a common error, which is something I know all too well. Last year, I asked Codex to help me migrate a module from callback style to async/await. To save trouble, I didn't ask it to generate a plan and just said "modify it as you see fit." It did modify it, but along the way, it took the initiative to "conveniently optimize" a global error handling logic of mine. The entire change became a mess. When reviewing, I got a headache looking at that diff. In the end, I simply ran git reset and started over—this time using /plan first to let it list "which files to modify, what to modify in each file, and what to absolutely not touch." Once confirmed, I let it go, and it passed on the first try.

💡 Summary in one sentence: The more complex and vague a task is, the more you need to run /plan first to establish a plan and confirm the direction before letting it take action.


05 Permission Tiers: Strict by Default, Loosened Gradually by Scenario

Why do this. Codex comes with an OS-level sandbox and has two key knobs: approval mode determines whether it needs to ask you before executing commands, and sandbox mode controls whether it can read/write directories and which files it can touch. Giving full permissions right from the start is like handing the steering wheel and the accelerator pedal to a new driver whose temperament you haven't figured out yet.

Analogy: This is like configuring permissions for a new intern. On the first day, you only give him permissions to read code and run tests locally. Once you get to know him and trust him, you gradually allow him to modify files and connect to the database. Nobody hands over the keys to the production environment to a newcomer on day one.

How to do it. The official recommendation is very direct:

  • Beginners should start with default permissions, keeping both approval and sandbox restricted.
  • Once you figure out a workflow and indeed need it to be smoother, gradually loosen them for trusted repositories or specific scenarios, rather than opening everything up at once.
ScenarioRecommended TierReason
Just starting out / Unfamiliar projectsDefault (Ask before acting, Sandbox restricted)See clearly what it wants to do before letting it proceed, secure
Your own trusted repositories / Repetitive tasksModerately loosen approvalsReduce the annoyance of constantly clicking "Approve"
Unfamiliar scripts / Third-party codeTighten to the maximumPrevent it from executing commands you did not expect

The official guide lists "giving Codex full computer permissions before figuring out the workflow" as a common error. My own lesson wasn't disastrous, but it was enough to make me remember: for a while, I found the constant confirmation annoying, so I set the approvals very loose. As a result, during a refactoring, it executed a cleanup command that I hadn't looked at closely, deleting several temporary files I thought I still needed—it wasn't a major disaster, but it was enough to make my heart skip a beat. Saving those few seconds of confirmation is not worth it.

💡 Summary in one sentence: Keep permissions strict by default, check carefully before letting it proceed; loosen them gradually only for trusted scenarios, and never open them all up just to save trouble.


06 Let It Self-Verify: Test, Check, and Review—Don't Just Let It "Finish Writing"

Why do this. This is the point with the highest value in my opinion. Don't let Codex stop right after writing the code—have it write tests, run relevant checks, and review the changes before handing them over to you. Doing this step well saves you from rounds of going back and forth where "it writes, you test, it errors, and you ask it to fix."

But there is a prerequisite: It must know what "good" looks like. Where does this standard come from? It is either written in the prompt or in AGENTS.md (see, we are back to Section 02).

How to do it. The "let it self-check in a closed loop" mentioned officially includes these actions, which you can write directly into your requirements:

  • Write or update tests for this change
  • Run the corresponding test suite
  • Run lint, formatting, and type checks
  • Confirm that the final behavior matches your requirements
  • Review the diff once to look for bugs, regressions, and dangerous patterns

There is a /review command in the CLI that is particularly valuable for this section: it can review in a PR-style comparison with the baseline branch, review uncommitted changes, review a specific commit, or review based on your custom instructions. If your team has a code_review.md and references it in AGENTS.md, Codex will follow that standard during review—when multiple people on a team collaborate, this keeps the review criteria consistent.

Counter-example. The official guide lists "not letting the agent see its own results" (i.e., not telling it how to run build and test commands) as a common error. I had a negative example of this: I asked it to modify a data processing function without asking it to run tests. It confidently claimed "completed, logic correct," and I believed it. As a result, the code threw an exception directly under boundary inputs—it had no chance of discovering this because I hadn't let it run tests. Since then, I've formed a habit: whenever modifying logic, the end of the prompt must include "after modifying, run <test command> and tell me once all tests are green." It's just a sentence, but it blocks the majority of reworks.

💡 Summary in one sentence: Let Codex handle testing, checking, and reviewing together before delivery, provided that you tell it the standard of "good" via prompts or AGENTS.md.


07 Obtain a Chain of Evidence First for Production Tasks, Then Talk About Fixing

Why do this. Local feature development can rely on tests to wrap things up. Production failures, however, require answering several hard questions: What is the original symptom seen by the user, how do you reproduce it, which log line corresponds to this request, and whether it has been verified again from the same user path after modification.

I now write this into my project rules: For production issues, gather evidence first, then make a judgment, and then fix. Codex will inspect code along clues, but if you start by saying "help me fix this," it will treat the place that looks most like the cause as the actual cause, and treat passing local tests as completion of the fix. In production tasks, neither of these judgments is sufficient.

How to do it. First, tell it not to modify code, but only to collect evidence. You can write the prompt like this:

text
先不要改代码。请按证据链排查这个线上问题:

1. 复现用户路径,记录请求方式、状态码、关键响应摘要和时间。
2. 查对应时间段的应用日志,只摘出相关错误行。
3. 找到涉及的配置、路由、任务或数据表,但不要修改生产状态。
4. 给出「已验证事实 / 待确认假设 / 下一步验证」三段结论。
5. 输出时脱敏,隐藏 token、私有访问链接、邮箱、手机号、订单号和内部地址。

This text pulls Codex back from "fixing directly" to "proving first." The final judgment it gives you must be traceable back to the evidence: which request failed, which line of the logs reported the error, which configuration was involved in this path, and what action to take next to disprove the hypothesis.

I will put a long-term rule in AGENTS.md specifically to constrain these types of tasks:

md
## 线上问题处理

- 先复现原问题,记录状态码、关键响应摘要、日志时间和验证路径。
- 未经确认,不要改生产数据、权限、可见性、计费、通知或工单状态。
- 输出内容必须脱敏,不要贴 token、用户信息、私有链接、密钥、完整 IP 或订单号。
- 修复后必须用原用户路径复查;本地测试通过不等于线上恢复。
- 如果不能复查,说明缺哪条证据、为什么缺、下一步谁能补。

Sanitization must retain information useful for making judgments. If you sanitize so much that you delete all the evidence, leaving only "some interface failed," the people who follow won't be able to troubleshoot. Keep the structure, and hide the sensitive values:

Original InformationSanitized Yet Still Usable Representation
https://example.com/private/path?token=secret_valuehttps://example.com/private/path?token=<token>
user@example.com<user-email>
order_20260201_123456<order-id>
Authorization: Bearer ...Authorization: Bearer <redacted>
2026-02-01 14:03:22 status=500Retain original time and status code

Time, status codes, error types, and route shapes can usually be kept; values that can directly identify users, accounts, keys, or internal assets must be hidden. This way, others can follow the evidence to make judgments without bringing sensitive information into PRs, issues, or public chats.

How to verify. The verification criteria for production tasks must go back to the original path. If an interface was broken, hit the same interface again and record the new status code and response summary; if a page was broken, use the browser to go through the user actions again; if a queue or cron task was broken, look at the next task's log and artifacts. If environment permissions are insufficient, don't write "unable to verify" vaguely; write clearly: missing production permissions, missing test account, missing external callbacks, or missing user confirmation.

💡 Summary in one sentence: For production tasks, don't let Codex guess the cause first, have it get the evidence chain first; verify from the original user path after fixing, and hide sensitive values during sanitization while keeping status codes, timestamps, and error shapes.


08 Delegate Heavy Work to Subagents, One Thread for One Task Only

Why do this. A session is not just chat history; it is a working thread that continuously accumulates context. The longer the thread and the more cluttered the contents, the more the quality drops. Therefore, how you manage threads directly affects the quality of the results.

Analogy: This is like managing your workbench. If a single desk has materials from three projects spread out at the same time, finding things and making decisions will become slower and messier. A desk with only one active task on it is the most efficient. Codex's thread is its workbench.

How to do it (two points).

First, one thread should do only one coherent thing. The original meaning of the official guide is: as long as it is still the same problem, stay in the same thread—it preserves the complete line of reasoning. Only when the work really forks, use /fork to start another one. In other words, split threads by tasks, not by projects—the anti-pattern to avoid most is "using a single thread from start to finish for a project," which causes the context to accumulate and grow fat, leading to worse and worse results.

Second, dump self-contained chore tasks to subagents. Let the main thread focus on the core issue, and toss tasks that "can be completed independently and have clear deliverables" like exploring code, writing tests, or doing triage to subagents. Don't let them consume the main thread's attention.

A few handy commands for managing threads (subject to your actual local codex --help):

  • /resume Resume chatting from an archived conversation
  • /fork Start a new thread while preserving the original record
  • /compact Compress earlier context into a summary when the thread gets too long (Codex will also do this automatically)
  • /status Take a look at the current session status

My current habit is "one task, one thread," and that thread is archived once the task is finished. This change looks small, but since I stopped using "one all-purpose thread for a project," the answers Codex gives me are noticeably less prone to "cross-contamination"—previously, it often used the context of another requirement from three days ago to contaminate the current judgment.

💡 Summary in one sentence: One thread for one task only; delegate heavy or chore tasks to subagents to prevent the context from growing bloated.


09 Onboarding Checklist: A Comparison Table of "Pitfall ❌ / Correct Practice ✅"

The essence of the first eight sections is wrapped up at the end of the official document with a "common mistakes" checklist. I have consolidated it into a comparison table for you to self-check—if you hit any item on the left, change it according to the right.

❌ Pitfalls I've Seen✅ Correct Practices
Stuffing persistent rules into prompts all at onceMove persistent rules into AGENTS.md or skills, and keep only one-time requirements in prompts
Not telling it how to run build and test commandsWrite the running and testing methods clearly in AGENTS.md so it can see its own results
Skipping planning and writing code directly for multi-step complex tasksRun /plan first for complex tasks to establish a plan and confirm the direction before taking action
Giving full permissions before figuring out the workflowStrict by default, loosen gradually based on trusted scenarios
Using a single thread from start to finish for a projectOne thread per task, only use /fork when work forks
Modifying the same set of files across multiple threads simultaneously without using git worktreeUse git worktree to open independent workspaces for parallel threads to avoid stepping on each other's toes
Hurrying to automate tasks that are not yet stableRun them manually until stable first, then consider consolidating them into a skill or automation
Staring at it step by step, unable to do anything else yourselfLet it run in parallel so you can free up your hands to do your own things
Fixing production issues without reproducing them firstFirst record original symptoms, request status, log timestamps, and hypotheses to be verified
Declaring production recovery as soon as local tests passGo back to the original user path to recheck, and record the status code, page behavior, or task logs after the fix
Pasting logs, links, and user information as they are into public PRsSanitize sensitive values, while retaining timestamps, status codes, error types, and route shapes

How to follow. Don't just read this table once. My recommendation is: next time you use Codex and feel that "things aren't smooth, and there's too much rework," come back and check the left column. Most likely, you can locate which item wasn't done well. None of these pitfalls were things I just heard about—they were all memorized only after hitting the wall myself.

💡 Summary in one sentence: Self-check against this comparison table. If you hit any item in the left column, modify it according to the right column; this works better than memorizing any "best practices" formulas.


10 Summary

This article didn't give you obvious platitudes, but instead provided eight practices that I have verified myself and that can directly change your usage:

  • Change Mindset: Treating Codex as a teammate to be continuously trained is the foundation of everything.
  • Write AGENTS.md: Consolidate persistent rules inside it—short, precise, and realistic.
  • Prompt Four-Piece Set: Goal + Context + Constraints + Verification. Fill in the blanks accordingly, and especially do not leave out verification.
  • Plan First, Act Later: Run /plan first for complex tasks; don't save on cheap course correction opportunities.
  • Permission Tiers: Strict by default, check carefully before letting it proceed.
  • Let It Self-Verify: Handle testing, checking, and reviewing together, provided that you tell it the standard of "good."
  • Gather Production Evidence First: Reproduction, logs, status codes, sanitization, and verifying original user paths—don't skip a single one.
  • Manage Threads Well: One thread for one task; delegate heavy work to subagents.

Now you should be able to: when you get any Codex task, subconsciously go through it—does this task need a plan first, are the prompt four-piece set fully filled out, are the rules in AGENTS.md sufficient, should it self-test, which permission tier should be used, and is it necessary to gather the production evidence chain first. Turn this set of practices into muscle memory, and your collaboration with Codex will shift from "relying on luck" to "having a structured method."


In the next article [37 Troubleshooting Common Issues], let's talk about something more down-to-earth: no matter how rules are followed, Codex will always have times when it causes trouble for you—command errors, breaking things, failure to connect, or abnormal behavior. Running into problems is not scary; what is scary is not knowing where to start troubleshooting. Here is a little food for thought: the "plan first, self-test frequently, and proceed in small steps" discussed in this article is actually mostly about preventing problems. What if a problem does occur? Where should your first reaction be to look? The next article will give you a sequence for troubleshooting.