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.
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.
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
| Include | Don't include |
|---|---|
| Project purpose and scope | Specific workflow steps (→ Skills) |
| Active rules and conventions | Long 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 |
A well-structured CLAUDE.md
# 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.
---
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
--- | Field | Type | What it does |
|---|---|---|
name | string | Identifier used in @agent-name mentions and /skill-name commands |
description | string ≤250 chars | Drives auto-discovery — Claude matches this against the user's request |
model | sonnet / opus / haiku | Model used when this agent/skill runs |
tools | list | Whitelist of allowed tools (Read, Write, Bash, WebSearch, etc.) |
disallowedTools | list | Blacklist approach — allow all except these |
permissionMode | string | default, acceptEdits, or plan |
memory | string | user, 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 description | Strong 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.
| Scope | Location | Visible to | Use for |
|---|---|---|---|
| Project | .claude/agents/ | Anyone with the project folder | Project-specific agents — commit to Git |
| User (global) | ~/.claude/agents/ | Only you, across all projects | Personal utilities you use everywhere |
| Plugin | Installed via /plugin | You, across all projects | Community agents and skills |
Resolution priority when names collide: session-level → project → user → plugin. The most local definition wins.
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.
| Weak | Strong ("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." |
Designing Subagents
6.1 What Makes a Good Subagent?
A subagent is the atomic unit of your agentic system. There are two kinds:
| Type | Prefix | Role | Example |
|---|---|---|---|
| Specialist | age-spe- | Executes a specific domain of responsibility — produces primary work | age-spe-researcher, age-spe-writer |
| Supervisor | age-sup- | Reviews or validates output from specialists — acts as a quality gate | age-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:
| Principle | What it means | Red flag |
|---|---|---|
| Single responsibility | One 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 contract | The agent knows exactly what it receives and what it returns. Ambiguous input = unpredictable output. | Instructions that say "handle whatever comes in" |
| Description as routing rule | The 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:
---
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
| Field | Value in example | Why this choice |
|---|---|---|
model | sonnet | Review tasks don't need deep reasoning — Sonnet is faster and cheaper |
tools | Read, Grep, Glob | Read-only whitelist — this agent can never accidentally modify files |
permissionMode | default | Always asks before acting — appropriate for a review agent |
memory | project | Remembers the team's style decisions across sessions, shared via Git |
6.3 Invoking Subagents
| Method | How | When to use |
|---|---|---|
| Automatic | Claude matches the request against all agent descriptions and delegates | Normal flow — works when descriptions are precise |
| Explicit mention | @age-sup-code-reviewer please review this PR | When you want a specific agent regardless of description matching |
| Session-as-agent | claude --agent age-sup-code-reviewer (CLI) | Start an entire session running as a specific agent |
| From a Skill | Reference the agent inside a skill's instructions | Multi-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 type | Recommended tools | permissionMode |
|---|---|---|
Specialist: research (age-spe-) | Read, Grep, Glob, WebSearch | default |
Specialist: writer (age-spe-) | Read, Write, Edit | acceptEdits |
Specialist: implementer (age-spe-) | Read, Write, Edit, Bash | default |
Supervisor: reviewer (age-sup-) | Read, Grep, Glob | plan |
permissionMode values:
default— Claude asks before any significant actionacceptEdits— auto-accepts file edits, asks for other actionsplan— 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 scope | Location | Shared via Git? | Use for |
|---|---|---|---|
user | ~/.claude/agent-memory/ | No | Personal preferences across all projects |
project | .claude/agent-memory/ | Yes | Team-shared context — style decisions, known patterns |
local | .claude/agent-memory/ | No (gitignored) | Machine-local state — temp data, work-in-progress |
6.6 Real Examples
Specialist: Competitive research analyst (non-coding)
---
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
---
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 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.md | Skill | Subagent | |
|---|---|---|---|
| What it is | Always-on context | Named, on-demand workflow | Isolated worker with its own context |
| Loaded when | Every session, automatically | When invoked by name or description match | When delegated to by name or description |
| Runs in | Main context window | Main window (or forked window) | Isolated context window |
| Use for | Conventions, rules, agent registry | Repeatable workflows, templates, procedures | Specialized 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.
.claude/skills/
└── ski-pr-review/
├── SKILL.md ← entry point
├── checklist.md ← referenced template
└── examples/
└── good-pr.md ← example for Claude to learn from ---
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
| Field | Values | Effect |
|---|---|---|
user-invocable | true / false | If true, creates a /skill-name slash command. If false, Claude-only invocation. |
allowed-tools | tool list | Tools available when this skill runs |
context | fork | Runs skill in an isolated context window — keeps main session clean |
agent | Explore / Plan | Used with fork mode to set the agent type in the forked context |
7.3 Invocation Modes
| Mode | How | When to use |
|---|---|---|
| User slash command | /pr-review | Explicit, human-triggered. Set user-invocable: true. |
| Auto (Claude-invoked) | Description match | Claude picks it up automatically when the task matches. Set user-invocable: false. |
| With arguments | /pr-review #123 | User passes input. Use $ARGUMENTS placeholder in SKILL.md. |
| Fork mode | context: fork | Heavy exploration that would bloat the main context. Runs in isolation. |
| Dynamic injection | !git status in skill body | Run shell commands and inject their output into the skill context. |
Using $ARGUMENTS
---
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)
---
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)
---
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 is | Multi-step orchestration across agents | Direct, atomic action | Reusable procedure |
| Who invokes it | User (/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 agents | No — user-initiated only | No — user-initiated only | Yes — agents discover it via description |
| Output shape | Complex — coordinates agents, produces multi-step output | Deterministic — same behavior every time | Varies per input and context |
| Use when | End-to-end pipeline: research → design → implement | Single action: export, publish, deploy | Procedure needed in multiple contexts |
.claude/commands/. The prefix (wor- vs com-) distinguishes their role. Workflows orchestrate multi-step processes across agents; Commands are atomic actions.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.
.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 ---
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
| Property | Skill | Command |
|---|---|---|
| Location | .claude/skills/<name>/SKILL.md | .claude/commands/<name>.md |
| Frontmatter | Rich: name, description, user-invocable, allowed-tools, context, agent | Minimal: description only |
| Supporting files | Can include templates, examples in subdirectory | Single flat file — no subdirectory |
| Body structure | Free-form steps and templates | Objective → Behavior → Expected Output → Constraints |
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)
---
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)
---
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 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
| Location | Behavior | Use for |
|---|---|---|
CLAUDE.md section | Always-on — every session, every agent | Universal project conventions (short) |
.claude/rules/rul-*.md | On-demand — loaded when referenced or matched | Detailed, 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:
## 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 rule | Effective rule |
|---|---|
Never use rm -rf | Instead of rm -rf, use trash (safer, recoverable) |
| Don't write long functions | Keep functions under 40 lines. If longer, extract a helper with a descriptive name. |
| No direct database queries | All DB access goes through the repository layer in /lib/db/ |
| Don't commit secrets | Use environment variables for credentials. Add any new secret keys to .env.example with a placeholder. |
Rules section in CLAUDE.md
## 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.md | Put in a KB file |
|---|---|
| Things agents need to know every session | Reference content that's only needed sometimes |
| Short conventions and rules | Long reference material (API docs, glossaries) |
| Agent registry | Domain-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.
.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:
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. 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.
.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 consult | Support document that extends a specific entity |
| Moderate length — loaded in full when needed | Dense or long — loaded conditionally by one agent |
| Self-contained: style guide, glossary, error codes | Supplementary: full API spec, detailed templates, question trees |
Reference resources conditionally from agent instructions:
# 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
| Event | Fires when | Common use |
|---|---|---|
PreToolUse | Before Claude uses a tool | Block dangerous operations, validate before writes |
PostToolUse | After a tool completes | Auto-lint after file save, log changes |
Stop | Claude finishes its response | Notify when a long task completes |
SessionStart | New session begins | Load context, restore state, greet |
Notification | Claude sends a notification | Route notifications to Slack, email, etc. |
Hook configuration in settings.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
| Type | What it does | Use for |
|---|---|---|
command | Runs a shell command or script | Linting, validation, file operations, notifications |
prompt | Injects a prompt into Claude's context | Lightweight checks requiring contextual understanding |
agent | Spawns a subagent (up to 50 tool turns) | Complex automated tasks triggered by events |
http | Makes an HTTP request | Webhooks, external integrations, logging services |
/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:
.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
{
"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.
.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 by | Agent or hook invocation | System event (automatic) | User (/com-name) |
| Format | .sh / .py executable | settings.json config | .md file with instructions |
| Use when | Automated procedure agents call | Event-driven reaction | User wants a shortcut |
Example: Validation script
#!/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