Why Token-Aware Planning Transforms Claude Code Results

By , Senior Full-Stack EngineerUpdated 12 min read

Boris Cherny, the creator of Claude Code, shared his workflow in late 2025: "If my goal is to write a Pull Request, I will use Plan mode, and go back and forth with Claude until I like its plan. From there, I switch into auto-accept edits mode and Claude can usually 1-shot it."

This approach produces exceptional results when I use it. But for complex features, I kept running into the same problem: Claude's context window would exhaust mid-implementation, leaving me with half-finished code and lost momentum. The plan was good, but the execution fell apart when the feature was too large for a single session.

So I built the ai-workflow plugin to systematize what Boris describes, with one critical addition: token-aware phase sizing. Instead of creating monolithic plans that overwhelm Claude's context, the plugin breaks features into properly-sized phases, each targeting 30-50k tokens. The result? Complex features that previously stalled mid-implementation now complete thoroughly, with consistent quality from start to finish. Throughout this blog, I'll use the OAuth integration I built for AccessHawk as the running example.

The Problem: Great Plans, Exhausted Context

Claude Code is remarkably capable at implementing features when given clear direction. The challenge isn't Claude's ability to write code. It's managing the finite context window during complex implementations.

What Happens Without Phase Planning

Here's a scenario every Claude Code user recognizes:

  1. You describe a complex feature (authentication, payment integration, multi-step workflow)
  2. Claude creates a solid implementation plan covering all the pieces
  3. Claude starts implementing, making great progress on the first few components
  4. Around 60-70% completion, context fills up with code, file reads, and tool outputs
  5. Claude's responses become shallow, missing edge cases it would normally catch
  6. You either start a new session (losing context) or push through with degraded quality
  7. The final 30% requires significant manual intervention or multiple follow-up sessions

The plan was correct. The implementation started strong. But the feature was simply too large for a single context window to handle effectively.

The Context Window Reality

Claude's context window is large but not infinite. Every file read, every tool call, every code block written consumes tokens. A typical feature implementation involves:

  • Codebase exploration: Reading existing files to understand patterns (5-20k tokens)
  • Planning discussion: Back-and-forth refinement of approach (3-10k tokens)
  • Implementation: Writing code, running tests, fixing issues (30-100k+ tokens)
  • Verification: Testing, debugging, iterating (10-30k tokens)

For a substantial feature, you're easily looking at 80-150k tokens of context usage. When you hit the ceiling, quality degrades. Claude starts forgetting earlier decisions, missing patterns it established, and producing inconsistent code.

The Solution: Properly-Sized Phases

The ai-workflow plugin solves this by introducing token-aware phase planning. Instead of one massive implementation session, features are broken into phases that each fit comfortably within Claude's context window.

Honorable mention to claude-mem, which addresses context continuity by carrying memory across sessions. It's a clever approach, but the MCP tool descriptions still consume initial context, and you're still working within a single session's limits. Token-aware phase planning takes a different approach: instead of preserving context, it structures work so each phase starts fresh with full capacity, leading to more consistent quality throughout complex implementations.

What Makes a Phase 'Properly-Sized'

The plugin targets 30-50k tokens per phase. This range isn't arbitrary. It accounts for:

  • Sub-agent overhead: Each phase runs in a fresh sub-agent with its own context
  • File reading: Understanding existing code before making changes
  • Implementation headroom: Space for iteration, debugging, and refinement
  • Quality buffer: Keeping context usage well below limits preserves response quality

A phase should be substantial enough to represent meaningful progress, but constrained enough that Claude can complete it thoroughly without degradation.

Phase Characteristics

Each phase in a well-structured plan includes:

  • Clear goal: What this phase accomplishes in concrete terms
  • Specific tasks: The individual implementation steps required
  • Acceptance criteria: How to verify the phase is complete
  • Files to modify: Explicit list of files that will be created or changed
  • Dependencies: Which phases must complete before this one can start
## Phase 2: OAuth Handlers & User Linking

