Manual refactoring across dozens of files burns time. You 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.
The Verification-First Architecture
Traditional coding agents generate diffs and stop. Claude Code pipelines add a verification layer that runs before human review. The agent executes the refactor, invokes static analysis tools, reads the output, and either completes or retries with error context.
Core pipeline stages:
- AST transform: TypeScript Compiler API parses source, applies deterministic rewrites, emits updated code.
- Agent generation: Claude receives the transform specification and produces candidate edits.
- Verification gate: Linters, type-checkers, and test suites run against the candidate output.
- Feedback loop: If verification fails, error messages feed back into the agent’s context for the next iteration.
- Human review: Only verified output reaches the pull request.
The orchestration boundary sits between the agent’s reasoning loop and the external tooling that enforces correctness. The agent doesn’t guess whether code is valid; it runs tsc --noEmit and reads the exit code.
Stop Hooks: Enforcing Mechanical Checks at the Agent Layer
Stop hooks block agent completion until a condition passes. Instead of letting Claude declare success after generating code, the pipeline injects a verification step that must return zero before the agent can finish.
Stop hook implementation pattern:
interface StopHook {
name: string;
check: () => Promise<{ passed: boolean; output: string }>;
maxRetries: number;
}
async function runWithStopHooks(
agent: ClaudeAgent,
hooks: StopHook[]
): Promise<RefactorResult> {
let attempt = 0;
while (attempt < hooks[0].maxRetries) {
const candidateCode = await agent.generate();
for (const hook of hooks) {
const result = await hook.check();
if (!result.passed) {
await agent.addContext({
role: "verification_failure",
content: `${hook.name} failed:\n${result.output}`
});
attempt++;
break;
}
}
if (allHooksPassed) {
return { code: candidateCode, verified: true };
}
}
throw new Error("Max retries exceeded");
}
The stop hook invokes tsc, eslint, or vitest as child processes, captures stdout/stderr, and parses the result. If the exit code is non-zero, the error output appends to the agent’s message history. The agent sees the exact type error or test failure and generates a fix in the next iteration.
AST Transforms: Deterministic Rewrites That Surface Type Errors Immediately
TypeScript’s Compiler API provides a visitor pattern for traversing and modifying syntax trees. The agent doesn’t edit raw strings; it applies transforms to the AST and emits updated source. This surfaces type errors at generation time, not after manual inspection.
Example transform: renaming a function across a codebase:
import ts from "typescript";
function renameFunctionTransform(
oldName: string,
newName: string
): ts.TransformerFactory<ts.SourceFile> {
return (context) => {
return (sourceFile) => {
const visitor = (node: ts.Node): ts.Node => {
if (
ts.isFunctionDeclaration(node) &&
node.name?.text === oldName
) {
return ts.factory.updateFunctionDeclaration(
node,
node.modifiers,
node.asteriskToken,
ts.factory.createIdentifier(newName),
node.typeParameters,
node.parameters,
node.type,
node.body
);
}
return ts.visitEachChild(node, visitor, context);
};
return ts.visitNode(sourceFile, visitor);
};
};
}
The transform runs against every file in the project. The agent receives the updated AST, emits code, and immediately runs tsc --noEmit. If the rename broke an import or call site, the type-checker output includes the file path, line number, and error message. The agent reads this and generates a fix for the next iteration.
The Ralph Wiggum Pattern: Looping Prompts Back with Error Output
The Ralph Wiggum pattern (named for the Simpsons character who repeats instructions until they work) feeds verification failures back into the agent’s context. The agent doesn’t stop after one attempt; it retries with the exact error message until the check passes or the retry cap is reached.
Feedback loop structure:
- Agent generates code.
- Verification hook runs
eslint --format json. - Hook parses JSON output and extracts rule violations.
- Hook appends violations to agent context: “ESLint found 3 errors: [details].”
- Agent generates a fix addressing the specific violations.
- Loop repeats until ESLint returns zero errors.
This pattern works because modern linters and type-checkers produce structured output. The agent doesn’t need to interpret vague error messages; it receives machine-readable diagnostics with file paths, line numbers, and rule IDs.
Prompt structure for feedback iteration:
You generated code that failed verification. Here are the errors:
File: src/utils/parser.ts
Line: 42
Error: TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
File: src/utils/parser.ts
Line: 58
Error: TS2322: Type 'undefined' is not assignable to type 'ParseResult'.
Fix these errors and regenerate the code.
The agent sees the exact type mismatch and the line number. It doesn’t need to re-read the entire file; it targets the specific lines that failed.
Circuit Breakers: Detecting Infinite Retry Loops
The Ralph Wiggum pattern can loop forever if the agent generates the same broken code repeatedly. Circuit breakers detect this by hashing error output and counting consecutive identical failures. After a threshold (typically 3), the pipeline exits and surfaces the failure to a human.
Circuit breaker logic:
interface CircuitBreaker {
errorHistory: string[];
threshold: number;
}
function checkCircuitBreaker(
breaker: CircuitBreaker,
errorOutput: string
): boolean {
const errorHash = hashString(errorOutput);
if (breaker.errorHistory.slice(-breaker.threshold).every(h => h === errorHash)) {
throw new Error("Circuit breaker tripped: identical errors repeated");
}
breaker.errorHistory.push(errorHash);
return true;
}
The breaker doesn’t compare full error text; it hashes the output to detect semantic equivalence. If the agent generates three consecutive attempts that produce the same type error, the pipeline assumes the agent is stuck and exits.
State Management: Serializing Context for Resumption or Rollback
Multi-stage refactoring pipelines need to resume after failures or rollback to a known-good state. The agent’s context (message history, verification results, file diffs) must serialize to disk so the pipeline can restart without losing progress.
State snapshot structure:
interface PipelineState {
sessionId: string;
currentStage: "transform" | "verify" | "complete";
messageHistory: Message[];
verificationResults: VerificationResult[];
fileDiffs: Map<string, { before: string; after: string }>;
retryCount: number;
timestamp: number;
}
function saveState(state: PipelineState): void {
const stateFile = `.refactor-state/${state.sessionId}.json`;
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
}
function loadState(sessionId: string): PipelineState | null {
const stateFile = `.refactor-state/${sessionId}.json`;
if (!fs.existsSync(stateFile)) return null;
return JSON.parse(fs.readFileSync(stateFile, "utf-8"));
}
The pipeline writes state after every verification attempt. If the process crashes or the agent hits a retry limit, the next invocation loads the state and resumes from the last checkpoint. This avoids re-running expensive AST transforms or re-generating code that already passed earlier stages.
Rollback uses the fileDiffs map to restore the original source. If verification fails after the retry cap, the pipeline applies the inverse diff and exits cleanly.
Orchestration Trade-offs
| Dimension | Agent-Only Approach | Verification-First Pipeline |
|---|---|---|
| Correctness guarantee | None (agent declares success) | Mechanical (linters/types must pass) |
| Latency per refactor | Single LLM call | Multiple calls + verification overhead |
| Failure mode | Silent bugs in generated code | Explicit failure after retry cap |
| Human review burden | High (must check every line) | Low (only review verified output) |
| Resumability | No (must restart from scratch) | Yes (state serializes to disk) |
| Cost per refactor | Low (one API call) | Higher (multiple retries + tool invocations) |
The verification-first approach trades latency and cost for correctness. If your refactor touches 50 files and breaks types in 10, the agent will retry until all 10 pass. This costs more tokens but eliminates the manual verification step.
When Type-Checking Fails Mid-Pipeline
Type-checking failures mid-pipeline trigger the feedback loop. The agent receives the full tsc output, including file paths and error codes. It doesn’t need to guess which files broke; the type-checker output is explicit.
Failure handling sequence:
- Agent generates code for 50 files.
tsc --noEmitruns and exits with code 1.- Pipeline parses stderr and extracts 8 type errors.
- Pipeline appends errors to agent context.
- Agent generates fixes for the 8 files.
tsc --noEmitruns again.- If errors remain, loop repeats. If zero errors, pipeline advances.
The agent doesn’t re-generate all 50 files; it targets the specific files that failed. This reduces token cost and latency for large refactors.
Observability: Logging Verification Attempts and Token Usage
Production pipelines log every verification attempt, token count, and retry reason. This exposes bottlenecks (which checks fail most often) and cost drivers (which refactors burn the most tokens).
Observability schema:
interface VerificationLog {
sessionId: string;
stage: string;
attempt: number;
checkName: string;
passed: boolean;
errorOutput?: string;
tokensUsed: number;
durationMs: number;
timestamp: number;
}
Logs stream to a structured logging backend (e.g., Datadog, Honeycomb) where you can query:
- Average retry count per refactor type.
- Which linter rules fail most often.
- Token cost distribution across verification stages.
- Refactors that hit the circuit breaker threshold.
This data informs prompt tuning. If the agent repeatedly fails on a specific ESLint rule, you adjust the system prompt to emphasize that rule.
Deployment Shape: Running Pipelines in CI vs. Local
Verification-first pipelines run in two modes: local (developer machine) and CI (GitHub Actions, GitLab CI).
Local mode:
- Developer invokes pipeline via CLI:
refactor-agent rename-function oldName newName. - Pipeline runs AST transform, invokes Claude, verifies locally, and writes diffs to disk.
- Developer reviews diffs and commits if satisfied.
CI mode:
- Pipeline runs on every pull request.
- Agent refactors code, verifies, and pushes a commit to the PR branch.
- CI logs include verification results and token usage.
- Human reviewer sees only verified output.
CI mode requires secrets management for Claude API keys and rate-limit handling. If the pipeline hits API limits mid-refactor, it serializes state and retries after backoff.
Security Boundaries: Sandboxing Tool Execution
Verification hooks execute arbitrary commands (tsc, eslint, vitest). If the agent generates malicious code that exploits a linter plugin, the pipeline could execute untrusted code. Sandboxing mitigates this.
Sandboxing strategies:
- Container isolation: Run verification hooks inside Docker containers with no network access.
- Filesystem restrictions: Mount only the project directory (read-only) and a scratch directory (write-only).
- Process limits: Use
ulimitto cap CPU, memory, and execution time for verification commands. - Allowlist binaries: Only permit known-safe binaries (
tsc,eslint) and block shell execution.
The pipeline never passes agent-generated code directly to eval() or exec(). All verification happens through pre-approved binaries with constrained environments.
Likely Failure Modes
Agent generates syntactically valid but semantically broken code:
- Verification hooks catch type errors but not logic bugs.
- Tests must cover the refactored code paths.
- If tests are missing, the agent can pass verification but break runtime behavior.
Circuit breaker trips on legitimate edge cases:
- Agent hits retry cap because the refactor requires manual intervention (e.g., resolving a merge conflict).
- Pipeline exits and surfaces the failure, but the agent was making progress.
- Mitigation: Increase retry cap or add human-in-the-loop checkpoints.
Verification tools have non-deterministic output:
- Some linters (e.g., Prettier) produce different output based on environment.
- Agent sees different errors on retry and loops forever.
- Mitigation: Pin tool versions and normalize output before hashing.
Token cost spirals on large refactors:
- Agent retries 10 times across 100 files, burning thousands of tokens per attempt.
- Cost exceeds budget before verification passes.
- Mitigation: Batch refactors into smaller chunks and set per-session token caps.
Technical Verdict
Use verification-first pipelines when:
- Refactoring touches more than 10 files and manual verification is expensive.
- You have comprehensive linter/type-checker/test coverage that catches correctness issues.
- Token cost is acceptable (expect 3-5x the cost of a single agent call).
- You need auditable correctness guarantees before human review.
Avoid when:
- Refactor is exploratory and you expect to iterate manually.
- Verification tools are slow (e.g., full test suite takes 10+ minutes).
- You lack structured output from linters (agent can’t parse error messages).
- Token budget is tight and retry cost