Environment & Login
Emergency Manual
"I'm a Pro member, why am I charged for API?" "It breaks when I switch computers" "Someone else configured this machine, and now my login is messed up" —— These are not mysteries, they can all be pinpointed to one of the 5 layers. This manual gives you a systematic inspection method, dual-tool symptom emergency guides, three major scenario scripts, and a tiered universal reset solution.
Symptom Quick Check + Problem Map
env | cut -d= -f1 | grep -iE 'anthropic|openai' to catch hijacked env vars, and unset them one by one;
② Clean re-login: /logout then /login (Codex: codex logout && codex login);
③ Verify identity: /status / codex login status, confirm the account and login method are what you expect. If not fixed, check symptoms below.Symptom Quick Check: Pinpoint your problem in 30 seconds
| If you encounter... | Go to |
|---|---|
| Can't login / Repeatedly asks to login / Invalid API key | Claude Code ER Guide · Codex ER Guide |
| I am a Pro member, but being charged API fees / org disabled | Credential Priority (Root Cause) → ER Guide · Billing & Quota |
| Prompts usage limit / 429 / 529 | ER Guide · Billing & Quota (CC / Codex) —— Not a login issue, don't reinstall blindly |
| Someone else configured this PC, and it messes up when I use it | Script A · Shared PC |
| Got a new PC, want to migrate environment exactly as is | Script B · New PC / Multi-device Roaming |
| SSH / Container / CI has no browser, how to login | Script C · Headless Environment |
| Changed config doesn't take effect / Company PC configs locked | ER Guide · Configuration (CC / Codex) |
| Company Proxy / Intranet: TLS errors, download failures | ER Guide · Network & Proxy (CC / Codex) |
| Command not found / Weird versions / Updates have no effect | ER Guide · Installation & Version (CC / Codex) |
| Can't explain what's wrong, want to systematically check | 01 · 5-Layer Diagnosis + Health Script |
| Want to see what a full troubleshooting process looks like | 11 · Case Reviews —— 4 real cases from symptom to root cause |
| Tried everything, want to safely start over | 12 · Universal Fix: 3-Level Reset |
Problem Map: All environment issues have 4 root causes
Claude Code and Codex "environment issues" seem diverse, but only have 4 root causes. Recognize the root cause, and all following chapters will map and fix them here.
| Root Cause | Typical Symptoms | Why it happens |
|---|---|---|
| ① Multiple installations coexist | Versions jump back and forth, update has no effect, command acts weird | Native installer, npm global, Homebrew/WinGet, IDE extension built-in copies —— 4 channels can coexist, whichever is earlier in PATH wins |
| ② Credential sources conflict | "I'm logged in but says Invalid API key", Pro member billed for API, organization disabled | Keys in environment variables have higher priority than your browser OAuth subscription —— One leftover export ANTHROPIC_API_KEY from someone else can hijack your entire session |
| ③ Configuration cascading override | "Changes don't take effect", company PC settings locked | Enterprise managed > CLI arguments > Project local > Project > User layer —— The layer you modified might be quietly overridden by a higher layer |
| ④ Network & System Environment | Login stuck, TLS errors, OAuth callback failed, download 403 | Company proxy/Private CA/Firewall blocking callback port; Inaccurate system clock can also fail token validation |
Two Tools, One Mental Model
Good news: The environment architecture of the two tools is highly isomorphic. Learn the methodology once, apply it to both.
| Claude Code | Codex | |
|---|---|---|
| Home Directory | ~/.claude (Can be moved via CLAUDE_CONFIG_DIR) | ~/.codex (Can be moved via CODEX_HOME) |
| Subscription Login | /login → Browser OAuth (claude.ai account) | codex login → Browser OAuth (ChatGPT account, callback localhost:1455) |
| Credential Storage | macOS Keychain; Linux/Win is .credentials.json | auth.json (Plain text) or system keyring (configurable) |
| Health Check Cmd | claude doctor / In-session /status /doctor | In-session /status /debug-config; Login logs codex-login.log |
Full comparison table in Chapter 13. All conclusions on this page are verified against official docs 2026-07 edition, sources are in footnotes of each section.
Five diagnostic layers
Check executable/version, environment variable names, authentication, loaded configuration, and the actual network endpoint. Multiple installations or proxy variables are not automatically wrong. Never print credential files or full environment values. Use Claude /status for loaded sources; do not assume an undocumented Codex /debug-config exists.
codex --version
claude --version
# Variable names only (macOS / Linux / WSL)
env | cut -d= -f1 | sort | grep -iE 'anthropic|claude|codex|openai|proxy' || true
Claude Code · Authentication
Managed settings precede CLI --settings, local project, shared project and user settings. Environment precedence is decided per key; arrays have exceptions. Authentication includes subscriptions, Console, API credentials, cloud providers and enterprise gateways. Desktop/cloud do not simply inherit CLI helpers.
Claude Code · Configuration
Managed settings precede CLI --settings, local project, shared project and user settings. Environment precedence is decided per key; arrays have exceptions. Authentication includes subscriptions, Console, API credentials, cloud providers and enterprise gateways. Desktop/cloud do not simply inherit CLI helpers.
Claude Code · Troubleshooting
Managed settings precede CLI --settings, local project, shared project and user settings. Environment precedence is decided per key; arrays have exceptions. Authentication includes subscriptions, Console, API credentials, cloud providers and enterprise gateways. Desktop/cloud do not simply inherit CLI helpers.
Codex · Authentication
Use the dedicated configuration chapter for provider IDs, authentication, endpoints, mutual exclusions and migration. Official ChatGPT login, API usage and gateway credentials are different paths with different access and billing.
Codex · Configuration
Use the dedicated configuration chapter for provider IDs, authentication, endpoints, mutual exclusions and migration. Official ChatGPT login, API usage and gateway credentials are different paths with different access and billing.
Codex · Troubleshooting
Use the dedicated configuration chapter for provider IDs, authentication, endpoints, mutual exclusions and migration. Official ChatGPT login, API usage and gateway credentials are different paths with different access and billing.
Playbook B · Switching Computers / Multi-Machine Roaming
Core principle in one sentence: Configs travel with you, credentials login fresh per machine, history stays put. Figure out "what to take, what to leave", and swapping machines takes 10 minutes.
What to Take, What to Leave (Dual Tool Comparison)
| Asset | Claude Code | Codex | How to Handle |
|---|---|---|---|
| Core Config | settings.json, global CLAUDE.md, skills/, agents/ | config.toml, profiles, global AGENTS.md | ✅ Goes into dotfiles repo, clone on new machine |
| Project Config | .claude/, .mcp.json, project CLAUDE.md | .codex/, repo AGENTS.md | ✅ Already in project git repo |
| Credentials | Keychain / .credentials.json | auth.json / Keychain | ❌ Do NOT copy: Re-login fresh on new machine (30 seconds), clean and secure |
| Session History | projects/, history.jsonl (Plaintext!) | Session data directory | ❌ Local assets don't migrate; continue sessions across machines via Claude's --teleport/Cloud sessions, and Codex Cloud Tasks |
| Caches/Plugins | plugins/, shell-snapshots/, etc. | Log directory | ➖ No backup needed, rebuilds automatically on new machine |
New Machine 10-Minute Standard Procedure
New Machine 10-Minute Standard Procedure
# 1. Install (Official native channels, do not mix with npm)
curl -fsSL https://claude.ai/install.sh | bash # Claude Code
npm install -g @openai/codex # Codex (or brew install codex)
# 2. Restore Configs (dotfiles method)
git clone git@github.com:your_name/dotfiles.git ~/dotfiles
ln -s ~/dotfiles/claude ~/.claude # Or export CLAUDE_CONFIG_DIR=~/dotfiles/claude
ln -s ~/dotfiles/codex ~/.codex # Or export CODEX_HOME=~/dotfiles/codex
# 3. Login once for each (NEVER copy credentials)
claude # Browser OAuth → /status to verify account and Login method
codex login # Browser OAuth → codex login status to verify
# 4. Final Health Check
claude doctor && bash ai-env-check.sh
CLAUDE_CONFIG_DIR/CODEX_HOME to a cloud sync drive folder (Note: if using a sync drive, ensure you exclude credentials and projects/ using .gitignore/ignore rules).References: Official ~/.claude Directory Guide · anthropics/claude-code#36693 (Multi-machine sync discussion)
Playbook C · SSH / Containers / Headless / CI
In environments without a browser, logging in requires a different approach. The official recommended paths for the two tools differ, so do not mix them up.
Claude Code: Three Paths
- SSH/WSL2/Container Interactive Use: Run
claudenormally, copy the OAuth URL from the terminal into your local browser to complete login, then paste the code back into the terminal (if pasting fails, useclaude auth loginto read from stdin). - CI / Scripts (Subscription Quota): Run
claude setup-tokenlocally to generate a 1-year OAuth token, store it in CI Secrets, and setCLAUDE_CODE_OAUTH_TOKENin the execution environment. Note that--baremode ignores this; for bare scenarios, useANTHROPIC_API_KEYorapiKeyHelperinstead. - CI (API Billing): Just use the
ANTHROPIC_API_KEYenvironment variable —— simplest, but uses pay-as-you-go billing.
Codex: Three Official Methods by Priority
- Device Code (Preferred):
codex login --device-auth, enter the one-time code in any local browser. Workspace admins might need to enable device code permissions first. - Copy auth.json (Official Fallback): Log in on a machine with a browser, then securely copy
~/.codex/auth.jsonto the target machine (scp / docker cp). If local credentials are in the keychain instead of a file, setcli_auth_credentials_storetofileand re-login first. - SSH Port Forwarding:
ssh -L 1455:localhost:1455 user@remotethen runcodex loginon the remote machine; the local browser handles the standard flow.
Codex CI Long-term Auth (Official auth.json Renewal Loop)
The official way to run CI using ChatGPT subscription quota —— leveraging Codex's mechanism to automatically refresh the token and write back to auth.json during runtime:
- Run
codex login(file storage) on a trusted machine, store the generatedauth.jsoninto CI Secrets management; - For each task: Restore auth.json → Run Codex (token goes stale if not refreshed for ~8 days, auto-renews during runtime) → Write back the refreshed auth.json to Secrets;
- Red lines: Do not share the same auth.json across concurrent tasks; Do not overwrite with the original old file every time; If the refresh chain breaks, go back to a trusted machine to re-login and seed a new one. For self-hosted runners, just providing a persistent
CODEX_HOMEis easier.
CLAUDE_CONFIG_DIR (Linux credentials live in .credentials.json inside it); For Codex, mount the CODEX_HOME volume. Red line: Credentials only go into volumes, never bake them into image layers.Company Network (Proxy / Private CA) Quick Lookup
| Claude Code | Codex | |
|---|---|---|
| HTTP Proxy | HTTPS_PROXY / HTTP_PROXY | Same as left, and ensure NO_PROXY includes localhost (for OAuth callback) |
| Private CA | NODE_EXTRA_CA_CERTS=/path/ca.pem | CODEX_CA_CERTIFICATE=/path/ca.pem |
| Login Method Locked | forceLoginMethod (Policy) | forced_login_method (Policy) |
Sources: Official Authentication (setup-token) · Official Codex CI/CD auth (2026-07 Edition)
Case Studies: From Symptoms to Root Causes
Four high-frequency real-world scenarios, walking through the 5-Layer Diagnostic Method from start to finish. Understand these four, and you can solve most "voodoo problems" yourself —— note how far the error text is from the actual root cause in each case.
Case I · "I'm a Pro subscriber, but it says organization disabled"
| Scene | Took over a colleague's old PC, installed Claude Code, logged in with subscription successfully. Asked a question and got API Error: 400 "This organization has been disabled". Reinstalled twice, no change. |
| Triage | L1 normal (single install, latest version); L2 hit —— env | cut -d= -f1 | grep -i anthropic caught an ANTHROPIC_API_KEY=sk-ant-…, tracing it back to ~/.zshrc left by the previous user. The Console organization for that key was long deleted. |
| Fix | unset the variable + delete the export line in rc file → Restart terminal → /status confirms Login method reverted to subscription. Took 3 minutes total, zero reinstalls needed. |
| Lesson | The error said "organization", you thought "subscription", but the actual culprit was "environment variable" —— Error text describes the result, not the root cause. This is why reinstalling (touching L1) never cures an L2 disease. |
Case II · "VS Code extension keeps saying Invalid API key, but terminal is fine"
| Scene | Running claude in terminal is perfect; VS Code extension repeatedly pops up Invalid API key · Please run /login, and stays blank even after successful login. Widespread community issue (classic form documented in anthropics/claude-code#12204). |
| Triage | L3 Credential layer hit, but root cause is L2: Three credentials co-exist on the machine —— OAuth login, manual API key, and shell env vars. The environment the terminal reads from rc files is different from what VS Code inherits upon graphical startup. They each picked different credentials; one valid, one invalid. |
| Fix | Keep only one credential source: Clear all ANTHROPIC_* vars and manual keys → Clean re-login for both CLI and extension → Both sides show the same subscription account via /status. |
| Lesson | "Terminal good, IDE bad" almost always means the two processes are seeing different environments. When multiple credentials coexist, nobody can guarantee which process grabs which —— always keep exactly one credential source. |
Case III · "Woke up and all parallel sessions demand re-login"
| Scene | Left three parallel Claude Code sessions open overnight, closed laptop lid. Woke it up in the morning and all three demanded login. Logging into one knocked the other two out —— like a ghost in the machine. |
| Triage | L2/L3 are clean. Counter-intuitively, it lands on L1 Version layer: Checked official changelog, versions before v2.1.211 had a known defect —— upon waking from sleep, multiple sessions concurrently renewed the same token, invalidating each other's logins. |
| Fix | Upgrade to ≥ v2.1.211 (renewal changed to single-process coordination), re-login once, never recurred since. |
| Lesson | For collective, weirdly-timed phenomena, check versions and changelogs first, rather than messing with your own config —— you can never diagnose the root cause locally for a bug the vendor has already patched. |
Case IV · "Codex ran stable in CI for a week, suddenly 401 across the board"
| Scene | Running CI on ChatGPT subscription quota: Saved local auth.json into Secrets, restored before each run. A week later, all pipelines started 401ing. Exported a fresh one locally, lasted a few more days, then repeated. |
| Triage | L3 Credential layer hit: Codex tokens go stale after ~8 days without refresh. During runs, it actually auto-renews and writes back to auth.json —— but the pipeline overwrites it with the "factory original" from Secrets every time, discarding all renewals. Once the refresh chain breaks, everything fails. |
| Fix | Close the loop per official CI docs: Restore → Run → Write the refreshed auth.json back to Secrets; Do not share the same credential across concurrent tasks. For self-hosted runners, simply providing a persistent CODEX_HOME fixes it once and for all. |
| Lesson | Credentials are alive, not configuration constants. For any issue that "breaks predictably every N days", suspect a time-expiring item missing its renewal channel. |
Case Basis: Official troubleshoot-install / authentication docs, anthropics/claude-code#12204, Codex CI/CD auth official guide (2026-07 verified); Machine and persona details are adapted for scenarios, but diagnostic paths and root causes represent real mechanisms.
Recoverable diagnostics and resets
Save errors, versions, effective configuration, and redacted logs. Reauthenticate only when evidence points to credentials. Do not erase entire configuration directories: partial backups cannot restore all sessions, skills, and state.
If isolation is needed, identify actual custom paths, make a complete timestamped copy, and verify readability. Preserve originals and change one confirmed item at a time. A failed reset does not prove a server-side cause.
Dual Tool Concept Map + Resource Index
One Table to Bridge Both Tools
| Concept | Claude Code | Codex |
|---|---|---|
| Home Directory / Move Env Var | ~/.claude / CLAUDE_CONFIG_DIR | ~/.codex / CODEX_HOME |
| User Config File | settings.json (JSON) | config.toml (TOML) |
| Global Memory/Instructions | ~/.claude/CLAUDE.md | ~/.codex/AGENTS.md |
| Credential Storage | macOS Keychain / .credentials.json | auth.json / Keychain (cli_auth_credentials_store) |
| View Current Creds/Status | /status | codex login status, /status |
| Config Health Check | claude doctor, /doctor, --safe-mode | /debug-config, codex-login.log |
| Env Var Hijack Sources | ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN | OPENAI_API_KEY (API Billing Mode) |
| CI Long-term Auth | claude setup-token → CLAUDE_CODE_OAUTH_TOKEN (1 Year) | auth.json restore→run→write loop; or API Key |
| Headless Login | Copy URL to local browser + paste code / claude auth login | --device-auth / SSH forward 1455 |
| Private CA | NODE_EXTRA_CA_CERTS | CODEX_CA_CERTIFICATE |
| Enterprise Forced Policy | forceLoginMethod / forceLoginOrgUUID | forced_login_method / forced_chatgpt_workspace_id |
| Multi-Account Isolation | CLAUDE_CONFIG_DIR + alias | CODEX_HOME + alias (Official 1st-class support under discussion) |
Resource Index (Sorted by Reliability)
| Resource | Description |
|---|---|
| Claude Code · Troubleshoot installation and login | Official install & login troubleshooting landing page —— The most complete "Error Message → Fix" mapping, check this first |
| Claude Code · Authentication | Official auth mechanism guide, the only authoritative source for credential priority order |
| Claude Code · Settings · ~/.claude Directory Detail | Official word on config cascading and directory contents |
| Codex · Authentication (→ learn.chatgpt.com) | Codex official auth docs: login methods, credential storage, headless solutions |
| Codex · CI/CD auth | Official CI long-term auth solution (auth.json renewal loop) |
| Claude Help Center · Install & Auth Troubleshooting | Supplemental official support perspective, includes help channels |
| madewithlove · Multi-account without logout · Josh Grossman · Windows dual accounts | Community practice: Two representative guides on CLAUDE_CONFIG_DIR isolation |
| ClaudeLog Troubleshooting · codex-multi-auth | Community troubleshooting cheat sheet and Codex multi-account tool |
| Related Chapters in this KB | Claude Code Guide · Config & Accounts Deep Dive · Codex Guide · Config & Accounts Deep Dive —— Config cascading, MCP locations, full env var tables are over there |