◂ Topic Center Official Docs Verified · 2026-07-18 Verified 2026-08-17
🚑 Login Errors · Config Conflicts · Migration Disasters —— Cured in One Page

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.

5-Layer Diagnosis1-Click Health Script3-Level ResetClaude Code × Codex Comparison
5 LayersBinary → Env Vars → Credentials → Config → Network, any symptom falls into one layer
1 ScriptRead-only check, understand full machine state in 30s
3-Level ResetSoft reset → Credential reset → Nuke reset, step-by-step without friendly fire
3 ScriptsShared PC / New PC / Headless, copy-paste by scenario
Methodology 00

Symptom Quick Check + Problem Map

⚡ 3 Sentences to Save Your Life (Try these first, 70% of problems end here) ① 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 keyClaude Code ER Guide · Codex ER Guide
I am a Pro member, but being charged API fees / org disabledCredential Priority (Root Cause) → ER Guide · Billing & Quota
Prompts usage limit / 429 / 529ER 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 itScript A · Shared PC
Got a new PC, want to migrate environment exactly as isScript B · New PC / Multi-device Roaming
SSH / Container / CI has no browser, how to loginScript C · Headless Environment
Changed config doesn't take effect / Company PC configs lockedER Guide · Configuration (CC / Codex)
Company Proxy / Intranet: TLS errors, download failuresER Guide · Network & Proxy (CC / Codex)
Command not found / Weird versions / Updates have no effectER Guide · Installation & Version (CC / Codex)
Can't explain what's wrong, want to systematically check01 · 5-Layer Diagnosis + Health Script
Want to see what a full troubleshooting process looks like11 · Case Reviews —— 4 real cases from symptom to root cause
Tried everything, want to safely start over12 · 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 CauseTypical SymptomsWhy it happens
① Multiple installations coexistVersions jump back and forth, update has no effect, command acts weirdNative 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 disabledKeys 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 lockedEnterprise managed > CLI arguments > Project local > Project > User layer —— The layer you modified might be quietly overridden by a higher layer
④ Network & System EnvironmentLogin stuck, TLS errors, OAuth callback failed, download 403Company proxy/Private CA/Firewall blocking callback port; Inaccurate system clock can also fail token validation
One-Sentence Core MantraWhen encountering any environment issue, DO NOT just reinstall. Use the 5-layer diagnosis in the next chapter to pinpoint which layer the issue is in —— 90% of "complex issues" are category ② (Credential conflict), clearing one environment variable fixes it; reinstalling instead introduces category ① problems.

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 CodeCodex
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 StoragemacOS Keychain; Linux/Win is .credentials.jsonauth.json (Plain text) or system keyring (configurable)
Health Check Cmdclaude doctor / In-session /status /doctorIn-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.

diagnose

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

依据:Codex configuration · Claude settings

claude-cred

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.

Authentication →

依据:Official reference

claude-config

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.

Configuration →

依据:Official reference

claude-er

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.

Troubleshooting →

依据:Official reference

codex-cred

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.

Authentication →

依据:Official reference

codex-config

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.

Configuration →

依据:Official reference

codex-er

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.

Troubleshooting →

依据:Official reference

Scenario Playbook 08

Playbook A · Shared Computer / Inheriting a Pre-configured Machine

The most frequent failure scene: You are a Claude Pro user, sitting at a computer someone else used, and hitting walls of errors. The root cause is almost always the same: The previous user's credentials and env vars are still alive, and their priority is higher than your login.

The 3 Pre-Checks (Do this before configuring)

  1. Check Env Vars and RC Residue: Run Chapter 01 Health Check script, focusing on L2 output —— export ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL (proxy config) / OPENAI_API_KEY in someone else's rc file are ticking time bombs.
  2. Check Credential Ownership: Run claude into session and /status to see whose account is logged in; same for codex login status. If it's someone else's, /logout / codex logout first.
  3. Check Global Config Pollution: Check if ~/.claude/CLAUDE.md, ~/.claude/settings.json, ~/.codex/config.toml, ~/.codex/AGENTS.md contain someone else's preferences or instructions —— these will directly impact all your conversations.

Choose Solution Based on Sharing Level

ScenarioRecommended SolutionHow-To
Temporarily borrowingTouch nothing of theirsOnly clear vars in current terminal session (unset ANTHROPIC_API_KEY etc., do not edit rc files), /logout your account immediately after use
Long-term shared machineCreate separate system accounts (Most formal)macOS/Windows per-user accounts: home dirs are naturally isolated, ~/.claude, keychain, and ~/.codex are invisible to each other, zero conflicts/leaks
Must share same system accountConfig Dir Isolation + AliasesSee below —— both tools support "moving the whole house"

Running Multiple Config Profiles on One System Account (Isolation Solution)

# ~/.zshrc —— Independent config dir + dedicated command for each person/account
# Claude Code: CLAUDE_CONFIG_DIR dictates where "home" is
alias claude-me='CLAUDE_CONFIG_DIR="$HOME/.claude-me" claude'
alias claude-work='CLAUDE_CONFIG_DIR="$HOME/.claude-work" claude'
# Codex: CODEX_HOME similarly
alias codex-me='CODEX_HOME="$HOME/.codex-me" codex'
alias codex-work='CODEX_HOME="$HOME/.codex-work" codex'
  • On first use, each directory walks through its own login; credentials, history, and configs are completely isolated. No more logging in and out repeatedly;
  • Anti-mixup trick: Use /color in different account sessions to change UI theme colors, instantly recognizing "who I am right now" (community madewithlove solution);
  • Note that Claude Code also has a global state file ~/.claude.json (MCP, etc.), which follows the directory if CLAUDE_CONFIG_DIR is set —— stop manually touching the one in the default location.
