DEV Community

Vibehackers
Vibehackers

Posted on • Originally published at vibehackers.io

Claude Code Hooks, Subagents & Power Features: The Complete Guide (2026)

Most people use Claude Code like a chatbot. Type a question, get an answer, type another question. That's maybe 20% of what it can do.

The other 80% -- hooks, subagents, custom slash commands, memory, auto mode -- is where it stops being a chatbot and starts being an autonomous coding partner. One that enforces your standards automatically, runs parallel workers on different parts of your codebase, remembers your project across sessions, and operates with minimal hand-holding.

We've been deep in these features since they shipped, and this is the guide we wish we had when we started. No docs rewriting. Just the practical stuff that actually changes how you work.

Claude Code Hooks: Automate Everything

Here's the fundamental problem with CLAUDE.md instructions: they're advisory. Claude follows them roughly 80% of the time. That's fine for coding style preferences. It's not fine for "never force-push to main" or "always run the linter after editing."

Claude Code hooks solve this. They're deterministic -- they execute 100% of the time, no exceptions. If something must happen every time, make it a hook.

What Hooks Actually Are

Hooks are user-defined actions that fire automatically at specific points in Claude Code's lifecycle. Think of them as git hooks, but for your AI coding agent. They can be shell commands, HTTP endpoints, LLM prompts, or even subagent invocations.

The lifecycle events you can hook into:

  • Session-level: SessionStart, SessionEnd
  • Per-turn: UserPromptSubmit -> PreToolUse -> PermissionRequest -> PostToolUse / PostToolUseFailure -> Stop
  • Async: FileChanged, CwdChanged, ConfigChange
  • Agent team: SubagentStart, SubagentStop, TaskCreated, TaskCompleted
  • Other: PreCompact, PostCompact, WorktreeCreate, WorktreeRemove

The Four Handler Types

1. Command hooks -- Run a shell script. Receives JSON event data via stdin. Exit code 0 means success, exit code 2 blocks the action, anything else is a non-blocking warning.

2. HTTP hooks -- POST event data to a URL. Great for integrating with external services, CI systems, or dashboards.

3. Prompt hooks -- Single-turn LLM evaluation. Returns yes/no. Useful for fuzzy checks that can't be done with a shell script.

4. Agent hooks -- Spawns a subagent with tool access (Read, Grep, Glob, etc.). The heavy artillery for complex validation.

Real Hook Examples

Block destructive git commands:

This is the hook everyone should set up first. Put this in your .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": ".claude/hooks/block-destructive.sh"
      }]
    }]
  }
}
Enter fullscreen mode Exit fullscreen mode

The script reads the command from stdin and blocks anything dangerous -- git push --force, git reset --hard, rm -rf, whatever you want to protect against. Exit code 2 stops Claude dead.

Auto-lint after every file edit:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": ".claude/hooks/lint-check.sh",
        "timeout": 600,
        "statusMessage": "Running linter..."
      }]
    }]
  }
}
Enter fullscreen mode Exit fullscreen mode

The Edit|Write matcher fires after any file modification. Your lint script runs, and if it fails, Claude sees the error and fixes it immediately. No more "oh I forgot to run the linter" commits.

Environment setup on directory change:

{
  "hooks": {
    "CwdChanged": [{
      "hooks": [{
        "type": "command",
        "command": ".claude/hooks/env-setup.sh"
      }]
    }]
  }
}
Enter fullscreen mode Exit fullscreen mode

The hook script can use $CLAUDE_ENV_FILE to persist environment variables across the session -- write export statements to it and they stick.

Where Hooks Live

Location Scope Shared?
~/.claude/settings.json All your projects No
.claude/settings.json This project Yes (via git)
.claude/settings.local.json This project No
Managed policy settings Organization-wide Yes
Skill/Agent frontmatter Component lifetime Depends

The decision tree is simple: team-wide rules go in .claude/settings.json (committed to git). Personal preferences go in settings.local.json or your user-level settings. Organization policies go in managed settings.

Claude Code Subagents: Parallel Workers

Subagents are where Claude Code becomes genuinely multi-threaded. Instead of one agent doing everything sequentially, you get specialized workers that handle tasks in parallel, each with their own clean context window.

The key insight: when a subagent processes a task, all the verbose intermediate work (test output, search results, log parsing) stays inside the subagent's context. Only the summary returns to the parent. Your main conversation stays clean and focused.

