Sunday, November 29, 2026

From Monolithic Scripts to Autonomous A2A Agents: Building a Self-Improving Refactoring Engine

From Monolithic Scripts to Autonomous A2A Agents: How We Built a Self-Improving Refactoring Engine

From Monolithic Scripts to Autonomous A2A Agents: How We Built a Self-Improving Refactoring Engine

Source Code & Architecture: Explore the full 7-agent implementation, Milvus policy store, and Docker setup on GitHub at github.com/htotapally/refactor-agent (multi_agents branch).

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:

  1. Prompt an LLM to refactor a file.
  2. Run Maven (mvn test).
  3. 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 SQLException on a Spring JDBC repository, or forgot MockitoExtension, 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]
  1. RepoScoutAgent: Scans the workspace, detects base packages, extracts repository conventions, and delegates indexing.
  2. ArchitectPlannerAgent: Generates a phased execution plan (refactor_plan.json) breaking the refactoring into verifiable steps (Domain → Repository → Service → Facade → Tests).
  3. 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.
  4. BuildVerificationAgent: An autonomous deterministic gatekeeper. Before invoking Maven, it runs zero-token auto-healers (normalizing missing package headers, stripping invalid throws SQLException signatures in repositories, and resolving canonical imports via RAG). Then it enforces regex/AST guardrails and runs mvn test, ArchUnit, and PMD 7.
  5. RuleDistillerAgent: Watches for steps where edge or heavy failed and frontier succeeded, distilling the root cause into a reusable rule.
  6. KnowledgeRetrieverAgent & KnowledgeCuratorAgent: Manage read/write access to our Milvus vector collections (codebase_chunks, agent_memories, and policy_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, BuildVerificationAgent hydrates its live policy from the store.
  • Whenever frontier rescues a failure that edge or heavy missed, RuleDistillerAgent extracts a structured DynamicPolicyEntry (validating regex syntax automatically) and promotes it straight into Milvus.
The Result: Expensive cloud model rescues continuously harden our deterministic verification layer, allowing future runs—and future repositories—to pass on Attempt 1 using fast local models.

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 and message/send task 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 ./mvnw to fail with set: Illegal option - due to CRLF line endings. Pre-installing Maven in the container image and invoking mvn directly eliminated cross-OS wrapper friction completely.
  • Deterministic Auto-Healing Beats Prompt Tuning: When a 3B model occasionally emitted a Java record without a package declaration, adding a 6-line path-to-package normalizer in BuildVerificationAgent solved 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:

  1. GitMergeRequestAgent: Automatically branching, committing verified changes, and opening a GitLab Merge Request / GitHub Pull Request with full audit metadata.
  2. 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.

Try It Yourself: Check out the complete source code, policies, and Docker Compose setup on GitHub at ://github.com.

From Hardcoded Scripts to a Self-Hardening MCP Agent: Cutting AI Refactoring Costs with a Frontier Teacher, Milvus Memory & Local Models

From Hardcoded Scripts to a Self-Hardening MCP Agent
Autonomous Engineering & AI Architecture

From Hardcoded Scripts to a Self-Hardening MCP Agent: Cutting AI Refactoring Costs with a Frontier Teacher, Milvus Memory & Local Models

In my previous post, A "Hello World" for Autonomous Engineering Agents, we proved that small local open-weights models (3B and 7B) can decompose a tightly coupled legacy Java service into a clean Spring Boot 3.5 layered architecture—passing Maven compilation, Mockito tests, ArchUnit rules, and PMD 7 static analysis.

At the end of that experiment, the orchestration lived inside a standalone Python runner (run_batch.py). That raised a natural engineering question: What happens when we graduate from a hardcoded script to a general-purpose, policy-driven Python agent (refactor-agent) exposed over MCP—and what does it actually take to make successive runs cheap, fast, and reliable?

Building and stress-testing refactor-agent across repeated clean-slate runs uncovered several hard truths about model verification, token economics, and how autonomous agents learn.

1. Converting a Script into a Policy-Driven Agent & MCP Microservice

While MCP servers act as standardized capability adapters (exposing vector stores, build tools, or databases), an autonomous agent behaves like a goal-driven backend microservice: it accepts a high-level goal, plans a multi-step workflow, verifies outputs against deterministic gates, and self-heals until the goal is met.

To make the runner reusable across repositories and languages, we extracted all Java/Spring logic out of Python code and into declarative configuration:

  • Pluggable PolicyVerificationFacade + policies/java_rules.yaml: Regex guardrails, AST/type normalizers, import healers, and Maven build gates live in external YAML policy packs rather than hardcoded Python checks.
  • Dual-Mode Entrypoint (refactor-agent):
    • CLI Mode (refactor-agent run): Executes phased refactoring directly against any target Git repository.
    • MCP SSE Server Mode (refactor-agent serve): Exposes refactor_repository on :8095/sse and auto-registers io.local/refactor-agent with our Official MCP Registry (:8090/v0/publish), allowing upstream orchestrators (like a Spring AI 1.0.0 client) to discover and invoke it dynamically.

2. The Token Economics Problem: Why Pure Local or Pure Cloud Both Fall Short

When we ran the newly packaged agent from scratch against a clean legacymess branch, two practical bottlenecks surfaced immediately:

  1. Local 7B Models Struggle with Cold-Start Planning & Unseen Rules: Generating a multi-step structured JSON architecture plan on a local 7B node frequently pushed past gateway timeouts, and small models (3B/7B) tripped when forced to infer undocumented repository conventions (like ArchUnit package boundaries or custom exception constructors) from raw source files.
  2. Sending Every Step to a Paid Frontier Model Is Wasteful: Frontier cloud models solve planning and architectural discovery in seconds, but paying frontier token rates for every file generation and retry across a 5-step refactoring does not scale economically.

3. The "Frontier Teacher → Milvus Cache → Local Student" Pattern

Instead of choosing between expensive cloud inference and slow cold-start local models, we split the lifecycle into a three-tier cascade routed through our Bifrost AI Gateway (:18080):

Tier 1 — Frontier Teacher (groq/openai/gpt-oss-120b → gpt-oss-20b)
  • One-Time Rule Bootstrap (--bootstrap-frontier): On the first pass against a repository, the Frontier model inspects pom.xml, ArchUnit guardrails, and target source files once, distilling architectural constraints and canonical imports into policies/DISCOVERED_RULES.md, and automatically uploads them into Milvus (codebase_chunks).
  • Fast Architecture Planning (~4 seconds): Using those cached rules, the Frontier tier generates refactor_plan.json in seconds instead of timing out on a local 7B node.
Tier 2 — Fast Local Edge Worker (qwen2.5-coder3b-8k on 192.168.1.171)
  • Armed with the Frontier-discovered rules in Milvus, Attempt 1 of every execution step runs locally at $0.00 marginal cost. Domain records, custom exceptions, repositories, and thin facades regularly pass compilation on Attempt 1 using just the 3B model.
Tier 3 — Heavy Local Escalation (qwen2.5-coder:7b on 192.168.1.172) & Frontier Safety Net
  • If Attempt 1 fails a guardrail or Maven gate, Attempt 2 escalates locally to the 7B model with the exact compiler diagnostic and Milvus episodic memory hints—reserving the cloud Frontier tier strictly as an Attempt 3 safety net.

4. Living the Life of a Model Verifier: Turning Every Failure into a Permanent Guardrail

One of the biggest takeaways from converting a one-off script into a repeatable agent is that models are probabilistic, while compilers are binary. Every time you reset to a clean branch (git reset --hard legacymess), an LLM can take a slightly different path—and expose a new edge case:

  • Domain Purity Drift: A model placed ResultSet mapping helpers directly inside a domain record, violating ArchUnit package boundaries—solved by adding a pure-domain-model regex rule.
  • Checked SQLException Leakage: A repository interface declared throws SQLException, breaking downstream Mockito unit tests—solved by forbidding checked SQLException in repository/ classes and enforcing throws Exception on @Test methods.
  • Stale RAG Imports vs. Disk Truth: Cached vector chunks occasionally suggested an older package path (com.example.demo.exception) over the newly generated com.example.demo.domain class on disk—solved by making local filesystem symbols authoritative over RAG suggestions during post-build import healing.
  • Gateway Rate Limits (429 / 413): Hitting free-tier rolling token-per-minute limits led to exponential backoff (3s → 6s → 9s) and automatic 120B → 20B → Local 7B failover inside TieredLLMRouter.

Each time a higher tier rescues a failed attempt, MemoryClient commits the (error_signature → verified_fix) lesson into Milvus (agent_memories)—turning runtime failures into compounding institutional memory so successive runs execute faster and cheaper.

5. Repeatable Results: Back-to-Back 5/5 Clean-Slate Runs

Once the Frontier-bootstrapped rules and episodic lessons were cached in Milvus, we ran consecutive clean-slate tests (git reset --hard legacymess && git clean -fd) without re-running --bootstrap-frontier:

  • Plan Generation: ~4 seconds via Frontier tier using cached Milvus rules.
  • Execution (Steps 1–5): Autonomous generation and verification of OrderSummary, OrderPersistenceException, OrderRepository, JdbcOrderRepository, OrderService (@Retryable), LegacyOrderReportService (in-place Strangler-Fig facade), and OrderServiceTest—passing Maven Surefire, ArchUnit, and PMD 7 cleanly across repeated runs, followed by automatic VRAM cleanup (keep_alive: 0) across both Ollama nodes.
Architecture Notes: refactor-agent • MCP • Milvus • Spring Boot 3.5 Self-Hardening Autonomous Engineering

From Monolithic Prompts to Microservice Agents: Cutting Enterprise AI Token Bloat with Local Caching and Deterministic Guardrails

From Monolithic Prompts to Microservice Agents: Cutting Enterprise AI Token Bloat

From Monolithic Prompts to Microservice Agents: Cutting Enterprise AI Token Bloat with Local Caching and Deterministic Guardrails

Lessons learned from decomposing a Java/Spring refactoring pipeline into a local-first, contract-driven multi-agent system.

As AI coding assistants become standard tools on engineering teams, two quiet anxieties are growing across organizations:

  1. The "I Don't Know, the AI Wrote It" Trap: When models generate thousands of lines of code behind opaque prompts, teams risk creating an unmaintainable black box where developers lose architectural ownership.
  2. Runaway Token Bloat: Sending entire repositories, error logs, and architectural rules to paid frontier cloud APIs on every iteration quickly costs enterprises an arm and a leg.

Recently, while packaging an autonomous Java/Spring Boot refactoring pipeline into a standalone Model Context Protocol (MCP) server, I realized we have already solved this exact class of problems before—when the industry moved from monoliths to microservices.

1. Opening the Black Box: Declarative Rules Over Blind Trust

The fear of "magic AI" comes from letting an LLM act without explicit, human-readable boundaries. When prompts hold hidden business rules and model outputs go straight into source control, nobody knows why decisions were made.

The solution is separating reasoning from policy. Instead of burying architectural standards inside prompt prose, we externalized every Java and Spring Boot standard into a declarative YAML policy file (java_rules.yaml) paired with a deterministic verification facade:

  • Human-Auditable Rules: Senior engineers define and version-control rules in plain YAML—requiring constructor injection, enforcing @Retryable exception ordering, banning JpaRepository when using JDBC, and validating Mockito test structure.
  • Deterministic Build Gates: The agent is never allowed to declare victory on its own. Every phased step must pass static policy guardrails, mvn test-compile, JUnit 5 tests, ArchUnit architecture guardrails, and PMD static analysis before moving forward.
  • Zero-Token Auto-Healers: When small local models make repeatable mechanical mistakes (like missing intra-project imports or adding redundant MockitoAnnotations.openMocks(this) calls), deterministic post-processors fix them in milliseconds using zero LLM tokens.
"Never spend LLM tokens to solve a problem that a regex rule, AST check, or compiler gate can enforce deterministically."

2. Monoliths vs. Microservices Applied to AI Agents

Early agent prototypes often look like software monoliths: one giant prompt or single mega-agent attempting to plan, scan every file, write code, resolve dependencies, and debug failures inside one massive context window. Just like monolithic applications, monolithic agents suffer from tight coupling, quadratic token bloat, and cascading failures.

By modeling agents after microservices, each component stays small, observable, and replaceable:

Dimension Monolithic Agent Anti-Pattern Microservice Agent Architecture
Scope One giant prompt handles planning, coding, and verification Single-purpose agents (refactor-agent, RAG/Memory service, Registry)
Discovery & Contracts Hardcoded function calls and brittle glue code Official MCP Registry (/v0/servers) with explicit toolName and allowedActions
Context Window Bloated full-repo dumps on every call Phased, step-by-step context scoped only to the active build gate
Replaceability Rewriting prompts breaks the entire pipeline Swap the underlying model or agent behind SSE (:8095/sse) with zero orchestrator changes

Just like a microservice, if a better coding model or refactoring engine arrives next year, we can replace refactor-agent behind its MCP contract without touching the Spring AI orchestrator or the memory store.

3. Fighting Token Bloat: Local Caching and Lesson Synchronization

Enterprise AI costs explode when systems treat every prompt as brand new—re-sending the same conventions, re-discovering the same compiler fixes, and defaulting to expensive frontier cloud models for routine tasks.

To prevent token bloat, we structured LLM routing as a tiered cascade backed by a local vector and episodic memory store (Milvus) and an LLM gateway (Bifrost):

Tier 0: Local Semantic & Episodic Cache (Milvus)  --> $0.00 (0 LLM tokens)
   │
   ▼ (Cache miss or code generation needed)
Tier 1: Local Edge Model (3B Coder on Edge Node)  --> $0.00 (Attempt 1 fast pass)
   │
   ▼ (Fails deterministic build/guardrail gate)
Tier 2: Local Heavy Model (7B Coder on GPU Node)  --> $0.00 (Planning & Attempt 2 retry)
   │
   ▼ (Only if both local tiers fail)
Tier 3: Paid Frontier Cloud API via Bifrost       --> Pay-per-use fallback (<5% of steps)
   │
   └──► Verified fix is committed back to Tier 0 local cache!

Why Local Caching & Synchronization Change the Economics

  • Hash-Deduplicated Knowledge Indexing: Workspace conventions, canonical import tables, and ArchUnit rules are indexed into local vector storage once using SHA-256 file hashes—never re-ingested unless a file changes.
  • Episodic Memory Across Runs: Whenever a retry succeeds after a compiler or guardrail error, the failure signature and verified fix are committed to local episodic memory. Future runs retrieve that lesson before hitting an expensive model.
  • Team-Wide Lesson Synchronization: In an enterprise environment, synchronizing verified episodic lessons and YAML policy updates across developer machines means one engineer's retry saves tokens for the entire organization. Paid cloud APIs become a circuit-breaker fallback rather than the default path.

Key Takeaways for Engineering Teams

  1. Keep humans in the driver's seat: Put architectural rules in version-controlled YAML and deterministic test gates, not opaque prompts.
  2. Design agents like microservices: Give each agent a single responsibility, clear MCP contracts, and independent deployability.
  3. Cache locally, escalate sparingly: Pair local 3B/7B models with episodic memory and deterministic auto-healers so paid frontier APIs are only called when genuinely needed—and cache what they teach you.

Built with Python, FastMCP/MCPServer, Spring AI, Bifrost LLM Gateway, Ollama, and Milvus.

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

Friday, November 27, 2026

Beyond Vibe Coding: Automating Log-Driven Java Defect Remediation with Local LLMs, ArchUnit, and PMD 7

Beyond Vibe Coding: Automating Log-Driven Java Defect Remediation with Local LLMs, ArchUnit, and PMD 7
Enterprise Java & AI Engineering

Beyond Vibe Coding: Automating Log-Driven Java Defect Remediation with Local LLMs, ArchUnit, and PMD 7

How to turn production stack traces into verified Spring Boot pull requests on local hardware without sacrificing architectural integrity.

Production Spring Boot services emit thousands of structured log events and distributed traces every hour. When an unhandled database error or configuration failure surfaces in those logs, the recovery workflow still looks remarkably manual: an engineer hunts down the stack frame, untangles tightly coupled legacy classes, writes a regression test, and opens a pull request.

In theory, large language models should accelerate that loop. In practice, sending proprietary Java repositories and sensitive production logs to external cloud APIs often hits immediate data governance and compliance walls. To find out whether open-weight models running entirely on local hardware can close that gap safely, I built an open-source reference pipeline in Java 21 and Spring Boot 3.5: autonomous-java-refactoring-guardrails.

The Starting Point: Runtime Failures Inside Legacy Code

Real production defects rarely hide inside clean, freshly scaffolded modules. They usually live in older service classes where infrastructure concerns and business logic have grown together over the years. In the legacymess branch of the repository, a single @Service class intentionally combines three common enterprise anti-patterns:

  • Field-injected configuration (@Value): Credentials and connection settings are injected directly into private fields, blocking plain constructor instantiation in fast unit tests.
  • Inline JDBC calls (DriverManager and ResultSet): SQL execution and connection management sit directly inside domain logic.
  • Swallowed exceptions (e.printStackTrace()): Database failures are caught, printed to standard error, and masked behind empty list returns.

When the database becomes unreachable or credentials expire, runtime logs capture raw PSQLException stack traces pointing straight to that service method. The goal of the harness is straightforward: take that captured log context, use a local LLM to extract a clean repository boundary with proper retry and exception-translation semantics, and prove architectural compliance before a human reviewer ever sees a pull request.

Preventing the “Green Build Illusion” with ArchUnit 1.3 and PMD 7

Running local code models across 3B, 7B, and 14B parameter sizes quickly reveals a trap I call the green build illusion. When prompted only to make the compiler and unit tests pass, smaller models routinely take shortcuts that undermine the codebase:

  • Leaving @Value fields untouched while wrapping the method signature to satisfy a prompt.
  • Importing java.sql.* directly inside @Service classes instead of isolating persistence behind a repository interface.
  • Returning hardcoded List.of() stubs or duplicating Mockito setup so assertions pass vacuously.

To prevent subtle architectural drift from slipping past a green Maven build, every automated refactoring pass is gated by an executable fitness function combining three verification layers:

@AnalyzeClasses(packages = "com.aiops.governance", importOptions = ImportOption.DoNotIncludeTests.class)
public class ArchitectureGuardrailTest {

    @ArchTest
    static final ArchRule services_should_not_use_field_injection =
        noFields().that().areDeclaredInClassesThat().areAnnotatedWith(Service.class)
            .should().beAnnotatedWith(Autowired.class)
            .orShould().beAnnotatedWith(Value.class);

    @ArchTest
    static final ArchRule services_should_not_access_jdbc_directly =
        noClasses().that().areAnnotatedWith(Service.class)
            .should().dependOnClassesThat()
            .resideInAnyPackage("java.sql..", "org.springframework.jdbc..");
}

Alongside ArchUnit 1.3 structural assertions, the Maven build enforces PMD 7 static rules to reject swallowed exceptions, unused imports, console print calls, and high cyclomatic complexity, while JUnit 5 and Mockito verify normal delegation, transient timeout propagation, and non-transient exception wrapping without booting a Spring context.

What Happened Across 3B, 7B, and 14B Local Models

Benchmarking identical log-driven refactoring tasks across three local model tiers highlighted clear operational trade-offs:

Model Tier Where It Excels Where It Struggles
3B (qwen2.5-coder:3b) Fast generation of Java record DTOs, custom exception hierarchies, and initial class skeletons on low-memory edge hardware. Prone to hallucinating Spring Data method signatures or leaving subtle Mockito stubbing mismatches across files.
7B (qwen2.5-coder:7b) Strong at resolving cross-file compiler errors, constructor injection, and Java 21 stream generics when fed structured Maven error output. Occasionally requires a second repair pass when refactoring deeply nested JDBC resource blocks.
14B (qwen2.5-coder:14b) Highest single-pass accuracy across multi-class Spring Boot 3.5 wiring and architectural decomposition. Noticeably slower prompt ingestion on CPU-bound systems; benefits from stage-level model unloading.

Key Takeaway: Models Are Frozen — Your Harness Learns

Core Engineering Principle: An open-weight model does not retain memory across retries; its weights are static. Reliable automation comes from encoding every recurring failure mode into deterministic code outside the model.

Instead of writing longer prompts whenever a model stumbled on Java 21 generics or missing imports, three deterministic patterns delivered far higher reliability:

  1. Bottom-Up Batch Decomposition: Generate domain records and repository interfaces first, verify compilation, and only then wire service classes and unit tests.
  2. Deterministic AST & Import Normalization: Promote recurring import resolutions and type fixes out of LLM retry loops into deterministic code recipes (such as OpenRewrite rules).
  3. Explicit Memory Management: Unload models (keep_alive: 0) between pipeline stages so local workstations and edge devices stay responsive during Maven compilation and test runs.

Scaling to Enterprise Observability: Jaeger, Kafka, and Automated PRs

To move from a local prototype to an enterprise microservice environment, the same verification loop connects directly to standard observability infrastructure:

1. Observability OpenTelemetry & Jaeger export stack traces to prod.exceptions.triaged 2. Triage & Slicing Deduplicate fingerprints, map repo & commit SHA, slice AST target context 3. Local LLM Escalation Phase 0 Plan & Batch Gen 3B → 7B → 14B + Deterministic Recipes 4. Zero-Trust Gate JUnit 5 + Mockito ArchUnit 1.3 + PMD 7 Open Verified PR
End-to-end log-driven defect remediation pipeline from OpenTelemetry/Jaeger traces and Kafka to local verification gates and GitHub Pull Requests.
  • Trace & Log Ingestion: OpenTelemetry and Jaeger export runtime exceptions to a dedicated Kafka topic (prod.exceptions.triaged).
  • Fingerprinting & Triage: A consumer groups duplicate stack traces, maps stack frames to exact source repositories and commit SHAs, and filters transient network noise from actionable code defects.
  • Isolated Local Remediation: A worker checks out a fix/<trace-id> branch, runs a planner to map affected interfaces, and escalates edits across 3B → 7B → 14B local models paired with deterministic recipes.
  • Zero-Trust Pull Request Gate: A pull request is opened on GitHub only if mvn test—including JUnit 5, Mockito, ArchUnit 1.3, and PMD 7—passes completely. Reviewers receive the diff alongside the original Jaeger trace link and guardrail report.

You can inspect the complete before-and-after code, guardrail tests, and batch orchestrator across the main, legacymess, and refactored branches in the autonomous-java-refactoring-guardrails GitHub repository.

About the Author
Hara Totapally is a software architect and engineering leader based in Ashburn, Virginia, with over twenty years of experience building enterprise Java platforms, distributed systems, and practical AI automation workflows.

Wednesday, November 25, 2026

From Zero Unit Tests to Self-Healing Java Code: Turning Production Logs into Automated Fixes on an 8GB Jetson Orin Nano

From Zero Unit Tests to Self-Healing Java Code: Turning Production Logs into Automated Fixes on an 8GB Jetson Orin Nano

In legacy or fast-moving codebases, production logs are often the most honest documentation you have. When an application crashes at 2:00 AM with zero unit test coverage, developers typically follow the same manual routine: read the stack trace, locate the failing method, write a test to reproduce the crash, patch the edge case, and verify the build.

I wanted to see if I could automate that entire loop—starting with zero unit tests and using only runtime log files as the source of truth—while running the AI model 100% locally on an 8GB NVIDIA Jetson Orin Nano.

The result is split across two open-source repositories:

  • The Target Application: springboot-calculator-seed — A deliberately unhardened Spring Boot REST API with zero unit tests.
  • The Autonomous Repair Control Plane: defect-repair-agent — A Python orchestrator that parses logs, slices Java ASTs, generates JUnit 5 tests and patches via Ollama (qwen2.5-coder:3b), and verifies fixes with Maven.

Here is how the system works, how it turns raw stack traces into dynamic regression tests, and what it took to make a 3-billion-parameter edge model reliable.


1. The Starting Point: Zero Tests, Real Runtime Crashes

To "eat our own dog food," I built springboot-calculator-seed with four atomic service methods (add, subtract, multiply, divide) accepting generic Java Number wrapper objects—and intentionally omitted all input validation and unit tests.

Because the methods were unhardened, sending malformed or edge-case HTTP requests immediately produced genuine production stack traces in logs/app.log:

  • POST /api/calc/divide with {"a": 10, "b": 0} threw java.lang.ArithmeticException: / by zero.
  • POST /api/calc/add with {"a": 10} (leaving b as null) threw java.lang.NullPointerException.

At this stage, the log file was the only signal describing what was broken and how the application was actually failing.

2. The Split-Node Architecture: Edge AI + Workstation Build

Running an LLM, a Python orchestrator, and a Java/Maven JVM build simultaneously on an 8GB Jetson Orin Nano quickly exhausts unified RAM. To keep inference fast and memory flat, I split the pipeline across two machines on my local network:

┌──────────────────────────────────────────────┐    LAN (HTTP)    ┌────────────────────────────────┐
│          64GB Windows Workstation            │ ───────────────► │   NVIDIA Jetson Orin Nano      │
│      (defect-repair-agent Control Plane)     │                  │   (8GB Unified RAM - Headless) │
│                                              │                  │                                │
│  1. log_parser.py  -> Extract stack frame    │                  │  • Ubuntu multi-user.target    │
│  2. java_slicer.py -> Slice atomic method    │                  │  • Ollama API (:11434)         │
│  3. jetson_agent.py -> Enforce guardrails    │ ◄─────────────── │  • qwen2.5-coder:3b            │
│  4. verifier.py -> Run mvnw.cmd test         │  Test & Patch    │    (num_ctx: 4096)             │
└──────────────────────────────────────────────┘                  └────────────────────────────────┘
  • 8GB Jetson Orin Nano (Inference Appliance): Booted into headless mode (multi-user.target) to free ~700 MB of GUI overhead, running Ollama with qwen2.5-coder:3b (~1.9 GB weights) and a strict num_ctx: 4096 cap.
  • 64GB Workstation (Control Plane & Build Runner): Executes defect-repair-agent, parses logs, slices Java source files, and runs mvnw.cmd test locally.

3. How Logs Drive Dynamic Unit Test Creation & Defect Repair

Instead of asking an LLM to scan an entire repository blindly, the pipeline uses the production stack trace as a surgical scalpel across four stages:

Stage 1: Stack Trace Extraction (log_parser.py)

log_parser.py scans logs/app.log, deduplicates repeated exceptions, and extracts the exact application frame (com.aiops.governance.calculator.service.CalculatorService), method name, exception type, and crashing line number.

Stage 2: Atomic AST Slicing (java_slicer.py)

Small 3B models lose accuracy when fed hundreds of lines of boilerplate. Using tree-sitter-java, java_slicer.py parses the target .java file and slices out only the exact method containing the crashing line—keeping the prompt tiny, focused, and fast.

Stage 3: Test-First Synthesis (jetson_agent.py)

Using the stack trace and the sliced method, the Jetson generates artifacts in three distinct steps:

  1. Dynamic JUnit 5 Test Generation: Because the repository started with zero tests, jetson_agent.py first generates a brand-new JUnit 5 test class (CalculatorService_divideAutoTest.java and CalculatorService_addAutoTest.java) targeting the exact failure inputs from the log.
  2. Closed-Loop Bug Reproduction: Before touching any application code, verifier.py runs mvnw.cmd test. The newly generated test must fail against the unpatched code—proving it genuinely reproduces the production crash.
  3. Atomic Method Patching: Once reproduction is confirmed, the Jetson rewrites only the sliced method to handle the edge case (IllegalArgumentException on null or zero divisor), and verifier.py patches the exact line range while keeping a .bak safety backup.

Stage 4: Verification & Auto-Rollback (verifier.py)

verifier.py runs mvnw.cmd test again. If the patch compiles and passes both the new regression test and existing tests, the fix is kept. If anything fails, verifier.py feeds the Maven [ERROR] lines back to the Jetson for a self-correction retry—and automatically restores the .bak file if all attempts fail.

4. What Made a 3B Model Reliable: Deterministic Guardrails

One of the biggest lessons from building defect-repair-agent is that prompts alone aren't enough for small local models—Python guardrails are essential:

  • Atomic Method Boundaries: Writing single-responsibility methods meant qwen2.5-coder:3b only ever had to reason about 6–10 lines of Java at a time.
  • Automatic Import Injection: When the 3B model occasionally omitted import org.junit.jupiter.api.Test;, Python injected the standard JUnit 5 imports deterministically before compiling.
  • Contract Normalization: Rather than letting the generated test and generated fix disagree on which exception class to throw, Python normalized the expected contract (IllegalArgumentException) across both artifacts.
  • Dynamic Exception Anchoring: Anchoring the prompt directly to the parsed stack trace (NullPointerException vs. ArithmeticException) prevented the model from hallucinating unrelated edge cases (like testing division by zero inside add()).

5. Live Execution Proof

Running .venv\Scripts\python.exe verifier.py against logs/app.log automatically generated the missing JUnit 5 test suite and hardened both crashing methods:

==========================================
[DEFECT] java.lang.ArithmeticException in com.aiops.governance.calculator.service.CalculatorService.divide() (Line 31)
[1/4] Asking Jetson (qwen2.5-coder:3b) to generate JUnit 5 reproduction test...
[2/4] Running mvnw test to verify bug reproduction...
[OK] Bug reproduced! Test failed as expected.
[3/4] Asking Jetson (qwen2.5-coder:3b) to generate method fix (Attempt 1/2)...
[4/4] Running mvnw test to verify patched method (Attempt 1/2)...
[SUCCESS] Fix verified! CalculatorService.java patched and CalculatorService_divideAutoTest.java passes.

What started as an untested Spring Boot API with runtime crashes in a log file ended with verified, passing JUnit 5 regression tests and hardened service methods—built autonomously on an 8GB edge GPU.


Explore the Code & What's Next

Both repositories are available on GitHub:

Next, I plan to expand the pipeline with real-time file tailing (log_watcher.py), automated Git branch/PR creation so human developers can review verified fixes with one click, and benchmarking qwen2.5-coder:7b on the Jetson as an automatic fallback tier for more complex service methods.

Tuesday, November 24, 2026

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform
AIOps Model Context Protocol MCP Registry Spring AI Jaeger Milvus RAG NVIDIA Jetson Orin Human-in-the-Loop Vibe Coding

From Local Beans to an Official MCP Agent Registry: Building a Distributed, Human-on-the-Loop AIOps Governance Platform

Transparency Disclaimer: I did not write a single line of code for this project. Every Java class, Docker Compose configuration, MCP server registration manifest, and frontend script in the aiops-governance-orchestrator repository was generated by Google AI based on my architectural requirements, iterative testing, and operational feedback.

1. Why Hardcoded Agents Hit a Wall

In Phase 1 of building the AIOps Governance Operations Center, all specialist agents—telemetry scouts, latency/error analysts, and remediation executors—lived as local Spring @Component beans inside a single JVM (:8085). While convenient for an initial prototype, coupling agents inside one application meant adding a new diagnostic specialist or upgrading an agent required recompiling and redeploying the entire orchestrator.

In Phase 2, the platform evolved into a distributed, polyglot agent ecosystem powered by the Official Model Context Protocol (MCP) Registry (:8090). Specialist agents now run as standalone containerized MCP servers (:8091, :8092, :8093), self-publish their capabilities and routing metadata on startup, and are discovered dynamically at runtime over MCP Server-Sent Events (SSE).

AIOps Governance & Official MCP Registry Distributed Architecture
Figure 1: Distributed AIOps Governance Architecture with Official MCP Registry (:8090), Standalone MCP Agents (:8091–:8093), Jaeger, Milvus, and NVIDIA Jetson Orin GPU.

2. Complete Service & Port Reference

Component Port Role in the Architecture
aiops-governance-orchestrator :8085 Core control plane, Operations Center Web UI, TelemetryScoutAgent, McpRegistryClient, and PolicyGatekeeperAgent.
Official MCP Registry :8090 Upstream Go-based MCP Registry (modelcontextprotocol/registry) serving POST /v0/publish and GET /v0/servers.
Registry PostgreSQL :5433 Stores published ServerJSON manifests, SSE URLs, tool names, match keywords, and routing priorities.
security-analyst-mcp :8091 Standalone Spring AI MCP server specializing in admin, auth, and forbidden span anomalies (priority: 5).
latency-analyst-mcp :8092 Standalone Spring AI MCP server specializing in latency SLO violations and HTTP 5xx errors (priority: 10).
remediation-executor-mcp :8093 Standalone Spring AI MCP executor handling approved actions (OPEN_CIRCUIT_BREAKER, CLEAR_CACHE).
geo-time-mcp-server :8083 Monitored Spring Boot microservice exposing /api/admin/remediate for live circuit-breaker control.
jaeger-aiops-guardian :8084 MCP bridge querying Jaeger traces and exposing structured span summaries to TelemetryScoutAgent.
Jaeger UI / Query :16686 / :16685 Distributed trace ingestion, visualization, and span latency/error lookup.
Milvus Vector DB / Attu :19530 / :8000 Vector storage for application-specific runbooks and SLO evaluation criteria (Attu provides the visual UI).
NVIDIA Jetson Orin (Ollama) :11434 Edge GPU inference running qwen2.5:3b for root-cause diagnosis and nomic-embed-text for RAG embeddings.

3. End-to-End Incident Detection & Execution Flow

During a governance scan, the orchestrator coordinates telemetry inspection, dynamic agent discovery, edge GPU reasoning, and human sign-off—recording exact millisecond durations for every stage and every Jaeger span segment.

End-to-End AIOps Incident Detection, MCP Discovery & Human-on-the-Loop Approval Sequence
Figure 2: Step-by-step incident detection, MCP Registry discovery, Jetson Orin GPU inference, and Human-on-the-Loop remediation sequence with real execution timings.
Stage 1 • Scout
39 ms
TelemetryScoutAgent queries Jaeger and extracts anomalous spans.
Stage 2 • MCP Analyst
~1.5 s warm
latency-analyst-mcp (:8092) diagnoses root cause on Jetson Orin GPU (12,411 ms cold model load).
Stage 3 • HITL Gate
< 1 ms
PolicyGatekeeperAgent pauses execution until an operator approves in the UI.
Stage 4 • MCP Executor
157 ms
remediation-executor-mcp (:8093) opens the circuit breaker on timeapi.

4. Architectural Deep Dive

What Agent Registry Is Used?

The platform runs the Official Model Context Protocol (MCP) Registry (modelcontextprotocol/registry on :8090) backed by PostgreSQL (:5433). On startup, each Spring Boot MCP agent (:8091, :8092, :8093) obtains a registry token via POST /v0/auth/none, validates its manifest against the 2025-12-11 MCP schema, and registers via POST /v0/publish. Custom routing metadata—role (ANALYST or EXECUTOR), toolName, matchKeywords, allowedActions, priority, and internalSseUrl—is stored inside _meta["io.modelcontextprotocol.registry/publisher-provided"].

How Do Jaeger and Milvus Fit Into the Architecture?

  • Jaeger (:16686) — Real-Time Anomaly Detection: Monitored applications export OpenTelemetry spans to Jaeger. During a scan, TelemetryScoutAgent fetches spans exceeding the app's sloMaxLatencyMs threshold or carrying error=true, attaching each segment (operationName, durationMs, hasError, and clickable traceId) directly to the incident card.
  • Milvus (:19530) — Context-Aware Runbook RAG: Operators upload runbooks or remediation policies in the UI (+ Upload Criteria (Milvus)). CriteriaKnowledgeService embeds the rules via nomic-embed-text on the Jetson Orin GPU and stores them in Milvus. Before calling a remote MCP analyst, the orchestrator retrieves the top matching runbook rules via vector similarity search so the LLM's recommendation respects service-specific constraints.

Where Are Jaeger Traces & Metrics Stored?

In the local Docker Compose stack, Jaeger runs as jaegertracing/all-in-one, storing trace spans in memory for fast, zero-setup local testing (traces clear when the container restarts). For persistent storage in production, switching Jaeger's SPAN_STORAGE_TYPE environment variable moves trace storage to Badger (local disk volume), Elasticsearch / OpenSearch, or Cassandra with zero changes to instrumented applications.

How Do You Adjust an Application's SLO?

  1. Open the Operations Center at http://localhost:8085 and locate the service under Onboarded Spring Boot Apps.
  2. Click Edit SLO & Policy to open the policy modal.
  3. Update Latency SLO Threshold (ms) (sloMaxLatencyMs), Allowed Actions, Evaluation Criteria, or the Require Human-on-the-Loop Approval toggle, then click Save Policy & SLO (POST /api/governance/apps).
  4. Subsequent governance scans immediately evaluate Jaeger spans against the updated SLO threshold.

Can You Onboard C#, Node.js, or Python Web Apps?

Yes — the orchestrator is completely language-agnostic. Any C# (.NET ASP.NET Core), Node.js (Express / NestJS), Python (FastAPI), or Go web service can be monitored as long as it fulfills two lightweight contracts:

  1. Export OpenTelemetry Traces to Jaeger: Configure the standard OpenTelemetry SDK/auto-instrumentation for C#, Node.js, or Python to export OTLP traces to Jaeger (http://localhost:4317 or :4318) with service.name matching the onboarded app name.
  2. Expose a Remediation Webhook: Expose an HTTP POST endpoint (such as /api/admin/remediate) accepting {"action": "...", "component": "..."} to toggle circuit breakers, flush caches, or adjust rate limits.
// Example C# ASP.NET Core Minimal API Remediation Webhook
app.MapPost("/api/admin/remediate", (RemediationRequest req) =>
{
    if (req.Action == "OPEN_CIRCUIT_BREAKER") CircuitBreakerState.Open(req.Component);
    if (req.Action == "CLEAR_CACHE") MemoryCacheManager.Clear(req.Component);
    return Results.Ok(new { status = "APPLIED", component = req.Component, action = req.Action });
});
// Example Node.js Express Remediation Webhook
app.post('/api/admin/remediate', (req, res) => {
  const { action, component } = req.body;
  if (action === 'OPEN_CIRCUIT_BREAKER') circuitBreakers.open(component);
  if (action === 'CLEAR_CACHE') caches.flush(component);
  res.json({ status: 'APPLIED', component, action });
});

5. Source Code Repository

Explore the full source code, Docker Compose manifests, and standalone MCP agent implementations on GitHub:
https://github.com/htotapally/aiops-governance-orchestrator.git