Building Agentic Flows with Claude Code

Part 2 — Building Blocks

Chapters 5-8 · File architecture, subagents, skills, commands, rules, and hooks.

Chapter 5

File System Architecture

5.1 The .claude/ Directory

Your entire agentic system lives in two places: CLAUDE.md at the project root and the .claude/ directory. Together they define everything Claude Code knows about how to behave in this project.

bash
your-project/
├── CLAUDE.md                              ← always loaded, every session
└── .claude/
    ├── commands/                           ← workflows (wor-*) + commands (com-*)
    │   ├── wor-content-pipeline.md         ← multi-step orchestration
    │   └── com-publish-article.md          ← atomic user action
    ├── agents/                             ← specialist (age-spe-*) + supervisor (age-sup-*)
    │   ├── age-spe-researcher.md           ← domain specialist
    │   ├── age-spe-writer.md
    │   └── age-sup-editor.md               ← validates output quality
    ├── skills/                             ← reusable capabilities (ski-*)
    │   ├── ski-format-output/
    │   │   └── SKILL.md                    ← skill entry point
    │   └── ski-weekly-report/
    │       └── SKILL.md
    ├── rules/                              ← behavioral constraints (rul-*)
    │   └── rul-citation-standards.md       ← structured: Context + Hard/Soft Constraints
    ├── knowledge-base/                     ← reference material (kno-*)
    │   ├── kno-style-guide.md
    │   └── kno-api-reference.md
    ├── resources/                           ← support docs extending entities (res-*)
    │   └── res-api-full-reference.md       ← loaded conditionally by agents
    ├── scripts/                             ← executable automation (scp-*)
    │   └── scp-lint-check.sh               ← .sh or .py in Claude Code
    ├── hooks/                               ← hook documentation (hok-*)
    │   └── hok-auto-lint.md                ← what the hook does and why
    ├── settings.json                        ← hook config, permissions, tool restrictions
    └── settings.local.json                  ← CC-exclusive permission overrides

Claude discovers everything in this structure automatically when you open the folder — no configuration file points to it. The convention is the configuration.

🔑
Key CC detail: Both Workflows (wor-*) and Commands (com-*) live in .claude/commands/. The prefix distinguishes their role, not the directory. Similarly, both Specialist (age-spe-*) and Supervisor (age-sup-*) agents share .claude/agents/.

5.2 CLAUDE.md — Your System's Brain

CLAUDE.md is loaded at the start of every session. It's the one file that's always in context — everything else is loaded on demand.

What goes in CLAUDE.md

IncludeDon't include
Project purpose and scopeSpecific workflow steps (→ Skills)
Active rules and conventionsLong reference content (→ KB files)
Agent registry (what agents exist and when to use them)Agent instructions (→ agent files)
Module boundaries (what each agent/folder owns)Content that changes per-task
🔑
The golden rule: If it applies to every session, it goes in CLAUDE.md. If it's a specific workflow, make it a Skill.

A well-structured CLAUDE.md

markdown
# Project: Content Pipeline

## Purpose
Automated system for researching, writing, and publishing articles.
Output language: English. Audience: senior professionals.

## Active Agents
| Agent | Trigger | Owns |
|---|---|---|
| @age-spe-researcher | Any research or fact-finding task | /research/ |
| @age-spe-writer | Draft creation from research | /drafts/ |
| @age-sup-editor | Review, scoring, final approval | /output/ |

## Rules
- Never modify files outside the agent's own directory
- All drafts must include a source citation for every factual claim
- Instead of deleting files, move them to /archive/ with today's date
- For detailed citation rules, see `.claude/rules/rul-citation-standards.md`

## Conventions
- Entity names: prefixed by type (age-spe-, ski-, rul-, etc.)
- File names: kebab-case, no spaces
- Dates: ISO 8601 (YYYY-MM-DD)

Production tips

  • Keep it under 5KB — it loads every session and consumes context
  • Use tables for module boundaries — scannable at a glance
  • Always provide alternatives in rules: "Instead of X, do Y"
  • If you find yourself writing multi-paragraph instructions → move them to a Skill

5.3 The Frontmatter Contract

Every agent and skill file starts with YAML frontmatter between --- delimiters. This is how Claude Code discovers, identifies, and routes to your components.

