Building Agentic Flows with Claude Code

Part 1 — Foundations

Chapters 1-4 · Mental models, setup, and the building blocks of every agentic system.

Chapter 1

Beyond the Chat Window

1.1 The Three Levels of Working with AI

Most people are stuck at Level 1 or 2. This guide takes you to Level 3.

Three levels: Chat, Configured Assistant, Agentic System Level 1 — The Chat You → AI → Response ✗ No memory ✗ No structure ✗ Resets every session Level 2 — Configured System Prompt One agent, all tasks ✓ Consistent persona ✗ Context limits ✗ Uneven quality Level 3 — Agentic Orchestrator A B C ✓ Specialists ✓ Parallel execution ✓ Reusable & scalable
Figure 1.1 — The three levels of working with AI. Each level is more powerful than the one before — and each has a ceiling.

Level 1 — The Chat

What it isOne prompt → one response. Session ends, memory resets.
Good forDrafting emails, quick Q&A, brainstorming, summarizing.
CeilingAnything requiring continuity, multiple steps, or reuse.

Level 2 — The Configured Assistant

What it isA system prompt gives the AI a persona, rules, and context. Consistent behavior across sessions.
Good forDedicated support bots, review assistants, domain-specific helpers.
CeilingOne agent still does everything. Context fills up. Quality degrades across domains.
⚠️
No matter how detailed your system prompt, you're asking one AI to be simultaneously a researcher, writer, editor, formatter, and project manager. That's not how specialists work.

Level 3 — The Agentic System

What it isA team of specialized AI agents, each with a bounded role, coordinated by an orchestrator.
Good forComplex, multi-stage workflows that need consistency, specialization, and scale.
CeilingYour ability to design the system — not a context window.
BenefitWhat it means in practice
SpecializationEach agent tuned for one job → more reliable, more predictable
ParallelismMultiple agents work simultaneously → faster results
ReusabilityAgents built once, used across many workflows
MaintainabilitySomething breaks? Fix one agent, not a 3,000-word prompt
ScaleMulti-stage processes that overwhelm one conversation become tractable

1.2 What Are Agentic Flows?

Definition: A structured AI system where specialized agents — each with bounded responsibilities and defined tools — are coordinated by an orchestrator to produce a reliable, repeatable output from a given input.

Three things make a flow "agentic" rather than just a long system prompt:

  1. Specialized agents — each knows exactly what it does and what it doesn't. A Fact-Checker doesn't style-edit. A Style Reviewer doesn't check facts. Constraint is a feature.
  2. An orchestrator — receives the high-level goal, breaks it into tasks, routes to the right agent, handles exceptions, assembles output. Think: project manager, not doer.
  3. Reliable, repeatable output — runs the same way every time. If results vary wildly between runs, the flow is broken.

The Mental Shift

FromTo
"What should I ask the AI?""What system should I design?"
One conversationAn architecture
Ad hoc promptingDefined roles and flows
Start over each timeBuild once, reuse forever

1.3 Why Claude Code?

Claude Code is a platform where you define AI systems using files, and Claude executes them. The name says "code" — the reality is much broader. It works equally well for:

  • Content pipelines (research → draft → edit → publish)
  • Operations (data extraction → classification → reporting)
  • Research (gather → synthesize → summarize)
  • Customer support (triage → draft response → escalate)
  • Business intelligence (monitor → analyze → report)

Your System Lives in Files

text
your-project/
├── CLAUDE.md                    ← system constitution (always loaded)
└── .claude/
    ├── agents/
    │   ├── researcher.md        ← subagent: research specialist
    │   ├── writer.md            ← subagent: content writer
    │   └── editor.md            ← subagent: review & editing
    ├── skills/
    │   └── weekly-report/
    │       └── SKILL.md         ← reusable workflow
    └── settings.json            ← hooks & permissions
BenefitWhat it enables
Version controlCommit to Git → full history, rollback, branching
CollaborationPush to repo → team shares the same agent config
PortabilityMove the folder → system moves with it
TransparencyRead every line → no hidden settings
💡
Claude Desktop's Code tab is the primary interface — no terminal required. The CLI is an alternative for power users who want scripting and automation. Both use the same .claude/ files.
Chapter 2

Getting Started with Claude Code

2.1 What You Need

RequirementDetails
Claude subscriptionPro ($20/mo), Max 5x ($100/mo), or Max 20x ($200/mo)
Claude DesktopmacOS or Windows — claude.com/download
A project folderAny folder on your local machine
Git (optional)Strongly recommended — version control for your agent files
PlanBest for
Pro ($20/mo)Learning, small workflows, occasional use
Max 5x ($100/mo)Regular professional use — Opus access included
Max 20x ($200/mo)Daily heavy use, multiple parallel sessions

