Skip to content

Claude Code

Claude Code is Anthropic’s official command-line interface (CLI) for AI-assisted software development. It is an agent, not an autocomplete: you give it a goal, and it reads files, runs commands, edits code, runs tests, and fixes its own mistakes — looping until the work is done.

This page explains how it works (the agentic loop), how to direct it (goals and verification), how to run it unattended (loops), and how to scale it (orchestration) — then covers the practical reference material: plugins, skills, CLAUDE.md, troubleshooting, and stacks.

Claude Code is a terminal-based AI coding assistant that can:

  • Read and understand your entire codebase
  • Execute shell commands and scripts
  • Create, edit, and delete files
  • Run tests and debug issues
  • Manage git operations (commits, PRs, branches)
  • Research documentation and APIs
  • Work autonomously on multi-step tasks, and spawn other agents to help

Unlike the web-based Claude chat interface, Claude Code operates directly in your development environment with full access to your filesystem and terminal. It runs in the terminal, in the desktop and web apps (claude.ai/code), and inside VS Code and JetBrains.

Everything else on this page is a refinement of one core mechanic. When you give Claude a task, it works through three phases that blend together and repeat:

“When you give Claude a task, it works through three phases: gather context, take action, and verify results. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work.” — Anthropic, How Claude Code works

┌─────────────────────────────────────────────┐
│ │
▼ │
gather context ──▶ take action ──▶ verify results ─┘
(read, grep, (edit, run, (tests, build,
search) commit) screenshot)
│ ▲
└────────── repeat until the task is done ──────┘
(you can interrupt at any point)

Two things power the loop: models that reason and tools that act. Claude Code is the agentic harness around the model — it provides the tools, context management, and execution environment that turn a language model into a capable coding agent. Each tool result feeds the next decision: run the tests, read the errors, search for the cause, edit the file, re-run the tests. The loop is model-driven — Claude decides what each step requires based on what it learned from the previous one, chaining dozens of actions together and course-correcting along the way.

You are part of the loop too. Escape is free — interrupt at any point to redirect; previous context is preserved and the interrupted output is discarded cleanly.

This is the practical version of Anthropic’s distinction in Building Effective Agents: a workflow is a system where steps are orchestrated through predefined code paths; an agent is a system where the model dynamically directs its own process and tool usage. Claude Code is the agent. The orchestration patterns later on this page are how you wrap workflows around it.

The agent is only as good as the goal you hand it. The single highest-leverage habit: separate exploration and planning from execution.

Press Shift+Tab to cycle permission modes until you reach Plan mode. In plan mode Claude explores and proposes a plan without editing your source files — it reads, greps, and answers questions, then writes a plan you approve before any code changes.

“Letting Claude jump straight to coding can produce code that solves the wrong problem. Use plan mode to separate exploration from execution.” — Anthropic, Best practices for Claude Code

The rule of thumb: if you could describe the diff in one sentence, skip the plan. Otherwise, plan first.

Anthropic’s recommended workflow has four beats:

PhaseWhat happens
1. ExploreEnter plan mode. Claude reads files and answers questions without making changes.
2. PlanAsk for a detailed implementation plan. You can open and edit the plan directly before approving it.
3. ImplementSwitch out of plan mode and let Claude code, verifying against the plan as it goes.
4. CommitAsk Claude to commit with a descriptive message and open a PR.

A reliable variant for well-specified changes: have Claude write the tests first, confirm they fail, commit them, then write the implementation and iterate until the tests pass. Tests are a target Claude can iterate against — which is exactly what makes the loop close on its own (see Verification).

For anything large, let Claude interview you about the feature, then have it write a self-contained spec to a file (e.g. SPEC.md) and start a fresh session to execute it. The most useful specs name the files and interfaces involved, state what is out of scope, and end with an end-to-end verification step. A spec on disk survives context compaction; a plan that only lives in the conversation does not.

# Bad: vague
"Fix the bug"
# Good: symptom + location + what "fixed" looks like
"The login form throws 'undefined is not a function' on submit.
Check src/components/LoginForm.tsx. Reproduce it with a failing test,
fix it, and confirm the test passes. Use context7 for React Hook Form docs."