yaml
---
name: age-spe-researcher
description: Researches topics using web search and synthesizes structured
  summaries with citations. Use for any information gathering, fact-checking,
  competitive analysis, or background research task.
model: sonnet
tools: WebSearch, Read, Grep
permissionMode: default
memory: project
---
FieldTypeWhat it does
namestringIdentifier used in @agent-name mentions and /skill-name commands
descriptionstring ≤250 charsDrives auto-discovery — Claude matches this against the user's request
modelsonnet / opus / haikuModel used when this agent/skill runs
toolslistWhitelist of allowed tools (Read, Write, Bash, WebSearch, etc.)
disallowedToolslistBlacklist approach — allow all except these
permissionModestringdefault, acceptEdits, or plan
memorystringuser, project, or local — enables persistent memory

The 250-character description budget

The description field is a routing rule, not a label. Claude reads it to decide whether to delegate a request to this agent. Front-load it with the specific situations and phrases that should trigger invocation.

Weak descriptionStrong description
"An agent that does research.""Researches topics using web search and returns structured summaries with citations. Use for information gathering, fact-checking, competitive analysis, or any task requiring current external data."
"Writes content.""Drafts long-form articles and blog posts from a research brief. Use after the researcher agent has completed its report. Applies the project style guide automatically."

5.4 Scope: Project vs. User

Claude Code resolves agents and skills from multiple locations. Understanding scope determines where to put each file.

ScopeLocationVisible toUse for
Project.claude/agents/Anyone with the project folderProject-specific agents — commit to Git
User (global)~/.claude/agents/Only you, across all projectsPersonal utilities you use everywhere
PluginInstalled via /pluginYou, across all projectsCommunity agents and skills

Resolution priority when names collide: session-level → project → user → plugin. The most local definition wins.

💡
A useful personal global agent: an age-spe-git-helper that knows your commit message conventions, or an age-spe-meeting-notes agent that formats notes into your preferred template — available in every project without copying files.

Description quality: the "what + when" pattern

Every description field should answer two questions: (1) What does this entity do — specific action, third person; (2) When should it be used — trigger context, specific conditions.

WeakStrong ("what + when")
"An agent that does research.""Researches topics using web search and returns structured summaries with citations. Use for information gathering, fact-checking, or any task requiring current external data."
"Validates output.""Reviews agent output for accuracy, completeness, and style guide compliance. Use after a specialist agent completes its task and before results are returned to the user."
Chapter 6

Designing Subagents

6.1 What Makes a Good Subagent?

A subagent is the atomic unit of your agentic system. There are two kinds:

TypePrefixRoleExample
Specialistage-spe-Executes a specific domain of responsibility — produces primary workage-spe-researcher, age-spe-writer
Supervisorage-sup-Reviews or validates output from specialists — acts as a quality gateage-sup-editor, age-sup-compliance-check

Both types share the same file format and live in .claude/agents/. Three principles determine whether either type will be reliable:

PrincipleWhat it meansRed flag
Single responsibilityOne domain. One job. If you struggle to name it in two words, it does too much.Agent names like "general-assistant" or "do-everything"
Clear input/output contractThe agent knows exactly what it receives and what it returns. Ambiguous input = unpredictable output.Instructions that say "handle whatever comes in"
Description as routing ruleThe description follows the "what + when" pattern: what it does + when to invoke it. Write it as if you're writing an if-statement.Descriptions that describe what the agent is rather than when to invoke it

6.2 Anatomy of a Subagent File

Every subagent is a single markdown file in .claude/agents/, named with the appropriate prefix (age-spe-* or age-sup-*). Here is a complete, annotated Supervisor example:

markdown
---
name: age-sup-code-reviewer             # prefix: age-sup- (supervisor)
description: Reviews pull request diffs for correctness, security issues,
  test coverage, and style guide compliance. Use when a PR is ready for
  review or when asked to check code quality on any file.
model: sonnet                           # fast enough for review tasks
tools: Read, Grep, Glob                 # read-only — never modifies files
permissionMode: default                 # asks before any action
memory: project                         # remembers team preferences across sessions
---

You are a senior code reviewer. Your job is to catch bugs, security
vulnerabilities, and style violations — not to rewrite working code.

## Review Process
1. Read the diff or files provided
2. Check for: logic errors, security issues, missing error handling,
   test coverage gaps, style guide violations
