Refactor your codebase with CircleCI Chunk AI agent
Content Marketing Manager
d function there, and before long you’re navigating a codebase full of inconsistent patterns, repeated logic, and code that’s harder to maintain than it should be. Refactoring is essential, but finding the time to clean up code while shipping features is a constant challenge.
The rise of AI-assisted development has accelerated this tension. AI coding assistants help teams ship features faster, but they don’t always produce consistent code. Different team members using different prompts can lead to varied patterns and styles. Meanwhile, the velocity of changes makes it harder to pause for cleanup. Technical debt compounds faster when you’re shipping faster.
Chunk, CircleCI’s autonomous CI/CD agent, addresses this by bringing AI-powered refactoring directly into your continuous integration pipeline. Unlike IDE-based tools that operate on files in isolation, Chunk can analyze your entire codebase in the context of your CI/CD environment, identify patterns across modules, and generate refactored implementations that follow consistent standards. In this guide, you’ll learn how to use Chunk to refactor code automatically.
Setting up Chunk
To get started with Chunk, you’ll need a CircleCI account with a project already running pipelines. If you’re new to CircleCI, check out the getting started guide to connect your repository.
You can follow along with your own project or use our demo project on GitHub if you’d like a ready-made example.
Once your project is running in CircleCI:
- Go to Chunk in the CircleCI web app sidebar.
- Click Set up Chunk and follow the prompts to authorize GitHub access. Chunk requires read access to analyze your repository and write access to create pull requests with its refactored code.
- Connect your Anthropic or OpenAI API key when prompted. Chunk uses your own API credentials, so your code is never sent to external providers for model training and data stays under your control.
Chunk integrates directly with your existing CircleCI pipelines without requiring any reconfiguration. Once authorized, it can analyze both your repository code and your build history to understand how your project works. For complete setup instructions, see the Chunk documentation.
Asking Chunk to refactor code
With Chunk enabled, go to Chunk in the sidebar. In the prompt interface, describe what you want Chunk to do.
Start with a simple prompt:
Refactor code
Click Submit and Chunk begins working. Because Chunk operates within your CI/CD environment, it can scan your entire repository for code smells, duplicated logic, and opportunities to improve structure. It then validates any changes by running your test suite, ensuring that refactoring doesn’t introduce regressions.
Reviewing the results
When Chunk completes its analysis, you’ll get a summary of the refactoring opportunities it found and the changes it made. From this page, you can review the details and decide whether to open a pull request. If you’re not satisfied with the changes, you can skip the PR and refine your prompt instead.
Chunk explains its changes:
Summary
Refactored multiple modules to improve code quality, readability,
and maintainability:
Extracted helper functions: Created focused utility functions to
encapsulate reusable logic in exporters, processors, transformers,
and validators
Modernized JavaScript syntax: Replaced verbose patterns with ES6+
features including destructuring, arrow functions, object shorthand,
template literals, and simplified conditionals
Reduced code duplication: Eliminated repeated logic by extracting
common patterns into named helper functions
Improved consistency: Standardized null checks (== null), error
handling patterns, and return statement formatting across all modules
Files changed:
- src/exporters/jsonExporter.js: Added filterEmptyArray,
filterEmptyObject, and createMetadata helpers
- src/processors/batch.js: Extracted executeTransform and
reportProgress functions
- src/processors/pipeline.js: Created executeStep and runStep helpers
- src/transformers/csvToJson.js: Added parseRow helper function
- src/transformers/normalize.js: Extracted normalizeString and
createNestedOptions utilities
- src/validators/currency.js: Added formatCurrency helper
- src/validators/date.js: Restructured with parseDateString and
validateDateComponents helpers
- src/validators/email.js: Moved regex to constant, simplified logic
- src/validators/phone.js: Added formatPhoneNumber helper
If the changes are good, click Open Pull Request to create a PR in your repository.
Before merging, review the refactored code to ensure the changes maintain existing functionality. Chunk runs your test suite to verify that nothing breaks, but you should still validate if the changes match your team’s expectations.
More targeted prompts
The simple “Refactor code” prompt works well for general cleanup. For more control over what Chunk changes, try targeted prompts.
To target a specific type of refactoring, run:
Remove code duplication in the validators directory
To focus on a single file, run:
Refactor src/processors/pipeline.js to use async/await instead of callbacks
To apply a specific pattern, run:
Extract shared validation logic into a common utility module
To improve naming, run:
Rename variables and functions in src/transformers to follow camelCase conventions
To modernize syntax, rund:
Update the codebase to use ES6+ features like destructuring and arrow functions
The more specific you make your prompt, the more focused Chunk’s refactoring will be.
Advanced configuration
Once you’re comfortable with the basics, you can fine-tune how Chunk operates with your project.
Environment setup
For projects with complex dependencies, external services, or specific runtime requirements, you can provide a .circleci/cci-agent-setup.yml file that tells Chunk exactly how to prepare your test environment.
This is important for refactoring because Chunk validates all changes by running your test suite. If your tests require specific setup, Chunk needs that same environment. Common use cases include:
- Database setup: If your integration tests need a database
- External services: Mock services or containers for API testing
- Build tools: Specific compilers, transpilers, or build systems
- Runtime configuration: Environment variables that affect how code executes
Here’s an example for a Node.js project:
version: 2.1
workflows:
main:
jobs:
- cci-agent-setup
jobs:
cci-agent-setup:
docker:
- image: cimg/node:20.11
steps:
- checkout
- run:
name: Install Dependencies
command: npm ci
- run:
name: Build Project
command: npm run build
Focus on environment preparation only. Don’t include actual test execution commands. Chunk will determine how to run tests based on your main config.yml.
Chunk will attempt to automatically create this file if it’s needed. You can also generate one manually by going to Organization Settings -> Chunk Tasks, and clicking the menu (…) for your task. Click Chunk Environment, then click Create File in GitHub. For more details, see the Chunk environment documentation.
Custom instructions
To ensure refactored code matches your team’s standards, create a claude.md or agents.md file in your repository root. Document your preferences for:
- Naming conventions (camelCase, snake_case, etc.)
- Import ordering and grouping rules
- Preferred patterns for async code
- Error handling conventions
- Code organization principles
- Anything else relevant to your refactoring effort
Chunk reads these files and applies your preferences when generating refactored code.
Safe refactoring
Chunk validates all refactoring changes by running your test suite before creating a pull request. If tests fail after refactoring, Chunk iterates on the changes until tests pass. This ensures refactoring doesn’t introduce regressions. For added safety, configure branch protection rules to require CI checks before merging.
This test-driven validation is one of the key advantages of having an AI agent embedded in your CI/CD pipeline. IDE-based refactoring tools can suggest changes, but they can’t automatically verify that those changes work in your real build environment.
Chunk in the AI development ecosystem
While AI coding assistants help you write code faster in your IDE, Chunk operates at the CI/CD layer where it can validate refactoring changes against your actual test suite and build process.
This creates a natural workflow for AI-assisted development. Use AI coding assistants to generate features quickly, then let Chunk clean up the inconsistencies that accumulate. Where IDE tools operate on individual files, Chunk can identify patterns across your entire codebase and apply consistent refactoring everywhere.
For teams using AI coding assistants, CircleCI also offers the CircleCI MCP Server, which connects AI assistants directly to your pipelines using the Model Context Protocol. This lets your IDE-based AI tools understand your build environment and test results, creating tighter feedback loops between code generation and validation. Together, Chunk and the MCP server create an integrated AI development workflow where code quality is maintained automatically.
Conclusion
Technical debt doesn’t have to slow your team down. Chunk analyzes your codebase, identifies opportunities for improvement, and generates cleaner code that follows best practices, all while ensuring your tests continue to pass. As AI-powered development increases the velocity of code changes, having an autonomous agent that maintains code quality becomes essential.
Ready to try it yourself? Sign up for a free CircleCI account and enable Chunk to start refactoring automatically.