Mastering Claude Code: A Practical Guide to Advanced Slash Commands
As you work in a long-running session, the "context window" (the amount of information Claude can remember) fills up with chat history, file contents, and terminal outputs. This can lead to increased
Primary Focus
developmentAI Tools Covered
What You'll Learn
- ✓When to Use `/compact`
- ✓Practical Steps
- ✓Practical Steps
- ✓Example Workflow
- ✓Practical Steps
- ✓Example
Guide Curriculum
Managing Context with `/compact`
The tell that you need /compact isn't the clock, it's Claude re-reading a file it already saw. Here's when to compact, why proactive beats reactive, and the 2026 focus argument.
- •When to Use `/compact`12m
- •Practical Steps12m
Automated Code Review with `/review`
The `/review` command acts as your automated senior developer, scanning recent changes or specific files to identify logical errors, security vulnerabilities, or best practice violations.
- •Practical Steps12m
- •Example Workflow12m
Generating Test Suites with `/test`
Writing unit tests is crucial yet often overlooked. The `/test` command instructs Claude to analyze your code and generate test cases using your project's preferred framework, such as Pytest, Jest, or Mocha.
- •Practical Steps12m
- •Example12m
Deep Logic Analysis with `/explain`
When diving into a legacy codebase or a complex pull request, the `/explain` command is your go-to tool for rapid onboarding. It breaks down complex algorithms into human-readable steps.
- •Practical Steps12m
- •Example12m
Rapid Bug Resolution with `/fix`
The `/fix` command is a powerful tool for resolving errors. When you encounter a runtime crash or failing test, `/fix` allows Claude to analyze the error log and propose a solution.
- •Practical Steps12m
- •Example Workflow12m
Structural Optimization with `/refactor`
Technical debt can accumulate through quick fixes. The `/refactor` command helps clean up code without altering its external behavior, focusing on readability, complexity reduction, and adherence to DRY principles.
- •Practical Steps12m
- •Example12m
Documentation Automation with `/doc`
Documentation often takes a backseat in development. The `/doc` command automates the creation of docstrings, README updates, and inline comments, ensuring your codebase remains maintainable.
- •Practical Steps12m
- •Example12m
Conclusion & Next Steps
Pick one habit before the rest: /review on every push. Plus an honest note on which command names are built-in versus conventional.
- •Start With One Habit12m
The 2026 Command Expansion: 60+ Slash Commands
- •New High-Value Commands Added in 202612m
Preview: First Lesson
Managing Context with `/compact`
When to Use `/compact`
Watch the token counter, not the clock. The tell that you need /compact isn't elapsed time, it's the moment Claude starts re-reading a file it already read, or asks you something you answered twenty messages ago.
That happens because old chat history, file dumps, and long terminal outputs are still sitting in the context window, crowding out the part that matters: your current task. Run /compact when a debugging session has sprawled, or right before you pivot to a new sub-task in the same session. Proactive beats reactive. Compacting at the start of a fresh sub-task keeps reasoning sharp. Compacting after the agent has already lost the thread just preserves the confusion.
Start learning with this comprehensive guide
This guide includes:
About the Author
Hiram Clark is the founder and managing editor of vybecoding.ai and sets editorial direction for the guides and news published here. Articles are drafted with AI assistance and edited before publication. He works hands-on with the AI development tools, workflows, and infrastructure covered on the site.
Full Guide Content
Complete lesson text — start the interactive course above for exercises and progress tracking.
Module 1Managing Context with `/compact`
1.1When to Use `/compact`
Watch the token counter, not the clock. The tell that you need /compact isn't elapsed time, it's the moment Claude starts re-reading a file it already read, or asks you something you answered twenty messages ago.
That happens because old chat history, file dumps, and long terminal outputs are still sitting in the context window, crowding out the part that matters: your current task. Run /compact when a debugging session has sprawled, or right before you pivot to a new sub-task in the same session. Proactive beats reactive. Compacting at the start of a fresh sub-task keeps reasoning sharp. Compacting after the agent has already lost the thread just preserves the confusion.
1.2Practical Steps
Three moves, in order:
- Notice the drift. Repeated questions, slower replies, or the agent forgetting a constraint you set earlier are the symptoms.
- Type
/compact. It summarizes the conversation so far and prunes the non-essential history, keeping only what you need to continue. - Keep going. The session continues with a lighter context.
One genuinely useful upgrade landed in 2026: /compact now takes a focus argument. /compact focus on the auth changes tells it what to protect when it summarizes, instead of letting it guess. Use that when you know exactly which thread matters and you don't want it summarized away.
Module 2Automated Code Review with `/review`
2.1Practical Steps
Run /review before you push, not after the PR comment lands. Two ways to aim it:
- Whole diff. Bare
/reviewreads every modified file in your current git diff. This is the pre-push pass. - One file. Point it at a path when you only care about a specific change:
/review src/auth_service.py.
/review is a real, built-in Claude Code command. It is the one command in this guide that ships out of the box and is worth wiring into muscle memory. It catches the class of bug that unit tests sail right past: logic errors, missing null checks, and security holes.2.2Example Workflow
# Inside Claude Code
/review src/auth_service.py
It reads the logic and gives you specific, line-anchored callouts, not vibes:
- "Potential SQL injection at line 42. Use a parameterized query."
- "This function has eight responsibilities. Split it at the boundary between validation and persistence."
- "Missing error handling when
useris null."
The line numbers and the why are the point. A reviewer that says "looks good" teaches you nothing. One that says "line 42, parameterize this" turns a review into a lesson.
Module 3Generating Test Suites with `/test`
3.1Practical Steps
Two steps, and the second one is where the value hides:
- Point it at the file you just wrote, while the logic is still fresh in your head.
- Run
/test src/utils/math_utils.py. It detects your existing framework, Pytest, Jest, Vitest, or Mocha, and writes tests in that style instead of inventing a new convention.
The win isn't the happy-path test you'd have written anyway. It's the edge cases you forgot. Negative inputs, zero, empty collections, the None you assumed couldn't happen.
3.2Example
Take a tax helper:
def calculate_tax(price: float, rate: float) -> float:
return price * rate
/test generates the obvious cases and a couple you probably skipped:
def test_calculate_tax_standard():
assert calculate_tax(100.0, 0.08) == pytest.approx(8.0)
def test_calculate_tax_zero_rate():
assert calculate_tax(100.0, 0.0) == 0.0
def test_calculate_tax_negative_price():
# edge case. Should a refund even be allowed here?
assert calculate_tax(-50.0, 0.08) == pytest.approx(-4.0)
That last test is the one that earns its keep. It doesn't just assert behavior, it asks a design question you have to answer. Treat generated tests as a first draft you review, not gospel you commit blind.
Module 4Deep Logic Analysis with `/explain`
4.1Practical Steps
New codebase, week one. Don't read it top to bottom. Run /explain on the five files that change most often (git log --format= --name-only | sort | uniq -c | sort -rn | head gives you that list), and you'll understand the system's spine in an afternoon instead of a fortnight.
Aim it at the part that scares you: the gnarly function, the class with too many hands in it, the reducer nobody wants to touch. Ask not just what it does but what its side effects and external dependencies are.
4.2Example
/explain src/middleware/auth_validator.ts
You get a step-by-step walkthrough: how the middleware processes a request, how it validates the JWT, what it does when the token has expired, and which preconditions, if violated, blow it up. The expiration-and-failure path is usually the part the original author under-documented, so it's the part /explain earns its keep on.
You can also describe the target in plain English instead of a path: /explain the reconciliation algorithm in src/state/reducer.ts.
Module 5Rapid Bug Resolution with `/fix`
5.1Practical Steps
Capture the error verbatim first. The single biggest lever on /fix quality is feeding it the exact trace, file, and line, not a paraphrase.
- Run the failing thing. Copy the real output, the whole traceback.
- Hand it over.
/fix the AttributeError in app.py, or paste the trace inline.
/fix is the most agentic command here. It doesn't just explain the bug, it reads the trace, finds the file and line, proposes a targeted patch, and asks before writing. It won't gut your codebase to fix a typo.5.2Example Workflow
# Error: Traceback (most recent call last):
# File "app.py", line 10, in
# AttributeError: 'NoneType' object has no attribute 'get'
/fix the AttributeError in app.py
It opens app.py, traces where the variable went None, and proposes a patch that handles the missing case instead of just silencing the symptom.
The difference between a good /fix and a bad one is entirely on you. Vague in, vague out. Compare these two prompts:
- Weak:
/fix the bug - Strong:
/fix TypeError: Cannot read properties of undefined, src/api/users.ts:142
The second one tells it where to look. The first makes it guess.
Module 6Structural Optimization with `/refactor`
6.1Practical Steps
One rule before you run it: no tests, no refactor.
/refactor reshapes internal structure without changing external behavior. But "without changing behavior" is a promise only a passing test suite can keep. Run it on untested code and you've traded readable code you understand for readable code you can't verify.
- Find the smell. A function that's too long, nested four deep, or copy-pasted three times.
- Confirm there are tests covering it. If there aren't, write them first, or walk away.
- Run
/refactoron that block.
6.2Example
Take the classic nested-pyramid function:
def process(data):
if data:
if 'id' in data:
if data['status'] == 'active':
# 50 lines of nested logic
/refactor flips it into guard clauses, so the happy path lives at the top level instead of four indents deep:
def process(data):
if not data or 'id' not in data:
return
if data.get('status') != 'active':
return
# the real logic, one level deep
Same behavior, half the cognitive load. When NOT to bother: code that's about to be deleted, and code with no test coverage. Refactoring without tests is how silent regressions get shipped.
Module 7Documentation Automation with `/doc`
7.1Practical Steps
Write the docs the same hour you write the code. Three months later you'll be reconstructing intent from memory, and memory lies.
- Finish the module. Run
/doc src/utils/validators.pywhile the design is still loaded in your own head. - Read what it wrote.
/docis accurate about the what, but it can't know the why you never wrote down. Add the business context it can't infer.
7.2Example
Before:
def calculate_tax(price, rate):
return price * rate
After /doc:
def calculate_tax(price: float, rate: float) -> float:
"""
Calculates the tax amount for a given price and rate.
Args:
price: Base amount before tax.
rate: Tax rate as a decimal (e.g., 0.08 for 8%).
Returns:
The calculated tax amount.
"""
return price * rate
It infers the types, names the arguments, and gives a usable one-line summary. What it can't infer is policy: is a negative price valid, what currency, what rounding rule. Those are the lines you add by hand, because they're the lines a future reader actually needs.
Module 8Conclusion & Next Steps
8.1Start With One Habit
Pick one habit and make it stick before you reach for the rest.
If you only adopt one thing from this guide, make it /review before every push. It's a built-in command, it costs you fifteen seconds, and it catches the security and logic bugs your tests were never written to find.
After that, in rough order of payoff:
/testas your Definition of Done. No function ships without generated tests that you've read and corrected./compactat sub-task boundaries. Don't wait for the session to feel sludgy./explainon day one of any new codebase. The five hottest files, before your first PR.
A word of honesty on command names. /review, /security-review, and /compact are genuine built-in Claude Code commands. Others described as /fix, /explain, /refactor, and /doc are conventional names for tasks Claude Code does well, but on a given install they may be plain prompts rather than literal slash commands. Type / in any session to see exactly which commands your version exposes. The next module is the verified 2026 built-in list.
Module 100The 2026 Command Expansion: 60+ Slash Commands
100.2New High-Value Commands Added in 2026
The 2026 Command Expansion
Claude Code's command surface grew up in 2026, from a handful of session utilities into a full agentic toolkit. Type / in any session to see the complete list your version actually exposes. Here are the ones that pay for themselves.
/ultraplan — Cloud Planning
Hands planning off to a cloud session in plan mode while your terminal stays free. Invoke with /ultraplan migrate the auth service to JWTs or include the word ultraplan in a normal prompt. When ready, open in your browser to leave inline comments, then either execute in the cloud or Approve plan and teleport back to terminal. Requires v2.1.91+ and a GitHub repository.
/batch — Parallel Codebase Changes
A bundled Skill that decomposes codebase-wide refactors into 5–30 independent units and spawns one background agent per unit in isolated git worktrees. Each agent implements, tests, and opens a pull request. /batch migrate src/ from Solid to React.
/rewind — Selective Rollback
Opens a scrollable list of every session prompt. Select a point and choose:
- Restore code and conversation — full revert
- Restore conversation — rewind conversation, keep current code
- Restore code — revert file changes, keep conversation
- Summarize from here — compress mid-session context without reverting
Aliases: /checkpoint, /undo.
/schedule — Cloud Routines (April 14, 2026)
Creates saved Claude Code configurations (prompt + repositories + connectors) that run on Anthropic-managed cloud infrastructure. No laptop required. Trigger types: scheduled (hourly/daily/weekly), API (HTTP POST), or GitHub events (PR opened, release created). Alias: /routines. Available on Pro, Max, Team, Enterprise.
/remote-control — Steer from Any Device
Exposes your running local session to claude.ai/code, the Claude iOS app, and the Claude Android app. Start a task at your desk, continue from your phone. The session runs on your machine, so the local filesystem and MCP servers stay available. Push notifications when tasks complete (v2.1.110+). Alias: /rc.
/teleport — Pull Cloud Session to Terminal
Pulls a claude.ai/code cloud session into your local terminal. Branch and conversation are fetched down, execution continues locally. Alias: /tp.
/autofix-pr — Autonomous CI Fix Loop
Spawns a cloud session watching the current branch's PR and pushes fixes when CI fails or reviewers comment. /autofix-pr only fix lint and type errors to narrow scope.
/ultrareview — Multi-Agent Code Review
Runs a multi-agent review in a cloud sandbox on the current PR or branch diff, examining for security vulnerabilities, performance issues, and architectural concerns.
/compact with Focus Instructions
Now accepts focus instructions as an argument: /compact focus on the auth changes or /compact retain only error handling patterns. Without a focus argument, Claude decides what to summarize. Combine with /rewind → Summarize from here for surgical mid-session compression.
Roll Your Own: .claude/commands/
Here's the part most "advanced slash command" guides skip. The most valuable commands on a real project aren't the built-ins at all. They're the ones you write. Drop a Markdown file in .claude/commands/ (project scope) or ~/.claude/commands/ (user scope, shared across every project) and its filename becomes a slash command. The format is a small YAML frontmatter block, then the prompt body. A real one from this codebase looks like this:
---
description: Resumes the session from a handoff slot or lists available slots.
model: sonnet
allowed-tools: [RunShellCommand, ReadFile]
---
# Agent Handoff: Resume
I am resuming state from slot $ARGUMENTS.
!./scripts/agent-handoff.sh load "$ARGUMENTS"
Three things to notice, all of which I confirmed by reading live command files on disk:
$ARGUMENTSis substituted with whatever you type after the command, so/r 3passes3in.- A line beginning with
!runs as a shell command and its output is injected into the prompt before Claude reads it. allowed-toolsscopes what the command may touch, andmodel:can pin a cheaper model for routine commands.
For multi-step capabilities, the heavier sibling is a Skill: a directory under .claude/skills/ containing a SKILL.md with name, description, and allowed-tools frontmatter, optionally pointing at a longer workflow.md. The skills in this project's .claude/skills/ directory, things like /content, /deploy, and /critic, are exactly that. Built-ins get you started. Custom commands and skills are where a team's actual workflow lives.
Quick Reference
| Command | What it does |
|---|---|
| /btw | Side question without adding to conversation history |
| /context | Visualize context usage with optimization suggestions |
| /effort [level] | Set model effort: low, medium, high, xhigh, max |
| /sandbox | Toggle sandbox mode |
| /recap | One-line session summary on demand |
| /security-review | Analyze changes for injection, auth, data exposure risks |
| /loop [interval] [prompt] | Repeat a prompt on a recurring interval |
| /diff | Interactive diff viewer for uncommitted changes |