3. For each issue found, state: file + line, severity (critical/major/minor),
   explanation, suggested fix

## Output Format
### Summary
[One paragraph: overall quality assessment]

### Issues Found
| Severity | File | Line | Issue | Suggestion |
|---|---|---|---|---|

### Approved?
[Yes / No / Yes with minor issues]

## Rules
- Never suggest rewriting code that works correctly
- Flag security issues as critical regardless of other quality
- If no issues found, say so explicitly — don't manufacture concerns

Frontmatter deep dive

FieldValue in exampleWhy this choice
modelsonnetReview tasks don't need deep reasoning — Sonnet is faster and cheaper
toolsRead, Grep, GlobRead-only whitelist — this agent can never accidentally modify files
permissionModedefaultAlways asks before acting — appropriate for a review agent
memoryprojectRemembers the team's style decisions across sessions, shared via Git

6.3 Invoking Subagents

MethodHowWhen to use
AutomaticClaude matches the request against all agent descriptions and delegatesNormal flow — works when descriptions are precise
Explicit mention@age-sup-code-reviewer please review this PRWhen you want a specific agent regardless of description matching
Session-as-agentclaude --agent age-sup-code-reviewer (CLI)Start an entire session running as a specific agent
From a SkillReference the agent inside a skill's instructionsMulti-step workflows where one skill delegates to multiple agents

6.4 Tool Restrictions: The Permission Boundary

Tool restrictions are the most important safety lever in subagent design. Be explicit — don't rely on instructions alone to prevent file modifications.

Agent typeRecommended toolspermissionMode
Specialist: research (age-spe-)Read, Grep, Glob, WebSearchdefault
Specialist: writer (age-spe-)Read, Write, EditacceptEdits
Specialist: implementer (age-spe-)Read, Write, Edit, Bashdefault
Supervisor: reviewer (age-sup-)Read, Grep, Globplan

permissionMode values:

  • default — Claude asks before any significant action
  • acceptEdits — auto-accepts file edits, asks for other actions
  • plan — only produces a plan, never executes

6.5 Persistent Memory for Subagents

Subagents can maintain memory across sessions via a MEMORY.md file. The first 200 lines are auto-loaded into every session with that agent.

Memory scopeLocationShared via Git?Use for
user~/.claude/agent-memory/NoPersonal preferences across all projects
project.claude/agent-memory/YesTeam-shared context — style decisions, known patterns
local.claude/agent-memory/No (gitignored)Machine-local state — temp data, work-in-progress
⚠️
Memory adds noise if used carelessly. Enable it only for agents that genuinely benefit from cross-session continuity — a researcher agent that remembers domain terminology, or a reviewer that remembers the team's style decisions.

6.6 Real Examples

Specialist: Competitive research analyst (non-coding)

markdown
---
name: age-spe-competitive-analyst
description: Analyzes competitors using public web sources and returns
  structured reports. Use for market research, competitive positioning,
  feature comparison, or pricing intelligence tasks.
model: opus
tools: WebSearch, Read
permissionMode: default
memory: project
---

You are a competitive intelligence specialist. Your outputs are
structured for executive review — factual, sourced, and actionable.

## Analysis Framework
For each competitor requested:
1. Company overview (size, funding, positioning)
2. Product features vs. ours (table format)
3. Pricing model and tiers
4. Recent news and strategic moves (last 6 months)
5. Threat level: Low / Medium / High — with justification

## Rules
- Only cite verifiable public sources — no speculation
- Always include the URL and date for every claim
- If data is unavailable, say so — don't estimate

Specialist: Documentation writer

markdown
---
name: age-spe-doc-writer
description: Generates technical documentation from code, comments,
  and specifications. Use for README files, API docs, changelog entries,
  or any documentation task.
model: sonnet
tools: Read, Write, Grep, Glob
permissionMode: acceptEdits
---

You are a technical writer specializing in developer documentation.

## Principles
- Clarity over completeness — one clear sentence beats three vague ones
- Show, don't tell — every concept gets a code example
- Audience: developers who are busy. Front-load the most important info.

## Output
- Write in active voice
- Use second person ("you", "your")
- Code examples must be runnable, not pseudocode
Chapter 7

Skills & Commands

7.1 Skills vs. Subagents vs. CLAUDE.md

