Skip to content
2026 Edition · Complete Guide & Cheatsheet

Claude Code CLI

From zero to productive. Install, configure, save tokens, and write quality code — the complete guide for test automation engineers and developers who want to vibe code with AI.

Node.js 18+@anthropic-ai/claude-codeSonnet 5 defaultOpus 4.8 · Fable 5Playwright · TypeScript
01Installation & First Launch

Node.js v18+ (use nvm to manage versions) and a paid Claude plan — Pro ($20/mo), Max 5x ($100/mo), Max 20x ($200/mo), or an API key.

Install & Launch
TERMINAL
# Install globally
$ npm install -g @anthropic-ai/claude-code

# Navigate to your project
$ cd ~/playwright-project

# Start Claude Code — browser opens for auth on first run
$ claude

# Or: use API key instead of subscription
$ export ANTHROPIC_API_KEY="sk-ant-..."
$ claude
💡
First thing to do after launch: Run /init to generate a starter CLAUDE.md. Then customize it with your project's stack, commands, and conventions.
Updating & Staying Current

Claude Code ships new features weekly and the model aliases only resolve correctly on a recent build (Sonnet 5's 1M window, for example, needs v2.1.193+). The native installer and npm global install auto-update in the background on startup — updates take effect the next time you launch. Homebrew, WinGet, and Linux package managers do not auto-update, and claude update does nothing on them — you upgrade through the package manager itself (Homebrew users: brew upgrade --cask claude-code).

TERMINAL
# See which version you're on
$ claude --version

# Update now — don't wait for the background check (native + npm installs)
$ claude update

# npm global install: upgrade explicitly.
# Avoid `npm update -g` — it respects the old semver range and may not bump.
$ npm install -g @anthropic-ai/claude-code@latest

# Homebrew / WinGet don't auto-update — upgrade manually.
# On these installs `claude update` silently does nothing; use the package manager.
$ brew upgrade --cask claude-code   # Claude Code is a cask — the --cask flag is required
> winget upgrade Anthropic.ClaudeCode

# Diagnose the install + see the result of the last auto-update attempt
$ claude doctor
Install MethodAuto-Updates?Manual Update
Native installer (recommended)✅ backgroundclaude update
npm global✅ backgroundnpm install -g @anthropic-ai/claude-code@latest
Homebrewmanualbrew upgrade --cask claude-code
WinGetmanualwinget upgrade Anthropic.ClaudeCode
apt / dnf / apkmanualsystem upgrade (e.g. apt upgrade claude-code)
ℹ️
Release channels & control — pick how fast updates reach you in settings.json (or /config → Auto-update channel):
  • "autoUpdatesChannel": "latest" (default) — new features as soon as they ship. "stable" — a build ~1 week old that skips releases with major regressions.
  • "minimumVersion": "2.1.100" — a floor; updates never install below it, so switching to stable won't downgrade you.
  • Disable the background check with "env": { "DISABLE_AUTOUPDATER": "1" } (claude update still works). Use DISABLE_UPDATES to block every update path, including manual.
02Pricing & Models
Plans
PlanPriceDefault ModelBest For
Free$0Trying Claude Code · usage limits apply
Pro$20/mo ($17 annual)Sonnet 5Learning, daily light usage
Max 5x$100/moOpus 4.8Daily development
Max 20x$200/moOpus 4.8Heavy professional use · Dynamic Workflows
Team Standard$20/seat/moSonnet 5Small teams
Team Premium$100/seat/moOpus 4.8Teams doing heavy agentic work
EnterpriseCustom · $20/seat + usageOpus 4.8 (pay-as-you-go)Org-wide · SSO · spend controls
APIPer tokenYou chooseCI/CD, automation
ℹ️
Free now includes Claude Code (CLI, with usage limits) — previously CLI access required a paid plan. Team split into two seat types: Standard ($20/seat, defaults to Sonnet 5) and Premium ($100/seat, defaults to Opus 4.8, ~5× the usage of Standard).
Plan ↔ Feature Matrix

What you actually get on each plan. Model access is controlled by aliases (opus, sonnet, haiku, fable) that resolve to a different concrete model depending on your account type — see Selecting a Model below.

FeatureFreeProMax 5xMax 20xTeamEnterpriseAPI
Claude Code (CLI / Desktop / VS Code)✅*
Sonnet 5 (sonnet alias)✅ defaultStandard: default
Opus 4.8 (opus alias)✅ default✅ defaultPremium: default✅ default
Haiku 4.5 (haiku alias)
Fable 5 (fable alias, opt-in via /model fable)✅†
Opus 4.8 Fast mode ($10/$50)
Dynamic Workflows (/workflows, ultracode)via /config
1M context — Opususage creditsincludedincludedincludedincludedfull access
1M context — Sonnet 5n/a — always 1Mn/a — always 1Mn/a — always 1Mn/a — always 1Mn/a — always 1Mn/a — always 1Mn/a — always 1M
SSO / admin / audit logsbasicSCIM + HIPAA
ℹ️
* Free tier now includes CLI access (usage limits apply) — this changed from earlier 2026, when Claude Code required a paid plan. † Fable 5 isn't available under zero data retention — the /model picker omits or disables it for those orgs.
Checking usage: run /usage inside a session for a plan-usage breakdown (skills, subagents, MCP servers), or /status for account + current model. Shared pool: Pro / Max usage is one counter across Claude chat and Claude Code. On Pro / Max you can also raise a monthly cap with /usage-credits.
Model Costs (API)
ModelInput / 1M tokOutput / 1M tokWhen to Use
Fable 5 (claude-fable-5)$10.00$50.00Hardest, longest-running agentic tasks — investigates, verifies, and self-corrects with less prompting
Opus 4.8 (claude-opus-4-8)$5.00$25.00Complex architecture, hard debugging — flagship for coding
Opus 4.8 (Fast mode)$10.00$50.00Same Opus quality at ~2.5× speed
Sonnet 5 (claude-sonnet-5)$3.00 ($2 intro¹)$15.00 ($10 intro¹)Daily coding — new default, best speed/intelligence balance
Haiku 4.5 (claude-haiku-4-5)$1.00$5.00Quick lookups, simple edits, subagents

¹ Sonnet 5's introductory pricing runs through Aug 31, 2026, then reverts to standard $3/$15. Previous-generation models (Opus 4.7, Opus 4.6, Sonnet 4.6, Opus 4.5, Sonnet 4.5) are still callable by full model ID if you need to pin a version, but Fable 5 / Opus 4.8 / Sonnet 5 / Haiku 4.5 are the recommended picks going forward.

💡
Rule of thumb: Subscription users report 90%+ savings vs. API pricing. If your monthly API equivalent exceeds $100 → get Max 5x. Exceeds $200 → get Max 20x.
ℹ️
How do these models actually compare to Codex, DeepSeek, and Gemini? See our Claude vs Codex vs DeepSeek vs Gemini comparison — code, autotests, business writing, reasoning, and long-context scores, with vendor claims cross-checked against independent trackers.
Selecting a Model

Four ways to set the model, in priority order (highest wins) — per Anthropic's model configuration guide:

#MethodScope
1/model <alias|name> (in-session)Immediate switch; with no argument opens the picker. Saves as your default for new sessions
2claude --model <alias|name>This launch only
3ANTHROPIC_MODEL=<alias|name>This launch only (env var)
4"model" field in settings.jsonPermanent, until changed
TERMINAL
# Aliases resolve to the current recommended model for your account —
# they update automatically as new models ship.
$ claude --model sonnet    # Sonnet 5 on the API/Pro; Sonnet 4.6 on Bedrock/Vertex/Foundry
$ claude --model opus      # Opus 4.8 on the API; Opus 4.7 on Claude Platform on AWS
$ claude --model haiku     # Haiku 4.5 everywhere
$ claude --model fable     # Fable 5 — hardest, longest-running tasks (not default anywhere)

# Pin an exact version instead of an alias (recommended for CI/CD):
$ claude --model claude-sonnet-5
$ claude --model claude-opus-4-8

# opusplan: Opus for planning, Sonnet for execution — best of both
$ claude --model opusplan

# Check what's active right now
$ claude
> /status
💡
Model aliases: default, best, opus, sonnet, haiku, fable, opusplan never hardcode a version — pin an exact model ID (e.g. claude-opus-4-8) in CI/CD or team settings so a Claude update doesn't silently change your pipeline's behavior.
Context Windows

The context window is how much Claude can "see" at once — every CLAUDE.md, every file read, and the whole conversation counts against it. When it fills, Claude auto-compacts (summarizes) to keep going.

ModelContextNotes
Fable 51M tokensAlways 1M on the Anthropic API
Opus 4.81M tokens1M on API; on Max/Team/Enterprise auto-upgraded to 1M — on Pro needs usage credits
Sonnet 51M tokensAlways 1M on API — no 200K variant, no [1m] suffix, no usage credits on any plan. Auto-compacts at ~967K
Haiku 4.5200K tokensNo 1M variant
⚠️
"I switched to Sonnet 5 and the context bar jumped to 100% instantly." Sonnet 5 is a 1M-context model on the API, so a full bar means the session is being budgeted at 200K instead of 1M. Three causes:
  • Old Claude Code version — Sonnet 5 needs v2.1.193+. Run claude update, then check claude --version.
  • CLAUDE_CODE_DISABLE_1M_CONTEXT=1 is set — unset it to restore the full 1M window.
  • Behind an LLM gateway (ANTHROPIC_BASE_URL points at one) — Claude Code can't verify 1M support, so it caps at 200K. Pick "Sonnet 5 (1M context)" in the /model picker (alias sonnet[1m]).
Also note: switching models mid-session re-reads the entire history uncached (the picker warns about this). If a large Opus session is switched to a model budgeted at 200K, the accumulated history instantly overflows the smaller window. Run /context to see exactly what's eating the window, and /clear before switching if you don't need the history.
TERMINAL
# Force the 1M window on an alias or full model name
/model sonnet[1m]
/model opus[1m]
/model claude-opus-4-8[1m]

# See what's consuming the context window right now
/context

# Change the auto-compact threshold for Sonnet 5's 1M window (default ~967K)
$ export CLAUDE_CODE_AUTO_COMPACT_WINDOW=800000

# Cap Sonnet 5 at a 200K window on purpose (e.g. to bound cost)
$ export CLAUDE_CODE_DISABLE_1M_CONTEXT=1
03CLI Commands & Flags
Launch Modes
TERMINAL
# Interactive session
$ claude

# One-shot: single prompt, get answer, exit
$ claude -p "explain the page object pattern in tests/pages/"

# Continue last conversation
$ claude --continue    # or -c

# Pick from recent sessions
$ claude --resume      # or -r

# Pipe input
$ cat test-results/errors.log | claude -p "explain these test failures"

# JSON output for scripting
$ claude -p "list all spec files" --output-format json

# Specify model — alias or full ID (see Pricing & Models → Selecting a Model)
$ claude --model sonnet    # Sonnet 5 — daily coding, default on Pro
$ claude --model opus      # Opus 4.8 — flagship for complex tasks
$ claude --model fable     # Fable 5 — hardest, longest-running tasks
System Prompt Flags
FlagActionRecommendation
--append-system-prompt "text"Add to defaultsUSE THIS
--append-system-prompt-file pathAppend from fileUSE THIS
--system-prompt "text"Replace ALL defaultsCAREFUL
--system-prompt-file pathReplace from fileCAREFUL
TERMINAL
# Best practice: append rules for Playwright project
$ claude --append-system-prompt "Always use Page Object Model. Import test from src/fixtures/base.fixture.ts, not @playwright/test."

# CI/CD: run with rules from file
$ claude -p "review tests/" --append-system-prompt-file .claude/ci-rules.md
Permission & Safety
TERMINAL
# Allow specific tools
$ claude --allowedTools "Read,Grep,Glob,Write,Edit"

# YOLO mode — skip all prompts (containers only!)
$ claude --dangerously-skip-permissions
⚠️
--dangerously-skip-permissions should only be used inside containers or isolated CI environments. Never run with this flag in production systems.
04Slash Commands

Type these inside a running Claude Code session.

Essential (daily use)
CommandWhat It DoesExample / Tip
/clearWipe context — fresh startUse between unrelated tasks!
/compactSummarize & reduce tokens/compact focus on page objects
/modelSwitch AI model (aliases or full ID)/model sonnet · /model claude-haiku-4-5
/effortSet reasoning depth: low/medium/high/xhigh/max/ultracode/effort high — default on Fable 5, Sonnet 5, Opus 4.8
/fastToggle Opus 4.8 fast mode (~2.5× speed, $10/$50 per 1M)For quick iterations
/plan (Shift+Tab)Plan mode — explore & propose before editingFor complex refactors
/reviewCode review current changesBefore committing
/rewindUndo to any checkpointAlso: double-tap Esc
Session Management
CommandWhat It Does
/renameName session: /rename playwright-auth-refactor
/exportSave conversation to file
/todosList tracked TODO items
/add-dirAdd extra directories: /add-dir ~/api-project
/usagePlan usage breakdown (skills, subagents, MCP servers)
/statusCurrent model + account info
/doctorHealth check installation
/permissionsManage allowed tools & commands
/output-styleChange response formatting
05Keyboard Shortcuts
ShortcutAction
EnterSend message
Shift + EnterNew line
Shift + TabCycle: Normal → Auto-accept → Plan mode
Option/Alt + TToggle extended thinking for this session
Ctrl + OToggle verbose thinking output
EscCancel current generation
Esc EscOpen rewind menu
Ctrl + CExit Claude Code
Ctrl + LClear screen (not context)
Recall previous message
ℹ️
Customize shortcuts: /keybindings → opens ~/.claude/keybindings.json. Changes apply instantly.
06Configuration Hierarchy

Claude Code uses a layered system. Higher specificity wins. Understanding this is key to making Claude write code the way you want.

FILE TREE
~/.claude/
    CLAUDE.md              ← Global: personal defaults for ALL projects
    settings.json          ← Global permissions, model preferences
    keybindings.json       ← Your keyboard shortcuts

./ (project root)
    CLAUDE.md              ← Project: team-shared (commit to git!)
    CLAUDE.local.md        ← Project: personal overrides (gitignored)
    .claudeignore          ← Files Claude should never read

./.claude/
    settings.json          ← Project settings (hooks, permissions)
    skills/
        SKILL.md           ← Project-wide skill
        playwright/
            SKILL.md       ← Domain-specific skill

./tests/
    CLAUDE.md              ← Directory-level: rules only for tests/
⚠️
Critical insight: Claude reads ALL applicable CLAUDE.md files on session start. Every token in these files counts against your context every single message. Keep them lean.
07CLAUDE.md — Project Context

This is the single most important file for code quality. It's your pair programmer's briefing. The golden rule: for each line, ask "Would removing this cause Claude to make mistakes?" If not, delete it.

Rules for an Effective CLAUDE.md
📏
Under 5K tokens

~3,500 words max. Every token is re-consumed every message. Bloated CLAUDE.md = wasted money.

🎯
Be specific, not verbose

"Use data-testid for selectors" beats a paragraph explaining why test-ids are preferred.

🔧
Include runnable commands

Build, test, lint commands prevent Claude from guessing and wasting tokens exploring.

🔄
Evolve it continuously

Found a new gotcha? Add it. Found a rule Claude already follows? Remove it.

Example: Playwright + TypeScript Project
CLAUDE.md
# Playwright E2E Test Framework

## Stack
Playwright 1.50+ · TypeScript 5.6+ · Faker.js · dotenv

## Commands
npm test              # run all tests
npm run test:ui       # Playwright UI mode
npm run test:chrome   # chromium only
npm run lint          # ESLint check
npm run typecheck     # TypeScript strict check

## Architecture
src/pages/       — Page Objects (extend BasePage)
src/fixtures/    — Custom Playwright fixtures (DI)
src/api/         — API client classes
src/utils/       — Env config, helpers, test data generator
src/data/        — Static test data, routes, users
tests/           — Test specs by feature

## Critical Rules
- ALWAYS import { test, expect } from `src/fixtures/base.fixture.ts`
  NOT from `@playwright/test`
- Use `data-testid` for selectors, never CSS classes
- Page objects: locators as readonly props, actions as methods
- Env vars via `src/utils/env.config.ts` — never hardcode
- Auth handled by `tests/auth.setup.ts` — tests start authenticated

## Naming
Files: kebab-case · Classes: PascalCase · Test IDs: kebab-case
Tests: start with "should" — "should login with valid credentials"

## Gotchas
- page.waitForTimeout() is an anti-pattern — use expect/waitForURL
- API tests don't use storageState — they get own token in beforeAll
- Never commit page.pause() — debug only
08Skills — Teach Claude Domain Knowledge

Skills are markdown instructions that Claude loads automatically when relevant. Unlike slash commands, Claude decides when to use them based on your request.

File Structure
FILE TREE
.claude/skills/
    SKILL.md                     ← Main project skill (auto-loaded)
    playwright-tests/
        SKILL.md                 ← Activated: "write a test", "fix spec"
    api-testing/
        SKILL.md                 ← Activated: "API test", "endpoint test"
    code-review/
        SKILL.md                 ← Activated: "review this", "check quality"
Skill Example: Playwright Test Writing
.claude/skills/playwright-tests/SKILL.md
---
name: playwright-tests
description: >
  Activated when writing, fixing, or modifying Playwright tests.
  Triggers: test, spec, e2e, playwright, page object, fixture.
---

# Playwright Test Guidelines

## Creating a New Test
1. Does it need auth? Import from the correct fixture:
   - Auth tests → `src/fixtures/auth.fixture.ts`
   - Regular tests → `src/fixtures/base.fixture.ts`
   - API only → `@playwright/test` directly

2. Create page object first if it doesn't exist:
   - Extend `BasePage` from `src/pages/base.page.ts`
   - Locators = readonly properties via `this.byTestId()`
   - Actions = methods, Assertions = `expectX()` methods

3. Register page object in `src/fixtures/base.fixture.ts`

## Locator Priority
1. getByTestId() ← most reliable
2. getByRole()   ← semantic
3. getByText()   ← visible text
4. getByLabel()  ← form fields
5. locator()     ← last resort

## Anti-Patterns
✗ page.waitForTimeout(ms) — use auto-waiting
✗ Hardcoded URLs — use ROUTES from data/routes
✗ Hardcoded creds — use USERS from data/users
✗ page.pause() in committed code
How Invocation Works
Auto-invocation
You: "Write a test for the checkout page"
→ Claude loads playwright-tests skill
→ Follows patterns from the skill
Explicit invocation
You: /playwright-tests login.spec.ts
→ Directly loads and applies skill
→ Useful for forcing specific behavior
09Hooks — Run on Every Event

Unlike prompts (which Claude may skip), hooks always execute. Use them for things that must happen every time — linting, type-checking, truncating output.

HookWhen It FiresExample Use
session-startNew session beginsLoad context, check dependencies
post-editAfter Claude edits a fileAuto-lint, auto-format
pre-commitBefore Claude commitsType-check, run affected tests
Setup for Playwright Project
.claude/settings.json
{
  "hooks": {
    "post-edit": [
      {
        "command": "npx eslint --fix $FILE 2>/dev/null || true",
        "description": "Auto-fix lint after every edit"
      }
    ],
    "pre-commit": [
      {
        "command": "npm run typecheck && npx playwright test --reporter=list 2>&1 | tail -20",
        "description": "Type-check + quick test before commit"
      }
    ]
  }
}
💡
Pro tip: truncate command output — Hook commands like | tail -20 or | head -50 prevent massive test logs from flooding your context window and eating tokens.
10Dynamic Workflows GA · all paid plans

Graduated from research preview to a full feature. A dynamic workflow is a JavaScript script Claude writes that orchestrates subagents at scale — Claude plans the script, a runtime executes it in the background (your session stays responsive), and each agent runs in its own clean context. Designed for codebase-wide audits, large migrations, and research that needs cross-checked sources — cases where a single conversation can't hold the whole plan.

Eligibility
PlanStatusNotes
ProOpt-inTurn on the Dynamic workflows row in /config
Max 5xAvailableCounts toward your plan usage like any session
Max 20xAvailableRecommended tier for large migrations
TeamAvailableAdmin can disable org-wide
EnterpriseAvailableToggle in Claude Code admin settings
APIAvailableVia Agent SDK's Workflow tool / non-interactive mode
FreeNot available
Two Ways to Trigger a Workflow
TERMINAL
# 1. Ask for one directly — include the keyword "ultracode" (or say
#    "use a workflow" in your own words)
> ultracode: migrate 240 spec files from Playwright 1.40 to 1.50 API,
  one subagent per directory under tests/. Each subagent should
  update imports, replace page.waitForTimeout() with explicit waits,
  run the suite for that dir, and report files touched + blockers.

# 2. Let Claude decide for every substantive task this session
/effort ultracode

# Monitor any run: phases, agent count, tokens, elapsed time
/workflows

# Built-in workflow for cross-checked research
/deep-research "What changed in Playwright's clock API between 1.40 and 1.50?"
💡
Why this beats one big session: intermediate results live in script variables, not Claude's context — only the final answer lands there. Agents run in parallel (up to 16 concurrent, 1,000 total per run), so wall-clock time is close to the slowest agent, not the sum. Runs you like can be saved as a reusable /command with s in the /workflows view.
⚠️
Know the limits: no mid-run user input (only permission prompts pause a run — for approval checkpoints, split into separate workflows); no direct filesystem/shell access from the script itself (agents do the work, the script coordinates); a workflow can use meaningfully more tokens than one conversation — test on a small slice (one directory, not the whole repo) before committing to a large run.
11Saving Tokens — 12 Commandments

Claude's context window fills up fast, and performance degrades as it fills. Managing tokens is the difference between hitting your limit in 1 hour vs. working all day.

1. /clear Between Unrelated Tasks
❌ Don't
Fix auth bug → write new page object → update config → all in one session → Context full of irrelevant history
✅ Do
Fix auth bug → /clear → write page object → /clear → update config → Each task gets clean context
2. /compact Proactively at 70%
# Don't wait for auto-compact at 95%. Do it manually at ~70%:
/compact focus on the auth setup refactoring decisions

# You can specify what to keep:
/compact keep only the page object patterns and fixture changes
3. Create a .claudeignore
.claudeignore
# Prevent Claude from reading these — saves thousands of tokens
node_modules/
dist/
build/
playwright-report/
test-results/
blob-report/
coverage/
*.lock
*.min.js
*.min.css
*.map
*.log
4. Use the Right Model for the Task
TaskModelCost
Hardest/longest-running refactors, ambiguous root-cause bugsFable 510×
Design fixture architecture, complex debuggingOpus 4.8
Write page objects & testsSonnet 5
Find a file, quick questionHaiku 4.50.2×
# Switch in-session (aliases resolve to the current recommended model):
/model haiku      # for exploration
/model sonnet     # back to normal work
/model opus       # for the hard part
/model fable      # for the hardest, longest-running part

# Reasoning depth is a separate, complementary lever:
/effort low       # short/scoped tasks, latency-sensitive
/effort high      # default on Fable 5, Sonnet 5, Opus 4.8 — balanced
/effort ultracode # plans a dynamic workflow for every substantive task
5. Be Specific in Prompts
❌ Vague — wastes tokens exploring
"Fix the test failures in the auth tests"
✅ Specific — goes straight to the problem
"Fix the timeout in tests/auth/login.spec.ts line 34. Expected: redirect to /dashboard after login. Actual: waitForURL times out after 30s."
6. Give Direct File Paths
❌ Claude searches entire codebase
"Where is the login page object?"
✅ Zero search tokens
"Update src/pages/login.page.ts to add a forgotPassword locator"
7. Use Subagents for Exploration
# Subagent gets its own clean context — doesn't pollute yours
> Use a subagent to explore the src/api/ directory
  and report: what endpoints exist, error handling patterns,
  and whether we have retry logic.

# Claude spawns a focused agent, explores, reports back
# Your main context stays clean
8. Keep CLAUDE.md Under 5K Tokens

Every token is consumed every single session. A 2,000-token CLAUDE.md costs ~$0.006/session with Sonnet. At 100 sessions/day across 5 devs, that's $9/month just for reading CLAUDE.md. If it's 10K tokens → $45/month on context alone.

9. Truncate Command Output
❌ All output enters context
"Run all Playwright tests" → 200 tests × verbose output = huge token dump
✅ Targeted output
"Run tests in tests/auth/ with --reporter=line and show only failures" → Minimal, relevant output
10. Name Sessions with /rename
/rename playwright-auth-refactor
/rename adding-checkout-page-object

# Later, resume by name — no need to re-explain context:
$ claude --resume
11. Use --continue When Resuming
# Picks up exactly where you left off — zero re-explanation needed
$ claude --continue    # or: claude -c
12. Monitor Token Usage
# In-session breakdown (skills, subagents, MCP servers, session cost):
/usage

# Authoritative billing (API workspaces):
https://platform.claude.com/usage

# Rule: compact at 70%, /clear at task boundaries
ℹ️
The Three Biggest Token Wastes: 1) Redundant file reads (fix with .claudeignore + specific paths) → 2) Long sessions with mixed tasks (fix with /clear) → 3) Bloated CLAUDE.md (fix with ruthless pruning). Fix these three and you cut your bill in half.
12All Config Files for Quality Code

