NEW: Claude Code Security — research preview →

Architecture

Internal mechanics - the agentic loop, context window, permissions, and compaction

Read time: 20 min

title: "Architecture" description: "Internal mechanics - the agentic loop, context window, permissions, and compaction" section: "Core" readTime: "20 min"

Architecture: Internal Mechanics

How Claude Code works under the hood.

Runtime Components

Claude Code is the agentic harness around the model: it provides the tools and manages the context the model sees. The loop is powered by two components.

1. Models

Claude models do the reasoning: read code, decide which tool to use next, and adjust based on results. Switch with /model or claude --model <name>.

2. Tools

Built-in tools fall into five categories:

CategoryWhat Claude can do
File operationsRead, edit, create, rename and reorganize files
SearchFind files by pattern, search content with regex, explore codebases
ExecutionRun shell commands, start servers, run tests, use git
WebSearch the web, fetch documentation, look up error messages
Code intelligenceType errors after edits, go to definition, find references (requires code intelligence plugins)

Claude also has orchestration tools for spawning subagents and asking you questions.

3. Supporting systems

Around the loop, the harness manages:

  • Context — CLAUDE.md, auto memory, skills, MCP tool names, and conversation history (see below)
  • Permissions — permission modes plus allow/ask/deny rules evaluated before each tool call
  • Sessions — every message, tool use, and result is written to a JSONL file under ~/.claude/projects/, which enables resume, fork, and rewind
  • Checkpoints — file snapshots taken before edits (Esc twice or /rewind to restore)

The Agentic Loop

Every task cycles through three phases that blend together:

Your prompt
   ↓
1. Gather context   (search, read files, check git state)
   ↓
2. Take action      (edit files, run commands)
   ↓
3. Verify results   (run tests, read output)
   ↓
Repeat until done — you can interrupt (Esc) or queue a correction at any point

A question may only need step 1; a bug fix cycles through all three repeatedly.

Where hooks fire in the loop

Point in the loopHook event
Session begins (also after resume / compaction)SessionStart
CLAUDE.md or rules files loadInstructionsLoaded
You submit a promptUserPromptSubmit
Before a tool runs (can block)PreToolUse
After a tool succeedsPostToolUse
Before compactionPreCompact
Claude finishes respondingStop

See Hooks for the full event list.

Context System

The context window holds:

  • System prompt and environment info (working dir, platform, git status)
  • Your CLAUDE.md files and unscoped .claude/rules/
  • Auto memory (first 200 lines / 25KB of MEMORY.md)
  • MCP tool names (full schemas are deferred and loaded on demand via tool search)
  • Skill descriptions (full skill bodies load only when used)
  • Conversation history: your messages, file contents, command outputs

Run /context inside a session to see what's using space.

Claude Code also adds its own context as system reminders — for example a note when a file changes on disk, and commit/PR attribution lines (configurable via the attribution and includeGitInstructions settings).

AGENTS.md — Cross-Tool Instruction File

AGENTS.md is an instruction-file convention used by many coding agents. Claude Code (v2.1.277+) can read it as your project instructions:

Your repository hasClaude reads
AGENTS.md, and no CLAUDE.md / CLAUDE.local.md in the working directory or aboveAGENTS.md
AGENTS.md and a CLAUDE.md or CLAUDE.local.mdCLAUDE.md files only
A CLAUDE.md that imports @AGENTS.mdCLAUDE.md, with AGENTS.md included through the import

Both AGENTS.md and .claude/AGENTS.md are read. AGENTS.local.md, AGENTS.override.md, and .agents/ are not read. Change the default with /config → Project instructions (claude-md-or-agents-md, claude-md-and-agents-md, claude-md, managed-only).

To keep one shared file and add Claude-specific instructions, import it:

# CLAUDE.md
@AGENTS.md
 
## Claude Code
Use plan mode for changes under `src/billing/`.

AGENTS.md is plain markdown — there is no required schema:

# AGENTS.md
 
## Shared Rules
- Always write tests
- Use TypeScript strict mode
- API keys never in code
 
## Commands
- Build: `pnpm build`
- Test: `pnpm test`

SOUL.md — Team Convention (Not Built In)

Some teams keep a SOUL.md describing values and communication style. Claude Code does not load SOUL.md on its own — pull it in with an @SOUL.md import from your CLAUDE.md if you want it in context.

# SOUL.md
 
## Identity
We are a team of senior engineers who value:
- Code clarity over cleverness
- User safety over speed
- Documentation over assumptions
 
## Communication
- Question assumptions
- Explain reasoning
- Always mention tradeoffs

Rules Layer: .claude/rules/