Departure Checklist (Shared Computer Etiquette)① /logout and codex logout yourself; ② Revert any temporarily exported variables; ③ Never write your API key into shared machine rc files; ④ Remember to clean sensitive project sessions (~/.claude/projects/ transcripts are plaintext).

References: Running multiple Claude accounts without logging out (madewithlove) · Two Claude accounts on one Windows PC (Josh Grossman) · codex-multi-auth (community tool)

Scenario Playbook 09

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)

AssetClaude CodeCodexHow to Handle
Core Configsettings.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
CredentialsKeychain / .credentials.jsonauth.json / Keychain❌ Do NOT copy: Re-login fresh on new machine (30 seconds), clean and secure
Session Historyprojects/, 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/Pluginsplugins/, 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
The Ultimate Fix for "Config Drift" Across MachinesThere is no official built-in multi-machine sync yet (upstream issue #36693 is discussing it). The correct approach right now: put all manually written configs into a dotfiles repo, leaving only symlinks on the machines —— commit when changed, pull on the other machine to sync; or simply point 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)

Scenario Playbook 10

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

  1. SSH/WSL2/Container Interactive Use: Run claude normally, 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, use claude auth login to read from stdin).
  2. CI / Scripts (Subscription Quota): Run claude setup-token locally to generate a 1-year OAuth token, store it in CI Secrets, and set CLAUDE_CODE_OAUTH_TOKEN in the execution environment. Note that --bare mode ignores this; for bare scenarios, use ANTHROPIC_API_KEY or apiKeyHelper instead.
  3. CI (API Billing): Just use the ANTHROPIC_API_KEY environment variable —— simplest, but uses pay-as-you-go billing.

Codex: Three Official Methods by Priority

  1. 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.
  2. Copy auth.json (Official Fallback): Log in on a machine with a browser, then securely copy ~/.codex/auth.json to the target machine (scp / docker cp). If local credentials are in the keychain instead of a file, set cli_auth_credentials_store to file and re-login first.
  3. SSH Port Forwarding: ssh -L 1455:localhost:1455 user@remote then run codex login on 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:

  1. Run codex login (file storage) on a trusted machine, store the generated auth.json into CI Secrets management;
  2. 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;
  3. 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_HOME is easier.
Container / DevContainer Persistent LoginMount the "home directory" as a volume so you don't have to re-login when the container rebuilds: For Claude Code, mount a volume pointed to by 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 CodeCodex
HTTP ProxyHTTPS_PROXY / HTTP_PROXYSame as left, and ensure NO_PROXY includes localhost (for OAuth callback)
Private CANODE_EXTRA_CA_CERTS=/path/ca.pemCODEX_CA_CERTIFICATE=/path/ca.pem
Login Method LockedforceLoginMethod (Policy)forced_login_method (Policy)

Sources: Official Authentication (setup-token) · Official Codex CI/CD auth (2026-07 Edition)

Case Studies 11

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"

SceneTook 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.
TriageL1 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.
Fixunset 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.
LessonThe 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"

SceneRunning 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).
TriageL3 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.
FixKeep 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"

SceneLeft 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.
TriageL2/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.
FixUpgrade to ≥ v2.1.211 (renewal changed to single-process coordination), re-login once, never recurred since.
LessonFor 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"

SceneRunning 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.
TriageL3 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.
FixClose 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.
LessonCredentials 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.

Ultimate Solution 13

Dual Tool Concept Map + Resource Index

One Table to Bridge Both Tools

ConceptClaude CodeCodex
Home Directory / Move Env Var~/.claude / CLAUDE_CONFIG_DIR~/.codex / CODEX_HOME
User Config Filesettings.json (JSON)config.toml (TOML)
Global Memory/Instructions~/.claude/CLAUDE.md~/.codex/AGENTS.md
Credential StoragemacOS Keychain / .credentials.jsonauth.json / Keychain (cli_auth_credentials_store)
View Current Creds/Status/statuscodex login status, /status
Config Health Checkclaude doctor, /doctor, --safe-mode/debug-config, codex-login.log
Env Var Hijack SourcesANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKENOPENAI_API_KEY (API Billing Mode)
CI Long-term Authclaude setup-token → CLAUDE_CODE_OAUTH_TOKEN (1 Year)auth.json restore→run→write loop; or API Key
Headless LoginCopy URL to local browser + paste code / claude auth login--device-auth / SSH forward 1455
Private CANODE_EXTRA_CA_CERTSCODEX_CA_CERTIFICATE
Enterprise Forced PolicyforceLoginMethod / forceLoginOrgUUIDforced_login_method / forced_chatgpt_workspace_id
Multi-Account IsolationCLAUDE_CONFIG_DIR + aliasCODEX_HOME + alias (Official 1st-class support under discussion)

Resource Index (Sorted by Reliability)

ResourceDescription
Claude Code · Troubleshoot installation and loginOfficial install & login troubleshooting landing page —— The most complete "Error Message → Fix" mapping, check this first
Claude Code · AuthenticationOfficial auth mechanism guide, the only authoritative source for credential priority order
Claude Code · Settings · ~/.claude Directory DetailOfficial 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 authOfficial CI long-term auth solution (auth.json renewal loop)
Claude Help Center · Install & Auth TroubleshootingSupplemental official support perspective, includes help channels
madewithlove · Multi-account without logout · Josh Grossman · Windows dual accountsCommunity practice: Two representative guides on CLAUDE_CONFIG_DIR isolation
ClaudeLog Troubleshooting · codex-multi-authCommunity troubleshooting cheat sheet and Codex multi-account tool
Related Chapters in this KBClaude Code Guide · Config & Accounts Deep Dive · Codex Guide · Config & Accounts Deep Dive —— Config cascading, MCP locations, full env var tables are over there