Here is every file you need to create in a new Playwright project to make Claude Code write production-quality code from day one.

Complete File Checklist
FILE TREE
playwright-project/
    CLAUDE.md                    ← Project brain (section above)
    CLAUDE.local.md              ← Your personal overrides (.gitignored)
    .claudeignore                ← Exclusions (section above)
    .claude/
        settings.json            ← Hooks + permissions (hooks section)
        skills/
            playwright-tests/
                SKILL.md         ← Test writing skill (skills section)
    .eslintrc.json               ← Linting rules Claude follows
    tsconfig.json                ← TypeScript strict mode config
    prettier.config.js           ← Formatting rules
    .editorconfig                ← Editor settings
    .env.example                 ← Template for environment vars
    .gitignore                   ← Include .env, auth/, reports/
    playwright.config.ts         ← Multi-project Playwright config
.claude/settings.json — Complete
.claude/settings.json
{
  "model": "sonnet",
  "permissions": {
    "allow": [
      "Read", "Glob", "Grep", "Write", "Edit",
      "Bash(npm run *)",
      "Bash(npx *)",
      "Bash(git *)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)"
    ]
  },
  "hooks": {
    "post-edit": [{
      "command": "npx eslint --fix $FILE 2>/dev/null || true",
      "description": "Auto-lint after every edit"
    }],
    "pre-commit": [{
      "command": "npm run typecheck && npm run lint",
      "description": "Quality gate before commit"
    }]
  }
}
The Quality Workflow
  1. 1
    Create config files

    Copy CLAUDE.md, .claudeignore, skills, settings.json, and .env.example from this guide. Commit everything except .env and CLAUDE.local.md.

  2. 2
    Launch Claude Code

    cd playwright-project && claude — Claude automatically reads CLAUDE.md, loads skills, applies hooks.

  3. 3
    Describe what you need

    "Create a page object for the checkout page with add-to-cart, remove-item, and proceed-to-payment actions. Then write tests for happy path and empty cart."

  4. 4
    Claude follows your patterns

    Because of your CLAUDE.md and skill file, Claude automatically uses BasePage, fixtures, test-ids, correct imports, and your naming conventions.

  5. 5
    Hooks auto-validate

    post-edit runs ESLint auto-fix. pre-commit runs type-check + lint. Quality is enforced without you asking.

