YouTip LogoYouTip

Codex Advanced

After completing the basic installation and first conversation, the real value of Codex lies in embedding it into your daily development workflow. This article covers five advanced directions: project configuration, session management, editor integration, CI/CD automation, and prompt engineering tips, helping you make Codex understand your project, remember your conventions, and work automatically in your pipeline. * * * ## 1. Using AGENTS.md to Write an "Onboarding Document" for Codex AGENTS.md is a project specification written for Codex, placed in the project root directory. It loads automatically on each startup and remains effective throughout the entire session. ### Why You Need It By default, Codex knows nothing about your project. It doesn't know whether you're using App Router or Pages Router, doesn't know which file to use for unified database operations, and doesn't know which files are off-limits. If you have to re-explain the background every time you start a conversation, efficiency will be very low and prone to errors. AGENTS.md makes this information write-once, use-forever, saving you the trouble of repeating yourself. ### What to Write An effective AGENTS.md typically contains four types of information: project overview, tech stack, important conventions, and prohibited actions. Here is a complete example: # AGENTS.md## Project OverviewThis is a SaaS application based on Next.js 14 + Prisma + PostgreSQL. Uses App Router, not Pages Router.## Tech Stack- Frontend: Next.js 14, React 18, TailwindCSS, shadcn/ui - Backend: Next.js API Routes, Prisma ORM - Database: PostgreSQL 15- Auth: NextAuth.js ## Important Conventions- All database operations must go through the prisma instance in lib/db.ts- API route errors are handled uniformly by lib/api-error.ts- Environment variables are in .env.local, reference .env.example ## Prohibited Actions- Do not modify prisma/schema.prisma unless explicitly requested- Do not delete any existing tests- Do not touch production environment .env files > The "Prohibited Actions" section is especially important. Codex actively infers which files need to be modified when executing tasks. Without clear boundaries, it might touch places you don't want it to. Writing the red lines clearly is much easier than fixing problems afterward. ### Configuration Hierarchy AGENTS.md supports three levels of nesting, with priority from low to high. Files closer to the current directory have higher priority. In the same directory, if AGENTS.override.md exists, the peer-level AGENTS.md will be skipped. | Level | Path | Scope | Priority | | --- | --- | --- | --- | | Global | ~/.codex/AGENTS.md | Cross-project universal conventions | Low | | Project | repo/AGENTS.md | Repository-level specifications | Medium | | Override | repo/services/payments/AGENTS.override.md | Subdirectory special rules | High | The global level is suitable for conventions that hold true across all projects, such as: # ~/.codex/AGENTS.md## Global Conventions- Prefer pnpm when installing dependencies - Always run npm test after modifying JavaScript files - Request confirmation before adding new production dependencies After configuration, you can verify correct loading with the following command: codex --ask-for-approval never "Summarize the current instructions." * * * ## 2. Session Management: Continuing Large Tasks Across Days The session management feature allows you to export the current conversation state to a file and resume directly next time, without needing to re-establish the background. ### Problem Background Codex's context window is limited. When handling a large task that spans multiple files and needs to be advanced in stages, if you close the terminal midway or switch to something else, the context breaks when you returnβ€”Codex doesn't remember what was discussed before or what decisions were made. Exporting sessions solves this problem, allowing you to restore to a previous conversation state at any point in time. ### Basic Usage Here are common commands related to session management: ## Examples # Export current session at any point during conversation /export session-2024-01-15.json # Resume next time /load session-2024-01-15.json # Directly resume the most recent session (most commonly used) codex resume --last # View all saved sessions ls ~/.codex/sessions/ ### When to Export You don't need to export after every conversation. The following situations are worth saving: | Scenario | Description | | --- | --- | | Multi-stage tasks spanning multiple days | Tasks conducted over multiple days with clear stage divisions; after saving, you can continue directly from where you left off | | Important architectural decisions | An important architectural decision was made with Codex, and subsequent tasks need to build upon this decision | | Complex debugging process | Debugging a complex bug, having already ruled out several directions, don't want to start from scratch next time | * * * ## 3. VS Code Integration Codex officially provides a VS Code extension. After installation, you can initiate conversations directly within the editor without switching to the terminal. ### Installation and Login Installation steps are as follows: * Step 1: Open the Extensions Marketplace (Cmd/Ctrl + Shift + X). * Step 2: Search for "Codex" or "OpenAI Codex" and install the official plugin. !(#) * Step 3: First-time use requires logging in with your ChatGPT account. * Step 4: The Codex icon appears in the sidebar and is ready to use. After installation, you can use the following shortcuts for quick operations: | Shortcut | Function | | --- | --- | | Alt + G | Send selected code to Codex with current file context | | Cmd + Shift + P | Open command palette, type "Codex" to see all available commands | ### BYO Mode (Users Without ChatGPT Subscription) If you've already configured your own API Key in the CLI (Anthropic, OpenAI, or other compatible providers), you can log in to the VS Code plugin with a free ChatGPT account. The plugin will automatically reuse the CLI's model configuration, not requiring ChatGPT Plus. | Applicable Scenario | Description | | --- | --- | | Have API Key but don't want additional ChatGPT subscription | Use your own API Key directly, no additional paid subscription needed | | Want VS Code and CLI to use consistent models | Plugin automatically reuses CLI configuration, consistent experience on both ends | * * * ## 4. CI/CD Integration Codex CLI supports running in headless mode, requiring no human interaction, suitable for integration into automated workflows. ### What Codex Can Do in Pipelines Here are common uses of Codex in CI/CD in headless mode: | Use Case | Description | Typical Trigger Timing | | --- | --- | --- | | Auto-update CHANGELOG | Automatically update CHANGELOG.md based on commit records after each main branch merge | After merging to main branch | | Generate API documentation | Automatically generate or sync API documentation based on code changes | After code push | | Automated code review | Automatically run code review and leave comments in PR pipelines | When PR is created or updated | ### GitHub Actions Example The following workflow automatically updates CHANGELOG.md with Codex based on the latest commits each time code is pushed to the main branch: ## Example # File path: .github/workflows/codex-changelog.yml name: Auto Update Changelog on: push: branches: jobs: update-changelog: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '22' - name: Install Codex CLI run: npm install -g @openai/codex - name: Run Codex Task env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} CODEX_QUIET_MODE: 1 run: | codex exec --full-auto "Update CHANGELOG.md based on latest commits" - name: Commit changes run: | git config --local user.email 'action@github.com' git add CHANGELOG.md git commit -m 'chore: update changelog ' git push There are two key configuration points to pay special attention to: | Configuration Item | Function | Description | | --- | --- | --- | | CODEX_QUIET_MODE: 1 | Suppress interactive output | Prevent pipeline from getting stuck waiting for interactive input | | --full-auto | Run in headless mode | Let Codex execute directly without human supervision, no confirmation needed | > When using in CI, it's recommended to clearly define the scope of files Codex is allowed to modify in automatic mode in the AGENTS.md at the project root, to prevent unexpected modifications due to prompt interpretation deviations. * * * ## 5. Prompt Engineering Tips The quality of Codex's output largely depends on how you ask questions. The following five tips address the most common problems new users encounter, each with specific examples. ### Tip 1: Provide Sufficient Context Codex cannot read minds. Instructions like "fix the bug" will make it guess, and the result is often not what you want. Here is a comparison example: | Not Recommended | Recommended | | --- | --- | | "Fix the bug" | "User gets TypeError: Cannot read properties of null when logging in, error occurs at line 42 of src/auth/login.ts, this function is responsible for verifying JWT tokens, help me find and fix this problem" | Effective context contains three elements: | Element | Description | Example | | --- | --- | --- | | Specific phenomenon | Error message or specific behavior | TypeError: Cannot read properties of null | | Involved location | File and line number | src/auth/login.ts line 42 | | Code responsibility | What this code is supposed to do | Verify JWT token | ### Tip 2: Complex Tasks in Two Steps For tasks with large scope of changes, first let Codex analyze and list the plan, confirm it's okay before executing. Doing it all at once seems faster, but the cost is greater when direction deviates. ## Example # Step 1: Analyze only, no modifications codex "Analyze code quality in src/api/ directory, list main issues, do not modify any files" # Step 2: Execute after confirming the plan codex "Okay, follow your plan, handle error handling issues first, I'll review the rest later" ### Tip 3: Use Ask Mode to First Understand the Codebase `ask` mode is read-only mode, suitable for understanding the structure and logic of existing code before making changes. Understanding before changing saves time compared to changing first and then understanding. #### Example # ask mode will not trigger any file modifications codex -a ask "How does this project handle user authentication? Map out the complete authentication flow" After understanding clearly, exit the current session and restart in editable mode: # Editable mode (requires confirmation) codex -a auto# Fully automatic execution (use with caution) codex -a full-auto Recommended workflow: ask ↓Understand code structure↓Determine modification plan↓Restart Codex↓Enter editable mode↓Execute modifications > Note: The CLI no longer supports using `/approvals` to switch permission modes during runtime; you need to specify with the `-a` parameter at startup. The desktop client still supports switching within a session. ### Tip 4: Use Negative Instructions to Define Boundaries Telling Codex what not to touch is equally important as telling it what to do. Especially for refactoring tasks involving multiple related files, unclear boundaries can easily lead to unnecessary collateral modifications. ## Example # Clearly define what not to modify codex "Refactor the date formatting functions in utils/date.ts, do not modify function signatures, do not change test files" ### Tip 5: Ask for Plan First, Then Execute For tasks you're not confident about, first let Codex list what it plans to do. This step takes almost no time, but lets you discover direction deviations early, avoiding going too far down the wrong path. # Ask for plan first codex "How do you plan to implement this feature? List the steps first, don't execute"# Confirm plan is reasonable before proceeding codex "Plan looks good, start executing step one" * * * ## Summary These five directions cover the complete path from "project configuration" to "daily operations" to "automation". You don't need to use all of them at the beginning. It's recommended to proceed in order: first write a good AGENTS.md to let Codex understand your project, then gradually integrate it into your VS Code workflow and CI/CD pipeline. Prompt engineering tips accumulate through daily use, which is more effective than trying to memorize them all at once.
← Cc SwitchCodex Usage β†’