Skip to content
Blog

Building a Code Refactoring Swarm: Analyzer, Transformer, and Test Runner

Build an ADK agent swarm that analyzes, rewrites, and test-verifies a Python module in a retry loop with Analyzer, Transformer, and Test Runner agents.

Published on • November 30, 2026

AI Assistant

“Refactor this module” is the task every developer wants an agent to do — and the one they quietly fear, because a model can rewrite 400 lines in seconds and still ship something that fails on line 12. The missing ingredient is not a better model. It is a verification loop: something that runs the test suite after every rewrite and forces the swarm to try again until the suite is green.

This post builds exactly that in Google Agent Development Kit (ADK): a refactoring swarm with three specialists — an Analyzer that diagnoses the code, a Transformer that applies an edit strategy, and a Test Runner that objectively grades the result — orchestrated by SequentialAgent and LoopAgent so the loop terminates on evidence rather than optimism.


1. Why a Single “Refactor Agent” Fails

One agent with a read_file tool and an edit_file tool will happily perform all three jobs in one breath: it reads a file, decides what to change, changes it, and then claims the tests still pass — because nothing in the loop makes that claim falsible.

Splitting responsibilities fixes this, because each specialist gets one question:

   ┌────────────┐      ┌──────────────┐      ┌──────────────┐
   │  ANALYZER  │ ───► │ TRANSFORMER │ ───► │ TEST RUNNER  │
   │ "What is   │      │ "Given a    │      │ "Is it true  │
   │  wrong?"   │      │  strategy,  │      │  now?"       │
   └────────────┘      │  make the   │      └──────┬───────┘
        LLM            │  edit"      │             │
                        └──────────────┘        pass/fail → state
                             LLM                    Python
                              │                        │
                              └───── LoopAgent ◄──────┘
                                   (retry until escalate)

Notice the type of each node: the first two are probabilistic (analysis and rewriting are judgment calls), the third is deterministic (running pytest is not a matter of opinion). ADK lets you mix them in one workflow because everything — LLM agent or plain Python class — is an agent that emits Events.


2. Architecture: Pipeline Inside a Retry Loop

The composition rule is simple: a SequentialAgent for one attempt, a LoopAgent around it for retries.

RefactorSwarm (LoopAgent, max_iterations=4)
 │
 └── attempt (SequentialAgent)
      ├── analyzer        (LlmAgent  → output_key="refactor_plan")
      ├── transformer     (LlmAgent  → output_key="proposed_patch")
      └── test_runner     (custom BaseAgent → state["test_result"])

The LoopAgent executes its sub_agents sequentially, over and over, until either the custom test runner emits an Event with actions=EventActions(escalate=True) (meaning: tests pass, stop looping) or max_iterations is hit (meaning: we gave up safely instead of burning tokens forever).


3. The Analyzer: Diagnosis, Not Edits

The Analyzer reads the target module and produces a structured plan. Two design choices keep it honest: it is told not to edit anything, and its output goes into a fixed state key so the Transformer consumes a contract, not free prose.

from typing import Any, Dict
import subprocess, tempfile, textwrap, pathlib

from google.adk.agents import Agent, BaseAgent, SequentialAgent, LoopAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event, EventActions
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from pydantic import BaseModel, Field


class CodeInput(BaseModel):
    path: str = Field(description="Path of the module to refactor.")
    source: str = Field(description="Full source text of the module.")
    tests: str = Field(description="pytest test file covering the module.")


analyzer = Agent(
    name="analyzer",
    model="gemini-3.8-flash",
    description="Diagnoses code smells and proposes a refactoring plan. Never edits code.",
    instruction="""
    You are a senior engineer reviewing a Python module and its tests.
    Identify concrete problems: duplication, dead branches, unclear naming,
    missing type hints, risky mutable defaults.
    Produce a numbered plan where every step is small and independently testable.
    Output ONLY the plan as markdown. Do not rewrite the module.
    """,
    output_key="refactor_plan",
)

The instruction deliberately forbids rewriting. In a swarm, agents that overreach destroy the separation that makes failures debuggable: when the transformer goes wrong, you want to know whether the plan was bad or the execution was bad.


4. The Transformer: Plan In, Patch Out

The Transformer receives the plan from session.state["refactor_plan"] (ADK substitutes {refactor_plan} into the instruction automatically) and must return a complete replacement for the module — deterministic to apply, no prose around it.

transformer = Agent(
    name="transformer",
    model="gemini-3.8-flash",
    description="Applies the approved refactoring plan to source code, preserving behavior.",
    instruction="""
    Refactoring plan to execute:
    {refactor_plan}

    Return the COMPLETE new source code of the module.
    Rules:
    - Preserve every public function signature and its behavior.
    - Do not rename test targets or change imports the tests rely on.
    - Output only Python source inside a single ```python block.
    """,
    output_key="proposed_patch",
)