Built-in Subagents

Agent Model Tools What It Does
Explore Haiku (fast) Read-only File discovery, code search, codebase exploration
Plan Inherits Read-only Research for plan mode
General-purpose Inherits All tools Complex multi-step operations
Bash Inherits Terminal only Running commands in separate context
Claude Code Guide Haiku None Answering questions about Claude Code itself

The Explore agent supports thoroughness levels: quick, medium, or very thorough. For large codebases, this alone saves you minutes of waiting.

Creating Custom Subagents

This is where it gets powerful. Create a .claude/agents/code-reviewer.md file:

---
name: code-reviewer
description: Reviews code for quality, security, and best practices
tools: Read, Glob, Grep
model: sonnet
maxTurns: 10
memory: project
---

You are a code reviewer. Analyze the provided code and give specific,
actionable feedback. Focus on:
- Security vulnerabilities
- Performance issues
- Error handling gaps
- Naming and readability

Be direct. Skip the compliments.
Enter fullscreen mode Exit fullscreen mode

That's it. Claude will now delegate code review tasks to this agent automatically when it matches the description. Or you can invoke it explicitly with @"code-reviewer (agent)" review the auth changes.

Key Frontmatter Options

The model field lets you pick the right tool for the job -- use haiku for fast read-only tasks, sonnet for balanced work, opus for hard problems. The permissionMode field controls how much autonomy the subagent gets (default, acceptEdits, dontAsk, bypassPermissions). The background field set to true runs it concurrently without blocking your main conversation.

Foreground vs Background

  • Foreground: Blocks your main conversation. Permission prompts pass through to you. Use for tasks where you need oversight.
  • Background: Runs concurrently. Pre-approves permissions before launch. Auto-denies anything not pre-approved. Use for independent tasks.

Press Ctrl+B to background a running task on the fly. Useful when you realize a task is going to take a while and you want to keep working.

Parallel Execution

Issue multiple subagent tasks in a single message and they run concurrently. For example: "Review the auth module for security issues, run the test suite for the API layer, and check the database migration for breaking changes" -- three subagents, running simultaneously, each with clean context.

For sustained parallelism across a large codebase, use Agent Teams instead -- one session acts as team lead, coordinating teammates who each work in their own 200K-token context window.

Claude Code Slash Commands: The Complete Cheatsheet

Claude Code has 50+ built-in commands. You don't need to memorize all of them. Here are the ones that actually matter:

Essential Commands

Command What It Does
/compact [instructions] Compress conversation, optionally focusing on specific topics
/clear Nuke conversation history and start fresh
/model [model] Switch models mid-session
/cost See token usage and spend
/diff Interactive diff viewer for all changes in the session
/rewind Revert conversation and code to a previous checkpoint
/plan [description] Enter plan mode (read-only research before execution)
/context Visualize context usage as a colored grid
/memory Browse and edit CLAUDE.md and auto-memory files
/permissions View and update permission rules
/export [filename] Export the conversation as plain text
/resume [session] Pick up where you left off in a previous session

Hidden Gems Most People Miss