2.2 Opening the Code Tab

Claude Desktop is the primary interface — no terminal required.

Claude Desktop Code tab Chat Code 📁 ~/projects/my-agent-system Model: Sonnet 4.6 ▾ Type your prompt... Proposed changes + CLAUDE.md Accept Reject ~ agents/writer.md Accept Reject ① Code tab ② Select folder ③ Pick model ④ Prompt ⑤ Review & approve diff
Figure 2.1 — Claude Desktop Code tab. Claude never modifies files without showing a diff and waiting for your approval.
  1. Open Claude Desktop → click the Code tab
  2. Click Select folder → choose your project folder
  3. Pick a model — Sonnet 4.6 for most tasks
  4. Start prompting in natural language

2.3 Your First Session

Start with a read-only prompt so Claude can explore without changing anything:

text
Analyze this project folder and tell me what it contains.

Every modification goes through the same approval loop:

Approval flow You type a prompt Claude reads relevant filesOn demand — not all at once Claude proposes changesDiff shown — nothing runs yet Accept? Yes Executes ↻ next turn No — retry
Figure 2.2 — The approval flow. Nothing is modified until you explicitly accept the diff.

2.4 How Your Files Connect

Claude Code works entirely with local files — nothing is uploaded to the cloud. When you select a folder, Claude automatically discovers CLAUDE.md and everything inside .claude/.

text
your-project/
├── CLAUDE.md                  ← always loaded at session start
├── .claude/
│   ├── agents/                ← subagent definitions
│   ├── skills/                ← reusable workflows
│   └── settings.json          ← hooks & permissions
└── your-other-files/
💡
Commit your .claude/ directory to Git. Your entire agentic system becomes version-controlled, shareable, and rollback-safe.

2.5 The CLI Alternative

bash
# Install
npm install -g @anthropic-ai/claude-code

# Run inside your project folder
cd your-project && claude
Desktop Code tabCLI
SetupZero — already installednpm install -g
InterfaceVisual diffs, GUIText-based diffs
Best forLearning, daily workAutomation, scripting, CI/CD
Same .claude/?

2.6 Authentication

MethodWhen to useHow
Browser loginPersonal use, Desktop, interactive CLIOAuth — same account as Claude.ai
API keyCI/CD, automation, scriptsexport ANTHROPIC_API_KEY=sk-ant-…
Chapter 3

How Claude Code Works — The Mental Model

3.1 The Conversation Loop

Claude Code is not a chatbot that happens to touch files. It's a read-modify-execute loop with you as the approver at every step.

Read-modify-execute loop You type a prompt Read relevant filesCLAUDE.md first, then on demand Reason + plan Propose changesYou approve or reject Accept Execute ↻ next turn Reject
Figure 3.1 — The read-modify-execute loop. Claude reads files on demand — a large project doesn't bloat the context from the start.

3.2 Essential Commands

CommandWhat it does
/helpList all available commands
/clearReset conversation, keep CLAUDE.md loaded
/compactCompress context to free up token space
/modelSwitch model mid-session (+ set effort level)
/planEnter Plan Mode — think before acting
/agentsView and manage active subagents
/hooksConfigure hooks interactively
/doctorRun diagnostics on your setup
@filenameReference a specific file in your prompt
!commandRun a shell command directly
@agent-nameExplicitly invoke a named subagent

3.3 Plan Mode — Think Before You Build

What it is: Claude analyzes your request, produces a plan, and waits for your approval before touching any file. Enter with /plan or Shift+Tab.

text
Explore ──→ Plan ──→ Implement ──→ Commit

  Read files   Design approach   Execute steps   Done
Use Plan Mode forSkip it for
Multi-file changesSingle file edits
Architectural decisionsQuick fixes
First time running a new workflowRoutine, familiar tasks
💡
For agentic system design, always use Plan Mode first. Design the architecture before building files.

3.4 Context Management

Every file read, tool call, and response consumes tokens from Claude's context window. When it fills, quality degrades.

StrategyWhen to use
/compactContext is filling up but you want to continue
/clearConversation has drifted — start fresh, CLAUDE.md stays loaded
New sessionTask is complete; starting something unrelated
Use subagentsHeavy exploration — each subagent has its own isolated context window

3.5 Model Selection

Use /model to switch mid-session. Default rule: start with Sonnet, escalate to Opus when needed.

ModelSpeedBest forContext
Sonnet 4.6Fast80%+ of tasks — coding, writing, analysis1M tokens
Opus 4.6SlowerComplex reasoning, architecture, agent teams1M tokens
Haiku 4.5FastestClassification, quick edits, high-volume tasks200K tokens