**Goal**: Implement provider handlers with auto-linking logic.

### Tasks

1. Create OAuth route handlers for each provider
2. Implement user linking logic (find by provider ID or email match)
3. Handle OAuth success flow with session creation
4. Add error handling for denial, missing email, rate limits

### Acceptance Criteria

- [ ] OAuth flows work end-to-end for all providers
- [ ] Existing users auto-link by email match
- [ ] New users created with profile data from provider
- [ ] Sessions created using existing session system
- [ ] Error cases handled gracefully

### Files to Create/Modify

- `server/routes/auth/github.get.ts` (new)
- `server/routes/auth/google.get.ts` (new)
- `server/utils/oauth.ts` (new)
- `server/utils/auth.ts` (add OAuth session helper)

Notice the specificity. Claude doesn't have to figure out what files to touch or what success looks like. Every phase is self-contained and actionable.

The Three-Command Workflow

The ai-workflow plugin provides three commands that cover the complete development lifecycle: planning, implementation, and verification.

/workflow-plan-phases: Structured Planning

This command transforms feature descriptions into implementation roadmaps. It starts by asking clarifying questions to understand requirements, then breaks work into appropriately-sized phases.

What it produces:
  • Phases targeting 30-50k tokens each
  • Clear acceptance criteria per phase
  • Dependency mapping between phases
  • Execution strategy recommendations (parallel, sequential, or mixed)
  • Estimated token usage per phase

The output is a structured markdown document saved to docs/plans/ that serves as the implementation blueprint.

# Describe your feature in detail, then invoke the command
/workflow-plan-phases Add GitHub and Google OAuth to my Nuxt app.
I already have passwordless OTP auth with sessions stored in MongoDB.
OAuth should integrate with existing sessions, not replace them.
Auto-link accounts when emails match. Import avatar and name from providers.
Add OAuth buttons to login, signup, and allow connecting/disconnecting in settings.

# Claude asks clarifying questions:
# - Should OAuth-only users be able to change their email?
# - What happens if a user tries to disconnect their only auth method?
# - Should we import profile data on every login or just the first?

# After discussion, Claude generates:
# docs/plans/oauth-implementation.md
# - Phase 1: Infrastructure & Schema (est. 25k tokens)
# - Phase 2: OAuth Handlers & Linking (est. 35k tokens)
# - Phase 3: Settings UI & Account Management (est. 30k tokens)
# - Phase 4: Login/Signup Integration (est. 25k tokens)
# - Phase 5: Testing & Documentation (est. 30k tokens)

/workflow-implement-phases: Orchestrated Execution

Before running this command, read through the entire plan that /workflow-plan-phases created. Use Claude Code to iterate on the plan: refine phase boundaries, clarify acceptance criteria, correct any inaccuracies, and remove anything that doesn't fit your requirements. The plan is a markdown file, so you have full control to shape it before execution.

Once you have an approved plan, this command orchestrates the implementation. It parses the plan document, analyzes dependencies, and executes phases using sub-agents.

Execution strategies:
  • Parallel: Independent phases run simultaneously for maximum speed
  • Sequential: Linear dependencies execute one after another
  • Mixed: Complex dependency graphs use optimal combination of both
Graceful failure handling:

If a phase fails, the orchestrator skips dependent phases while continuing independent work. You don't lose progress on unrelated phases because one component hit an issue.

# Execute the plan
/workflow-implement-phases docs/plans/oauth-implementation.md

# Claude analyzes dependencies:
# Phase 1 → Phase 2 → Phase 3 (Settings)
#                  → Phase 4 (Login UI)
#        → Phase 5 (depends on all)

# Execution begins:
# [Phase 1] Starting: Infrastructure & Schema...
# [Phase 1] Complete: Schema updated, indexes created
# [Phase 2] Starting: OAuth Handlers & Linking...
# [Phase 3] Starting: Settings UI... (parallel with Phase 2 continuation)
# [Phase 4] Starting: Login/Signup Integration... (parallel)
# ...

