Module 2 — The agentic loop, built-in tools and the context window
Module 1 put Claude Code in your hands; this module opens the hood. Understanding the agentic loop and what each built-in tool does is understanding why one session can cost a tenth of another for the same work. Then come the commands that steer the context — /context, /compact, /clear, /btw, /usage — followed, on Kiosque, by a map of the codebase and a targeted compaction.
The loop: context, action, verification
When you submit a task, Claude does not write code immediately. It runs a three-phase loop that intermixes: gather context by reading files and searching, act by calling tools that edit or execute, verify by running tests, a lint, a command. Every tool call returns a result the model observes, which informs the next decision. This is not a pipeline: Claude can read, edit, re-read, correct, re-run the tests, in a dozen iterations inside the same turn.
Two components drive the loop: the model that reasons (picked via /model, with effort set via /effort) and the tools that act. The rest — Claude Code — is an agentic harness: it exposes tools, manages context, executes and reports results. You stay in the loop: Esc interrupts the current call; typing a correction without stopping steers the trajectory on the next turn without losing work in progress.
Catalog of built-in tools
Built-in tools split into five functional families. The names below are the exact identifiers used in permission rules (Tool(...)), subagent tools: lists, and hook matchers.
- Files:
Readreads,Editperforms a targeted replacement,Writecreates or overwrites,NotebookEditedits a Jupyter cell.Readdoes not require authorization inside the working directory;EditandWritedo in Manual mode. AnEdit(...)rule implicitly grants the matchingRead. - Search:
Grep(pattern in file contents),Glob(name pattern),LSP(definitions, references, type diagnostics — via a code-intelligence plugin). - Execution:
Bash(Unix shell),PowerShell(Windows, when enabled),Monitor(background process that streams every output line back to Claude). - Web:
WebFetch(URL),WebSearch(search). - Orchestration:
Agent(subagent with its own window),Skill(loads a skill),AskUserQuestion(multiple-choice question to the user),SendMessageandListAgents(cross-session messaging).
On top of these sit utility tools: EnterPlanMode / ExitPlanMode (plan mode, module 8), EnterWorktree / ExitWorktree (git worktrees), TaskCreate / TaskList / TaskUpdate (task list), CronCreate / CronList / CronDelete (scheduled prompts via /loop), RemoteTrigger (cloud routines via /schedule), ToolSearch (on-demand loading of deferred MCP tools), Workflow (dynamic workflow), PushNotification (desktop or mobile notification). TodoWrite is disabled by default in favor of the Task* family.
Tools that require permission by default are those that write or execute: Bash, Edit, Write, NotebookEdit, PowerShell, Monitor, WebFetch, WebSearch, EnterWorktree, Skill, Workflow, Artifact. Bash is an exception for a predefined set of read-only commands (ls, pwd, git status) that never prompt; Bash(git log *) adds anything you want to the allowlist.
A permission rule always follows the format Tool(specifier). For Bash, the specifier is a command pattern (Bash(npm run *)); for Read/Edit/Write, a path (Edit(app/**)); for WebFetch, a domain (WebFetch(domain:docs.example.com)); for Skill, a name (Skill(deploy *)). Module 7 walks through every combination.
The context window: what fills it
The context window is everything Claude sees on each turn. It contains, in order:
- The system prompt: base instructions, tool definitions,
output-styles,--append-system-prompttext. - The project context:
CLAUDE.mdfiles merged from the top of the tree down to your folder, rules withoutpaths:, automatic memory (the first 200 lines or 25 KB ofMEMORY.md), skill descriptions. - The MCP tool definitions — only the names and server instructions: full schemas are deferred by tool search (module 11).
- The conversation: your messages, Claude's replies, tool results.
The first three layers rarely change from one turn to the next: that is where prompt caching kicks in. The fourth layer grows and gets re-compacted on demand.
/context shows a colored grid of usage, with optimization suggestions, loaded memory files, MCP server cost, and any overflow. Pass all to expand each item. Read /context before a compact: it is the only reliable way to know who is eating the tokens.
/compact, /clear, /btw: free up without starting over
Three commands manage space:
/compact [instructions]summarizes the conversation so far and replaces the history. Without an argument, Claude decides what to keep; with a directive —/compact focus on the payment bug, drop everything else— it targets. The command runs a separate request with the same system prompt, all your tools, the history, and a summarization instruction./clear [name]opens an empty conversation. Project memory andCLAUDE.mdstay loaded. An optional name labels the previous conversation in/resume. Aliases:/reset,/new./btw [question]asks a side question whose answer does not enter the history. Ideal for "by the way, what is an optimistic lock?" without polluting the conversation. Without an argument,/btwredisplays your last side question (v2.1.212+; previously a question was required).
Other commands in the same neighborhood: /autocompact <auto|tokens> sets when auto-compaction triggers (/autocompact 500k, /autocompact auto) — v2.1.221+; /rewind (aliases /checkpoint, /undo) rewinds or summarizes from a specific message, covered in module 8; /recap produces a one-line summary without touching the context.
What survives /compact
When /compact runs, Claude Code summarizes the conversation but re-reads certain things from disk:
- The system prompt and output style stay intact (outside the history).
- The repo
CLAUDE.md, rules withoutpaths:, automatic memory and the plan-mode plan are re-injected from disk. - Rules with a
paths:frontmatter and nestedCLAUDE.mdfiles reload when Claude re-reads a matching file. - Up to five recently modified files are re-read; a file over 5,000 tokens returns as a bare path reference.
- Bodies of invoked skills come back, capped at 5,000 tokens per skill and 25,000 tokens total.
SessionStarthooks that match thecompactsource re-fire, and their output is added.
Corollary: an instruction given only inside the conversation disappears. If you want it to persist, it belongs in CLAUDE.md — module 3.
The prompt cache: why some actions cost more
The API reuses the initial part — the prefix — of each request if it matches the previous one. Claude Code deliberately places the system prompt first, then the project context, then the conversation. Appending at the end of the conversation breaks nothing; changing the system prompt invalidates everything after it. That is why some commands trigger one slow, expensive turn, then subsequent turns recover their rhythm.
Actions that invalidate the cache:
- Changing model (
/model) — each model has its own cache; a confirmation is asked while the cache is warm. - Changing effort level on most models (Fable 5.1 with an API key or subscription is an exception).
- Enabling fast mode (
/fast on): a header change flips the cache key. - Connecting or disconnecting an MCP server whose tools sit in the prefix (rare since tool search).
- Denying a whole tool via a deny rule on the bare name (
Bash,WebFetch): the definition leaves the system prompt. - Changing output style with
/config outputStyle=.... - Compacting the conversation with
/compact. - Accumulating so many images that the CLI drops the oldest.
- Updating Claude Code: the first request after a restart rebuilds the cache.
Actions that preserve the cache: editing repo files, editing CLAUDE.md mid-session (only re-read at startup or after /clear / /compact), changing permission mode, invoking a skill or a command, running /recap or /rewind.
Fix the model and effort level before your first question. Every mid-session switch costs you a full prefix rebuild. The simple rule: sonnet + high at startup, switch only for a complex plan.
Delegate to a subagent to save context
When a search will read twenty files, bloating the main window to keep only a summary is a bad trade. A subagent (module 10) runs in its own context window: it reads, searches, correlates, and returns only the summary. Two commands trigger this offloading: /subtask <task> launches a forked subagent that inherits the conversation and whose result flows back into the current thread; /fork [prompt] copies the conversation into a new background session and keeps you here (follow it via claude agents or /tasks).
Reading cost: /usage
/usage (aliases /cost, /stats) reports for the session: input tokens, output tokens, cache read and cache write per model, estimated cost, API call time. A Prompt cache (main) line shows the percentage of input tokens served from the cache, the number of misses, the likely cause of the last one (for example likely cause: tool definitions changed), and whether the cache is warm or cold (v2.1.251+, labels v2.1.260+).
On a subscription, /usage adds a recent breakdown by skill, subagent, plugin, MCP server (24 h or 7 days, toggle d/w), with flags whenever a category exceeds 10%. /usage-credits opens the credits screen or sends a request to your admin.
Running example: mapping and compacting Kiosque
In the Kiosque repo, we start a session in sonnet with high effort and ask:
Walk me through the flow of an order end to end: from the HTTP
request `POST /commandes` to payment confirmation. Cite the files
in app/ involved and the SQLAlchemy tables touched.
Claude calls Read on app/commandes.py, Grep on the models, opens app/paiements.py, Read on models.py, Grep on the migrations. Every call is visible in the transcript (Ctrl+O). /context reveals that the conversation has reached 60,000 tokens, half of which are from files read.
Before tackling the paiements.py rewrite, we compact with a directive:
/compact keep only the order-flow summary and the data models;
drop everything else, in particular the code snippets read.
The summary comes back at 8,000 useful tokens. The cache rebuilds on the next turn, then /usage confirms that the Prompt cache (main) line is cached at 90%.
Common mistake: /clear instead of /compact
/clear throws away the entire conversation, including what Claude just understood about the repo: we replay identical reads on the next turn. Reserve /clear for unrelated task switches; between two steps of the same task, /compact with a directive keeps what matters.
Summary
- The agentic loop chains gather, act and verify; every tool observes a result that informs the next step.
- Built-in tools fall into five families; the exact identifiers (
Read,Bash,Edit…) are the ones used in permission rules and hook matchers. - The context window stacks system prompt, project context, tool definitions, conversation;
/contextvisualizes it. /compactwith a directive beats/clearin the middle of a task: you keep what matters.- Prompt caching pays the prefix once; changing model, effort or output style forces a full rebuild.
/usagereads real cost; the Prompt cache line tells you whether your session is recycling its prefix well.- A subagent keeps large reads out of your main window;
/subtaskand/forkare the entry points.
Next module: CLAUDE.md, rules and memory: teach the project to Claude — so half of that context reloads automatically at every session without you typing anything.