Skip to content

Common Workflows: Exploring, Fixing, Refactoring Guide

Core Concept LearningAugust 18, 202612 min read

Claude Code excels at five core workflows: exploring a new codebase, diagnosing and fixing bugs, refactoring code for clarity or performance, running and understanding tests, and coordinating deployments. This guide walks through each workflow with real prompts, expected outcomes, and common pitfalls. You'll learn when to use which approach, how to structure prompts for clarity, and how to validate Claude's work before committing.

The mental model: Claude Code is a thought partner. You ask it to explore, understand, propose, and implement. Your job is to sanity-check the output and decide whether to merge. The faster you iterate—ask Claude, review, refine—the more productive you both become. Once you've mastered these manual workflows, Claude Code auto mode can chain them autonomously; to extend any workflow with event-driven triggers, see the hooks guide.

Workflow 1: Explore a New Codebase

You're new to a project. Instead of reading docs (which are often stale), ask Claude Code to map the codebase:

Prompt:

1Explore this TypeScript/React monorepo. Map its structure:2 31. High-level architecture: What are the main modules/packages?42. Data flow: How does data move through the system? (e.g., API → service → DB)53. Key dependencies: What external packages is it built with?64. Entry points: Where does the app start? (main.ts, index.js, etc.)75. Testing: How are tests organized? (test/, __tests__, .test.ts?)8 9Output a markdown document with sections for each. Include examples (file names, key functions).

Expected result: Claude returns a 2–3 page markdown file mapping the codebase structure, listing main packages, showing a request flow diagram, and naming 3–5 key files to study. This is far faster than scrolling through a repo.

What to do next: - Read Claude's map to orient yourself. - Jump to files Claude mentioned; read them in order. - Ask follow-up questions: "Explain how authentication works in this codebase" (Claude reads auth files and explains the flow).

Common mistake: Asking Claude to "explore the entire codebase" without scope. Instead, ask for a specific map (architecture, data flow, tests) so Claude focuses.

Quick reference

  • Scope your questions: 'backend architecture', 'database schema', 'API endpoints' are better than 'everything'.
  • Follow-ups: after the map, ask about specific modules or patterns; Claude has full context now.
  • Diagrams: ask Claude to generate a mermaid diagram of the architecture (Claude can output mermaid syntax).
  • Code samples: ask Claude to show examples (a typical request flow, key function signatures).
  • Outdated docs: docs may be stale; ask Claude to verify against current code.

Remember this

Explore workflow: ask Claude to map codebase structure, data flow, dependencies; output a markdown guide. Follow up with specific questions.

Workflow 2: Bug Fix Workflow

Bug fix follows a pattern: diagnose → reproduce → fix → test → PR.

Step 1: Describe the Bug

1Bug report: When uploading a large file (>100 MB), the API returns 500 with "request entity too large". Users expect a graceful 413 error.2 3Context: Upload endpoint is POST /api/files/upload (see src/api/files.ts).

Step 2: Ask Claude to Diagnose

1In this codebase, diagnose why large file uploads fail with 500 instead of 413.2 31. Find the upload endpoint code42. Identify the size limit (default or configured value)53. Explain where the error is thrown (framework default or custom middleware?)64. Show what the current error response looks like75. Suggest a fix to return proper 413 status

Step 3: Claude Proposes a Fix Claude reads the upload code, finds the middleware, sees that Express's default body parser throws 500 instead of 413. Claude proposes:

1// Add custom error handling for payload too large2app.use((err, req, res, next) => {3  if (err.type === 'entity.too.large') {4    return res.status(413).json({ error: 'File too large. Max 100 MB.' });5  }6  next(err);7});

Step 4: You Review - Is the fix correct? (Check docs for Express error types.) - Does it handle edge cases? (Multiple files? Nested uploads?) - Will it break existing behavior? (Will 413 break any client code?)

If satisfied, say "Implement this fix."

