# AST-Driven Agent Refactoring: How Claude Code Pipelines Verify Their Own Output Before Human Review

> Source: <https://dev.to/mech_app_ai/ast-driven-agent-refactoring-how-claude-code-pipelines-verify-their-own-output-before-human-review-122i>
> Published: 2026-11-25 10:08:14+00:00

**Recommendation:** Wrap refactoring agents in stop hooks that run tsc, eslint or vitest and append failure output to the agent's context, capping retries so the agent fixes errors before human review.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

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.

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:**

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 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:**

``` js
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.

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:**

``` python
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 (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:**

`eslint --format json`.
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.

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.

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.

| 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.

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:**

`tsc --noEmit` runs and exits with code 1.
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.

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:

This data informs prompt tuning. If the agent repeatedly fails on a specific ESLint rule, you adjust the system prompt to emphasize that rule.

Verification-first pipelines run in two modes: local (developer machine) and CI (GitHub Actions, GitLab CI).

**Local mode:**

`refactor-agent rename-function oldName newName`.
**CI mode:**

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.

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:**

`ulimit` to cap CPU, memory, and execution time for verification commands.`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.

**Agent generates syntactically valid but semantically broken code:**

**Circuit breaker trips on legitimate edge cases:**

**Verification tools have non-deterministic output:**

**Token cost spirals on large refactors:**

**Use verification-first pipelines when:**

**Avoid when:**