Reference files with @path, point at an existing good example (“HotDogWidget.tsx is the pattern to follow”), and delegate, don’t dictate — give context and direction, then trust the agent to figure out the details. For UI work, paste a screenshot of the target design and ask Claude to compare its result against it and fix the differences.

This is the most important idea on the page. Claude stops when the work looks done. Without a check it can run, “looks done” is the only signal available — and you become the verification loop, noticing every mistake by hand.

“Give Claude a check it can run: tests, a build, a screenshot to compare. It’s the difference between a session you watch and one you walk away from.” — Anthropic, Best practices for Claude Code

A “check” is anything that produces a pass/fail: a test suite, a build exit code, a linter, a script that diffs output against a fixture, or a browser screenshot compared against a design. Give Claude one and the loop closes itself — Claude does the work, runs the check, reads the result, and iterates until it passes.

Four ways to gate the stop, from lightest to most rigorous:

MechanismHow it works
In one promptAsk Claude to run the check and iterate in the same message.
Across a session — /goalSet the check as a /goal condition. A separate evaluator re-checks it after every turn and Claude keeps working until it holds.
Deterministic gate — Stop hookA Stop hook runs your check as a script and blocks the turn from ending until it passes. (Claude Code overrides the hook and ends the turn after 8 consecutive blocks, so a broken check can’t trap you.)
Second opinion — verification subagentA fresh model tries to refute the result, so the agent doing the work isn’t the one grading it. The bundled /code-review skill does this automatically.

This is Anthropic’s evaluator-optimizer pattern: one call generates, another evaluates and feeds back, in a loop — most effective when you have clear criteria and iterative refinement adds measurable value.

“Most best practices are based on one constraint: Claude’s context window fills up fast, and performance degrades as it fills. The context window is the most important resource to manage.” — Anthropic, Best practices for Claude Code

Anthropic calls the discipline of curating that window context engineering: finding the smallest set of high-signal tokens that maximize the odds of the outcome you want. As a window fills, models exhibit context rot — recall and accuracy degrade. Treat context as a finite resource with diminishing returns.

LeverWhen to use it
/clearReset between unrelated tasks. If you’ve corrected Claude more than twice on the same issue, the context is cluttered with failed approaches — /clear and start fresh with a better prompt. A clean session almost always beats a long one full of corrections.
/compact [instructions]Summarize the conversation while preserving code and decisions. Auto-compaction kicks in near the limit; /compact Focus on the API changes steers what survives.
SubagentsResearch and verbose exploration run in a separate context window and report back only a summary — so reading 20 files to answer one question doesn’t bloat your main thread. This isolation is why subagents are the key to long sessions.
CLAUDE.mdDurable, per-session context that reloads every conversation — the place for rules that must survive compaction. Keep it lean: a bloated CLAUDE.md causes Claude to ignore your instructions.

“Loop” means two related things, and the wiki keeps them separate: (1) the built-in agentic loop running unattended until a goal is met, and (2) the community “Ralph” technique of wrapping the CLI in an external shell loop. Plus the headless mode that makes both scriptable.

/loop is a bundled skill that re-runs a prompt or slash command while your session stays open. What you pass decides the mode:

You provideExampleBehavior
Interval + prompt/loop 5m check the deployFixed interval (rounded to 1-minute cron granularity).
Prompt only/loop check whether CI passedSelf-paced — Claude picks each delay (1 min – 1 hr) based on what it saw.
Nothing/loopRuns the built-in maintenance prompt (continue unfinished work → tend the current PR → cleanup passes).

The self-paced mode is the interesting one: short waits while a build is finishing, longer waits when nothing is pending — and it can end itself by simply not scheduling the next wake-up once the task is provably complete. (Fixed-interval loops run until you press Esc or hit the 7-day expiry.) In dynamic mode Claude prefers events over polling — watching a background process and reacting to output rather than re-running a prompt on a timer.

For truly unattended scheduling that runs without your machine open, use Routines (/schedule, cloud, ≥1 hr interval) or GitHub Actions — not /loop.

claude -p "<prompt>" (a.k.a. --print) runs the agent loop to completion non-interactively, prints the result, and exits with a status code your pipeline can branch on. This is the CLI surface of the Agent SDK — the same loop, tools, and context management, scriptable.

