Home / Session 3
session-3.md — ~/hacking-with-ai
3

Plan Mode Mastery

Think before you code

45 min Plan Mode + Agent Teams Loading...
Session 3 of 8

// Overview

Plan Mode is Claude Code's superpower for complex features. Learn to use Shift+Tab to switch to read-only exploration mode, design before implementing, and leverage Agent Teams for parallel work with worktree isolation.

Learning Objectives

// Setup

Review Kafka patterns in the codebase

bash
cd my-full-app
# Review existing Kafka consumers and producers
Verify: Understand the @RetryableTopic pattern used in this codebase

// Challenge

Add rate change detection to the Kafka pipeline

30m +15m bonus

The codebase already has KafkaMessagesConsumer with @RetryableTopic and FxRatesCache. Your challenge: EXTEND it to detect significant rate movements (>1% change from cached rate) and publish alerts to a new output topic. Use ONLY prompts — no keyboard coding allowed!

✓ Success Criteria

  • Used Plan Mode to explore existing KafkaMessagesConsumer first
  • Understood FxRatesCache and how rates are currently processed
  • Extended (not recreated) the existing consumer pipeline
  • Detects >1% rate changes by comparing incoming vs cached rates
  • Publishes rate change alerts to a new Kafka topic
  • Integration test passes
  • Zero keyboard coding
⚠ Hints (click to reveal)
  • Start in Plan Mode (Shift+Tab) to explore KafkaMessagesConsumer first
  • The consumer already caches rates in FxRatesCache — compare before updating
  • Use 'run the tests' after each major change
  • Bonus: Try a 2-agent team (one implements, one writes tests) with worktree isolation — CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude
  • Run 'claude agents' to verify your agent definitions are loaded correctly

Code Playground

Interactive

Try These Prompts

Plan Mode - Explore
Explore KafkaMessagesConsumer.java. How does it process rates? What's the FxRatesCache and how does it store rates? How does @RetryableTopic work here? What happens in the DLT handler?
Press Shift+Tab first to enter Plan Mode
Expected: Claude explores the existing consumer and cache without making changes
Plan Mode - Design
Design adding rate change detection to the existing Kafka pipeline: compare incoming rates with cached rates in FxRatesCache, detect >1% movements, publish alerts to a new rate-alerts topic. Create a detailed plan that EXTENDS the existing code.
Stay in Plan Mode for the design phase
Expected: Claude creates implementation plan that extends existing consumer
Exit Plan Mode - Implement
Implement the consumer following the plan. Create all necessary classes and configuration.
Exit Plan Mode (Shift+Tab again) to allow edits
Expected: Claude implements the full solution
Verify with Tests
Write integration tests using Testcontainers that verify: happy path processing, retry on transient errors, DLT handling for permanent failures. Run all tests.
Tests verify the complete flow
Expected: Claude writes comprehensive tests and runs them

Code Examples

Rate Change Detection Extension
// EXTEND the existing KafkaMessagesConsumer — don't recreate it!
// The consumer already caches rates in FxRatesCache.
// Add rate change detection BEFORE updating the cache.

@Component
@RequiredArgsConstructor
public class RateChangeDetector {

    private static final double SIGNIFICANT_CHANGE_THRESHOLD = 0.01; // 1%
    private final FxRatesCache fxRatesCache;
    private final KafkaTemplate<String, RateChangeAlert> alertTemplate;

    /**
     * Call this from the existing consumer BEFORE updating the cache.
     * Compare incoming rate with cached rate to detect significant movements.
     */
    public void detectAndAlert(CurrencyPair pair, FxExchangeRate newRate) {
        FxExchangeRate cachedRate = fxRatesCache.getRate(pair);
        if (cachedRate == null) return; // First rate for this pair, no comparison

        double changePercent = calculateChangePercent(cachedRate, newRate);
        if (Math.abs(changePercent) > SIGNIFICANT_CHANGE_THRESHOLD) {
            var alert = new RateChangeAlert(
                pair, cachedRate, newRate, changePercent, Instant.now()
            );
            log.info("Significant rate change detected",
                kv("pair", pair),
                kv("change", String.format("%.4f%%", changePercent * 100)));
            alertTemplate.send("rate-alerts", pair.toString(), alert);
        }
    }