In agent and skill frontmatter, use the alias — not the full model string:

yaml
---
model: sonnet    # fast, cost-effective — use by default
model: opus      # complex reasoning
model: haiku     # fast, simple tasks
---
Chapter 4

The Anatomy of an Agentic System

4.1 Core Components

Every agentic system — regardless of complexity — is built from ten entity types. In Claude Code, each maps to a specific file, directory, or configuration.

EntityLocation in Claude CodeRole
Workflow.claude/commands/wor-*.mdOrchestrates multi-step processes. Coordinates agents, manages handoffs, and assembles results across steps.
Agent Specialist.claude/agents/age-spe-*.mdExecutes a specific domain of responsibility. One job, clear boundaries, own context window.
Agent Supervisor.claude/agents/age-sup-*.mdReviews or validates output from other agents. Quality gate, not a worker.
Skill.claude/skills/ski-*/SKILL.mdReusable capability package. Triggered by name or description match. Can be shared across agents.
Command.claude/commands/com-*.mdDirect, deterministic action triggered by the user. Always manual, always atomic.
Rule.claude/rules/rul-*.mdBehavioral constraint. Can live in CLAUDE.md (always-on) or as standalone files (on-demand).
Knowledge Base.claude/knowledge-base/kno-*.mdReference information consulted on demand. Never executed — only read.
Resource.claude/resources/res-*.mdSupport document that extends other entities. Loaded conditionally when the main entity needs extra detail.
Script.claude/scripts/scp-*.shExecutable automation — validation, deployment, data processing. In Claude Code: .sh or .py files.
Hook.claude/settings.jsonEvent-driven automation. Fires on system events, not user commands. Documentation in .claude/hooks/hok-*.md.

Naming Conventions

Every entity file follows a strict prefix system. This makes entities identifiable at a glance and enables automatic discovery.

EntityPrefixExample
Workflowwor-wor-content-pipeline.md
Agent Specialistage-spe-age-spe-email-classifier.md
Agent Supervisorage-sup-age-sup-output-validator.md
Skillski-ski-format-output/SKILL.md
Commandcom-com-quick-translate.md
Rulerul-rul-output-standards.md
Knowledge Basekno-kno-brand-guidelines.md
Resourceres-res-api-full-reference.md
Scriptscp-scp-lint-check.sh
Hookhok-hok-auto-lint.md

All names use kebab-case, no spaces, no uppercase. The name field in frontmatter is limited to 64 characters; the description to 250. Descriptions should follow a "what + when" pattern: what it does, and when it should be used.


4.2 How They Relate

Component relationship map — 10 entity types Rules (rul-)Constrain everything inside Workflow (wor-)Orchestrates the flow Specialist Aage-spe- Specialist Bage-spe- Supervisorage-sup- Skills (ski-)Reusable capabilities Knowledge Base (kno-)Consulted, never executed Resources (res-)Extends other entities Scripts (scp-).sh / .py executables Commands (com-)User-invoked, atomic User ↓ Hookshok- invokes / uses consults / references Workflows and Commands both live in .claude/commands/ — but Workflows orchestrate; Commands are atomic.
Figure 4.1 — Rules constrain everything. Workflows route to Agents (Specialists and Supervisors). Agents use Skills, consult Knowledge Bases, and reference Resources. Scripts automate procedures. Commands are user-invoked shortcuts. Hooks fire independently on events.
  • Workflow (wor-) orchestrates the flow — invokes Agents, manages handoffs
  • Specialists (age-spe-) execute domain work; Supervisors (age-sup-) validate output
  • Agents use Skills and run Scripts
  • Commands are invoked directly by the user — they bypass the Workflow
  • Rules constrain everyone — including the Workflow
  • Knowledge Base and Resources are consulted, never executed
  • Hooks fire on events, not on commands
🔑
In Claude Code, both Workflows (wor-*) and Commands (com-*) live in .claude/commands/. The prefix is what distinguishes them — not the directory.

4.3 Component Reference

Workflow (wor-)

  • Receives the high-level goal; breaks it into steps; routes to the right agents; manages handoffs; assembles output
  • In Claude Code: .claude/commands/wor-*.md
  • The orchestrator of the system — not a worker, but a coordinator

Agent Specialist (age-spe-)

  • Exactly one domain of responsibility — nothing more
  • Defined in .claude/agents/age-spe-*.md with YAML frontmatter
  • Has its own isolated context window
  • Invoked automatically (description match) or explicitly via @agent-name

Agent Supervisor (age-sup-)

  • Reviews, validates, or scores output produced by Specialists
  • Defined in .claude/agents/age-sup-*.md
  • Acts as a quality gate — does not produce primary work, only evaluates it
  • Use when you need a "second pair of eyes" before results leave a step