The three configuration layers serve different purposes. Choosing the wrong one creates bloat, duplication, or agents that do too much.

CLAUDE.mdSkillSubagent
What it isAlways-on contextNamed, on-demand workflowIsolated worker with its own context
Loaded whenEvery session, automaticallyWhen invoked by name or description matchWhen delegated to by name or description
Runs inMain context windowMain window (or forked window)Isolated context window
Use forConventions, rules, agent registryRepeatable workflows, templates, proceduresSpecialized domain work, parallel execution
Example"Always use British English""Run our PR review checklist""Research agent that searches and synthesizes"

7.2 Anatomy of a Skill

Skills live in .claude/skills/<skill-name>/SKILL.md. A skill directory can contain supporting files — templates, scripts, examples — that the skill references.

bash
.claude/skills/
└── ski-pr-review/
    ├── SKILL.md             ← entry point
    ├── checklist.md         ← referenced template
    └── examples/
        └── good-pr.md       ← example for Claude to learn from
markdown
---
name: ski-pr-review
description: Runs the team PR review checklist on the current branch diff.
  Checks correctness, security, test coverage, and style. Invoke with
  /ski-pr-review or when asked to review a pull request.
user-invocable: true
allowed-tools: Read, Grep, Bash
---

# PR Review Skill

Run our standard PR review process on the provided diff or branch.

## Steps
1. Read the diff: `!git diff main...HEAD`
2. Load the review checklist from `checklist.md`
3. Evaluate each checklist item against the diff
4. Generate a structured review report

## Output Format
Use the template in `checklist.md`. Return the completed checklist
plus a Summary and Verdict (Approve / Request Changes / Needs Discussion).

Key frontmatter fields for skills

FieldValuesEffect
user-invocabletrue / falseIf true, creates a /skill-name slash command. If false, Claude-only invocation.
allowed-toolstool listTools available when this skill runs
contextforkRuns skill in an isolated context window — keeps main session clean
agentExplore / PlanUsed with fork mode to set the agent type in the forked context

7.3 Invocation Modes

ModeHowWhen to use
User slash command/pr-reviewExplicit, human-triggered. Set user-invocable: true.
Auto (Claude-invoked)Description matchClaude picks it up automatically when the task matches. Set user-invocable: false.
With arguments/pr-review #123User passes input. Use $ARGUMENTS placeholder in SKILL.md.
Fork modecontext: forkHeavy exploration that would bloat the main context. Runs in isolation.
Dynamic injection!git status in skill bodyRun shell commands and inject their output into the skill context.

Using $ARGUMENTS

markdown
---
name: summarize
description: Summarizes a document or URL into key points.
user-invocable: true
---

Summarize the following: $ARGUMENTS

Return:
- 3-sentence overview
- 5 key points as bullets
- Any action items or decisions

The user types /summarize https://example.com/article and the URL is injected at $ARGUMENTS.


7.4 Real Examples

Weekly report generator (non-coding)

markdown
---
name: weekly-report
description: Generates the team's weekly status report from Git history,
  Jira tickets, and notes. Run every Friday. Invoke with /weekly-report.
user-invocable: true
allowed-tools: Read, Bash, Grep
---

# Weekly Report Skill

Generate this week's team status report.

## Data Collection
1. Pull this week's commits: `!git log --since="7 days ago" --oneline`
2. Read any notes in `/notes/this-week.md` if it exists
3. Check `/projects/` for files modified this week: `!find projects/ -newer projects/ -name "*.md"`

## Report Structure
Generate a Markdown report with:

### This Week
[What shipped, what was completed]