/workflow-preflight: Quality Verification

Before committing changes, this command runs comprehensive code quality checks. It auto-detects configured tools across your project and runs them in optimal sequence.

Another honorable mention to the code-simplifier agent Boris's team open-sourced. It's designed to clean up code after long sessions or simplify complex PRs. I've found it fundamental for maintaining clean code. The two complement each other well: code-simplifier refactors for readability, while preflight verifies nothing broke in the process.

Check sequence:
  1. Formatting: Prettier, ESLint fix, rustfmt, gofmt
  2. Type checking: TypeScript, mypy, dotnet build
  3. Linting: ESLint, Ruff, golangci-lint, Clippy
  4. Testing: Jest, Vitest, pytest, go test, cargo test

Supported ecosystems: Node.js/TypeScript, Python, .NET, Go, and Rust.

# Run preflight checks with auto-fix enabled
/workflow-preflight --fix

# Output:
# [Formatting] Running prettier... PASS
# [TypeCheck] Running tsc --noEmit... PASS
# [Linting] Running eslint... FIXED (2 issues auto-corrected)
# [Testing] Running vitest run... PASS (47 tests)
#
# Preflight Status: READY TO COMMIT

Real-World Example: OAuth in Minutes, Not Days

Recently, I needed to add GitHub and Google OAuth to my SaaS application alongside existing passwordless authentication. This isn't a trivial feature. It involves database schema changes, multiple OAuth handlers, account linking logic, UI updates across login, signup, and settings pages, plus comprehensive testing.

The Planning Phase

I started with /workflow-plan-phases and described the requirement. Claude asked clarifying questions:

  • Should OAuth create new sessions or integrate with existing session management?
  • How should account linking work when emails match?
  • What happens if an OAuth-only user tries to change their email?
  • Should profile data (avatar, name) be imported from providers?

After this discussion, Claude generated a five-phase implementation plan with clear dependencies:

## Dependency Analysis

Phase 1 (Infrastructure)

Phase 2 (OAuth Handlers) ← depends on schema from Phase 1

Phase 3 (Settings) ← depends on handlers from Phase 2

Phase 4 (Login/Signup UI) ← depends on handlers from Phase 2

Phase 5 (Testing) ← depends on all previous phases

Recommended Execution: Sequential (Phases 3 and 4 can run in parallel after Phase 2)

Each phase included specific tasks, acceptance criteria with checkboxes, and explicit file lists. No ambiguity about what needed to happen.

The Implementation

With the plan approved, I ran /workflow-implement-phases. Claude's sub-agents executed each phase in sequence, with Phases 3 and 4 running in parallel once Phase 2 completed.

What I observed:
  • Each phase completed thoroughly with all acceptance criteria met
  • No context exhaustion, as each phase ran in fresh sub-agent context
  • Error handling was comprehensive, as Claude had headroom to think through edge cases
  • Code patterns remained consistent across phases

The actual implementation took minutes of Claude's coding time. What took longer? Setting up OAuth apps in GitHub and Google's developer consoles, configuring client IDs and secrets in Doppler, and waiting for Google's OAuth consent screen approval.

Verification with Unit Tests and ai-security

The final phase included comprehensive unit tests written by Claude during implementation. These covered the OAuth user linking logic, provider disconnect protection, session creation from OAuth, and edge cases like email matching with different providers.

Authentication code also demands security scrutiny. After implementation, I ran my ai-security plugin to audit the OAuth implementation.

# Run security audit on OAuth implementation
/security-audit

# Claude analyzed:
# - OAuth state parameter handling (CSRF protection)
# - Token storage and session management
# - Account linking logic for privilege escalation risks
# - Error handling for information disclosure
# - Rate limiting on OAuth endpoints

The combination of thorough implementation (via properly-sized phases), unit tests written during implementation, and automated security verification (via ai-security) gives confidence that the feature is both complete and secure.

Why This Matches Boris Cherny's Approach

