From Monolithic Scripts to Autonomous A2A Agents: How We Built a Self-Improving Refactoring Engine
Modernizing legacy enterprise codebases with Large Language Models sounds straightforward until you try it on a real repository with strict architectural boundaries, static analysis rules, and build gates.
When we started building refactor-agent, our goal was clear: take a tightly coupled legacy Java/Spring service (LegacyOrderReportService) and decompose it into a clean, layered Spring Boot 3.5 architecture—complete with domain DTOs, custom exceptions, NamedParameterJdbcTemplate repositories, @Retryable services, thin facades, JUnit 5/Mockito unit tests, ArchUnit checks, and PMD 7 static analysis.
Here is the honest engineering story of how we evolved from a monolithic Python script into a containerized, dual-protocol (A2A + MCP) 7-agent system backed by tiered LLM routing and a self-improving Milvus policy store.
Phase 1: The Monolithic Script Trap
Like most AI engineering efforts, Version 1 started as a single Python script running a linear loop:
- Prompt an LLM to refactor a file.
- Run Maven (
mvn test). - If it fails, paste the error back into the prompt and retry.
Where It Broke Down
- Token Waste & Latency: Sending massive context windows to a frontier cloud model on every retry was slow and expensive, while local 3B/7B models struggled when asked to handle discovery, planning, code generation, and import resolution all at once.
- Fragile Prompt-Driven Rules: Every time a model hallucinated an invalid import, declared
throws SQLExceptionon a Spring JDBC repository, or forgotMockitoExtension, we found ourselves manually editing static YAML files and prompt templates. - No Memory Across Runs: When a frontier model finally rescued a tricky failure on Attempt 3, that lesson vanished the moment the script exited.
Phase 2: Decomposing Into 7 Single-Responsibility Agents
With 30 years of enterprise architecture behind the design, the solution wasn't "a better prompt"—it was separation of concerns. We decomposed the monolith into seven single-action agents coordinated sequentially with explicit Pydantic contracts:
[RepoScout] ─► [ArchitectPlanner] ─► [CodeTransformer ⇄ BuildVerifier] ─► [RuleDistiller]
│ │ │
▼ ▼ ▼
[KnowledgeCurator] ◄─────────────── [Milvus DynamicPolicyStore] ◄─────── [KnowledgeRetriever]
RepoScoutAgent: Scans the workspace, detects base packages, extracts repository conventions, and delegates indexing.ArchitectPlannerAgent: Generates a phased execution plan (refactor_plan.json) breaking the refactoring into verifiable steps (Domain → Repository → Service → Facade → Tests).CodeTransformerAgent: Executes each step using tiered LLM routing via Bifrost—starting with a fast local Edge (3B) model, escalating to Heavy (7B) on failure, and reserving Frontier (120B) strictly as a last-resort rescue tier.BuildVerificationAgent: An autonomous deterministic gatekeeper. Before invoking Maven, it runs zero-token auto-healers (normalizing missingpackageheaders, stripping invalidthrows SQLExceptionsignatures in repositories, and resolving canonical imports via RAG). Then it enforces regex/AST guardrails and runsmvn test, ArchUnit, and PMD 7.RuleDistillerAgent: Watches for steps whereedgeorheavyfailed andfrontiersucceeded, distilling the root cause into a reusable rule.KnowledgeRetrieverAgent&KnowledgeCuratorAgent: Manage read/write access to our Milvus vector collections (codebase_chunks,agent_memories, andpolicy_rules).
Phase 3: Turning Frontier Rescues Into Permanent Guardrails (DynamicPolicyStore)
The biggest architectural breakthrough was eliminating manual YAML maintenance. We built DynamicPolicyStore backed by Milvus (policy_rules):
- On startup, static baseline rules seed idempotently into Milvus.
- Between every refactoring step,
BuildVerificationAgenthydrates its live policy from the store. - Whenever
frontierrescues a failure thatedgeorheavymissed,RuleDistillerAgentextracts a structuredDynamicPolicyEntry(validating regex syntax automatically) and promotes it straight into Milvus.
Phase 4: Standardizing for Enterprise A2A + MCP & Docker
To plug refactor-agent into our broader enterprise AIOps ecosystem alongside Bifrost (:18080), Milvus (:19530), Jaeger (:16686), and our Spring AI Governance Orchestrator (:8085), we standardized the external interface using the Dual-Protocol Hub-and-Spoke pattern:
- MCP SSE (
/sse): Exposes fine-grained tools (refactor_repository,scout_repository,verify_repository,query_knowledge_base) and auto-publishes to our Official MCP Registry (:8090). - Standard A2A JSON-RPC 2.0 (
/.well-known/agent.json&POST /a2a): Exposes an industry-standard Agent Card andmessage/sendtask lifecycle (working→completed|failed) returning structured JSON artifacts. - Containerized Runtime: Packaged on Ubuntu 24.04 with Eclipse Temurin JDK 21, Maven, and Python 3.12, attached directly to our Docker Compose service mesh (
mcp_default,mcp-registry_default,aiops-governance-orchestrator_default).
Real-World Lessons From the Trenches
Containerizing a polyglot AI + Java build agent taught us a few practical lessons worth sharing:
- Line Endings Kill Build Wrappers: Mounting a Windows repository into a Linux container caused
./mvnwto fail withset: Illegal option -due to CRLF line endings. Pre-installing Maven in the container image and invokingmvndirectly eliminated cross-OS wrapper friction completely. - Deterministic Auto-Healing Beats Prompt Tuning: When a 3B model occasionally emitted a Java
recordwithout apackagedeclaration, adding a 6-line path-to-package normalizer inBuildVerificationAgentsolved it in under a millisecond—zero extra LLM tokens required. - Container Mesh Over Host IPs: Wiring the container directly onto existing external Docker networks (
mcp-bifrost-gateway,mcp-demo,mcp-registry) eliminated host firewall headaches and cut inter-service latency to near zero.
What's Next: Closing the Autonomous AIOps Loop
With the containerized A2A/MCP 7-agent engine passing all 5 refactoring and verification gates cleanly from scratch, only two links remain to close the full autonomous incident-to-PR loop:
GitMergeRequestAgent: Automatically branching, committing verified changes, and opening a GitLab Merge Request / GitHub Pull Request with full audit metadata.- Event-Driven Kafka Ingestion: Consuming production log/trace anomaly events from Kafka to trigger A2A refactoring runs automatically.
The shift from scripting to multi-agent architecture isn't about writing more Python—it's about boxing probabilistic LLMs inside deterministic engineering invariants so they can safely ship production code.

