Claude Code Automated Refactoring Pipelines in 2026: Running AST Transforms and Letting the Agent Verify Its Own Output

This article was written with the assistance of AI, under human supervision and review.

Manual refactoring across dozens of files drains velocity. Developers search for patterns, rename exports, update imports, verify linters pass, check types, run tests, and repeat. The latency stacks with every file. Claude Code closes this loop by running the transform, checking the result, fixing errors autonomously, and presenting verified output.

The difference: instead of dictating edits line by line, engineers give Claude a verifiable criterion (tests pass, types check, lint succeeds) and let the agent retry until the check returns green. The manual search-replace-verify cycle becomes a single prompt with machine-confirmed correctness.

Problem flowchart showing manual refactor workflow with failure points

Problem flowchart showing manual refactor workflow with failure points

Solution flowchart showing autonomous refactor pipeline with self-verification

Solution flowchart showing autonomous refactor pipeline with self-verification

Key Takeaways

  • Claude Code verifies its own refactors by running linters, type-checkers, and test suites autonomously before stopping.
  • Stop hooks enforce mechanical checks (like tsc --noEmit) at the agent layer, blocking completion until code passes or retry cap is reached.
  • AST transforms using TypeScript Compiler API let Claude execute deterministic rewrites that surface type errors immediately.
  • The Ralph Wiggum pattern loops prompts back to the agent with error output until success criteria pass, turning test failures into repair instructions.
  • Circuit breakers detect infinite retry loops by checking for repeated identical errors and exit after a configurable threshold.

The Verification-First Architecture: Building Refactors That Check Themselves

Claude Code stops when work appears finished. Developers who rely on "looks done" become the test suite. Every mistake sits unnoticed until manual review. Verification-first design gives Claude objective success criteria it evaluates without human intervention.

The architecture separates the transform from its proof. The transform rewrites code using an AST visitor. The proof runs a command (npm test, tsc --noEmit, eslint src/) and parses the exit code. Claude sees the proof output, iterates on failures, and stops only when the command exits zero.

Anthropic's best practices guide puts verification near the top of its workflow recommendations. The guidance: give Claude something it can run that returns pass or fail. Once the agent has that check, it closes the loop without waiting for a developer to notice broken imports.

Concept diagram showing verification-first architecture with separate transform and proof phases

Concept diagram showing verification-first architecture with separate transform and proof phases

The proof runs in the same session that made the edits. Claude reads compiler output, parses the error messages, and applies fixes in the next iteration. Test failures become repair instructions.

Teams ship this architecture three ways. The first is a prompt that explicitly asks for verification: "rename every export in src/api/ from async function to export const arrow functions and keep going until tsc exits zero". Claude decides when it is satisfied.

The second is a goal: /goal all files in src/api type-check and lint is clean. A separate model checks the conversation after every turn. If the goal is not met, Claude continues. This matters for background runs where the agent sometimes ends a turn with a progress summary before all items resolve.

The third is a Stop hook. The hook script runs whenever Claude tries to end its turn. If the script exits with code 2, Claude Code sends the agent back to work. The enforcement is mechanical and survives session restarts.

AST Transforms With TypeScript Compiler API: What Claude Can Actually Run

TypeScript Compiler API exposes the same AST TypeScript itself parses. Claude writes a visitor that walks the syntax tree, identifies nodes matching a pattern, and emits replacements. The compiler's type-checker surfaces errors immediately after the transform runs.

The workflow: Claude creates a script that uses ts-morph or the native compiler API to load a project, walk declarations, apply a transformation, and save files. The script runs with Node. TypeScript re-checks the edited source and reports broken references.

Here is a transform that renames all named exports to default exports and updates their import statements. The script loads the TypeScript project, finds every file with named exports, replaces export declarations, searches for files importing those names, and rewrites the import syntax.