Boris describes his workflow as: plan first, refine iteratively, then execute. The ai-workflow plugin systematizes exactly this pattern while solving the context exhaustion problem.

Plan Mode, Systematized

Boris uses Claude's Plan mode to iterate on approach before implementation. The /workflow-plan-phases command does the same, but adds:

  • Token-aware sizing: Plans are automatically structured to fit context windows
  • Dependency analysis: Execution order is determined by phase relationships
  • Acceptance criteria: Clear verification points prevent incomplete phases
  • Persistent documentation: Plans are saved to docs/plans/ for reference

Auto-Accept with Sub-Agents

Boris switches to auto-accept mode after planning, trusting Claude to execute. The /workflow-implement-phases command takes this further by using sub-agents for each phase.

Sub-agent advantages:
  • Fresh context for each phase (no accumulated bloat)
  • Parallel execution where dependencies allow
  • Graceful failure handling (failed phases don't block independent work)
  • Consistent quality throughout implementation

Verification as a Principle

Boris emphasizes verification: "give Claude a way to verify its work...will 2-3x the quality." The ai-workflow plugin supports this through:

  • Acceptance criteria: Each phase has explicit success conditions
  • Preflight checks: Automated type checking, linting, and testing
  • Integration with ai-security: Security verification for sensitive implementations

Installation & Getting Started

The ai-workflow plugin is part of my open-source Claude Code plugin marketplace, which also includes ai-security, ai-ado, ai-performance, and ai-git plugins.

Quick Start

# Add the plugin marketplace
/plugin marketplace add charlesjones-dev/claude-code-plugins-dev

# Install the ai-workflow plugin
/plugin install ai-workflow@claude-code-plugins-dev

# Plan a feature (provide detailed requirements)
/workflow-plan-phases Add Stripe subscription billing to my SaaS app.
Need monthly and annual plans with usage-based overage charges.
Integrate with existing user auth. Handle webhooks for payment events.
Add billing settings page and invoice history.

# Review and refine the generated plan, then implement
/workflow-implement-phases docs/plans/stripe-billing.md

# Verify before committing
/workflow-preflight --fix

The Broader Plugin Ecosystem

The ai-workflow plugin works well alongside the other plugins in the marketplace:

ai-security: Post-Implementation Verification

After implementing authentication, authorization, or data handling features, run /security-audit to verify OWASP Top 10 compliance and catch security anti-patterns. Read the full ai-security guide.

ai-ado: Work Item Integration

If you're working in Azure DevOps, use /ado-create-feature and /ado-create-story to create work items for your planned phases, then /ado-log-story-work to log completed implementation with git commit detection. Read the full ai-ado guide.

ai-git: Commit Management

After completing phases, use /git-commit-push for intelligent commit message generation that analyzes your changes and matches repository conventions.

ai-performance: Optimization Analysis

For features involving database queries, API endpoints, or rendering logic, run /performance-audit to identify N+1 queries, bottlenecks, and optimization opportunities.

Plan First, Size Right, Execute Confidently

Boris Cherny's insight is correct: a good plan dramatically improves Claude Code's implementation quality. The ai-workflow plugin takes this principle and makes it systematic, adding the critical element of token-aware phase sizing that prevents context exhaustion.

The difference is substantial. Instead of watching Claude's responses degrade as context fills up, each phase runs in fresh context with full capacity. Instead of manually tracking which parts are done and what comes next, the orchestrator handles dependency analysis and execution order. Instead of hoping the implementation is complete, acceptance criteria provide explicit verification points.

For my OAuth implementation, the shift was dramatic: what would have been days of implementation, debugging, and iteration became minutes of Claude's coding time. The bottleneck moved from writing code to external dependencies like OAuth provider configuration.

That's the productivity transformation properly-sized phases enable. Not just faster implementation, but higher quality implementation with consistent depth throughout.

Contact

Drop me a line. I read everything and reply within a day.

Required fields are marked “(required)”.