    private double calculateChangePercent(FxExchangeRate old, FxExchangeRate current) {
        return (current.value().doubleValue() - old.value().doubleValue())
               / old.value().doubleValue();
    }
}
Agent Definition (.claude/agents/)
# .claude/agents/backend-dev.md
---
description: Backend development specialist
isolation: worktree
background: true
tools: Read, Write, Edit, Bash
# disallowedTools: WebSearch, WebFetch
# permissionMode: default | plan | bypassPermissions
# skills: code-review, refactor
# mcpServers: my-server
# hooks: onStart, onComplete
# memory: project | user | local
# maxTurns: 50
---

You are a backend development specialist.
Focus on implementing service layer code,
database queries, and API endpoints.

# .claude/agents/test-writer.md
---
description: Test writing specialist
isolation: worktree
background: true
tools: Read, Write, Edit, Bash
---

You are a test writing specialist.
Write comprehensive unit and integration tests
following the project's testing patterns.

# Supported frontmatter fields:
# description, isolation, background, tools,
# disallowedTools, permissionMode, skills,
# mcpServers, hooks, memory, maxTurns
Plan Mode Workflow
Plan Mode Workflow
==================

1. Enter Plan Mode (Shift+Tab)
   - Claude explores but doesn't edit
   - Safe to investigate the codebase

2. Design Phase (still in Plan Mode)
   - Ask Claude to plan the implementation
   - Review and refine the plan
   - Approve or adjust

3. Exit Plan Mode (Shift+Tab)
   - Claude can now make edits
   - "Implement the plan"

4. Verify
   - "Run the tests"
   - "Show me what changed"

5. Safety Net: /rewind
   - If implementation doesn't match the plan,
     use /rewind to restore code AND conversation
     to a previous checkpoint
   - Checkpoints are created automatically
   - Pick any prior turn to roll back to

Subagents:
  Plan Mode spawns subagents for:
  - Parallel file exploration
  - Independent analysis tasks
  - Background test running

  Built-in subagent types:
  - Explore: uses Haiku, read-only tools only
  - Plan: inherits current model, read-only
  - General-purpose: all tools available

  Use Agent(agent_type) in agent defs to restrict
  which subagent types can be spawned.

  memory frontmatter field enables cross-session
  learning with scopes: user, project, local
  Agents remember patterns across conversations.

Managing Agents:
  /agents — interactive command for managing subagents
  claude agents — lists all configured agents
  (from .claude/agents/*.md files)

Agent Teams:
  Multi-agent coordination for large tasks.
  Enable: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude
  Or: claude --agent-teams
  - Lead agent delegates to specialist agents
  - Agents work in parallel on subtasks
  - Automatic message delivery between agents
  - Worktree isolation: each agent gets its own branch
  - Proof: 16-agent team wrote 100K+ line Rust C compiler

Worktree Isolation:
  ┌─ main branch ──────────────────────────┐
  │                                         │
  │  ┌─ agent-1 worktree (implement) ──┐   │
  │  │  isolated copy of repo          │   │
  │  └─────────────────────────────────┘   │
  │                                         │
  │  ┌─ agent-2 worktree (test) ───────┐   │
  │  │  isolated copy of repo          │   │
  │  └─────────────────────────────────┘   │
  │                                         │
  └─────────────────────────────────────────┘
  Flags: --worktree / -w (CLI)
         isolation: "worktree" (agent defs)
  Hook events: WorktreeCreate, WorktreeRemove

  Status line hooks include a "worktree" field with:
    name, path, branch, and original repo directory
    (available when running in a --worktree session)

Agent Hook Metadata:
  Hook events now include:
  - agent_id: identifies the subagent
  - agent_type: present for subagents and --agent
  Enables tracking and automation of agent workflows.

VS Code Plan View:
  Plans now render as full markdown documents in VS Code.
  Add comments directly on plan steps for feedback.

Background Agents:
  background: true in agent definitions
  Ctrl+F to kill background agents

CLI --agents flag:
  claude --agents '[{"name":"dev",...}]'
  Provide dynamic JSON agent definitions at runtime
  (overrides .claude/agents/ files for that session)

// Key Takeaways

// Resources

Plan Mode & Subagents Agent Teams Checkpointing & /rewind Spring Kafka @RetryableTopic