Teaching Small Local Models to Refactor Enterprise Java: A "Hello World" for Autonomous Engineering Agents
Asking an LLM to write a standalone function in a chat window is easy. Getting small, local open-weights models (3B and 7B parameters) to autonomously decompose a tightly coupled legacy Java service into a clean, multi-layered Spring Boot 3.5 architecture—and pass Maven compilation, JUnit 5 + Mockito tests, ArchUnit architecture rules, and PMD 7 static analysis from scratch—is a completely different engineering problem.
Think of this project as the true "Hello World" of agentic software engineering: the LLM is never trusted blindly, but operates inside a deterministic harness of living vector memory, tiered local inference routing, and automated verification gates.
What We Accomplished
1. Multi-Node Tiered Inference Routing (Edge 3B → Heavy 7B)
Instead of sending every prompt to a massive cloud frontier model, the orchestrator (run_batch.py) routes requests through a local Bifrost AI Gateway across two physical Ollama nodes:
- Planner & Escalation Tier (
qwen2.5-coder:7b): Generates the 5-step JSON refactoring plan (refactor_plan.json) and steps in automatically whenever a step fails its first attempt. - Fast Edge Worker (
qwen2.5-coder3b-8kon NVIDIA Jetson): Handles first-pass file generation at low latency. Once our institutional knowledge base matured, even the 3B edge model generated valid, ArchUnit-compliant Java code and passing JUnit 5 + Mockito unit tests on Attempt 1. - Automatic GPU Lifecycle Management: Explicitly unloads models (
keep_alive: 0) across nodes after planning and upon exit so VRAM remains clean.
2. Living Institutional Memory with Milvus (codebase_chunks & agent_memories)
Model weights are static, so institutional knowledge lives externally in Milvus behind a Spring Boot MCP/RAG service:
- Semantic Convention & API Retrieval (
codebase_chunks):CONVENTIONS.md,JAVA_IMPORTS.md, andArchitectureGuardrailTest.javaare chunked and SHA-256 hash-tracked so unchanged files skip re-indexing while updated rules sync immediately. - Episodic Self-Healing (
agent_memories): Whenever a step fails on Attempt 1 and succeeds on Attempt 2 or 3, the agent commits(error_signature → verified_fix)into Milvus. On future runs, semantic search retrieves those exact lessons before retrying.
3. Deterministic Pre-Flight Guardrails & Automated Normalization
Small models frequently trip over predictable Java/Spring quirks—hallucinated JPA imports, field @Autowired injection, MockitoAnnotations.openMocks double-mocking, or instantiating abstract Spring DataAccessException classes. Instead of burning slow compiler cycles on known failure modes:
fix_imports.py([IMPORT-FIX]): Strips hallucinated imports and resolves valid symbols deterministically against the project's classpath.- Pre-Flight AST/Regex Gates & Type Normalizers (
[TYPE-FIX]): Enforces constructor injection (private final), verifies dual(String)and(String, Throwable)constructors on customRuntimeExceptiontypes, enforces@Retryable+TransientDataAccessExceptioncatch ordering, and blocks invalid Mockito patterns in milliseconds beforemvnw.cmdeven launches.
4. End-to-End 5-Step Legacy Decomposition from Scratch
Starting from a single monolithic LegacyOrderReportService wired with @Value JDBC credentials and raw java.sql.* calls, the pipeline autonomously executes and verifies five gated steps:
- Extract Domain Model & Errors (
compilegate): Immutable Java 21record(OrderSummary) + customOrderPersistenceException. - Define Persistence Boundary (
compilegate): PlainOrderRepositoryinterface +@RepositoryJdbcOrderRepositoryusingNamedParameterJdbcTemplate. - Refactor Business Service (
compilegate): Constructor-injectedOrderServiceannotated with@Retryable(retryFor = TransientDataAccessException.class)and clean exception translation. - Strangler-Fig Legacy Facade (
compilegate): RefactorsLegacyOrderReportServiceinto a zero-SQL thin@Servicefacade delegating toOrderServiceso existing callers never break. - Isolated Unit Tests (
testgate): GeneratesOrderServiceTest(@ExtendWith(MockitoExtension.class)) and passes Maven Surefire, ArchUnit (ArchitectureGuardrailTest), and PMD 7 cleanly.
System Architecture
What's Next: Packaging into a General-Purpose refactor-agent
Now that the core loop is proven end-to-end on Java and Spring Boot, the next evolution is extracting the language-specific checks behind a pluggable VerificationFacade (backed by externalized YAML policy packs) and packaging the runner into an installable CLI (refactor-agent --repo <path> --goal "<task>") capable of refactoring any codebase while sharing a single compounding Milvus knowledge base.
Check out the repository and follow the progress here: https://github.com
No comments:
Post a Comment