### Next Week
[What's planned]

### Blockers
[Anything blocking progress]

### Metrics
[Any numbers worth tracking]

Save the report to `/reports/YYYY-MM-DD-weekly.md`

Competitive research skill (fork mode)

markdown
---
name: competitor-scan
description: Deep research on a competitor. Forks into Explore mode
  to avoid polluting the main session context.
user-invocable: true
context: fork
agent: Explore
allowed-tools: WebSearch, Read
---

Research $ARGUMENTS as a competitor. Cover:
1. Product overview and positioning
2. Pricing tiers
3. Key differentiators vs. our product
4. Recent news (last 3 months)
5. User sentiment (reviews, social)

Return a structured report saved to `/research/competitors/$ARGUMENTS.md`

7.5 Workflows, Commands & Skills

In Claude Code, three types of invocable entities share space. Understanding when to use each is critical:

Workflow (wor-)Command (com-)Skill (ski-)
What it isMulti-step orchestration across agentsDirect, atomic actionReusable procedure
Who invokes itUser (/wor-name)User (/com-name)User (/ski-name) or Claude (auto-match)
Lives in.claude/commands/wor-*.md.claude/commands/com-*.md.claude/skills/ski-*/SKILL.md
Reusable by agentsNo — user-initiated onlyNo — user-initiated onlyYes — agents discover it via description
Output shapeComplex — coordinates agents, produces multi-step outputDeterministic — same behavior every timeVaries per input and context
Use whenEnd-to-end pipeline: research → design → implementSingle action: export, publish, deployProcedure needed in multiple contexts
🔑
In Claude Code, Workflows and Commands both live in .claude/commands/. The prefix (wor- vs com-) distinguishes their role. Workflows orchestrate multi-step processes across agents; Commands are atomic actions.
💡
Decision heuristic: Coordinates agents across steps → Workflow (wor-). Single action, always the same → Command (com-). Reusable by agents → Skill (ski-).

7.6 Anatomy of a Command

Commands live as flat markdown files in .claude/commands/, prefixed with com-. Workflows (wor-) share the same directory. No subdirectory structure — each file is one entity.

bash
.claude/commands/
├── wor-content-pipeline.md       ← workflow (multi-step orchestration)
├── com-deploy-staging.md         ← command (atomic action)
├── com-export-system.md
└── com-publish-version.md
markdown
---
description: Deploys the current branch to the staging environment.
  Runs tests, builds, and pushes to staging via the deploy script.
  Use with /deploy-staging before requesting a production review.
---

# Command: Deploy to Staging

Run the full staging deployment pipeline for the current branch.

## Behavior
1. Run the test suite: `!npm test`
2. Build the project: `!npm run build`
3. Execute the deploy script: `!bash scripts/deploy-staging.sh`
4. Report the deployed URL and any warnings

## Expected Output
A confirmation message with:
- Deployed URL
- Build duration
- Any test warnings

## Constraints
- Never deploy if tests fail — stop and report the failures
- Never deploy the `main` branch to staging — staging is for feature branches only
- If the deploy script exits non-zero, report the error verbatim

Key differences from Skill files

PropertySkillCommand
Location.claude/skills/<name>/SKILL.md.claude/commands/<name>.md
FrontmatterRich: name, description, user-invocable, allowed-tools, context, agentMinimal: description only
Supporting filesCan include templates, examples in subdirectorySingle flat file — no subdirectory
Body structureFree-form steps and templatesObjective → Behavior → Expected Output → Constraints
🔑
Naming convention: Commands use the com- prefix (e.g., com-export-system.md). Workflows use wor- (e.g., wor-content-pipeline.md). Skills use ski- as a directory name (e.g., ski-pr-review/SKILL.md).

7.7 Command Examples

Export system (delegates to a script)

markdown
---
description: Exports the current project as a standalone git repository.
  Initializes version tracking, creates initial commit, and optionally
  pushes to GitHub. Use with /export-system after completing a build.
---

# Command: Export System

Initialize this project as its own independent Git repository.

## Behavior
1. Validate that the project directory contains the expected structure
2. Initialize a Git repo if one doesn't exist
3. Create a `.gitignore` for temporary and sensitive files
4. Create a `VERSION` file set to `0.1.0`
5. Make an initial commit and tag it `v0.1.0`
6. If `gh` CLI is available, offer to create a private GitHub repo

## Expected Output
Confirmation with:
- Repository path
- Initial version tag
- GitHub URL (if created)

## Constraints
- Never overwrite an existing Git repository — if `.git/` exists, stop and warn
- Never commit files matching `.env*` or `*credentials*`

Quick translate (lightweight, self-contained)

markdown
---
description: Translates the content of a file or selection to a target
  language while preserving formatting and code blocks. Use with
  /quick-translate <language> to translate the current selection.
---

# Command: Quick Translate

Translate the provided content to $ARGUMENTS while preserving:
- All Markdown formatting
- Code blocks (leave code untranslated)
- Links and references

## Behavior
1. Identify the target language from `$ARGUMENTS`
2. Translate all human-readable text
3. Preserve technical terms, proper nouns, and code snippets
4. Return the translated content in the same format

## Expected Output
The full translated content, ready to paste or save.

## Constraints
- Never translate code, variable names, or file paths
- If no target language is specified, ask the user before proceeding
- Maintain the original document structure exactly
Chapter 8

Rules, Knowledge Bases & Hooks

8.1 Rules: Constraining Behavior

A rule is a restriction or convention that shapes behavior without executing anything. Rules don't do work — they constrain work.

Where rules live

LocationBehaviorUse for
CLAUDE.md sectionAlways-on — every session, every agentUniversal project conventions (short)
.claude/rules/rul-*.mdOn-demand — loaded when referenced or matchedDetailed, domain-specific rules (security, compliance, style)

Standalone rule files

For rules that need more structure than a CLAUDE.md bullet point, create standalone files in .claude/rules/ with the rul- prefix. Use this structured format:

markdown
## Context

This rule ensures that all generated output follows the organization's
brand guidelines. Without it, agents produce inconsistent formatting
that requires manual correction.

## Hard Constraints

- Never use first person in customer-facing content.
- Never exceed 80 characters per line in code comments.
- Never commit files without running the linter first.

## Soft Constraints

- Prefer active voice over passive voice.
- Use tables for structured comparisons instead of bullet lists.
- Keep function names under 30 characters when possible.

Hard Constraints are mandatory — agents must never violate them. Soft Constraints are preferred behaviors that can be overridden by context. This distinction gives agents clear guidance on what's negotiable and what isn't.

Writing effective rules

Rules that only say what not to do fail — agents don't know what to do instead. Always provide the alternative:

Weak ruleEffective rule
Never use rm -rfInstead of rm -rf, use trash (safer, recoverable)
Don't write long functionsKeep functions under 40 lines. If longer, extract a helper with a descriptive name.
No direct database queriesAll DB access goes through the repository layer in /lib/db/
Don't commit secretsUse environment variables for credentials. Add any new secret keys to .env.example with a placeholder.

Rules section in CLAUDE.md

markdown
## Rules

### File Modifications
- Never modify files outside the agent's designated directory
- Instead of deleting, move to /archive/YYYY-MM-DD/
- All new files go in the appropriate module directory — never at project root

### Code Style
- Functions: under 40 lines. Extract helpers rather than growing functions.
- Variable names: descriptive, no single letters except loop counters
- Instead of comments explaining what, write code that explains itself

### Output
- All agent outputs in Markdown unless the user requests another format
- Tables preferred over bullet lists for structured comparisons

8.2 Knowledge Bases: Reference on Demand

A knowledge base is a file (or set of files) that agents consult when they need reference information — not instructions, but facts, definitions, and context.

KB vs. CLAUDE.md: when to use which

Put in CLAUDE.mdPut in a KB file
Things agents need to know every sessionReference content that's only needed sometimes
Short conventions and rulesLong reference material (API docs, glossaries)
Agent registryDomain-specific knowledge an agent uses for a task

The key to a useful KB: tell agents when to read it, not just what it contains.

bash
.claude/knowledge-base/
├── kno-style-guide.md       ← brand voice, tone, formatting rules
├── kno-api-reference.md     ← internal API endpoints and parameters
├── kno-error-codes.md       ← known errors and resolution steps
└── kno-domain-glossary.md   ← product and industry terminology

Reference KB files in agent instructions like this:

markdown
When writing any customer-facing content, read `kno-style-guide.md`
for tone, vocabulary, and formatting requirements.

If you encounter an API error, check `kno-error-codes.md` before
attempting a workaround.
💡
Pitch the agent on why the file is worth reading. "See docs/api.md for complex endpoints" works better than "API docs are in docs/api.md".

8.3 Resources: Support Documents (res-)

Resources are a first-class entity type — not just a pattern. They extend other entities when their content is too long or too detailed for the main file. Resources live in .claude/resources/ with the res- prefix.

bash
.claude/resources/
├── res-api-full-reference.md    ← detailed API specs (loaded conditionally)
├── res-deployment-checklist.md  ← extended deployment procedures
└── res-interview-questions.md   ← question trees for discovery

KB vs. Resource: when to use which

Use a Knowledge Base (kno-)Use a Resource (res-)
Standalone reference any agent might consultSupport document that extends a specific entity
Moderate length — loaded in full when neededDense or long — loaded conditionally by one agent
Self-contained: style guide, glossary, error codesSupplementary: full API spec, detailed templates, question trees

Reference resources conditionally from agent instructions:

markdown
# Agent instructions (in the agent .md file)

For standard tasks, use the short API summary below.
For complex API usage or if you encounter a FooBarError,
read `res-api-full-reference.md` in `.claude/resources/`.

## Quick API Reference
POST /items — create item (body: {name, type})
GET  /items/{id} — get item by ID
DELETE /items/{id} — delete item (requires admin role)

The agent loads the full resource only when it needs it — keeping the normal path lean and fast.


8.4 Hooks: Event-Driven Automation

Hooks fire automatically when system events occur — not in response to user commands. They're automation, not agents.

Hook events

EventFires whenCommon use
PreToolUseBefore Claude uses a toolBlock dangerous operations, validate before writes
PostToolUseAfter a tool completesAuto-lint after file save, log changes
StopClaude finishes its responseNotify when a long task completes
SessionStartNew session beginsLoad context, restore state, greet
NotificationClaude sends a notificationRoute notifications to Slack, email, etc.

Hook configuration in settings.json

json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "./scripts/lint.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude finished\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

Handler types

TypeWhat it doesUse for
commandRuns a shell command or scriptLinting, validation, file operations, notifications
promptInjects a prompt into Claude's contextLightweight checks requiring contextual understanding
agentSpawns a subagent (up to 50 tool turns)Complex automated tasks triggered by events
httpMakes an HTTP requestWebhooks, external integrations, logging services
💡
Use /hooks to configure hooks interactively — Claude will walk you through the setup and write the settings.json entry for you.

Hook documentation files

While hooks are configured in settings.json, you can document them in .claude/hooks/hok-*.md. These files explain what each hook does and why — useful for team onboarding and debugging:

bash
.claude/hooks/
├── hok-auto-lint.md           ← documents the PostToolUse lint hook
└── hok-safety-check.md        ← documents the PreToolUse safety hook

Three hooks worth having in every project

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "prompt",
          "prompt": "Before running this command, confirm it won't cause irreversible changes. If it could delete data or modify production, stop and ask the user."
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{
          "type": "command",
          "command": "npx prettier --check $CLAUDE_FILE_PATH 2>/dev/null || true",
          "timeout": 10
        }]
      }
    ],
    "Stop": [
      {
        "matcher": ".*",
        "hooks": [{
          "type": "command",
          "command": "echo 'Task complete' | terminal-notifier -title 'Claude Code'",
          "timeout": 5
        }]
      }
    ]
  }
}