Command Why It Matters
/btw <question> Ask a quick side question -- uses full context but no tools, and the answer gets discarded from history. Perfect for "btw, what does this function do?" without polluting your conversation.
`/effort [low\ medium\
{% raw %}`/fast [on\ off]`
/batch <instruction> The big one. Spawns parallel background agents in isolated git worktrees, each handling one unit of work, each opening its own PR. For large-scale refactors across many files.
/loop [interval] <prompt> Run a prompt repeatedly on a timer. /loop 5m check if the deploy finished. Session-scoped, auto-expires after 3 days.
/branch [name] Fork the conversation at the current point. Great for exploring two approaches without losing either.
/security-review Analyze your branch changes for security vulnerabilities before you merge.
/remote-control Make your local session available from claude.ai, iOS, or Android. Control your coding agent from your phone.
/insights Generate a report analyzing your usage patterns. Find out where your time goes.
/voice Push-to-talk voice input, tuned for coding vocabulary.

Custom Slash Commands (Skills)

You can create your own slash commands. The old .claude/commands/ system has been merged into skills. Create a file at .claude/skills/deploy/SKILL.md:

---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
allowed-tools: Bash(gh *)
---

Deploy $ARGUMENTS to production:
1. Run the test suite
2. Build the application
3. Push to the deployment target
Enter fullscreen mode Exit fullscreen mode

Now /deploy staging is a command. The disable-model-invocation: true flag means only you can trigger it -- Claude won't accidentally deploy during a normal conversation.

Skills support dynamic context injection too. Wrap shell commands in !`command` and the output gets injected before Claude sees the prompt:

---
name: pr-summary
---
- PR diff: !`gh pr diff`
- Changed files: !`gh pr diff --name-only`

Summarize this PR for the team.
Enter fullscreen mode Exit fullscreen mode

Skill locations follow the same pattern as everything else: ~/.claude/skills/ for global, .claude/skills/ for project-level.

Claude Code Memory: How It Remembers Your Project

Claude Code has two memory systems that work together. Understanding both -- and what goes where -- is one of the biggest Claude Code best practices for getting consistent results.

CLAUDE.md: The Instructions You Write

CLAUDE.md is the file where you tell Claude how to work in your project. It's loaded at the start of every session. Think of it as the onboarding doc you'd give a new developer.

The hierarchy:

Scope Location Who Sees It
Managed policy /Library/Application Support/ClaudeCode/CLAUDE.md (macOS) All org users
Project ./CLAUDE.md or ./.claude/CLAUDE.md Team (via git)
User ~/.claude/CLAUDE.md Just you

Files in your directory hierarchy above the working directory load in full at launch. Files in subdirectories load on demand when Claude reads files there.

What to put in CLAUDE.md:

  • Build and test commands (things Claude can't infer)
  • Code style conventions
  • Project architecture and file organization
  • Git workflow rules
  • Common workflows

What NOT to put in CLAUDE.md:

  • Things Claude already does correctly (every unnecessary line dilutes the ones that matter)
  • Vague guidance ("be careful" adds nothing)
  • Anything that must happen 100% of the time (make it a hook instead)

The budget is real: Keep it under 200 lines per file. Claude's compliance drops noticeably past 150-200 instructions. Use the @path/to/file import syntax to pull in additional files without bloating the main CLAUDE.md. HTML comments are stripped before injection, so you can leave notes for humans without wasting tokens.

Auto Memory: What Claude Writes For Itself

Auto memory lets Claude accumulate knowledge across sessions without you writing anything. As Claude works, it saves notes: build commands that worked, debugging insights, discovered preferences.

Where it lives: ~/.claude/projects/<project>/memory/

~/.claude/projects/<project>/memory/
  MEMORY.md          # Index file (first 200 lines loaded every session)
  debugging.md       # Topic file (loaded on demand)
  api-conventions.md # Topic file (loaded on demand)
Enter fullscreen mode Exit fullscreen mode

The first 200 lines of MEMORY.md (or 25KB, whichever comes first) load at session start. Topic files load on demand when Claude needs them.

Between sessions, an AutoDream process runs automatically -- pruning stale entries, merging related info, and refreshing to reflect the current project state. It's like memory consolidation during sleep.

Manage it with /memory to browse files and toggle auto-memory on/off. Or disable it entirely with autoMemoryEnabled: false in settings.

Subagents can maintain their own persistent memory too, via the memory frontmatter field -- scoped to user, project, or local.

Auto Mode: The Middle Ground

There's always been a tension in Claude Code's permission model. The default mode asks you to approve every file edit, every command, every action. It's safe but slow -- you end up mashing Enter through approvals. The alternative, --dangerously-skip-permissions, removes all guardrails. Fast but terrifying.

Auto mode, announced March 24, 2026, splits the difference.

How It Works

Before each tool call, an internal safety classifier evaluates the action:

  • Safe actions (reading files, writing code, running tests): proceed automatically, no approval needed.
  • Risky actions (mass file deletion, data exfiltration, malicious code execution): blocked entirely. Claude gets redirected to a different approach.

You don't configure the categories. The classifier handles it. Anthropic is upfront about limitations: it may occasionally allow ambiguous actions or block benign ones. There's a small impact on token consumption and latency.

How to Enable

CLI: claude --enable-auto-mode, then cycle to it using Shift+Tab during a session.

Desktop/VS Code: Toggle in Settings, then select from the permission mode dropdown.

Currently available as a research preview on the Team plan, with Enterprise and API support coming soon. Anthropic recommends using it in isolated environments (containers, VMs, worktrees) for maximum safety.

When to Use What

  • Default mode: When you're learning, or working on sensitive production code and want oversight on every change.
  • Auto mode: Daily development work. You trust the agent but want guardrails against catastrophic mistakes.
  • --dangerously-skip-permissions: Isolated CI environments, throwaway branches, or when you truly don't care. Never on production.

Claude Code Tips: 10 Things Most People Miss

Rapid-fire practical stuff. Each of these individually saves you time. Together they compound.

1. /compact with focus instructions. Don't just compact blindly. Run /compact focus on the auth refactor and database changes to tell Claude what to preserve when it compresses context. The difference in continuity is dramatic.

2. Git worktrees for parallel agents. claude --worktree feature-x (or -w feature-x) creates an isolated working copy. Run multiple Claude Code sessions against the same repo without file conflicts. The /batch skill uses this automatically.

3. /effort max for hard problems. This unlocks extended thinking on Opus 4.6. Architecture decisions, complex debugging, multi-file refactors -- throw max at them. The thinking quality difference is real.

4. /fast for quick tasks. Toggle fast mode when you need a quick answer or simple edit. Don't waste Opus-level thinking on "rename this variable."

5. MCP Tool Search auto-activates. When your loaded tool definitions exceed 10% of context (common if you use multiple MCP servers), Tool Search kicks in automatically. It reduces token overhead by 85% by only loading tool schemas when they're actually needed.

6. /remote-control from your phone. Run /rc, scan the QR code, and control your local Claude Code session from claude.ai or the mobile app. Your files never leave your machine -- only chat messages and tool results flow through an encrypted bridge.

7. /loop for monitoring. /loop 5m check if the deploy finished and notify me. /loop 1h summarize new errors in the log. Session-scoped, max 50 tasks, auto-expires after 3 days. Fires between your turns.

8. /batch for large-scale changes. When you need the same change across 20 files or 10 services, /batch spawns one background agent per unit of work, each in an isolated git worktree, each opening its own PR. This is the Claude Code workflow for large refactors.

9. Voice dictation works. /voice enables push-to-talk. Hold spacebar to speak, release to send. The transcription is tuned for coding vocabulary -- it handles "regex," "OAuth," "localhost," and function names surprisingly well. Mix voice and typing in the same message.

10. /insights reveals your patterns. Generate a report analyzing your Claude Code usage. Find out which tasks eat the most tokens, which workflows are most efficient, and where you're wasting time. Data-driven improvement for your AI-assisted coding workflow.

The Ideal Claude Code Workflow

Here's how all these pieces fit together into a coherent Claude Code workflow:

Start with CLAUDE.md. Set up your project instructions -- build commands, architecture notes, coding standards. Keep it under 200 lines. Use imports for anything beyond that. Run /init if you're starting fresh.

Add hooks for the non-negotiables. Linting after every edit. Blocking destructive git commands. Environment setup on directory change. Anything that must happen 100% of the time is a hook, not an instruction.

Create subagents for repeated tasks. Code review, test writing, documentation -- if you delegate the same type of work repeatedly, make it a subagent with the right model, tools, and instructions. They run in clean context and return summaries.

Build custom slash commands for your workflows. /deploy, /pr-summary, /release-notes -- whatever your team does repeatedly. Skills with disable-model-invocation: true for dangerous operations so Claude can't trigger them accidentally.

Let auto memory handle the rest. As Claude works in your project, it learns: which build commands work, what debugging approaches succeed, your implicit preferences. This accumulates across sessions automatically.

Use auto mode for flow. Once you trust your hooks and subagents, auto mode lets you stay in flow without mashing Enter through approvals. The safety classifier catches the genuinely dangerous stuff.

Go parallel when scale demands it. Git worktrees (-w flag) for running multiple sessions. /batch for large-scale changes. Subagents for concurrent tasks within a session. Agent Teams for complex multi-part projects.

The through-line is this: Claude Code's power features exist to move you from "human approving every action" to "human setting policy, AI executing within guardrails." Hooks enforce the rules. Subagents handle the delegation. Memory provides continuity. Auto mode removes the friction.

That's not a chatbot. That's a coding partner.


For more on Claude Code pricing and plans, see our Claude Code pricing guide. For context engineering fundamentals, check our context engineering guide. And for how it compares to the competition, read Claude Code vs Codex.

Top comments (0)