Library
Claude Code Mastery · Chapter 1 of 10Preview
Chapter 01

Foundations &
Mental Models

Think like an AI builder, not just a prompt writer.

Beginner FriendlyPracticalClaude CodeAgentic AI
A Handbook For Builders
Foundations &
Mental Models
Chapter 01
The Claude Code Handbook
Prologue

Welcome, future AI builder.

You are about to learn a craft that, ten years ago, only a handful of researchers could practice. Today, with a tool called Claude Code, you can design software that thinks alongside you — reading your files, planning changes, writing code, running commands, and improving its own work. This book will teach you how to think about that superpower so you use it like a professional, not a tourist.

This first chapter is intentionally slow. Before you write a single prompt, you need the right mental models. Prompts are just the surface. What really separates a hobbyist from a professional AI developer is a clear picture of what the model is doing inside — how it sees your project, how it plans, how it acts, and how it recovers from mistakes. Once you can see that clearly, everything else in this handbook becomes easy.

By the end of this chapter, you will have built three tiny AI systems by hand — a Travel Assistant, a Customer Support Agent, and a Study Planner — and you will understand exactly why each one works.

Section 0.1

Learning Objectives

By the end of this chapter you will be able to:

  • Explain what AI, Generative AI, and Agentic AI actually are — in plain English.
  • Describe how Claude Code differs from ChatGPT and why that matters for builders.
  • Walk through the four-step loop every agent follows: Observe → Think → Act → Reflect.
  • Identify the six primitives of agent thinking: context, memory, planning, reasoning, reflection, and iteration.
  • Write clear prompts and diagnose why bad prompts fail.
  • Design a small agent (Travel Assistant, Support Agent, Study Planner) from scratch.
Claude Code — Terminal
Screenshot placeholder
Learning objectives dashboard as displayed at the start of Chapter 1 in the printed edition.
Figure — Learning objectives dashboard as displayed at the start of Chapter 1 in the printed edition.
Section 0.2

A Real-World Analogy

Imagine you hire a very smart, very fast intern on their first day at your company. This intern reads any document you hand them in seconds, writes surprisingly good first drafts, and never gets tired. But they have three quirks. First, they have no memory of yesterday — every morning they walk in as a stranger. Second, they can only see what is on the desk in front of them right now. Third, they will always try to give you an answer, even when they should say "I don't know."

Working with Claude Code is exactly like working with that intern — except this intern can also open files, run terminal commands, and edit your codebase. Your job as a professional AI builder is to design the desk. What do you put in front of the intern? What instructions? What examples? What guardrails? When do you let them act, and when do you make them stop and plan? That is the entire craft.

Part I · Concepts

1. What is AI?

"AI" is one of the most overloaded words of the decade. Let's cut through the noise with a definition that will serve you for the rest of this book:

Notice the phrase "until recently." The frontier of AI is always moving. When spell-checkers first appeared, they were considered AI. Now they are just "features." The AI of 2026 — the kind you will build in this book — is the kind that reads, writes, and reasons in natural language.

The three layers you will actually work with

Almost everything in this book fits inside one of three concentric circles:

diagramclaude-code
   ┌──────────────────────────────────────────┐
   │                 AI                       │  ← everything smart
   │   ┌──────────────────────────────────┐   │
   │   │        Generative AI             │   │  ← creates new content
   │   │   ┌──────────────────────────┐   │   │
   │   │   │       Agentic AI         │   │   │  ← creates AND acts
   │   │   │   (this is Claude Code)  │   │   │
   │   │   └──────────────────────────┘   │   │
   │   └──────────────────────────────────┘   │
   └──────────────────────────────────────────┘
Claude Code — Terminal
Screenshot placeholder
Concentric diagram of AI → Generative AI → Agentic AI as printed on page 6 of the handbook.
Figure — Concentric diagram of AI → Generative AI → Agentic AI as printed on page 6 of the handbook.
Part I · Concepts

2. What is Generative AI?

Generative AI is the subset of AI whose job is to generate new content — text, code, images, audio, video. Under the hood, a generative model is a very large statistical machine that has read a huge portion of the public internet and learned to predict what token (roughly a word or a piece of a word) comes next.