Keeping the interface stable is the transformer’s core constraint: the test suite is the arbiter, and an agent that “improves” a function name the tests import will be graded as a regression. The prompt says so explicitly, because a model that is not told where the fence is will step over it.


5. The Test Runner: A Deterministic Custom Agent

Here is the swarm’s spine. TestRunnerAgent subclasses BaseAgent, writes the current source and tests to a temp directory, runs pytest, and records the outcome in session state. No model is involved, so the verdict cannot be talked into compliance.

class TestRunnerAgent(BaseAgent):
    """Runs pytest on the proposed source and records pass/fail in state."""

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        request: CodeInput = ctx.session.state["code_input"]
        source = ctx.session.state.get("proposed_patch") or request.source

        with tempfile.TemporaryDirectory() as tmp:
            root = pathlib.Path(tmp)
            (root / "module_under_test.py").write_text(_strip_fence(source))
            (root / "test_module.py").write_text(request.tests)
            proc = subprocess.run(
                ["python", "-m", "pytest", "-q", "--no-header", str(root)],
                capture_output=True, text=True, timeout=60,
            )
            passed = proc.returncode == 0

        ctx.session.state["test_result"] = "green" if passed else "red"
        ctx.session.state["test_output"] = (proc.stdout + proc.stderr)[-2000:]

        # Escalate stops the LoopAgent; only do it when the suite passes.
        yield Event(author=self.name, actions=EventActions(escalate=passed))


def _strip_fence(text: str) -> str:
    text = text.strip()
    if text.startswith("```"):
        text = text.split("\n", 1)[1]
    if text.endswith("```"):
        text = text.rsplit("```", 1)[0]
    return text

Subclassing BaseAgent requires declaring sub-agents (if any) as annotated fields and passing them through super().__init__, since BaseAgent is a Pydantic model with extra='forbid' — a common stumbling block when your constructor silently accepts nothing. Also note the timeout: a deterministic runner must be bounded too, or a test that hangs stalls the whole swarm.


6. Wiring the Swarm Together

attempt = SequentialAgent(
    name="refactor_attempt",
    sub_agents=[analyzer, transformer, TestRunnerAgent(name="test_runner")],
)

root_agent = LoopAgent(
    name="refactoring_swarm",
    max_iterations=4,
    sub_agents=[attempt],
)


async def main():
    session_service = InMemorySessionService()
    runner = Runner(
        agent=root_agent, app_name="refactor", session_service=session_service
    )
    session = await session_service.get_or_create(
        app_name="refactor", user_id="dev_42"
    )
    session.state["code_input"] = CodeInput(
        path="utils/report.py",
        source=pathlib.Path("utils/report.py").read_text(),
        tests=pathlib.Path("tests/test_report.py").read_text(),
    )

    async for event in runner.run_async(
        session=session, message="Refactor this module without changing behavior."
    ):
        if event.actions and event.actions.state_delta:
            delta = event.actions.state_delta
            if "test_result" in delta:
                print("test_result →", delta["test_result"])
        if event.actions and event.actions.escalate:
            print("tests green — loop terminated")


if __name__ == "__main__":
    import asyncio, pathlib
    asyncio.run(main())

The run trace reads like a build log: test_result → red on attempt 1 (the analyzer’s plan was too aggressive), test_result → green on attempt 2 with escalate=True, and the LoopAgent exits before touching iteration 3. Each attempt’s events carry the state_delta for audit and debugging.

A note on ADK 2.0: the template workflows used here are being superseded by graph-based and dynamic workflows (the SequentialAgent / ParallelAgent / LoopAgent classes are deprecated in Python and TypeScript in favor of the newer Workflow construct). The swarm’s logic — sequence, condition, bounded retry — maps one-to-one onto graph routes if you migrate, and the custom TestRunnerAgent is unaffected either way.


7. What Makes the Swarm Reliable

Every claim has a refuter. The analyzer’s plan and the transformer’s patch are both hypotheses; only the test runner is a fact. Making the fact deterministic is what turns a hallucination-prone workflow into a build system.

State is the data bus. output_key passes artifacts between agents without stuffing them into prompts manually, and event.actions.state_delta gives you a machine-readable trace of every handoff.

Loops are bounded. max_iterations converts “retry until green” into “retry four times, then report failure” — the difference between a pipeline and a runaway bill.

Checklist

  1. Separate diagnosis, execution, and verification into three agents with one job each.
  2. Make the verifier deterministic — a custom BaseAgent running the real test suite, not an LLM grading its own homework.
  3. Connect stages with output_key and read them as {state_key} in downstream instructions.
  4. Wrap a SequentialAgent attempt in a LoopAgent with max_iterations, and escalate only on success.
  5. Constrain the transformer to preserve public interfaces, or the tests will punish legitimate refactors.
  6. Inspect event.actions.state_delta in your logs; it is the swarm’s flight recorder.
  7. On ADK 2.0, plan a migration path to graph workflows — the same three-node logic, with explicit edges and retries.

Sources