8.5 Scripts: Executable Automation (scp-)

Scripts are executable automated procedures — validation, deployment, data processing, or any task that runs as a shell command or Python script. They live in .claude/scripts/ with the scp- prefix.

bash
.claude/scripts/
├── scp-lint-check.sh          ← shell script for linting
├── scp-validate-schema.py     ← Python validation script
└── scp-deploy-staging.sh      ← deployment automation

In Claude Code, scripts are always executable files (.sh or .py), not markdown descriptions. They are run by agents, hooks, or workflows — not invoked directly by users.

Script vs. Hook vs. Command

Script (scp-)Hook (hok-)Command (com-)
Triggered byAgent or hook invocationSystem event (automatic)User (/com-name)
Format.sh / .py executablesettings.json config.md file with instructions
Use whenAutomated procedure agents callEvent-driven reactionUser wants a shortcut

Example: Validation script

bash
#!/bin/bash
# scp-validate-structure.sh
# Validates that the project follows the expected directory structure

REQUIRED_DIRS=("agents" "skills" "rules" "knowledge-base")
MISSING=()

for dir in "${REQUIRED_DIRS[@]}"; do
  if [ ! -d ".claude/$dir" ]; then
    MISSING+=("$dir")
  fi
done

if [ ${#MISSING[@]} -gt 0 ]; then
  echo "Missing directories: ${MISSING[*]}"
  exit 1
fi

echo "Structure valid."
exit 0

An agent or hook can reference this script: bash .claude/scripts/scp-validate-structure.sh

Ready to build?

AiAgentArchitect generates complete agentic systems from a single conversation.

Explore on GitHub