That single mechanism — "predict the next token, then the next, then the next" — is powerful enough to write emails, translate languages, explain code, and, as you will see in a moment, drive an entire autonomous agent.

Part I · Concepts

3. What is Agentic AI?

Agentic AI is Generative AI plus a body. Instead of only producing text, an agent can also take actions in the world — read a file, run a command, call an API, edit code, open a browser. Then it observes the result of the action and decides what to do next. This loop is what makes Claude Code feel different from a chatbot.

diagramclaude-code
   Chatbot:    You  →  Model  →  Text  →  You
   Agent:      You  →  Model  →  Action  →  World  →  Observation
                                                          │
                                                          ▼
                                                       Model  →  Next action ...
Claude Code — Terminal
Screenshot placeholder
Side-by-side illustration of a chatbot loop vs. an agentic loop.
Figure — Side-by-side illustration of a chatbot loop vs. an agentic loop.

A modern agent like Claude Code has three things a chatbot does not:

  • Tools — it can run bash, edit files, search the web, call your APIs.
  • A workspace — it can see your project, not just your last message.
  • A loop — it can act, observe, and correct itself many times before answering you.
Part I · Concepts

4. AI vs Traditional Programming

Traditional programming and AI programming look similar on the surface — you type, a computer does something — but the underlying contract is completely different.

AspectTraditionalAI / Claude Code
InstructionsExact rules (if / else)Natural language + examples
BehaviorDeterministicProbabilistic
Failure modeCrash / bugWrong-but-confident answer
DebuggingStack tracesPrompt & context inspection
SkillSyntax masteryCommunication + system design
Speed of iterationCompile → run → testAsk → observe → refine
Part II · Tools

5. Claude Code vs ChatGPT

People often ask, "Isn't Claude Code just ChatGPT for developers?" Not quite. They live in different rooms of the same building.

DimensionChatGPT (chat UI)Claude Code (agent)
Where it livesBrowser tabYour terminal, inside your project
What it seesOnly the current chatYour files, folders, git history
What it can doReply with textRead/write files, run commands, call tools
Ideal forExplaining, brainstormingBuilding, refactoring, shipping
Failure surfaceWrong textWrong text + wrong actions on disk
Mental modelA tutorA junior engineer with keys to the repo
Claude Code — Terminal
Screenshot placeholder
Claude Code running inside a developer's terminal, with the file tree visible on the left.
Figure — Claude Code running inside a developer's terminal, with the file tree visible on the left.
Claude Code — Terminal
Screenshot placeholder
The same task attempted in ChatGPT — text only, no ability to edit the file.
Figure — The same task attempted in ChatGPT — text only, no ability to edit the file.
Part II · Tools

6. How Claude Code Thinks

When you send a message to Claude Code, an enormous amount of invisible work happens in a fraction of a second. Understanding this pipeline is the single biggest jump from beginner to professional.

pipelineclaude-code
Your message
   │
   ▼
Assemble context  ─────────►  system prompt + project files + rules
   │
   ▼
Plan              ─────────►  break the goal into steps
   │
   ▼
Choose tool       ─────────►  read_file? edit_file? bash? search?
   │
   ▼
Execute           ─────────►  actually run it
   │
   ▼
Observe result    ─────────►  did it work? did it break?
   │
   ▼
Reflect / iterate ─────────►  keep going or answer you
Claude Code — Terminal
Screenshot placeholder
Animated pipeline visualization from the interactive edition, showing each stage lighting up in sequence.
Figure — Animated pipeline visualization from the interactive edition, showing each stage lighting up in sequence.

You almost never see stages 2–6. You see your message go in and an answer come out. But your job is to design an environment where those hidden stages have everything they need to succeed.

Part II · Tools

7. Observe → Think → Act → Reflect

Every serious agent — Claude Code included — runs a version of this four-step loop. Memorize it. Print it. Tape it to your monitor.

