Hooks System: Complete Guide to 26 Events, 5 Hook Types and stdin-stdout Protocol
Chapter 43: Claude Code Slash Commands: Custom Workflows and Skill Reuse
43.1 What Are Slash Commands
In the Claude Code interactive interface, you can enter commands prefixed with / to trigger predefined workflows. These are called Slash Commands.
Claude Code ships with a set of built-in system-level slash commands, such as:
/clear— clear the context of the current session/compact— compress conversation history to free context space/help— show help information
But the truly powerful feature is custom slash commands — you can create project-specific commands that encapsulate repetitive workflows into a short invocation, ready to call whenever you need it.
Imagine: every time you need to add a feature, you have to tell Claude "write the tests first, make sure they fail, then write the implementation, make sure they pass, then update the docs." With a custom command, you just type /feature and Claude automatically follows this complete workflow.
43.2 Where Custom Commands Live
Custom slash commands are stored in the .claude/commands/ directory, with each command as a Markdown file:
project root/
└── .claude/
└── commands/
├── feature.md # the /feature command
├── review.md # the /review command
├── debug.md # the /debug command
├── deploy-check.md # the /deploy-check command
└── refactor.md # the /refactor command
The filename (without the .md extension) becomes the command name. feature.md corresponds to /feature.
You can also store personal global commands in ~/.claude/commands/, which are available across all projects:
~/.claude/
└── commands/
├── standup.md # daily standup summary (globally available)
├── pr-review.md # PR review workflow (globally available)
└── explain.md # code explanation (globally available)
43.3 The Command File Format
A command file is essentially a prompt for Claude, with some special syntax support.
Basic Format
# /feature — Full Feature Development Workflow
You are helping me develop a new feature. Please follow these steps:
## Step 1: Understand Requirements
Ask the user:
- Feature name and purpose
- Acceptance criteria
- Scope of affected modules or files
## Step 2: Write Failing Tests
Before implementing, write tests first:
1. Create test file(s) if they don't exist
2. Write test cases based on acceptance criteria
3. Run tests — confirm they fail (red)
4. Show the user the failing test output
## Step 3: Implement the Feature
Implement based on what the tests require:
1. Analyze test cases to understand expected behavior
2. Write minimal implementation to make tests pass
3. Run tests — confirm they pass (green)
## Step 4: Refine and Document
1. Check that code conforms to project conventions
2. Refactor if necessary (keep tests passing)
3. Update or create relevant documentation
When finished, provide the user with a brief implementation summary.
Using $ARGUMENTS to Accept Parameters
Command files can use the $ARGUMENTS placeholder, which is replaced by the text the user types after the command:
# /explain — Code Explanation
Please explain the following code or file: `$ARGUMENTS`
Your explanation should include:
1. The primary purpose of this code
2. Key design decisions
3. Potential improvement areas
4. Usage examples
Use clear language appropriate for an intermediate developer.
Usage:
/explain src/utils/tokenizer.ts
$ARGUMENTS is replaced with src/utils/tokenizer.ts, so Claude knows exactly what to explain.
Referencing Context with @file
Inside a command file, you can use @filepath syntax to reference files in the project, injecting their content into the command's context:
# /review — Code Review
Please review: $ARGUMENTS
Apply the following standards during the review:
@docs/code-review-checklist.md
Provide feedback along these dimensions:
1. Code correctness
2. Performance considerations
3. Security
4. Readability and maintainability
5. Test coverage
Conclude with an overall score (1–10) and the most important improvement recommendations.
43.4 A Practical Command Library
The following is a set of battle-tested custom commands covering common daily development scenarios:
/feature: TDD Feature Development
# /feature — TDD Feature Development
Feature name or description: $ARGUMENTS
Implement this feature following TDD:
**Phase 1: Planning (do not write code yet)**
1. Analyze which files need to be modified
2. Identify the core behaviors to test (3–5 key scenarios)
3. Confirm your understanding with me before proceeding
**Phase 2: Write Tests**
1. Create or update test files
2. Write a test case for each core behavior
3. Run: `pnpm test` — confirm ALL new tests fail (this is correct)
4. Show me the failing test output
**Phase 3: Implement**
1. Write minimal implementation to make tests pass
2. Run tests — confirm all pass
3. Show me the final passing test output
**Phase 4: Wrap Up**
1. Verify code conforms to conventions in CLAUDE.md
2. Refactor if necessary (keep tests passing)
3. Summarize what you did in one paragraph
/review: Code Review
# /review — Code Review
Target: $ARGUMENTS
**Review process:**
First, read and understand: $ARGUMENTS
Then evaluate along these dimensions:
**1. Functional Correctness**
- Is the logic correct?
- Are edge cases handled?
- Is error handling complete?
**2. Code Quality**
- Are names clear and meaningful?
- Does each function have a single responsibility?
- Is there repeated code that could be extracted?
**3. Performance**
- Are there obvious performance issues (N+1 queries, unnecessary re-renders)?
- How will this behave with large data volumes?
**4. Security**
- Are there SQL injection, XSS, or other vulnerabilities?
- Is sensitive data handled correctly?
**5. Testability**
- Are existing tests adequate?
- Are there important untested scenarios?
Finally, provide prioritized improvement recommendations:
P0 = must fix, P1 = recommended, P2 = optional optimization.
/debug: Systematic Debugging
# /debug — Systematic Debugging
Problem description: $ARGUMENTS
Help me debug this problem systematically:
**Step 1: Understand the Problem**
- What are the symptoms? (actual behavior vs. expected behavior)
- When did this problem start?
- Can it be reliably reproduced?
**Step 2: Gather Information**
Please review:
1. Relevant error logs (if any)
2. Involved source files
3. Recent git changes: `git log --oneline -10`
**Step 3: Form Hypotheses**
Based on the gathered information, list 2–3 possible causes, ranked by likelihood.
**Step 4: Validate Hypotheses**
For each hypothesis, propose a specific verification method (add logging, write a test case, etc.).
**Step 5: Apply the Fix**
Once the root cause is confirmed, implement the fix and verify the problem is resolved.
/migrate: Database Migration Assistant
# /migrate — Database Migration
Migration requirement: $ARGUMENTS
**WARNING: Database migrations are high-risk operations. Follow these steps strictly.**
**Step 1: Analyze Impact**
1. Which tables will be modified?
2. Is any data transformation needed?
3. Will existing queries or indexes be affected?
4. Roughly how much data is in production? (affects migration duration)
**Step 2: Prepare Migration Script**
1. Modify schema.prisma (if applicable)
2. Generate migration: `pnpm db:migrate`
3. Review the generated SQL and confirm it matches expectations
**Step 3: Local Validation**
1. Apply migration locally: `pnpm db:push`
2. Run related tests
3. Manually verify data integrity
**Step 4: Rollback Plan**
Write out the rollback steps if the migration fails.
**Important reminders:**
- Never run migrations during peak traffic
- Always back up production data before migrating
- Consider blue-green deployment to minimize downtime
/standup: Daily Standup Summary (Global Command)
# /standup — Daily Standup Summary
Generate a standup summary based on today's work.
**Gather data by running:**
1. `git log --since="yesterday" --author="$(git config user.name)" --oneline`
2. `git diff --stat HEAD~5 HEAD`
**Summary format:**
**Yesterday:**
[Summarize completed work based on git log]
**Today:**
[Ask the user for today's plan, or infer from incomplete work]
**Blockers:**
[Any issues needing help?]
Keep the summary concise and professional — 3 to 5 sentences.
43.5 Advanced Command Techniques
Chaining Commands
In one command, you can guide Claude to prompt the user to run the next command when finished, creating a chained workflow:
# /new-component — Create New React Component
Create a React component named `$ARGUMENTS`.
1. Under `src/components/$ARGUMENTS/`, create:
- `index.tsx` (component body)
- `$ARGUMENTS.test.tsx` (test file)
- `$ARGUMENTS.stories.tsx` (Storybook stories)
- `types.ts` (type definitions)
2. Implement a component skeleton with proper Props types and basic JSDoc
3. When done, prompt the user:
"Component created. Consider running `/review src/components/$ARGUMENTS/` for a code review."
Conditional Logic in Commands
Command files support natural-language conditional logic — Claude will adapt its behavior to the actual situation:
# /cleanup — Code Cleanup
Clean up $ARGUMENTS.
**If it is a TypeScript file:**
- Fix all TypeScript errors
- Remove unused imports
- Ensure all exported functions have type annotations
**If it is a test file:**
- Remove duplicate test cases
- Ensure each test has a clear description
- Check for commented-out tests (delete or restore them)
**If it is an entire directory:**
- First list the files in the directory
- Process them one by one in priority order
- Provide a completion summary
Using Bash Commands to Gather Context
A command file can direct Claude to run shell commands to gather information before making decisions:
# /health-check — Project Health Check
Perform a health check on the current project by collecting and analyzing:
**Code quality**
```bash
npm run lint 2>&1 | head -50
Test status
npm test -- --passWithNoTests 2>&1 | tail -20
Dependency security
npm audit --audit-level=moderate 2>&1 | head -30
TypeScript errors
npx tsc --noEmit 2>&1 | head -30
Based on the above output, provide an assessment of the project's current health and a prioritized list of issues to address.
## 43.6 Skill Reuse: Building a Team Command Library
The most powerful value of custom slash commands is **team skill sharing**. When an engineer figures out a highly effective workflow, they can encode it as a command file, commit it to the project repository, and make it available to the entire team.
### Best Practices for Building a Command Library
**1. Command naming convention**
verb-noun format: /create-component # create a component /test-api # test an API /review-pr # review a PR
single-word commands (common actions): /review # code review /debug # debugging /deploy # deployment check /migrate # database migration
**2. Document each command**
Each command file should begin with a clear header:
```markdown
# /review — Code Review
**Purpose**: Conduct a thorough code review of a specified file or directory
**Arguments**: File or directory path (optional — if omitted, reviews currently modified files)
**Examples**:
/review src/api/users.ts
/review src/components/
**Output**: Prioritized list of improvement recommendations
---
[Command content...]
3. Evolving commands over time
As the project grows, commands need updating. Record the command library's change history in CLAUDE.md and encourage team members to submit improvements when a command no longer meets their needs:
## Slash Command Guide
Project commands live in `.claude/commands/`.
Commonly used commands:
- `/feature <description>` — TDD feature development
- `/review <file>` — code review
- `/debug <problem>` — systematic debugging
If a command's workflow doesn't meet your needs, please submit a PR to improve it.
43.7 Commands and Hooks Working Together
Slash commands and hooks form a powerful partnership:
- Commands orchestrate the workflow: the
/featurecommand guides Claude through the TDD process step by step - Hooks enforce quality baselines: regardless of which command triggered a file write, post-tool hooks automatically run formatting and type checks
This layered design means:
- Commands handle the "what to do" and "how to do it" orchestration
- Hooks handle "quality floor" mechanical enforcement
Together, they form the complete engineering loop of Claude Code in production use.
Summary
Slash commands are the core tool for workflow automation in Claude Code.
Key takeaways:
- Custom commands are stored in
.claude/commands/; each.mdfile is one command $ARGUMENTSaccepts user input;@filepathinjects file content- Commands are structured prompts for Claude; they can describe complex multi-step workflows in natural language
- A practical command library covers: feature development, code review, debugging, database migrations, and more
- A team-shared command library is an effective mechanism for skill reuse and workflow standardization
- Commands and hooks are complementary: commands handle process orchestration; hooks handle quality enforcement