Skill (ski-)

  • A named, reusable capability package — not a worker, but a procedure
  • Triggered by name (/skill-name) or automatic description match
  • Lives in .claude/skills/ski-*/SKILL.md
  • Can fork a new context window for heavy work

Command (com-)

  • A direct, deterministic action — a "saved prompt" that always produces the same behavior
  • User-invoked only via /command-name — no agent or workflow delegates to a Command
  • Lives in .claude/commands/com-*.md with minimal YAML frontmatter
  • Use for atomic, repeatable tasks: export a system, publish a version, apply optimizations

Rule (rul-)

  • A constraint, not a capability
  • Two locations: in CLAUDE.md (always-on, every session) or as standalone files in .claude/rules/rul-*.md (loaded on demand)
  • Always written as "Instead of X, do Y" — never just a prohibition
  • Standalone rule files use a structured format: Context, Hard Constraints, Soft Constraints

Knowledge Base (kno-)

  • Static reference content: style guides, API docs, domain glossary
  • Lives in .claude/knowledge-base/kno-*.md
  • Tell agents when to read it: "If you encounter an error, read kno-error-codes.md"

Resource (res-)

  • Support document that extends another entity when its content is too long or too detailed
  • Lives in .claude/resources/res-*.md
  • Referenced conditionally: "For complex API usage, read res-api-full-reference.md"
  • Keeps the main entity lean — the agent loads the resource only when needed

Script (scp-)

  • Executable automated procedure — validation, deployment, data processing
  • In Claude Code: .claude/scripts/scp-*.sh or scp-*.py (executable files)
  • Run by agents or hooks, not invoked directly by users

Hook (hok-)

  • Fires automatically on system events — file save, session start, task complete
  • Configured in .claude/settings.json (the runtime configuration)
  • Documentation lives in .claude/hooks/hok-*.md (what the hook does and why)

4.4 Decision Tree: Which Component Do I Need?

Component decision tree — 10 entity types New item for your system Behavioral constraintor convention? Yes Rule No Coordinates multipleagents across steps? Yes Work-flow No Runs repeatedlyon different inputs? Yes Skill No Direct user action,deterministic output? Yes Command No Single job, clearboundaries? Yes Agentspe / sup No Reference infoto consult on demand? Yes KBor Res No Automated procedure(validate, deploy, process)? Yes Script No Fires on a system eventautomatically? Yes Hook No CLAUDE.md Produces work → Specialist (age-spe-) Validates work → Supervisor (age-sup-) Standalone reference → KB (kno-) Extends another entity → Resource (res-)
Figure 4.2 — Eight questions route any new element to the right entity type. Sub-decisions distinguish Specialist from Supervisor agents, and KB from Resources.
MistakeProblemFix
Orchestration logic inside an AgentScope creep — "God Agent"Move routing to a Workflow (wor-) or a dedicated Skill
Workflow when you need a CommandCommands are atomic; Workflows coordinate multi-step flowsIf single action → Command (com-). If multi-step → Workflow (wor-)
Skill when you need a RuleSkills are invoked; Rules are always-onIf always applies → Rule in CLAUDE.md or .claude/rules/
Everything in CLAUDE.mdContext fills every sessionMove workflow logic to Skills, long rules to rul-*.md files
Command when you need a SkillCommands can't be reused by agentsIf other agents need it → Skill (ski-)
KB when you need a ResourceKB is standalone; Resources extend entitiesIf it supplements an agent's instructions → Resource (res-)
Rules as negatives onlyAgents don't know what to do insteadAlways: "Instead of X, do Y"

4.5 A Minimal Working System

The smallest valid agentic system needs just three things:

text
your-project/
├── CLAUDE.md
└── .claude/
    └── agents/
        └── age-spe-researcher.md

CLAUDE.md

markdown
# Project: Market Research Assistant

## Purpose
This system researches topics and returns structured summaries.

## Rules
- Always cite sources
- Use the researcher agent for all information gathering
- Output in Markdown with clear section headers

## Agents
- **@age-spe-researcher** — handles all research and fact-finding tasks

.claude/agents/age-spe-researcher.md

yaml
---
name: age-spe-researcher
description: Researches topics using web search and returns structured
  summaries with citations. Use for any information gathering,
  fact-checking, or background research task.
model: sonnet
tools: WebSearch, Read
---

You are a research specialist. When given a topic:
1. Search for current, authoritative sources
2. Synthesize findings into a clear summary
3. List all sources with URLs

Output format:
## Summary
[2-3 paragraph synthesis]

## Key Facts
- [bullet list]

## Sources
- [URL] — [one-line description]

One rule set, one specialist. Start here — add complexity only when the task demands it.