13Troubleshooting & Common Problems

Most install and version weirdness comes down to which claude binary your shell actually runs. Start every diagnosis with these four commands — the real path tells you which package manager owns the install, and therefore how to update it.

TERMINAL
# 1. Which binary runs — and are there several on your PATH?
$ which -a claude

# 2. Follow it to the real install (reveals Homebrew cask / npm / native)
$ readlink -f "$(which claude)"

# 3. Your running build vs. the latest published on npm
$ claude --version
$ npm view @anthropic-ai/claude-code version

# 4. One-shot health check: install method, auth, last auto-update attempt
$ claude doctor
SymptomLikely CauseWhere to Fix
Updated, but --version stays oldThe claude on PATH isn't the one you updated — another install shadows it↓ Version won't update
npm install -g does nothingA Homebrew cask at /opt/homebrew/bin/claude shadows the npm binary↓ Version won't update
brew upgrade says “already latest”, npm has newerHomebrew cask trails the npm release by ~1–2 days↓ Version won't update
claude: command not found after nvm useGlobal install lives inside one Node version's bin dir↓ nvm: claude vanished
On Pro/Max but usage burns API creditsANTHROPIC_API_KEY in your env overrides the subscription↓ Auth & billing
Sonnet 5 context bar jumps to 100%Session budgeted at 200K instead of 1M↑ Context Windows (§02)
Updated, but still on the old version

The classic trap: you run an update command, it reports success, but claude --version is unchanged — because the claude on your PATH is a different install than the one you upgraded. On macOS the usual culprit is a Homebrew cask at /opt/homebrew/bin/claude, which sits earlier on PATH than the npm global binary and quietly wins. Read the real path, then update with the manager that owns it.

readlink -f shows…Install MethodCorrect Update Command
…/Caskroom/claude-code/…Homebrew caskbrew upgrade --cask claude-code
…/node_modules/@anthropic-ai/claude-code/…npm globalnpm install -g @anthropic-ai/claude-code@latest
~/.local/… or ~/.claude/… (single binary)Native installerclaude update
❌ npm 'installs' — version never changes
$ npm install -g @anthropic-ai/claude-code added 2 packages $ claude --version → still old # because: which claude → /opt/homebrew/bin/claude # (a Homebrew cask, earlier on PATH)
✅ Consolidate onto one manager
$ brew uninstall --cask claude-code $ npm install -g @anthropic-ai/claude-code@latest $ hash -r # forget the cached old path $ which claude # now ~/.nvm/.../bin/claude ✓
⚠️
Homebrew reports "already the latest" while npm has a newer build. The claude-code cask definition trails the npm release by a day or two, so a fresh version (say 2.1.201) can still be unavailable via Homebrew while brew upgrade keeps calling 2.1.193 current. That's expected — either wait for the cask to catch up, or switch to npm / the native installer to get releases the day they ship.
ℹ️
Still old right after a successful update? Restart fully. A running Claude Code process keeps its version in memory — the status line updates on the next launch, not live. Quit completely, relaunch, then re-check claude --version.
nvm: "claude: command not found" after switching Node

