Sunday, November 29, 2026

A "Hello World" for Autonomous Engineering Agents: Refactoring Legacy Java with Small Local Models, Milvus Memory & ArchUnit Guardrails

Teaching Small Local Models to Refactor Enterprise Java

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.

Source Code & Refactored Branch: Explore the full orchestration harness, Milvus RAG/memory integration, deterministic guardrails, and generated Spring Boot slice on GitHub at htotapally/autonomous-java-refactoring-guardrails (refactored) .

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-8k on 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, and ArchitectureGuardrailTest.java are 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 custom RuntimeException types, enforces @Retryable + TransientDataAccessException catch ordering, and blocks invalid Mockito patterns in milliseconds before mvnw.cmd even 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:

  1. Extract Domain Model & Errors (compile gate): Immutable Java 21 record (OrderSummary) + custom OrderPersistenceException.
  2. Define Persistence Boundary (compile gate): Plain OrderRepository interface + @Repository JdbcOrderRepository using NamedParameterJdbcTemplate.
  3. Refactor Business Service (compile gate): Constructor-injected OrderService annotated with @Retryable(retryFor = TransientDataAccessException.class) and clean exception translation.
  4. Strangler-Fig Legacy Facade (compile gate): Refactors LegacyOrderReportService into a zero-SQL thin @Service facade delegating to OrderService so existing callers never break.
  5. Isolated Unit Tests (test gate): Generates OrderServiceTest (@ExtendWith(MockitoExtension.class)) and passes Maven Surefire, ArchUnit (ArchitectureGuardrailTest), and PMD 7 cleanly.

System Architecture

CLI Orchestrator run_batch.py (--replan) SHA-256 Workspace Indexer CONVENTIONS / IMPORTS / ArchUnit Milvus: codebase_chunks Semantic Rules & API Signatures Milvus: agent_memories Episodic Error → Fix Lessons Bifrost AI Gateway (:18080) Tiered Router & VRAM Unloader Ollama Node 1 (Jetson) qwen2.5-coder3b-8k (Attempt 1) Ollama Node 2 (Heavy) qwen2.5-coder:7b (Plan & Retry) 5-Step Execution Engine Domain → Repo → Service → Facade → Test Normalizers & Pre-Flight Gates fix_imports.py + [TYPE-FIX] + AST Rules Deterministic Build Gate mvnw test (JUnit 5 + ArchUnit + PMD 7) Green Build & Self-Learning Commits Verified Fixes to Milvus

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