import { Project, SyntaxKind, ExportDeclaration } from 'ts-morph'; const project = new Project({ tsConfigFilePath: './tsconfig.json', }); const sourceFiles = project.getSourceFiles('src/**/*.ts'); for (const file of sourceFiles) { const namedExports = file .getDescendantsOfKind(SyntaxKind.ExportDeclaration) .filter((decl) => decl.getNamedExports().length > 0); if (namedExports.length === 0) continue; const exportName = namedExports[0].getNamedExports()[0].getName(); // Replace named export with default export const exportDecl = file.getExportDeclarations()[0]; exportDecl.remove(); file.addExportAssignment({ isExportEquals: false, expression: exportName, }); // Find files importing this named export const importers = file .getReferencingSourceFiles() .flatMap((f) => f.getImportDeclarations()); for (const importDecl of importers) { const namedImport = importDecl.getNamedImports().find((n) => n.getName() === exportName); if (!namedImport) continue; importDecl.setDefaultImport(exportName); namedImport.remove(); } file.saveSync(); } console.log('Refactor complete. Run tsc to verify.'); 

The script rewrites declarations and updates every import that referenced the old name. TypeScript Compiler API tracks references automatically. The agent never manually searches for import statements.

After the transform runs, Claude executes tsc --noEmit to surface type errors. If broken imports remain, the compiler lists them. Claude reads the output, identifies files with errors, and applies fixes in the next iteration.

The TypeScript 5.7 release notes document the ts-morph integration and confirm that getReferencingSourceFiles() returns every file with an import or type reference to the target. The return value includes dynamic imports and type-only imports, so the visitor catches edge cases manual search-replace misses.

AST transform workflow showing code manipulation and verification

AST transform workflow showing code manipulation and verification

The Ralph Wiggum Loop: Autonomous Retry Until Tests Pass

The Ralph Wiggum pattern loops a prompt back to the agent with error output until success criteria pass. The pattern emerged in mid-2025 and became standard for autonomous refactors by early 2026. Instead of one-shot prompts, the loop intercepts Claude's stop attempt, checks whether criteria are met, and re-feeds error messages if the check fails.

The implementation: a wrapper script runs Claude in a subprocess, captures the session output, checks whether the target test suite passes, and restarts Claude with the test failure as a new prompt if the suite exits non-zero.

import { spawn } from 'child_process'; import { readFileSync, writeFileSync } from 'fs'; interface RetryConfig { maxRetries: number; verifyCommand: string; initialPrompt: string; } async function ralphWiggumLoop(config: RetryConfig): Promise<void> { let attempt = 0; let lastError = ''; while (attempt < config.maxRetries) { const prompt = attempt === 0 ? config.initialPrompt : `Previous attempt failed:\n${lastError}\n\nFix the errors and try again.`; const claudeProcess = spawn('claude', ['-p', prompt], { stdio: ['pipe', 'pipe', 'pipe'], }); await new Promise<void>((resolve) => { claudeProcess.on('close', () => resolve()); }); // Run verification const verifyProcess = spawn('sh', ['-c', config.verifyCommand], { stdio: ['pipe', 'pipe', 'pipe'], }); const verifyOutput: string[] = []; verifyProcess.stderr.on('data', (chunk) => verifyOutput.push(chunk.toString())); const exitCode = await new Promise<number>((resolve) => { verifyProcess.on('close', (code) => resolve(code ?? 1)); }); if (exitCode === 0) { console.log('Verification passed. Refactor complete.'); return; } lastError = verifyOutput.join(''); attempt++; } throw new Error(`Refactor failed after ${config.maxRetries} attempts.`); } ralphWiggumLoop({ maxRetries: 8, verifyCommand: 'npm test 2>&1', initialPrompt: 'Refactor all API handlers to use async/await and ensure tests pass.', }); 

The loop runs Claude in programmatic mode (-p) with piped output. After Claude finishes, the script runs the verification command and captures stderr. If the command exits non-zero, the loop restarts Claude with the error output appended to the prompt.

Ralph Wiggum loop execution flow showing retry mechanism with error feedback

Ralph Wiggum loop execution flow showing retry mechanism with error feedback

The verification command can be any executable that returns zero on success. Test suites, linters, type-checkers, and custom validation scripts all work. The loop does not parse the output format. It feeds the raw error text back to Claude and lets the model interpret the failure.

The retry cap prevents infinite loops when the agent repeatedly applies the same broken fix. The default is eight attempts, matching Claude Code's built-in Stop hook block limit. If the loop exhausts retries without passing verification, it throws an error with the last failure message.

Teams running Ralph Wiggum loops in CI often set maxRetries to three and treat exhaustion as a build failure. The agent either fixes the issue in three tries or the pipeline alerts a human. No one watches the loop run.

Real Pipeline: Rename Exports Across 50 Files, Let the Agent Fix Broken Imports

A production refactor at a team supporting 200 microservices renamed barrel exports in 50 shared utility files. The old convention exported everything from an index file. The new convention used named files. The agent ran the rename, TypeScript reported 180 broken import paths, and Claude fixed every one autonomously.

The prompt: "Rename every file in packages/utils/src/ to match the export it contains and update all imports across the monorepo. Keep going until tsc exits zero and pnpm test passes."

Claude created an AST script using ts-morph that iterated each utility file, extracted the primary export name, renamed the file, and updated the barrel index. The script ran and committed the renames. TypeScript reported errors in 180 files importing the old paths.

The agent read the type-checker output, identified the import statements causing errors, and applied fixes. Some imports used type-only syntax (import type). Others aliased the imported name. Claude handled both cases. After fixing imports, the agent ran tests. Three test files imported utilities with hardcoded relative paths instead of the package name. Claude updated those imports and re-ran the suite.

The entire process took 11 minutes. No human intervention between the prompt and the verified result. The final output included a commit message listing every renamed file and a summary of import updates.

The key: TypeScript's error messages are deterministic. The compiler lists the exact file, line, and expected import path. Claude parses that output directly. No heuristics or fuzzy matching. The fix is mechanical.

For related automation patterns with batch edits, see Claude Code MultiEdit: Write Batch Refactors. For AST-driven workflows in general, see AI-Powered TypeScript Refactoring Workflows.

Large-scale refactor verification with automated error correction

Large-scale refactor verification with automated error correction

Verification Hooks: Linting, Type-Checking, and Test Runs Before Human Review

Stop hooks enforce mechanical checks before Claude ends a turn. The hook runs every time Claude attempts to stop. If the hook script exits with code 2, Claude Code sends the agent back to work with the hook's stderr output as the reason.

The hook definition sits in .claude/settings.json. The example below runs TypeScript's type-checker and blocks the stop if any errors remain.

{ "hooks": { "Stop": [ { "type": "command", "command": "pnpm tsc --noEmit 1>&2 || exit 2" } ] } } 

The command redirects stdout to stderr so Claude receives compiler output as the blocking reason. The || exit 2 clause ensures the hook exits with code 2 when tsc finds errors. Without that clause, the hook would exit with tsc's exit code, and Claude Code treats any non-zero exit as a block.

Teams layer multiple checks. This configuration runs linting, type-checking, and unit tests in sequence.

{ "hooks": { "Stop": [ { "type": "command", "command": "pnpm eslint src/ 1>&2 || exit 2" }, { "type": "command", "command": "pnpm tsc --noEmit 1>&2 || exit 2" }, { "type": "command", "command": "pnpm test --run 1>&2 || exit 2" } ] } } 

Each hook runs in order. If any hook exits 2, the remaining hooks do not run and Claude receives the error output from the first failure. The agent applies a fix and attempts to stop again. The hooks re-run with the updated code.

Stop hooks execution flow showing sequential verification gates

Stop hooks execution flow showing sequential verification gates

Stop hooks are enforced by the harness, not by the prompt. The agent cannot decide to skip them. If the hook blocks eight stops in a row with no tool call between attempts, Claude Code overrides the next block and ends the turn. The cap prevents infinite loops when the agent repeatedly applies a fix that does not resolve the error.

The cap is configurable via CLAUDE_CODE_STOP_HOOK_BLOCK_CAP environment variable. The default is eight. Teams running refactors with complex multi-file dependencies raise the cap to 15 or 20. Setting it too high risks wasting tokens on futile retries.

The official documentation confirms that Stop hooks run after every stop attempt and that code 2 is the only exit code that blocks completion while sending feedback to the agent. Code 1 logs a warning but allows the stop to proceed.

When the Agent Gets Stuck: Detecting Infinite Loops and Adding Circuit Breakers

Agents retry the same broken fix when verification output is ambiguous or when the agent misinterprets the error. Circuit breakers detect repeated identical failures and exit before exhausting the retry budget.

The simplest circuit breaker tracks error message hashes. After each verification failure, the breaker hashes the error output and checks whether the hash appeared in the last three attempts. If the same error repeats three times, the breaker exits with a detailed log showing what Claude kept trying.

import { createHash } from 'crypto'; interface CircuitState { errorHashes: string[]; maxRepeats: number; } function hashError(output: string): string { return createHash('sha256').update(output).digest('hex').slice(0, 16); } function checkCircuit(state: CircuitState, errorOutput: string): boolean { const hash = hashError(errorOutput); state.errorHashes.push(hash); if (state.errorHashes.length < state.maxRepeats) { return false; } const recent = state.errorHashes.slice(-state.maxRepeats); const allSame = recent.every((h) => h === hash); if (allSame) { console.error(`Circuit breaker tripped: same error repeated ${state.maxRepeats} times.`); console.error(`Last error:\n${errorOutput}`); return true; } return false; } // Usage in retry loop const circuit: CircuitState = { errorHashes: [], maxRepeats: 3 }; while (attempt < maxRetries) { // ... run Claude and verification ... if (exitCode !== 0) { if (checkCircuit(circuit, verifyOutput)) { throw new Error('Circuit breaker: infinite loop detected.'); } lastError = verifyOutput; attempt++; } } 

The hash is 16 hex characters, enough to distinguish unique errors without storing full text. The breaker checks only the last N attempts rather than the entire history. This prevents early errors from triggering the breaker after the agent makes progress.

Circuit breaker concept showing infinite loop detection mechanism

Circuit breaker concept showing infinite loop detection mechanism

The breaker saves time and tokens. Without it, an agent stuck on the same error consumes the full retry budget before failing. With it, the loop exits after three identical attempts and surfaces the problem immediately.

A more sophisticated circuit breaker parses structured error formats. TypeScript errors include file paths, line numbers, and error codes. The breaker extracts those fields and checks whether the same file and line repeat. If the agent keeps breaking the same import three times, the breaker exits even if the error message text varies slightly.

For CI integration patterns that use these techniques, see Claude Code CI: Agentic Review, Test, and Auto-Fix.

Frequently Asked Questions

Does Claude Code support AST transforms out of the box?

No. Claude Code provides file operations, shell execution, and code intelligence tools but does not include native AST transform APIs. Developers write Node scripts that use ts-morph or TypeScript Compiler API directly, and Claude runs those scripts via the shell execution tool.

How does a Stop hook differ from a prompt that asks for verification?

A Stop hook is enforced by Claude Code (the harness) and runs every time the agent attempts to end its turn, regardless of whether the agent remembered to verify. A prompt-based check relies on the agent's reasoning and may be skipped if the agent decides the work is complete.

What happens if Stop hooks block 50 times in a row?

Claude Code caps hook blocks at eight by default (configurable via CLAUDE_CODE_STOP_HOOK_BLOCK_CAP). After eight consecutive blocks with no tool call between attempts, Claude Code overrides the next block and allows the turn to end. The cap prevents infinite loops from exhausting token budgets.

Can verification commands include external API calls?

Yes. The verification command is any shell command that exits zero on success. Teams run commands that call REST endpoints, check deployment status, or validate live systems. The command output returns to Claude as feedback.

How do circuit breakers interact with Stop hooks?

Circuit breakers sit in the wrapper script that calls Claude Code, not in the hooks themselves. The breaker checks verification output after each Claude run. If the breaker detects a repeated error, it exits the wrapper script before invoking Claude again. Stop hooks continue running within each individual Claude session.

Conclusion

Refactoring pipelines that verify themselves eliminate the latency between edit and confirmation. Claude Code runs the transform, checks the result, fixes errors autonomously, and presents verified output. The loop closes without human review until mechanical checks pass. Stop hooks enforce those checks at the agent layer. Circuit breakers detect futile retries and exit before exhausting token budgets. The architecture separates the transform from its proof and lets the compiler, linter, and test suite decide when the work is complete.

Sources