Danila (Dayfing)
Back to writing
1,794 words9 min

Claude Code hooks, subagents, and worktrees for reliable workflows

Repository instructions in CLAUDE.md or AGENTS.md are useful onboarding notes for a model, yet they remain advisory text inside a prompt window rather than an enforceable runtime boundary. As a coding session grows through file reads, tool logs, and context compaction, or when an untrusted issue description enters the conversation, a model can skip a formatting check or propose an unsafe shell command despite clear written rules. Treating agent workflows as software systems means moving safety checks, verification loops, and task isolation out of prose and into deterministic lifecycle hooks, scoped subagents, and isolated Git worktrees.

This architecture builds on the control-plane model outlined in agentic coding workflows and complements the instruction structure described in AGENTS.md for coding agents. Instead of asking the model to remember every constraint on every turn, the local runtime enforces invariants around tool execution, delegates noisy research to disposable contexts, and isolates concurrent edits at the filesystem level.

Why prompt instructions fail as policy gates

Advisory rules compete with everything else inside the context window. When an agent investigates a failing test suite across twenty files, stack traces and search output push earlier instructions further from the most recent tokens. Even without malicious input, long multi-step tasks create instruction drift where the agent skips running tsc before reporting completion or runs a broad git clean command to clear untracked build artifacts.

Permission prompts alone do not solve this gap efficiently. Clicking approve on every shell invocation breaks flow and trains engineers to accept commands without reading flags, while blanket allowlists leave destructive subcommands exposed. Lifecycle hooks documented in the Claude Code hooks reference sit directly between the model's tool intent and operating-system execution, evaluating structured JSON payloads deterministically in code before or after tools run.

Control layer Enforcement timing Can block execution Context cost Primary role in production
CLAUDE.md and AGENTS.md Prompt assembly No Medium, grows with file size Architecture norms, test commands, naming rules
Permission allow and deny rules Tool dispatch Yes Negligible Coarse tool, path, and command boundaries
PreToolUse hook Before tool executes Yes Low Regex or AST checks on commands, path protection
PostToolUse hook After tool succeeds Feeds back errors Low to medium Targeted typechecks, lints, output redaction
Stop and SubagentStop hooks Before turn finishes Yes, up to loop cap Low Final test gate and dirty-tree verification
Subagent with isolation: worktree Separate agent process Isolates filesystem Isolated from main thread Parallel feature work and conflict-free builds

Deterministic guardrails with PreToolUse, PostToolUse, and Stop

Claude Code exposes lifecycle events that receive JSON on standard input and return structured JSON decisions on standard output. Three events cover most engineering guardrails: PreToolUse validates arguments before side effects happen, PostToolUse verifies modified files immediately after edits, and Stop checks repository invariants before the agent hands control back to the developer.

Blocking destructive commands in PreToolUse

A PreToolUse hook fires before a matched tool executes. Using a "matcher" alongside an optional "if" condition narrows execution so the hook script only spawns on relevant calls rather than slowing down every file read. In .claude/settings.json, you can wire a shell guard that intercepts Bash commands matching rm * or git * and inspects the full command string:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(rm *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-bash.sh"
          },
          {
            "type": "command",
            "if": "Bash(git *)",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-bash.sh"
          }
        ]
      }
    ]
  }
}

Inside .claude/hooks/guard-bash.sh, parse .tool_input.command with jq and emit hookSpecificOutput with permissionDecision: "deny" when a forbidden pattern appears. Returning exit code 0 with no JSON falls through to the normal permission flow:

#!/usr/bin/env bash
set -euo pipefail

COMMAND=$(jq -r '.tool_input.command // ""')

if printf '%s' "$COMMAND" | grep -Eq '(^|[;&|[:space:]])(rm[[:space:]]+-rf|git[[:space:]]+push[[:space:]]+(--force|-f)|git[[:space:]]+reset[[:space:]]+--hard)'; then
  jq -n --arg reason "Blocked destructive shell pattern by repository PreToolUse policy" '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: $reason
    }
  }'
  exit 0
fi

exit 0

Apply the same pattern to Edit|Write matchers to protect sensitive paths such as .env*, .claude/settings.json, .claude/hooks/, or production deployment manifests. Because the hook runs outside the model's reasoning loop, no amount of prompt persuasion can override the deny verdict.

Running targeted checks in PostToolUse

Waiting until the end of a twenty-file refactor to run a typechecker forces the model to untangle cascading errors across unrelated modules. A PostToolUse hook attached to "Edit|Write" receives tool_input.file_path and tool_response immediately after disk changes land. Keeping the script fast and scoped to the touched package prevents latency drag:

#!/usr/bin/env bash
set -euo pipefail

FILE_PATH=$(jq -r '.tool_input.file_path // ""')

case "$FILE_PATH" in
  *.ts|*.tsx)
    OUTPUT=$(npx tsc --noEmit --pretty false 2>&1) || {
      jq -n --arg ctx "Typecheck failed after editing $FILE_PATH:\n$OUTPUT" '{
        decision: "block",
        reason: $ctx
      }'
      exit 0
    }
    ;;
esac

exit 0

When the typecheck fails, returning decision: "block" with reason feeds the compiler diagnostics directly into the next model step while the edited file is still fresh in context. The PostToolUse response also supports hookSpecificOutput.updatedToolOutput for redacting noisy logs or accidental secret prints on built-in and MCP tools, though note that the command has already executed before PostToolUse fires. Use PreToolUse to prevent leaks, and use PostToolUse for immediate verification or context hygiene.

Enforcing completion gates in Stop hooks