Modular markdown instruction files, one topic per file. All .md files are discovered recursively.

  • Project rules: .claude/rules/ (loaded with the same priority as .claude/CLAUDE.md)
  • User rules: ~/.claude/rules/ (apply to every project; loaded before project rules)
~/.claude/rules/
├── common/
│   ├── api-safety.md
│   └── git-hygiene.md
├── typescript/
│   └── strict-mode.md
└── python/
    └── type-hints.md

Rules are instructions, not hooks. A rule without frontmatter loads every session. Add paths frontmatter (the only field Claude Code reads) to load it only when Claude reads or edits a matching file:

---
paths:
  - "src/**/*.{ts,tsx}"
---
 
# TypeScript Rules
- Strict mode, no `any`

Rules are context, not enforcement. To hard-block something like rm -rf, use a PreToolUse hook or a permission deny rule.

MCP and context: MCP tool definitions are deferred by default — only tool names and server instructions enter context until Claude loads a specific tool via tool search. Set ENABLE_TOOL_SEARCH=false to load everything upfront. CLI tools like gh or aws are still more context-efficient than MCP servers; disable unused servers with /mcp.

Permission Modes Internals

Press Shift+Tab to cycle modes, or start with claude --permission-mode <mode>.

ModeWhat runs without asking
default (shown as Manual)Reads only
acceptEditsReads, file edits, common filesystem commands (mkdir, mv, cp…)
planExplores and proposes a plan; no source edits
autoClassifier reviews actions instead of you
dontAskOnly pre-approved tools; anything that would prompt is denied
bypassPermissionsEverything — isolated containers/VMs only

Deny rules block in every mode, including bypassPermissions.

Auto Mode Decision Order

For each action (first match wins):
  1. Matches an allow / ask / deny rule → resolve immediately
  2. Read-only action or file edit in working dir → auto-approve
     (except protected paths and first read outside working dirs)
  3. Everything else → classifier model reviews it
     - Allowed → runs
     - Blocked → notification, listed in /permissions "Recently denied"
  3 blocks in a row or 20 total → auto mode pauses, prompting resumes

Auto mode is available on all plans (admins on Team/Enterprise can turn it off with disableAutoMode) and requires a supported model (e.g. Opus 4.6+, Sonnet 4.6+ on the Anthropic API). With v2.1.283+, it is the built-in starting mode for interactive terminal and VS Code sessions. Start it explicitly with claude --permission-mode auto.

Compaction Algorithm

By default, Claude Code compacts when the conversation reaches the model's context limit (models with a native 1M window compact at about 967K tokens; Sonnet 4.6 / Opus 4.6 without extended context at 200K). When it runs:

1. Clear older tool outputs first
2. Summarize the conversation if still needed
3. Reload startup context: system prompt, CLAUDE.md, auto memory, MCP tools
4. Re-read up to 5 most recently modified files Claude touched
   (files > 5,000 tokens come back as a path reference only)
5. Re-inject the bodies of skills you invoked (truncated if large)

Path-scoped rules and nested CLAUDE.md files are summarized away and reload only when a matching file is touched again. If a single huge output makes context refill immediately, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping.

Controls:

  • /compact focus on the API changes — compact now with a focus
  • A "Compact Instructions" section in CLAUDE.md — what to preserve
  • /autocompact 500k, the autoCompactWindow setting, or CLAUDE_CODE_AUTO_COMPACT_WINDOW — set the window (100K–1M tokens)
  • CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50 — trigger earlier (can only lower the threshold)

CLAUDE_CODE_SUBAGENT_MODEL

Set the default model for subagent delegation:

{
  "env": {
    "CLAUDE_CODE_SUBAGENT_MODEL": "haiku"
  }
}

Resolution order: per-invocation model → the subagent's model frontmatter → CLAUDE_CODE_SUBAGENT_MODEL → the main conversation's model. With nothing set, subagents use the main conversation's model. Because it is only a default, add CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1 (v2.1.257+) to apply one model to every subagent, teammate, and workflow agent.

Token Budget Best Practices

/effort low|medium|high          # Lower effort for simple tasks
MAX_THINKING_TOKENS: 8000        # Only on fixed-budget models; adaptive models ignore it
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE: 50  # Compact earlier
CLAUDE_CODE_SUBAGENT_MODEL: haiku    # Cheaper delegation

Other high-impact habits: /clear between unrelated tasks, Sonnet for most work and Opus for hard reasoning, move workflow-specific CLAUDE.md content into skills, and delegate verbose operations (test runs, logs) to subagents.

For reference, Anthropic reports an average of around $13 per developer per active day ($150–250/month) across enterprise deployments, with 90% of users below $30 per active day. Check yours with /usage.


Next Steps