Terminal window
# One-shot, pre-approved tools, no prompts
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
# Structured output for pipelines
claude -p "summarize the open PRs as JSON" --output-format json | jq '.result'
# Unix filter: pipe a build log in, get an explanation out
cat build-error.txt | claude -p "explain the root cause" > diagnosis.txt

Flags that matter for unattended runs:

FlagPurpose
--output-formattext (default), json (result + cost + session id), or stream-json (newline-delimited events).
--allowedTools "Bash,Read,Edit"Pre-approve tools so the run never blocks on a prompt.
--permission-modeSession-wide baseline instead of listing tools (acceptEdits, dontAsk for locked-down CI).
--bareSkip auto-discovery of hooks, skills, plugins, MCP, and CLAUDE.md for a reproducible run; load context back explicitly. (Anthropic says this will become the -p default.)
--continue / --resume <id>Multi-turn headless — resume the last session, or a captured session_id.

Geoffrey Huntley’s “Ralph” is the canonical community loop — named after Ralph Wiggum for being “deterministically bad in a non-deterministic world.” In its purest form it is one line:

Terminal window
while :; do cat PROMPT.md | claude ; done

Why it works: each iteration gets a fresh context window. The loop never accumulates a transcript — state lives in files the next iteration re-reads (PROMPT.md for fixed instructions, a fix_plan.md checklist sorted by priority, specs/* as source of truth). The agent’s prior work persists on disk and in git, so the fresh agent sees the modified files, not a bloated history. The discipline that makes it reliable:

  • One item per loop when things wobble; relax as the project stabilizes.
  • Search before assuming code doesn’t exist (use subagents for read/search/plan, not for edits).
  • No placeholders — instruct it bluntly to write full implementations, not stubs that merely compile.
  • Verification gates as backpressure — types, tests, linters. “The faster the validation wheel turns, the more iterations you can run.”

Long, unattended loops fail in predictable ways. The field-measured playbook from our agent-reliability work and the broader community:

Failure modeMitigation
Context exhaustion / rot (degrades near the window limit)Fresh context per iteration; keep state in files, not the transcript. The single biggest lever.
Drift off-specA spec + a ticked checklist; one item per loop; watch and re-plan manually — there’s no automatic drift detector.
Silent placeholder / partial workVerification gate (tests/types) as the only “done” signal; never accept a completion claim without fresh evidence.
Hangs / silent failuresTimeout + retry-on-hang, capped at 2 attempts; redirect stdin from /dev/null for scripted children.
Clobbering under parallelismIsolate each agent in a git worktree, or have parallel agents return text instead of editing the same files.
Manufactured / marginal work (fixed-interval loop, empty backlog)No automatic detector — the agent always finds something. Use self-paced mode so it can self-terminate, set an explicit stop condition, and treat “backlog exhausted” as stop, not “keep finding tasks.” A loop is a watchdog (detect external change), not a builder-on-a-timer.

A useful redundancy rule for critical-path sub-tasks: run K=2 in parallel and take the first that succeeds — at a ~20% per-run hang rate, two independent attempts reach ~95% success for 2× the cost. A generate → review-and-fix pass (length-2 refinement) reliably adds 25–50 points of quality, much of it from recovering a missed tool call. Cap concurrency (corruption appears past ~32 simultaneous agents).

A single agent is a loop. Orchestration is wrapping a workflow around one or more agents — fanning work out, verifying it independently, and synthesizing the result. Start from Anthropic’s guidance and only climb the ladder when a rung is justified:

“We recommend finding the simplest solution possible, and only increasing complexity when needed. This might mean not building agentic systems at all.” — Anthropic, Building Effective Agents

PatternDefinitionUse when
Prompt chainingDecompose into a fixed sequence; each step processes the previous step’s output.The task splits cleanly into ordered subtasks. Add a programmatic “gate” between steps.
RoutingClassify an input and direct it to a specialized follow-up.Distinct input types each deserve a specialized prompt — separation of concerns.
ParallelizationRun subtasks simultaneously and aggregate. Sectioning = independent parts in parallel; voting = same task many times for confidence.Work fans out, or you want multiple attempts for a higher-confidence answer.
Orchestrator-workersA central LLM dynamically breaks down the task, delegates to workers, and synthesizes results.You can’t predict the subtasks in advance — the orchestrator decides them at runtime.
Evaluator-optimizerOne call generates, another evaluates and feeds back, in a loop.Clear evaluation criteria + iterative refinement adds measurable value.

The line between parallelization and orchestrator-workers is whether the subtasks are known up front (fan out a fixed set) or decided at runtime (the orchestrator invents them).

Subagents are how Claude Code does orchestration natively. Each subagent runs in its own fresh, isolated context window with a custom system prompt, specific tool access, and independent permissions — and returns only a summary to the main thread.

“Use one when a side task would flood your main conversation with search results, logs, or file contents you won’t reference again: the subagent does that work in its own context and returns only the summary.” — Anthropic, Subagents docs

Define them as Markdown files with YAML frontmatter:

---
name: code-reviewer
description: Reviews diffs for correctness and security. Use proactively before merge.
tools: Read, Glob, Grep # inherits all tools if omitted
model: sonnet # sonnet | opus | haiku | fable | inherit
---
You are a code reviewer. When invoked, analyze the diff and report only
gaps that affect correctness or the stated requirements...
ScopeLocation
This project (check into git).claude/agents/*.md
All your projects~/.claude/agents/*.md
One session--agents CLI flag
A pluginthe plugin’s agents/ dir

Key mechanics: parallel research (“research the auth, database, and API modules in parallel using separate subagents”); nested subagents up to depth 5 (only the top-level summary returns); isolation: worktree to give an agent its own copy of the repo so parallel edits don’t collide; routing cheap work to Haiku to control cost. Forked agents share the parent’s prompt cache — which is why 5 parallel agents forked from one context cost about the same as 1.

Multi-agent isn’t free. From Anthropic’s multi-agent research system:

“Agents typically use about 4× more tokens than chat interactions, and multi-agent systems use about 15× more tokens than chats.”

Token usage alone explained ~80% of performance variance in their evals — multi-agent works because it spends enough tokens to solve the problem. So it pays off for breadth-first tasks (many independent directions, information exceeding one context window, lots of complex tools) where the task value justifies the cost — and it hurts for tasks where all agents need shared context or have tight dependencies (coding has fewer truly parallel sub-tasks than research). Match the effort to the question: a fact-find needs one subagent; a complex investigation might warrant ten with clearly divided responsibilities.

The community maintains skills that implement these patterns as one-command spawners. They map directly onto Anthropic’s taxonomy:

SkillPatternWhat it does
/team-featureOrchestrator-workersSpawns backend + frontend + e2e-tester + reviewer for a feature spanning layers.
/team-reviewParallelization + evaluatorSecurity, architecture, and quality reviewers produce severity-rated findings before merge.
/team-investigateParallelization (voting)Investigators pursue competing hypotheses for an unclear bug.
/team-researchEvaluator-optimizerResearchers challenge each other’s findings before you build.
/team-refactor, /team-migrateOrchestrator + validatorRisky multi-file changes with a safety-focused validator and rollback plan.
/team-swarmParallelization at scaleFans work to N OS-isolated agents (Proxmox LXCs) or auto-routes security work to Vibe.
/deep-researchOrchestrator-workers + evaluatorFan-out web search → fetch → adversarially verify claims → synthesize a cited report.
/vibe-orchestratorRoutingRoutes grunt work (file generation, bulk edits) to self-hosted Mistral Vibe; Claude plans and reviews.
/irregular-reviewPipeline + evaluatorNative MR review against self-hosted GitLab + bounty checks + multi-reviewer panel.
/cloud-escalatorRouting (escalation)Self-hosted Claude pulls in a one-shot cloud Claude for the hard sub-tasks.

For the design principles behind these — when to fan out, how to verify, how to avoid clobbering — see Agentic Patterns.

Many developers consider running a local LLM (e.g. Llama or Devstral via Ollama) with an MCP stack to avoid cost and rate limits.

FeatureClaude CodeSelf-Hosted / Local Agent
SetupImmediate (install & login)High (build the harness yourself)
IntelligenceState of the art (Opus 4.8 / Sonnet 4.6 / Haiku 4.5). High coherence on long multi-step tasks; up to 1M-token context.Varies. Local models often struggle with long-context agentic loops.
Reliability”Just works.” Orchestration, context management, and verification are handled for you.”The agentic problem.” Self-hosted agents get stuck in loops or lose context without heavy tuning.
CostPaid subscription / APIFree (excluding hardware)

Verdict: If you’re building the self-hosted harness, keep building — and see our Claude Code Self-Hosted guide. But to get work done today with an agent that reliably navigates your repo, Claude Code is the most polished option. For a polished open-source alternative supporting self-hosted models, see Mistral Vibe; for a sandbox-isolated web agent, OpenHands; for an LSP-aware TUI, OpenCode. Side-by-side specs live in the CLI agent comparison.

The difference is autocompletion vs. delegation. Copilot suggests the next few lines while you type — it’s an assistant, great for typing speed. Claude Code takes a goal (“read the auth module, add a password-reset flow, create the files, and write tests”) and goes away and does it — it’s an agent, reading the whole repo, running terminal commands, and fixing its own mistakes when tests fail. Use both: Copilot for in-flow assistance, Claude Code for feature implementation and heavy lifting.

Claude Code evolves weekly. Review changelogs regularly (monthly at the slowest) — new built-in capabilities land often. One recent example: /chrome interaction, which gives the agent “eyes” and deep debugging access to a real browser via the Chrome DevTools MCP.

  1. Research first — use context7 (below) to fetch current docs before implementing against an unfamiliar library.
  2. Check plugins — a plugin may already solve your problem.
  3. Start simple — built-in tools before plugins; the simplest workflow before multi-agent.
  4. Match task to modelhaiku for quick/cheap tasks, the strongest model for hard reasoning.

The /llms.txt standard is a “sitemap for LLMs” — it helps models quickly understand your site or docs. Context7 leverages this at scale, acting as a giant searchable database of up-to-date documentation. Add an llms.txt to your own projects to make them legible to agentic tools.

Claude Code with plugins is considered state of the art for agentic coding. Plugins add commands, specialized subagents, MCP servers, and hooks.

Marketplace / PluginRepoDescription
superpowersobra/superpowersAgentic skills framework & methodology — TDD and systematic workflows.
oh-my-claudecodeYeachan-Heo/oh-my-claudecodeMulti-agent orchestration with 5 modes: Autopilot, Ultrapilot (parallel), Swarm, Pipeline, Ecomode.
awesome-claude-code-subagentsVoltAgent100+ specialized subagents for specific tasks.
awesome-claude-code-pluginsccpluginsCurated slash commands, subagents, MCP servers, and hooks.
ralph-loopOfficial marketplaceThe Ralph technique as a Stop-hook plugin (see Loops).
claude-plugins-officialPre-installedOfficial Anthropic plugins.

Essentials to install:

  1. Context7 — fetches up-to-date documentation; the single most useful add-on.
  2. Explanatory Output Style — surfaces “why” nuggets during execution.
  3. Ralph Loop — looping strategies for completing whole apps unattended.
  4. Serena — configure it to not open a browser popup on every load.

Install by asking (“install the superpowers plugin”) or via the /plugin slash command. Watch context cost: plugins, MCP servers, and CLAUDE.md all consume tokens — audit them (see Context Management).

Skills are reusable instruction packets that load on trigger — enforcing a process, formatting output, or spawning a team. They install as Markdown at ~/.claude/skills/<name>/SKILL.md. The orchestration skills above spawn agent teams; the ones below enforce discipline and provide reference.

These are “rigid” — follow them exactly.

SkillUse before
/brainstormingAny creative work — explore intent before implementation.
/test-driven-developmentWriting implementation code.
/systematic-debuggingProposing any bug fix.
/verification-before-completionClaiming work is done — evidence before assertions.
/writing-plansA multi-step task — plan before touching code.

The /executive-summary skill applies Joseph McCormack’s BRIEF Lab framework — “Brevity is confidence. Length is fear.”

ElementPurpose
BBackgroundContext from the audience’s last known state
RRelevanceWhy it matters now
IInformationOnly the essential facts
EEndingClear conclusion or next step
FFollow-upAnticipate questions
SkillCovers
/claudeflareAll Cloudflare services — Workers, D1, R2, KV, Durable Objects, Pages, Turnstile, Queues, Wrangler CLI
/cloudflare-analyticsD1 query insights, wrangler tail, deployment tracking, observability
/ui-ux-pro-max50 design styles, palettes, font pairings, framework stacks

CLAUDE.md — Your Project’s AI Rules File

Section titled “CLAUDE.md — Your Project’s AI Rules File”

CLAUDE.md is the most important configuration in Claude Code: it reloads at the start of every conversation, giving Claude persistent context it can’t infer from code alone. Precedence (highest last):

  • ~/.claude/CLAUDE.md — global rules (all projects)
  • ~/.claude/rules/*.md — domain rules (Docker, Cloudflare, etc.)
  • /path/to/project/CLAUDE.md — project-specific (highest priority)
# Project Name
## Critical Rules (MUST READ)
- Deployment: `./deploy.sh` (never manual rsync)
- Database: lowercase tables, snake_case fields
- NEVER: [specific anti-patterns for your project]
## Stack
- Runtime: Cloudflare Workers · DB: D1 · Frontend: React + Vite
## Common Commands
npm run dev # local development
./deploy.sh # production deploy
## Lessons Learned
### [Date] — [Issue Title]
**Problem / Root Cause / Fix**
  1. rsync --delete — always --dry-run first.
  2. Fail fast — startup scripts must exit on missing env vars.
  3. Deploy → verify — always curl/check after deploying.
  4. Never guess schemas — inspect the DB before writing queries.
  5. Dry-run everything — deploy scripts, sync scripts, rsync.

Full rules + lessons: Project Rules & Lessons Learned and the Vibe Coding repo.

The “state of the art” debugging prompt — combine research, current docs, and the right agents:

“To fix this, research online and/or check the context7 plugin, then look at the available subagents and pick the set best suited to debug it.”

A systematic flow beats jumping to a fix:

  1. Describe the symptom with exact error messages.
  2. Reproduce it with a failing test — now you have a target the loop can close on.
  3. Research“use context7 to check [library] docs for this error.”
  4. Delegate“use the debugger subagent to analyze this stack trace.”
  5. Verify — show the test passing, don’t just assert it’s fixed.

The “vibecoded” stack for modern, edge-native development.

LayerTechnologyNotes
RuntimeCloudflare WorkersEdge compute.
FrameworkReact Router 7Go-to for edge compatibility.
DatabaseCloudflare D1Serverless SQLite at the edge.
StorageCloudflare R2S3-compatible, zero egress fees.
AIWorkers AIEdge inference.
WorkflowsCloudflare WorkflowsDurable execution for multi-step tasks.
TestingPlaywrightE2E.
ComponentsStorybookComponent isolation.
Package MgrpnpmFast, disk-efficient.
MonorepoTurborepoBuild system.
AutomationStagehandBrowser automation for agents.

Why this stack? Deep integration across Workers, D1, R2, and AI yields extremely low-latency apps; React Router 7 has superior edge compatibility vs. Next.js; Stagehand and Workflows are built for the agentic future.

Cloudflare ServiceAlternativeWhen to consider
WorkersVercel Edge, Deno Deploy, Fastly ComputeDifferent edge locations, existing vendor
D1Turso, PlanetScale, NeonMySQL compat, complex queries
R2AWS S3, Backblaze B2, MinIOAWS ecosystem, self-hosted
Workers AIReplicate, Together AI, OllamaDifferent models, self-hosting
ContainersFly.io, Railway, RenderMore container features, persistent storage
LayerTechnology
BackendNode.js / Python / Go
FrontendReact / Vue / Svelte
DatabasePostgreSQL / SQLite
ORMPrisma / Drizzle
TestingVitest + Playwright

Playwright tips: use semantic selectors (getByRole, getByLabel) over CSS; isolate tests with fresh browser contexts; mock APIs with MSW for deterministic tests.

For pricing models, API credits, military procurement advice, and billing, see the dedicated guide:

👉 Claude Code Funding & Subscriptions 👈

To benchmark Claude Code against Codex CLI, Gemini Code Assist, Cursor, Windsurf, or Copilot, see the CLI + IDE agent pricing snapshot.

Authoritative Anthropic sources behind this page: