這並不是一篇零基礎上手指南,需要您有一點點 Codex 使用經驗。由於本人對於 官方倉庫 所用 Rust 語言並不了解,所有信息均來自 PR 和 Issue 討論,可能存在經驗主義錯誤,如有事實偏差,還望指正。本文偏向於 Windows 的調教指南,如果這你都能看完,想必 MacOS/Linux 更能得心應手。
基礎配置 config.toml#
工欲善其事,必先利其器。對於 Codex 這個工具,強烈建議把配置文檔看一遍 config.md
在 ~/.codex/config.toml
中配置基礎的 Codex
model = "gpt-5-codex" # Codex 0.36.0 支持
model_reasoning_effort = "high" # 使用最大推理能力
model_reasoning_summary = "detailed" # 在終端顯示詳細的推理總結(ctrl+T查看)OpenAI 沒有推理過程,只有推理總結
model_verbosity = "high" # 不懂,總之要拉滿
model_supports_reasoning_summaries = true # 強制啟用推理總結,針對於自定義 API KEY 的
hide_agent_reasoning = false # 允許顯示更多的 AGENT 內部思考過程
disable_response_storage = true # 不允許 OpenAI 服務端存儲你的對話
approval_policy = "never" # 配了但沒用,總之先放著,建議通過 /approvals 配置
sandbox_mode = "workspace-write" # 配了但沒用,總之先放著,建議通過 /approvals 配置
# allow network in workspace-write mode
[sandbox_workspace_write]
network_access = true
命令#
codex --help
是一個好習慣
終端執行 codex
後進入,輸入 /
你能得到目前支持的一些快捷命令。
/status#
最常用的命令,用於檢查當前的權限和 GPT-5 模型配置。如果你是自定義 API Key,更應該多使用該命令檢查是否使用了正確模型。
/approvals#
授予 Codex 權限,目前有三種,如果超出權限限制,就需要用戶手動確認:
- Read Only:默認權限,只能讀取文件(實操下來限制太多,和 Agent Coding 自由理念相悖,一個任務可能要十多次手動批准。太麻煩)
- Auto:讀寫,運行命令(實測一點也不 Auto,還是有太多手動批准)
- Full Access:讀寫、使用網絡工具(雖然官方一再聲明小心操作,但這是我的日常使用的方式,真正的 Auto,整個過程不需要一次確認)
個人傾向日常選用 Full Access
,可以在每次運行 Codex 時添加額外的命令參數,無需每次重新選擇權限:
codex --dangerously-bypass-approvals-and-sandbox
/mcp#
如果你是 Windows 開發者,遵從 mcp_servers 一定會配置失敗。通常進入 Codex 你會看到
Program not found
或 request timed out
需要在原教程文檔基礎上增加如下:
- 新增
command
指向具體的 npx 位置 - 新增
env
包含 SYSTEMROOT
[mcp_servers.context7]
command = "C:\\Program Files\\nodejs\\npx.cmd"
args = ["-y", "@upstash/context7-mcp", "--api-key", "<your_api_key>"]
env = {SYSTEMROOT = 'C:\Windows'}
恢復 / 繼續對話#
resume/continue 恢復對話功能仍然在開發中,所以
--help
中還沒有增加對應的說明,但當前可用
與 Codex 的對話是保存在本地目錄 ~/.codex/sessions
下的,我們可以執行如下命令來選擇最近對話列表恢復,繼續對話。
codex --resume
continue 直接恢復上一次對話,無需選擇
codex --continue
工具調用#
為了最快、最準確的幫助 Codex 完成搜索,我們需要針對性的使用不同的工具。
不同的系統平台,Shell 工具也有所不同,本文主要聚焦於 Windows 平台,旨在引導 Codex 使用正確的命令和工具,減少錯誤重試、降低單次任務執行的時長。
Codex 支持在代碼倉庫根目錄添加 AGENTS.md
文件來指導 Codex 在該倉庫下遵守的規則,如:倉庫技術棧、工具調用等。
目前主要使用三種:fd, ripgrep 和 ast-grep。
- 按文件名找 →
fd
- 按文本內容找 →
rg
(ripgrep) - 按代碼結構 / 語義找 →
sg
(ast-grep)
Windows 安裝#
winget install sharkdp.fd BurntSushi.ripgrep.MSVC ast-grep
ripgrep 安裝後需要手動添加到環境變量,自行解決
AGENTS.md
#
在實際操作過程中,發現只聲明可用工具而不引導具體用法,經常會偏離預期,因此建議複製如下完整的配置,按需調整。
## Tool Priority
- Filename search: `fd`.
- Text/content search: `rg` (ripgrep).
- AST/structural search: `sg` (ast-grep) — preferred for code-aware queries (imports, call expressions, JSX/TSX nodes).
### AST-grep Usage (Windows)
- Announce intent and show the exact command before running complex patterns.
- Common queries:
- Find imports from `node:path` (TypeScript/TSX):
- `ast-grep -p "import $$ from 'node:path'" src --lang ts,tsx,mts,cts`
- Find CommonJS requires of `node:path`:
- `ast-grep -p "require('node:path')" src --lang js,cjs,mjs,ts,tsx`
- Suggest rewrite (do not auto-apply in code unless approved):
- Search: `ast-grep -p "import $$ from 'node:path'" src --lang ts,tsx`
- Proposed replacement: `import $$ from 'pathe'`
### Search Hygiene (fd/rg/sg)
- Exclude bulky folders to keep searches fast and relevant: `.git`, `node_modules`, `coverage`, `out`, `dist`.
- Prefer running searches against a scoped path (e.g., `src`) to implicitly avoid vendor and VCS directories.
- Examples:
- `rg -n "pattern" -g "!{.git,node_modules,coverage,out,dist}" src`
- `fd --hidden --exclude .git --exclude node_modules --exclude coverage --exclude out --exclude dist --type f ".tsx?$" src`
- ast-grep typically respects `.gitignore`; target `src` to avoid scanning vendor folders:
- `ast-grep -p "import $$ from '@shared/$$'" src --lang ts,tsx,mts,cts`
- If needed, add ignore patterns to your ignore files rather than disabling ignores.
系統通知#
Codex 支持在任務執行完成後執行自定義事件,我們可以利用這一特性實現 Windows 系統彈窗通知。
Codex 文檔見 https://github.com/openai/codex/blob/main/docs/config.md#notify
- ~/.codex/config.toml
notify = ["powershell.exe","-NoProfile","-ExecutionPolicy","Bypass","-File","C:\\Users\\<username>\\.codex\\notify.ps1"]
- ~/.codex/notify.ps1
param(
[Parameter(Mandatory = $true)]
[string]$json
)
# 解析 JSON(Codex 把一段 JSON 作為 argv[1] 傳進來)
try {
$payload = $json | ConvertFrom-Json
} catch {
$payload = @{}
}
$title = 'Codex'
$msg = $payload.'last-assistant-message'
if (-not $msg) {
if ($payload.type) {
$msg = "Event: $($payload.type)"
} else {
$msg = 'Codex has an update.'
}
}
# 可選:截斷過長文本,注意只用 ASCII 的三點號,避免亂碼
if ($msg -and $msg.Length -gt 240) {
$msg = $msg.Substring(0,240) + '...'
}
# 只用 Toast,不要任何 Popup 兜底
Import-Module BurntToast -ErrorAction Stop
New-BurntToastNotification -Text $title, $msg | Out-Null
Codex Prompt 調試技巧#
每次修改 [AGENTS.md](http://AGENTS.md)
後,多使用 ctrl+T
查看其思考過程,看看命令的調用、思考過程是否符合你的預期。若不符,直接與 Codex 對話詢問該如何調整 AGENTS.md
,多重複幾輪一般都能得到比較滿意的結果。
[開始]
|
v
[修改 [`AGENTS.md`](http://AGENTS.md)]
|
v
[Ctrl+T 查看當前思考過程/軌跡]
|
v
{是否符合你的預期?}
|是
v
[提交/應用變更]───►(結束或進入下一任務)
^
|否
|
v
[與 Codex 對話:詢問如何調整 [`AGENTS.md`](http://AGENTS.md)]
|
v
[根據建議再次修改 [`AGENTS.md`](http://AGENTS.md)]
|
└───────────────循環回到───────────────┐
v
[Ctrl+T 查看當前思考過程/軌跡]
Spec-kit (實驗性)#
模仿 spec-kit 建立了一套實現新功能的規範,包含三個流程:spec, plan 和 do。
還在嘗試優化中,因此未利用 codex/prompts.md 方式注入指令,而是通過 AGENTS.md
來時刻調整測試,在對話時輸入 /spec
和 /plan
和 /do
即可。
- /spec 開頭,輸入你想要實現的功能,Codex 會自動在 specs 文件夾下生成一個 Markdown 文件
- /plan 開頭,Codex 會自動在 plans 文件夾下生成一個帶有日期的 Markdown 文件
- /do 會自動按照 plan 任務實現。
不必嚴格遵從上述三個順序來執行,如果 spec 文件不符預期,完全可以繼續多輪對話調整滿意後,再輸入 /plan
來引導生成 plan 文件。
## Stage-Gated Workflow (spec/plan/do)
- Mode: Opt-in. The workflow applies only when the user explicitly uses `/spec`, `/plan`, or `/do`. Routine Q&A or trivial edits do not require these stages.
- Triggers: A message containing one of `/spec`, `/plan`, or `/do` activates or advances the workflow. Once active, stages must proceed in order with explicit user approval to advance.
- Guardrails:
- Do not modify source code before `/do`. Documentation/spec files may be edited only in `/spec`.
- Do not skip stages or proceed without user confirmation once the workflow is active.
- If scope changes, return to the appropriate prior stage for approval.
- Respect sandbox/approval settings for all actions.
- When to Use
- Use the workflow for new features, structural refactors, multi-file changes, or work needing traceability.
- Skip the workflow (no triggers) for routine Q&A, diagnostics, or one-off trivial edits.
- Entry Points and Prerequisites
- `/spec` is the canonical entry point for new efforts.
- `/plan` requires an approved `/spec`. If unclear which spec applies, pause and ask the user to identify the correct file(s) under `specs/`.
- `/do` requires an approved `/plan`.
- `/spec` (Specifications; docs only)
- Purpose: Capture a concrete, reviewable specification using spec-kit style.
- Output: Markdown spec(s) under `specs/` (no code changes). Share a concise diff summary and links to updated files; wait for approval.
- Style: Specs are canonical and final. Do not include change logs or “correction/更正” notes. Incorporate revisions directly so the document always reflects the current agreed state. Historical context belongs in PR descriptions, commit messages, or the conversation — not in the spec.
- Recommended contents:
- Problem statement and context
- Goals and non-goals
- Requirements and constraints (functional, UX, performance, security)
- UX/flows and API/IPC contracts (as applicable)
- Acceptance criteria and success metrics
- Alternatives considered and open questions
- Rollout/backout considerations and telemetry (if relevant)
- `/plan` (High-level Plan; docs only)
- Purpose: Turn the approved spec into an ordered, verifiable implementation plan.
- Inputs: Approved spec file(s) in `specs/`.
- Ambiguity: If the relevant spec is unclear, pause and request clarification before writing the plan.
- Style: Plans are canonical and should not include change logs or “correction/更正” notes. Incorporate revisions directly so the plan always reflects the current agreed state. Historical notes should live in PR descriptions, commit messages, or the conversation.
- Output:
- An ordered plan via `update_plan` (short, verifiable steps; Task is merged into Plan and tracked here).
- A plan document in `plans/` named `YYYY-MM-DD-short-title.md`, containing:
- Scope and links to authoritative spec(s)
- Assumptions and out-of-scope items
- Phases/milestones mapped to acceptance criteria
- Impacted areas, dependencies, risks/mitigations
- Validation strategy (tests/lint/build) and rollout/backout notes
- Approval status and next stage
- Handoff: Await user approval of the plan before `/do`.
- `/do` (Execution)
- Purpose: Implement approved plan steps with minimal, focused changes and file operations.
- Actions:
- Use `apply_patch` for file edits; group related changes and keep diffs scoped to approved steps.
- Provide concise progress updates and a final summary of changes.
- Validate appropriately: run `pnpm lint`, `pnpm format`, `pnpm build`, and relevant tests.
- If material changes to the plan are needed, pause and return to `/plan` (or `/spec`) for approval.
- Output: Implemented changes, validation results, and a concise change summary linked to the plan checklist.
### Plans Directory
- Location: `plans/` at the repository root.
- Filename: `YYYY-MM-DD-short-title.md` (kebab-case title; consistent dating).
- Style: Plan docs are the canonical source of truth for the implementation approach; avoid embedding change logs or “correction/更正” notes. Update the plan in place as decisions evolve.
- Contents:
- Title and summary
- Scope and linked specs (paths under `specs/`)
- Assumptions / Out of scope
- Step-by-step plan (short, verifiable)
- Validation strategy (tests/lint/build)
- Approval status and next stage
- Process:
- During `/plan`, create or update the relevant file in `plans/` and share a short summary in the conversation. Await approval before `/do`.
WSL2#
如果你在 Windows 下讓 Codex 執行任務,你會發現它經常調用命令失敗然後重試,如此循環。雖然最終都會成功,但浪費了很多時間,個人推測這是因為 GPT-5 Unix Shell 訓練數據太多而 Powershell 數據太少導致的幻覺,Codex 總是下意識調用 Unix Shell 命令來處理。
那麼有沒有辦法解決呢?當然有!打不過就加入 ——WSL2。
以 Windows 11 為例,在 Powershell 執行 wsl --install
即可安裝 WSL2。
這種情況下,有兩種方式選擇:
- Windows 端代碼 + WSL2 Codex 環境,適用於開發 Windows 端的程序,比如 Electron Windows,.NET 等
- WSL2 代碼 + WSL2 Codex 環境,比如 Vue Web 開發
對於後者,所有都能正常在 WSL2 環境內運行,就不做說明了,而前者 Windows + WSL2 混用就需要解決一個問題:如何在 WSL2 調用 Windows 端的 npm/pnpm
,執行定義好的 pnpm typecheck
pnpm lint:fix
等。
在 WSL2 Codex 對話時,要求其調用 pwsh.exe 來執行 pnpm typecheck
來檢查,如此即可。
we're in WSL2, please using pwsh.exe to run `pnpm <script>`
完整 AGENTS.md#
還在調整中,不要完全照抄,最好還是通過 ctrl+T
查看整個過程,如果遇到 Codex 經常會出錯的命令,選擇性的修刪適合自己的 AGENTS.md
。
主要適配內容:
- Windows/WSL2 支持,優先使用 Powershell 支持的命令,對於任何 npm 包安裝都必須請示用戶,避免混亂的依賴項
- 使用 fd,ripgrep,ast-grep 搜索文件、文本和代碼片段,更快更直接
- spec/plan/do 工作流,先確定規範,再編寫計劃,最後實現
# AGENTS Guidelines
## Windows Environment Notice
- Prefer PowerShell (`pwsh`/`powershell`) when on Windows.
- Prefer using pwsh.exe to run `pnpm <script>` when on WSL2.
- WSL2 may be used for non-package-manager commands only (e.g., `rg`, `tar`). Avoid running Node builds in WSL due to OS mismatch.
- WSL2 cross-drive performance: accessing repos under `/mnt/c|d|e/...` goes through a filesystem bridge and can be slower for full scans. Prefer scoping to subtrees, excluding heavy folders, or running the same searches with native Windows binaries in PowerShell for large/iterative scans.
- Do not auto-run dependency installs. The user must run `pnpm install` in Windows PowerShell manually and then confirm completion.
- Do not modify `package.json`/lockfiles to add or update dependencies without explicit user approval. Propose dependencies in `/spec` or `/plan`, and ask the user to run `pnpm add <pkg>` (or `pnpm install`) and confirm.
- Do not call Unix text tools directly in PowerShell (e.g., `sed`, `awk`, `cut`, `head`, `tail`). Use PowerShell-native equivalents instead:
- `head` → `Select-Object -First N`
- `tail` → `Get-Content -Tail N`
- paging → `Out-Host -Paging` or `more`
- substitution/replace → `-replace` with `Get-Content`/`Set-Content`
## Tool Priority
- Filename search: `fd`.
- Text/content search: `rg` (ripgrep).
- AST/structural search: `sg` (ast-grep) — preferred for code-aware queries (imports, call expressions, JSX/TSX nodes).
### AST-grep Usage
- Announce intent and show the exact command before running complex patterns.
- Common queries:
- Find imports from `node:path` (TypeScript/TSX):
- `ast-grep -p "import $$ from 'node:path'" src --lang ts,tsx,mts,cts`
- Find CommonJS requires of `node:path`:
- `ast-grep -p "require('node:path')" src --lang js,cjs,mjs,ts,tsx`
- Suggest rewrite (do not auto-apply in code unless approved):
- Search: `ast-grep -p "import $$ from 'node:path'" src --lang ts,tsx`
- Proposed replacement: `import $$ from 'pathe'`
### Search Hygiene (fd/rg/sg)
- Exclude bulky folders to keep searches fast and relevant: `.git`, `node_modules`, `coverage`, `out`, `dist`.
- Prefer running searches against a scoped path (e.g., `src`) to implicitly avoid vendor and VCS directories.
- Examples:
- `rg -n "pattern" -g "!{.git,node_modules,coverage,out,dist}" src`
- `fd --hidden --exclude .git --exclude node_modules --exclude coverage --exclude out --exclude dist --type f ".tsx?$" src`
- ast-grep typically respects `.gitignore`; target `src` to avoid scanning vendor folders:
- `ast-grep -p "import $$ from '@shared/$$'" src --lang ts,tsx,mts,cts`
- If needed, add ignore patterns to your ignore files rather than disabling ignores.
## Temporary Research Files
- Canonical location: store all temporary research artifacts (downloaded READMEs, API docs, scratch notes) under `docs/research/`.
- Do not place temporary files at the repository root or outside `docs/research/`.
- Commit policy: avoid committing temporary files unless they are necessary for traceability during `/spec` or `/plan`. If committed, keep the scope minimal and store them under `docs/` only.
- Naming: use descriptive names with date or task context (e.g., `docs/research/2025-09-11-wsl-notes.md`).
- Cleanup: after completing a task (`/do`), evaluate whether each temporary file is still required. Remove unneeded files, or promote essential content into curated docs under `docs/` or into `specs/`/`plans/`.
## Stage-Gated Workflow (spec/plan/do)
- Mode: Opt-in. The workflow applies only when the user explicitly uses `/spec`, `/plan`, or `/do`. Routine Q&A or trivial edits do not require these stages.
- Triggers: A message containing one of `/spec`, `/plan`, or `/do` activates or advances the workflow. Once active, stages must proceed in order with explicit user approval to advance.
- Guardrails:
- Do not modify source code before `/do`. Documentation/spec files may be edited only in `/spec`.
- Do not skip stages or proceed without user confirmation once the workflow is active.
- If scope changes, return to the appropriate prior stage for approval.
- Respect sandbox/approval settings for all actions.
- When to Use
- Use the workflow for new features, structural refactors, multi-file changes, or work needing traceability.
- Skip the workflow (no triggers) for routine Q&A, diagnostics, or one-off trivial edits.
- Entry Points and Prerequisites
- `/spec` is the canonical entry point for new efforts.
- `/plan` requires an approved `/spec`. If unclear which spec applies, pause and ask the user to identify the correct file(s) under `specs/`.
- `/do` requires an approved `/plan`.
- `/spec` (Specifications; docs only)
- Purpose: Capture a concrete, reviewable specification using spec-kit style.
- Output: Markdown spec(s) under `specs/` (no code changes). Share a concise diff summary and links to updated files; wait for approval.
- Style: Specs are canonical and final. Do not include change logs or “correction/更正” notes. Incorporate revisions directly so the document always reflects the current agreed state. Historical context belongs in PR descriptions, commit messages, or the conversation — not in the spec.
- Recommended contents:
- Problem statement and context
- Goals and non-goals
- Requirements and constraints (functional, UX, performance, security)
- UX/flows and API/IPC contracts (as applicable)
- Acceptance criteria and success metrics
- Alternatives considered and open questions
- Rollout/backout considerations and telemetry (if relevant)
- `/plan` (High-level Plan; docs only)
- Purpose: Turn the approved spec into an ordered, verifiable implementation plan.
- Inputs: Approved spec file(s) in `specs/`.
- Ambiguity: If the relevant spec is unclear, pause and request clarification before writing the plan.
- Style: Plans are canonical and should not include change logs or “correction/更正” notes. Incorporate revisions directly so the plan always reflects the current agreed state. Historical notes should live in PR descriptions, commit messages, or the conversation.
- Output:
- An ordered plan via `update_plan` (short, verifiable steps; Task is merged into Plan and tracked here).
- A plan document in `plans/` named `YYYY-MM-DD-short-title.md`, containing:
- Scope and links to authoritative spec(s)
- Assumptions and out-of-scope items
- Phases/milestones mapped to acceptance criteria
- Impacted areas, dependencies, risks/mitigations
- Validation strategy (tests/lint/build) and rollout/backout notes
- Approval status and next stage
- Handoff: Await user approval of the plan before `/do`.
- `/do` (Execution)
- Purpose: Implement approved plan steps with minimal, focused changes and file operations.
- Actions:
- Use `apply_patch` for file edits; group related changes and keep diffs scoped to approved steps.
- Provide concise progress updates and a final summary of changes.
- Validate appropriately: run `pnpm lint`, `pnpm format`, `pnpm build`, and relevant tests.
- If material changes to the plan are needed, pause and return to `/plan` (or `/spec`) for approval.
- Output: Implemented changes, validation results, and a concise change summary linked to the plan checklist.
### Plans Directory
- Location: `plans/` at the repository root.
- Filename: `YYYY-MM-DD-short-title.md` (kebab-case title; consistent dating).
- Style: Plan docs are the canonical source of truth for the implementation approach; avoid embedding change logs or “correction/更正” notes. Update the plan in place as decisions evolve.
- Contents:
- Title and summary
- Scope and linked specs (paths under `specs/`)
- Assumptions / Out of scope
- Step-by-step plan (short, verifiable)
- Validation strategy (tests/lint/build)
- Approval status and next stage
- Process:
- During `/plan`, create or update the relevant file in `plans/` and share a short summary in the conversation. Await approval before `/do`.
經驗之談#
- 主動讓 Codex 調用特定工具:不要把所有的注意事項都寫入到 AGENTS.md 中,用戶還會需要擔負一些心智針對不同的場景引導 Codex 使用更為合適的工具,比如用
git diff
可能更能提供準確的上下文。 - 盡可能在對話時提供完整的信息來源:Codex 查找代碼的方式非常原始,如 grep, ripgrep 等,很有可能搜不到你想要的內容。比如你想要詢問為什麼實例化了兩次,請順帶給出兩次出現的地方:函數、文件名等信息,能減少 Codex 的誤判或者搜索代碼的時間。Codex 提供了
@
快捷命令來幫助你快速搜索文件名。 - 網頁搜索盡量使用網頁端 ChatGPT-5-Thinking:搜索更快更完整,非常擅長對於 GitHub 項目的檢索:包括不限於源碼、項目結構、issue、PR 等。特別適合了解某個開源項目的功能,單獨開一個長對話和 ChatGPT 聊聊,受益良多。
總結#
AI 工具日新月異,一個新的工具崛起,不要妄想能三分鐘上手掌握,也不要過於依賴他人的博客文檔和結論,AI 工具千人千面,每個人都有各自的編程習慣,需要花幾天慢慢了解工具特性和背後的大語言模型習慣,根據自己的需求和喜好來調教獨屬於自己的 AI 工具。
面對新興事物,莫要故步自封在一個工具上吊死,保持好奇心,勇於探索未知的可能。