Step 1
Observe
Read files, logs, errors, the user's message.
Step 2
Think
Decide what the goal really is and how to break it into steps.
Step 3
Act
Run one tool: edit a file, execute a command, call an API.
Step 4
Reflect
Check the result. Did it work? What should change next?
Claude Code — Terminal
Screenshot placeholder
The four-step agent loop rendered as a circular diagram with arrows returning to Observe.
Figure — The four-step agent loop rendered as a circular diagram with arrows returning to Observe.
Part III · Anatomy

8. Context, Memory, Planning, Reasoning, Reflection, Iteration

Context

Context is everything the model can see right now: your message, the files it has opened, the tools it has available, the rules you gave it. If it is not in the context, it may as well not exist. This is the single most important concept in the book.

Claude Code — Terminal
Screenshot placeholder
A visualization of the context window as a limited-size window sliding over a long document.
Figure — A visualization of the context window as a limited-size window sliding over a long document.

Memory

Memory is context that survives across turns. Claude Code implements memory by re-reading key files (like AGENTS.md or a memory index) at the start of a task. There is no magical brain — memory is just structured re-reading.

Planning

Before touching a single file, a mature agent writes a plan: "First I will read these three files. Then I will change function X. Then I will run tests." Planning trades a few extra seconds for dramatically fewer wrong actions.

Reasoning

Reasoning is the invisible chain of "because → therefore" steps between context and action. You can encourage more reasoning by asking, "Think step by step," or by giving the model examples of the reasoning you expect.

Reflection

Reflection is the moment after an action where the agent asks, "Did that actually work?" Running tests, re-reading a file, checking a diff — all forms of reflection.

Iteration

Iteration is the loop itself. Real problems are almost never solved in a single shot. The best builders design workflows that make iteration cheap and safe.

Part IV · Craft

9. Prompt Engineering Basics

A prompt is a piece of writing addressed to a very literal, very fast, slightly forgetful collaborator. Good prompts share five qualities. We call them the CRISP checklist.

LetterQualityWhat it means
CContextSay who the model is and what project it is inside.
RRoleGive it a clear job: "You are a senior travel planner…"
IIntentState the goal in one sentence.
SStructureSay what the output should look like.
PProofAsk it to show its reasoning or cite what it used.
Claude Code — Terminal
Screenshot placeholder
The CRISP checklist illustrated as a five-column card in the printed workbook.
Figure — The CRISP checklist illustrated as a five-column card in the printed workbook.
Part IV · Craft

10. Good Prompt vs Bad Prompt

Let's see the difference on a concrete task: writing a project README.

Bad prompt

promptclaude-code
write a readme for my app

This is almost useless. There is no context (what app?), no role, no structure, no audience, no length target. The model has to guess everything, and it will guess generically.

Good prompt

promptclaude-code
You are a senior technical writer.

Project: "Sprintly" — a lightweight sprint planner for 2–5 person startup teams.
Stack: Next.js, TypeScript, Supabase.

Write a README.md aimed at a new developer joining the team.

Structure:
1. One-paragraph pitch
2. Feature list (bullets, max 6)
3. Local setup (numbered steps with commands in code blocks)
4. Folder layout (as a tree)
5. Contribution rules (3 short paragraphs)

Tone: friendly but precise. Length: ~500 words.
End the file with: "Happy shipping."

Line by line:

  • You are a senior technical writer. — sets the role.
  • Project: "Sprintly" ... — gives context.
  • Stack: Next.js, ... — more context, so examples match the reality.
  • Write a README.md aimed at a new developer — states intent and audience.
  • The numbered list — provides structure so the output is predictable.
  • Tone / length / ending sentenceconstraints that make the output reviewable.
Part V · Live Examples

11. Live Example — Travel Assistant

You are going to build a tiny Travel Assistant. It will take a destination and a budget, and produce a three-day itinerary. We will do it in three passes so you can feel each primitive at work.

Pass 1 — Plain prompt

promptclaude-code
Plan a 3-day trip to Kyoto for $600.

The result will be generic: "Day 1 – visit temples," etc. Fine for a demo, useless for a real traveler. Time to add role and structure.

Pass 2 — Add role, structure, constraints

promptclaude-code
You are a Kyoto-based local guide with 10 years of experience.

Goal: Plan a 3-day trip for a first-time visitor.