A global npm install lives inside a single Node version's directory. Switch Node with nvm use (or open a shell where a different version is default) and that bin/ leaves your PATH — so claude looks like it vanished.

TERMINAL
# A global install lives inside ONE Node version:
#   ~/.nvm/versions/node/v24.12.0/bin/claude
# After `nvm use 20` that bin dir leaves PATH and claude "disappears".

# Fix A — pin a default Node so the same install stays on PATH
$ nvm alias default 24

# Fix B — (re)install under whichever Node you actually run
$ nvm use 24 && npm install -g @anthropic-ai/claude-code@latest
Auth & billing — subscription vs. API key

If you're on Pro or Max but your usage drains API credits, an ANTHROPIC_API_KEY in your environment is overriding the subscription. A key exported from a shell profile silently wins over /login.

TERMINAL
# Is a key set that you didn't mean to use?
$ echo $ANTHROPIC_API_KEY

# Use your subscription instead — unset, then relaunch
$ unset ANTHROPIC_API_KEY

# Inside a session: confirm active auth + model
> /status

# Switch or refresh the browser login
> /login
💡
First-run auth opens a browser. On a remote / SSH / headless box it won't — Claude Code prints a URL instead: open it on any machine, approve, and paste the code back. If /status still shows API billing after unsetting the variable, check ~/.zshrc / ~/.bashrc for a lingering export ANTHROPIC_API_KEY.
ℹ️
Already covered above: Sonnet 5 context bar jumps to 100% (Context Windows) · update channels, minimum version & disabling the auto-updater (Updating & Staying Current).
14References & Official Docs

Always check official sources for the latest updates. This guide reflects the state as of July 2026: Claude Sonnet 5 is the new default balanced model on Pro / Team Standard (introductory pricing $2/$10 per MTok through Aug 31, 2026); Opus 4.8 remains the default on Max / Team Premium / Enterprise pay-as-you-go / API; Claude Fable 5 is generally available (launched June 9, 2026) as an opt-in model for the hardest, longest-running tasks — select it with /model fable.