Step 5: Claude Implements and Tests Claude creates a test to verify the fix:

1describe('Large file upload', () => {2  it('returns 413 for files > 100 MB', async () => {3    const largeFile = Buffer.alloc(101 * 1024 * 1024); // 101 MB4    const res = await request(app).post('/api/files/upload').attach('file', largeFile);5    expect(res.status).toBe(413);6    expect(res.body.error).toContain('too large');7  });8});

Step 6: Create a PR Claude commits the fix and opens a PR with: - Title: "Fix: Return 413 for large file uploads" - Description: Explains the issue, the fix, and test coverage.

Prompt for the whole workflow in one go:

1Fix this bug: Large file uploads return 500 instead of 413.2 31. Diagnose the issue in the codebase42. Implement a fix53. Write tests to verify it works64. Create a PR with the fix, test, and clear description7 8Use best practices: graceful error handling, meaningful error messages, comprehensive tests.

Quick reference

  • Repro steps: always ask Claude to reproduce the bug first (ensures understanding).
  • Error messages: Claude should suggest user-friendly error messages, not generic 'error'.
  • Regression tests: add a test that would have caught this bug before.
  • Backwards compatibility: confirm the fix doesn't break APIs or client code.
  • Monitoring: ask Claude to suggest monitoring/alerts for this bug type.

Remember this

Bug fix workflow: diagnose → propose → review → implement → test → PR. Use a single prompt for the whole workflow or break into steps for more control.

Workflow 3: Refactoring Workflow

Refactoring improves code quality without changing behavior. Use Claude Code for safety: it can refactor, run tests, and confirm nothing broke.

Prompt:

1Refactor the authentication module (src/auth/) for clarity and performance:2 31. Identify code smells: duplication, unclear names, overly complex logic42. Propose improvements (DRY principle, clearer naming, smaller functions)53. Implement the refactor64. Run the test suite to confirm no behavior changed75. Show before/after code snippets highlighting the improvements8 9Focus on: reducing duplication, improving readability, maintaining 100% test coverage.

What Claude does: - Identifies duplicate token validation logic (appears in 3 places). - Proposes extracting to a shared validateToken() function. - Renames confusing variables: ttokenPayload. - Splits a 200-line function into 4 smaller functions, each with a single responsibility.

What you do: - Review the before/after code. - Run the tests yourself locally to confirm. - Check that the refactor aligns with team standards (naming conventions, file structure). - Approve and Claude creates a PR.

Best practices: - Refactor small modules first (lower risk). - Always keep tests passing during refactoring. - Pair refactoring with documentation updates if names changed. - Use feature branches so refactors can be reverted if issues arise.

Prompt for specific refactor types: - "Reduce cyclomatic complexity by extracting helper functions" - "Replace string-based flags with enums" - "Remove duplicate validation logic across these 3 files" - "Rename variables for clarity: t→token, u→user, req→request"

Quick reference

  • Test coverage: before refactoring, ensure tests pass 100%; verify after refactoring.
  • Incremental: refactor in small chunks; avoid combining multiple refactors in one PR.
  • Code review: refactors often change more lines than the actual logic; reviewers appreciate clear before/after.
  • Avoid premature optimization: refactor for clarity first; optimize only if benchmarks show a bottleneck.
  • Backwards compatibility: refactors should never change public APIs; if they do, it's a breaking change.

Remember this

Refactoring workflow: identify code smells, propose improvements, implement, run tests, create PR. Keep tests passing throughout.

Workflow 4: Testing Workflows

Claude Code can write, debug, and run tests. Use it for:

Writing Tests

1Write comprehensive tests for the payment processing module (src/payments/processor.ts).2 3Cover these cases:41. Successful payment: valid amount, valid card, expect success52. Insufficient funds: amount > balance, expect 'insufficient funds' error63. Declined card: issuer declines, expect 'card declined' error74. Network timeout: payment service times out, expect retry + eventual failure85. Edge case: amount = $0.01 (minimum), should succeed9 10Output Jest test file with clear test names, setup/teardown, mocks for payment service.

Running Tests and Debugging Failures

1Run the full test suite. If any tests fail, diagnose the failure:2 31. Show the failing test and error message42. Explain why it failed (e.g., mock not set up correctly, timing issue)53. Propose a fix64. Re-run to confirm it passes

Integration Testing

1Write integration tests that exercise the full flow:2- Create a test user3- Add a test payment method4- Process a payment5- Verify the transaction is recorded in the database6- Verify emails are sent7 8Use a test database, mock payment service, test fixtures.

Quick reference

  • Unit tests: test individual functions in isolation; mock dependencies.
  • Integration tests: test how modules work together; use real or in-memory database.
  • E2E tests: test full user flows; slower but catch real issues.
  • Coverage: aim for >80% code coverage; critical paths should be >95%.
  • Flaky tests: avoid time-dependent tests or non-deterministic behavior; use fixed seeds.

Remember this

Testing workflow: ask Claude to write tests (unit, integration, E2E), run them, debug failures. Aim for high coverage on critical paths.

Workflow 5: Deployment Coordination

Deployment involves code review, testing, approval, and rollout. Claude Code can orchestrate:

1Prepare a release for deployment:2 31. Collect all merged PRs since the last release (tag: v1.0.0)42. Summarize changes: new features, bug fixes, breaking changes53. Update CHANGELOG.md and package.json version (following semver)64. Run the full test suite75. Build the app and verify no errors86. Create a release PR with the summary and version bump97. Suggest a checklist for final approval (code review, QA sign-off, ops review)

Claude does: - Generates a changelog: "v1.0.1: Fixed large file upload bug, improved auth error messages." - Bumps version: 1.0.0 → 1.0.1 (semver patch for bug fixes). - Runs CI: confirms all tests pass. - Creates a PR with the changelog and version bump.

You do: - Review the changelog (is it complete? accurate?). - Approve if ready. - Claude merges and tags the release. - CI/CD deploys to staging, then production.

Advanced: Canary Deployment

1Deploy to 10% of production traffic first. Monitor metrics (error rate, latency) for 1 hour.2If metrics are good, roll out to 100%.3If metrics are bad, rollback.4 5Show me the deployment strategy and health check prompts for Claude to monitor during canary.

Quick reference

  • Versioning: follow semver (major.minor.patch); major for breaking changes, minor for features, patch for bugs.
  • Changelog: include PR links, user-facing descriptions, internal technical notes if relevant.
  • Testing: run full test suite, smoke tests on staging before production.
  • Approval gates: require code review, QA approval, and ops sign-off before production.
  • Rollback: keep a rollback plan; if production breaks, revert quickly to the previous release.

Remember this

Deployment workflow: prepare release (changelog, version, tests), create PR, get approval, deploy to staging, then production with monitoring.

Real Examples and Prompts

Here are production-ready prompts you can copy and adapt:

Explore React Component Library

1Analyze this React component library. Output a markdown guide with:21. Component hierarchy: which components depend on which?32. Common patterns: hooks patterns, prop naming, styling approach43. Entry points: what's exported from index.ts?54. Dev workflow: how to dev locally? (npm start, Storybook, etc.)65. Testing: how are components tested? (Jest, React Testing Library, etc.)7 8Include code examples for each section.

Diagnose Performance Issue

1Our API is slow: /api/users endpoint takes 2-3 seconds for 1000 users.2 31. Analyze the endpoint code (src/api/users.ts)42. Identify bottlenecks: N+1 queries? Full table scans? Inefficient loops?53. Propose optimizations (database indexes, query joins, caching)64. Show before/after performance estimates75. Implement the fastest fix that doesn't require DB schema changes

Migrate to TypeScript

1I have a JavaScript file (src/utils/helpers.js) with no types. Migrate it to TypeScript:2 31. Analyze the file to infer types42. Add JSDoc or TypeScript types to all functions53. Create a .d.ts file if external packages need typing64. Update tests to .test.ts75. Confirm the build passes with strict: true in tsconfig8 9Output the converted file and any new .d.ts files.

Add Feature: Dark Mode

1Add dark mode support to this React app (Tailwind CSS):2 31. Analyze current styling setup (light mode)42. Add dark: variants to Tailwind config53. Update all components to support dark mode (dark:bg-slate-900, etc.)64. Add a toggle button in the navbar75. Persist preference to localStorage86. Respect system dark mode preference on first visit97. Write tests for toggle and persistence10 11Output updated files and test file.

Quick reference

  • Be specific: include file paths, line numbers, error messages if available.
  • Context: tell Claude what you've tried already (so it doesn't repeat failed attempts).
  • Constraints: mention time pressure, tech debt, or team standards to respect.
  • Success criteria: define what 'done' looks like (tests pass, performance improves by 50%, etc.).
  • Follow-ups: after Claude completes, ask 'Why did you choose that approach?' to understand trade-offs.

Remember this

Real prompts: be specific about files, context, constraints, and success criteria. Copy and adapt examples for your codebase.

Common Mistakes and How to Avoid Them

Mistake 1: Vague Prompts ❌ Bad: "Fix the API" ✅ Good: "The POST /api/users endpoint is returning 500 for valid requests. Debug and fix it; start with the endpoint code in src/api/users.ts."

Mistake 2: Ignoring Claude's Proposed Code If Claude proposes a fix and you don't review it, bad code can slip through. Always: - Read Claude's output before approving. - Ask clarifying questions: "Why did you choose this approach vs. X?" - Test locally before merging.

Mistake 3: Long-Running Tasks Without Checkpoints If you ask Claude to "refactor the entire backend," it might run for 30 min and produce incorrect output. Instead: - Break into smaller tasks: "refactor the auth module" → review → "refactor the payment module". - Use checkpoints: "implement step 1, then wait for approval before step 2."

Mistake 4: Not Providing Context If Claude doesn't know the project's conventions, it might output code that doesn't match your style. Provide: - File structure (where do you put tests, types, configs?) - Naming conventions (camelCase? snake_case?) - Tech stack (what versions of dependencies?) - Team standards (if you have a style guide, link it).

Mistake 5: Trusting Claude's Tests Without Running Them Claude can write tests, but they may not cover all cases. Always: - Run tests locally. - Check coverage reports. - Ask Claude to add edge cases if coverage is low.

Mistake 6: Not Setting Realistic Time Limits If you ask Claude to "refactor the entire payment system" without a time limit, it might take 2 hours. Instead: - Break into smaller tasks with 15–30 min estimated duration. - Ask Claude for a plan first: "What's your refactoring plan? How long will each step take?" - Set time budget: "You have 30 min; prioritize clarity over perfect optimization."

Mistake 7: Assuming Claude Knows Your Business Claude doesn't know that "order" means a customer purchase in your domain (not a sorting operation). Clarify: - "Order" in this codebase = customer purchase; see Order class in models/Order.ts. - "User" = person who logged in; "Admin" = special user with elevated permissions.

Recovery from mistakes: If Claude's output is wrong, don't blame Claude. Instead: - Ask Claude to review its own output: "Does this implementation handle the [edge case]?" - Provide feedback: "This doesn't match our naming convention; update variable names from t to token." - Iterate: "That didn't work. Here's the error: [error]. Can you fix it?"

Quick reference

  • Vagueness: precise prompts save time; Claude works better with concrete details.
  • Review before merge: Claude's output is usually good but not always perfect.
  • Test locally: don't trust Claude's tests; run them yourself.
  • Break into steps: avoid long-running single prompts; use checkpoints.
  • Provide context: team conventions, file structure, domain knowledge.

Remember this

Avoid vague prompts, always review output, test locally, break large tasks into steps, provide business context.

Best Practices Checklist

Before pushing Claude Code output to production:

Code Quality - [ ] Claude's code follows your team's style guide (naming, formatting, structure). - [ ] No new linting errors: run npm run lint or equivalent. - [ ] Type-safe: if using TypeScript, strict mode passes (npm run type-check). - [ ] No security issues: check for hardcoded secrets, unvalidated input.

Testing - [ ] Tests pass: npm run test succeeds. - [ ] Coverage maintained: new code doesn't drop test coverage below team threshold (usually >80%). - [ ] Edge cases covered: asked Claude to add tests for boundary conditions. - [ ] Manual testing: tried the feature/fix locally; works as expected.

Documentation - [ ] Comments added: complex logic is explained; why, not just what. - [ ] README updated: if this changes how someone uses the module. - [ ] CHANGELOG updated: summarize the change for users. - [ ] API docs: if this changes a public API, docs are updated.

Deployment Safety - [ ] Backwards compatible: if this changes an API, old clients still work. - [ ] Migrations included: if this changes the database schema, migration scripts are provided. - [ ] Monitoring in place: added logging or alerts for this feature. - [ ] Rollback plan: if this breaks production, you can quickly rollback.

Review Readiness - [ ] PR title is clear: describes the change, not "fix" or "update". - [ ] PR description includes: what changed, why, how to test, risks. - [ ] Related issues linked: PR references GitHub issues it resolves. - [ ] Screenshots/gifs if UI changed: shows visual changes.

Before merging: - [ ] Code review approved: at least 1 team member reviewed and approved. - [ ] CI passes: all automated checks (lint, tests, build) passed. - [ ] Protected branch rules met: any branch protection rules are satisfied.

Quick reference

  • Automate checks: use pre-commit hooks and CI to catch issues early.
  • Peer review: even if Claude seems right, get a human to review before merge.
  • Test in staging: deploy to a staging environment before production.
  • Monitor after deploy: watch metrics (error rate, latency, exceptions) for 30 min after deploy.
  • Document decisions: if you override Claude's suggestion, document why for future reference.

Remember this

Best practices: follow style guide, maintain test coverage, document changes, test locally, get peer review, monitor after deploy.

Key takeaway

Claude Code workflows—explore, fix, refactor, test, deploy—form a cycle that accelerates development. The key is iteration: ask Claude, review the output, refine, and repeat. Over time, you'll learn what prompts work best for your codebase and team style.

Practice checklist: 1. Explore: Ask Claude to map a module you're unfamiliar with. Review the output; does it match the actual code? 2. Fix: Find a small bug in your codebase. Ask Claude to diagnose and fix it. Review, test locally, create a PR. 3. Refactor: Pick a messy function. Ask Claude to refactor it for clarity. Compare before/after code. 4. Test: Ask Claude to write tests for a function. Run them; do they pass? Add edge cases if coverage is low. 5. Deploy: Use Claude to prepare a release (changelog, version bump, PR). Review and merge.

Each workflow teaches you how to structure prompts and review Claude's output. Start small; build confidence.

Share:
PK

Polo Khan

Lead Author & Systems Architect

Software engineer and distributed systems architect specializing in backend scalability, cloud-native infrastructure, databases, and AI engineering workflows. Author and maintainer of Core Concept Learning.

Human-Engineered & Fact-CheckedOriginal Visual DiagramsEditorial Standards →Send Feedback

Related Articles

When you run Claude Code in a project, it can execute bash commands, read and edit files, fetch data from the web, and c

Read

A workflow is a graph of agents connected by data flow: agent-A produces output, agent-B consumes it, agent-C fans out t

Read

VS Code is where most developers spend their day—and Claude Code transforms it into an AI-powered IDE. The extension bri

Read

Explore this topic

Keep learning

Follow a structured path or browse all courses to go deeper.