Constraints:
- Total spend under $600 (excluding flights)
- Traveler prefers walking + trains, no taxis
- Include 1 quiet temple, 1 food market, 1 evening spot per day
- Vegetarian-friendly meals

Format the answer as a table with columns:
Day | Morning | Afternoon | Evening | Est. cost
Claude Code — Terminal
Screenshot placeholder
Kyoto travel plan rendered as a table in Claude Code's terminal output.
Figure — Kyoto travel plan rendered as a table in Claude Code's terminal output.

Pass 3 — Turn it into an agent

A prompt is a one-shot request. An agent is a loop. Here is the same idea, described as an agent brief you could give Claude Code:

agent-briefclaude-code
Agent: TravelPlanner

Role:
- Act as a local guide for the requested city.

Inputs:
- destination, days, budget_usd, preferences

Tools available:
- web_search   (find current opening hours & prices)
- write_file   (save the itinerary to itinerary.md)

Process (loop):
1. Observe user inputs and confirm they are complete.
2. Think: outline day-by-day themes.
3. Act: use web_search to check 1–2 uncertain facts.
4. Reflect: does the plan fit the budget? If not, adjust.
5. Write itinerary.md and summarize in chat.
Part V · Live Examples

12. Live Example — Customer Support Agent

Now let's build a support agent for a fictional SaaS called Sprintly. This is a great example because it forces you to think about guardrails — the rules that keep an agent from doing something embarrassing.

agent-briefclaude-code
Agent: SprintlySupport

Role:
- Friendly, calm, first-line support for Sprintly customers.

Knowledge:
- Read /docs/faq.md and /docs/pricing.md at the start of every conversation.

Rules (hard):
- NEVER promise refunds or discounts.
- NEVER invent features that are not in /docs/faq.md.
- If unsure, respond: "Let me hand you to a human teammate."

Style:
- Max 4 short sentences per reply.
- Always end with one clarifying question.

Loop:
1. Observe the user's message and the FAQ.
2. Think: which FAQ entry (if any) matches?
3. Act: reply politely, cite the FAQ section.
4. Reflect: did I follow all hard rules? If not, rewrite before sending.
Claude Code — Terminal
Screenshot placeholder
The Sprintly support agent responding to a customer question, citing the FAQ file it just read.
Figure — The Sprintly support agent responding to a customer question, citing the FAQ file it just read.
Part V · Live Examples

13. Live Example — Study Planner Agent

Finally, let's design an agent that helps a student prepare for an exam. This example introduces memory — the agent must remember progress across days.

agent-briefclaude-code
Agent: StudyPlanner

Role:
- Personal tutor building a daily study plan for one student.

Inputs:
- subject, exam_date, hours_per_day, current_level (1-5)

Memory:
- Read /memory/student.md before each session.
- After each session, append: date, topics covered, confidence (1-5).

Tools:
- read_file, write_file

Loop:
1. Observe: read student.md and today's inputs.
2. Think: which topic is next given past sessions and exam_date?
3. Act: generate today's 3-block plan (theory / practice / review).
4. Reflect: does the plan match the student's confidence trend?
5. Update memory.
Claude Code — Terminal
Screenshot placeholder
The StudyPlanner agent updating /memory/student.md after a session, showing the appended progress line.
Figure — The StudyPlanner agent updating /memory/student.md after a session, showing the appended progress line.
Part VI · Craft

Best Practices

  • Design the desk, not the intern. Change what the model sees, not who it is.
  • Prefer files over long prompts. A prompt is temporary; a file is memory.
  • Make the loop explicit. Write Observe / Think / Act / Reflect into your brief.
  • Reflect with tools, not vibes. Run tests, re-read files, diff outputs.
  • Ship small, ship often. Every iteration teaches you what the model actually does.
Part VI · Craft

Common Mistakes

  • Expecting deterministic output from a probabilistic model.
  • Writing very long prompts instead of very clear ones.
  • Forgetting to give the agent tools — then blaming it for being "just talk."
  • Skipping guardrails on customer-facing agents.
  • Blaming the model when the real bug is missing context.
Part X · Wrap-up

Summary & Key Takeaways