Agents frequently summarize work as complete when one edge-case test remains unrun. A Stop hook evaluates the session right as Claude prepares to end its turn. Its JSON payload includes stop_hook_active, last_assistant_message, background_tasks, and session_crons. Checking stop_hook_active is mandatory so a persistent failure does not trap the session in an infinite continuation loop, alongside Claude Code's built-in cap of eight consecutive stop-hook continuations:

#!/usr/bin/env bash
set -euo pipefail

INPUT=$(cat)
STOP_ACTIVE=$(printf '%s' "$INPUT" | jq -r '.stop_hook_active // false')
PENDING_BG=$(printf '%s' "$INPUT" | jq -r '(.background_tasks // []) | length')

if [ "$STOP_ACTIVE" = "true" ] || [ "$PENDING_BG" -gt 0 ]; then
  exit 0
fi

if ! git diff --quiet -- src/; then
  if ! npm test -- --runInBand >/tmp/claude-stop-test.log 2>&1; then
    TAIL=$(tail -n 30 /tmp/claude-stop-test.log)
    jq -n --arg msg "Targeted tests failed before handoff:\n$TAIL" '{
      hookSpecificOutput: {
        hookEventName: "Stop",
        additionalContext: $msg
      }
    }'
  fi
fi

Using hookSpecificOutput.additionalContext rather than an error exit keeps the transcript clean while prompting the agent to inspect and repair the failing suite before finishing. Check background_tasks as shown above so the hook does not trigger premature test runs while background subagents or shell watchers are still running.

Isolating research and parallel tasks in subagents

Main conversation context is a scarce shared buffer. When the primary agent greps through hundreds of files, reads generated schema dumps, or inspects lengthy CI logs, those tokens stay in conversation history and degrade later reasoning quality. The Claude Code subagents documentation addresses this directly by running subagents in separate context windows with custom system prompts, explicit tool allowlists, and independent turn budgets.

Store project-level subagents in .claude/agents/*.md and personal reusable agents in ~/.claude/agents/*.md. Each file uses YAML frontmatter for configuration followed by the system prompt body. Two design rules keep subagent catalogs fast and safe: keep the description field concise because Claude Code warns when combined custom agent descriptions exceed 15,000 tokens, and grant each worker only the tools its role requires.

Here is a read-only security and architecture reviewer configured to run on a faster, lower-cost model without write access:

---
name: security-reviewer
description: Audits staged diffs and changed modules for auth, SQL, and secret leaks without modifying files.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: sonnet
permissionMode: plan
maxTurns: 15
---

Inspect the target files or git diff in read-only mode. Report concrete line numbers, reproduction paths, and missing validation checks. Never propose speculative refactors outside the changed surface.

Separating read-only triage (Explore, Plan, or a custom reviewer) from implementation means raw search results and file dumps never enter the main thread. The subagent digests the evidence and returns a compact summary of exact paths, symbol names, and constraints.

Combining Git worktrees with scoped permissions

Running two editing agents inside the same working directory causes immediate collisions: git status mixes unrelated diffs, package managers race on lockfiles, and one agent's test build overwrites another's output directory. Setting isolation: worktree in a subagent definition, or launching sessions with --worktree, gives each parallel worker an independent linked Git worktree and branch.

---
name: module-implementer
description: Implements isolated feature slices inside a dedicated Git worktree and runs unit tests.
tools: Read, Edit, Write, Grep, Glob, Bash
model: sonnet
isolation: worktree
maxTurns: 30
---

Implement only the assigned module and its unit tests inside your assigned worktree. Run the targeted test command before returning the branch name and changed file list.

Claude Code enforces two runtime checks when worktree isolation is active. First, Bash and PowerShell commands must resolve their working directory inside the assigned worktree rather than the main checkout; commands that escape fail with an error. Second, for Bash, Claude Code inspects command text and blocks git redirects or runtime-computed command invocations that cannot be proven to stay within the isolated tree. Combine isolation: worktree with WorktreeCreate and WorktreeRemove hooks when repositories need extra bootstrap steps such as copying untracked .env.test templates or linking cached build artifacts.

Keep permissions scoped per role even inside a worktree. An implementer needs Edit, Write, and scoped test commands, not network deployment keys or global package writes. Pair worktree subagents with a dedicated read-only reviewer subagent after each slice finishes, then merge branches sequentially once tests pass.

Defending against untrusted repositories and MCP injection

Code repositories and external tools are active attack surfaces. A cloned third-party repository can embed instructions inside a README.md, test fixture, pull request comment, or MCP server response telling an agent to read ~/.ssh/id_rsa, print environment tokens, or rewrite .claude/hooks/ to bypass future checks. The threat model and mitigation principles in prompt injection and MCP security apply directly to local coding agents.

Enforce three structural boundaries before opening an unfamiliar codebase or enabling external MCP integrations:

  1. Audit .claude/settings.json, .claude/hooks/, .claude/agents/, and .mcp.json before trusting a repository, because project-scoped hooks execute local binaries automatically on matching events. Note that plugin-distributed subagents intentionally ignore hooks, mcpServers, and permissionMode frontmatter fields to prevent untrusted plugins from escalating privileges.
  2. Block writes to configuration and hook paths inside your global ~/.claude/settings.json PreToolUse rules so a repository prompt injection cannot self-modify guardrails mid-session.
  3. Isolate untrusted builds and test execution inside disposable containers or locked-down build hosts hardened according to Linux VPS hardening practices, without mounting personal credentials, cloud tokens, or production SSH keys into the agent's environment.

Advisory prompts tell an agent what good engineering looks like; hooks, subagent boundaries, and Git worktrees make sure the workflow holds even when context drifts or inputs turn hostile.

More