Saturday, December 5, 2026

Building a Self-Healing Neuro-Symbolic Java Refactoring Agent with Spring Boot, JavaParser, and Langfuse

Self-Healing Neuro-Symbolic Java Refactoring with Spring Boot, JavaParser, and Langfuse

Updating older Java code—like moving field-injected @Autowired services and inline JDBC queries into constructor injection and clean repository layers—requires more context than regex rules offer, yet raw LLM outputs break easily without strict checks.

We built and verified ast-code-transformer-agent, a Spring Boot 3 / Java 21 A2A microservice that pairs probabilistic model generation with deterministic JavaParser guardrails, Maven/ArchUnit build checks, tiered routing, and OpenTelemetry + Langfuse tracing.

Source code on GitHub: htotapally/astcodetransformeragent

1. System Architecture

Instead of writing unverified model output straight to disk, every generated file runs through a deterministic check loop before a task completes:

A2A Client / Orchestrator POST /a2a (W3C traceparent) ast-code-transformer-agent (Spring Boot 3 / Java 21) Context Collector • CONVENTIONS.md & RAG rules • Direct collaborator classes • Token budget cap (~1,100 tokens) Tiered Model Router (Bifrost) • Tier 1 (edge): Local 3B coder • Tier 2 (heavy): Local 7B coder • Tier 3 (frontier): Cloud fallback Deterministic Guardrail & Build Gate 1. JavaParser AST Sanitizer Fixes package names • Injects missing Java/Spring/SLF4J/JUnit imports • Merges duplicate DTOs 2. Maven & ArchUnit Gate Runs `./mvnw test -B` + architecture rules • Feeds errors back for retries & RescueEpisodes OTLP Traces (Virtual Thread Context) Langfuse Graph & Trace View Multi-agent topology • RescueEpisode & token metrics

Figure 1: Neuro-symbolic pipeline combining tiered Bifrost routing with JavaParser guardrails and Maven/ArchUnit gates.

2. Key Lessons Learned From Real Runs

Running this pipeline end-to-end on a legacy Spring Boot slice (spring-di-refactor-slice) revealed several practical realities of agent engineering:

  1. All Models Are Not Interchangeable:
    • Small local models (qwen2.5-coder:3b) are fast for boilerplate but often miss cross-package imports or duplicate nested DTOs unless backed by deterministic AST rules.
    • Reasoning-tuned cloud models (qwen3, gpt-oss-120b) introduce gateway-specific behaviors—such as routing output into reasoning channels instead of message.content, emitting tool-call tokens on raw code prompts, or hitting free-tier Input Tokens Per Minute (ITPM) limits when full repository contexts are sent.
    • Mid-sized local models (qwen2.5-coder:7b) paired with bounded context (~1,100 tokens/call) and AST guardrails reliably refactor multi-file Spring services without external rate limits.
  2. LLM-to-Rule Distillation Dramatically Improves Reliability:
    Whenever an LLM failed on a mechanical mistake, encoding that invariant into AstCodeSanitizer permanently eliminated that failure class:
    • Enforcing package declarations directly from target file paths.
    • Auto-injecting common Java, Spring (@Service, @Repository, @Value), SLF4J, and JUnit/Mockito imports.
    • Detecting when multiple classes declare duplicate nested records (OrderSummary) and deterministically promoting them into a shared domain package.
  3. Context Propagation Across Java 21 Virtual Threads Matters:
    Wrapping virtual thread executors with OpenTelemetry's Context.taskWrapping(...) ensured every parallel file generation, AST sanitization, and Maven test run stitched cleanly into a single connected Langfuse Graph View:

Figure 2: Unified execution graph in Langfuse showing parallel file generation (12/12), knowledge retrieval (20/20), AST sanitization (12/12), and Maven/ArchUnit verification gates (3/3) across Java 21 virtual threads.

3. What We Are Building Next: Reusable Enterprise AIOps Agents

With our v1 baseline verified (TASK_STATE_COMPLETED, all unit tests and ArchUnit guardrails passing), our next phase decomposes monolithic logic into reusable, composable building blocks for enterprise multi-application governance:

  1. Extract build-verifier (mvn compile / test + ArchUnit) as a Reusable Worker:
    Decouple MavenBuildVerificationAgent into a standalone MCP/A2A tool service so code-transformer-agent, incident-triage-agent, and future dependency-upgrade agents can share a single build verification capability.
  2. Build incident-triage-agent Wired to Our Existing OTel Collector:
    • Subscribe to ERROR logs from our existing OpenTelemetry Collector across multiple enterprise microservices (service.name).
    • Compute a deterministic SHA-256 fingerprint from (service.name + rootException + orderedAppCallChain + targetSourcePath) so distinct NullPointerException call paths are isolated while duplicate log bursts are atomically deduplicated in PostgreSQL.
    • Synthesize scoped ArchitecturePlans and dispatch them to ast-code-transformer-agent with full W3C traceparent continuity.
  3. Externalize symbol_import_dictionary to PostgreSQL with Conflict Guardrails:
    Persist learned simple_name -> FQN mappings in Postgres while skipping ambiguous simple names (Date, List) so AST import healing grows smarter across repositories without introducing type collisions.
  4. Add Automated Langfuse Evaluators:
    Combine deterministic trace scores (build_test_passed, escalation_efficiency) with an LLM-as-a-Judge evaluator to continuously benchmark prompt and model updates.

Wednesday, December 2, 2026

Beyond the Chatbot: Building Adaptive UIs with Hybrid Neuro-Symbolic Agents

Beyond the Chatbot: Building Adaptive UIs with Hybrid Neuro-Symbolic Agents
Spring Boot • Spring AI • Bifrost → Qwen 2.5 7B

Beyond the Chatbot: Building Adaptive UIs with Hybrid Neuro-Symbolic Agents

Most AI applications today default to a single interaction pattern: a free-text chat box. While conversational interfaces are great for open-ended brainstorming, forcing every user interaction through an unstructured text loop creates friction, latency, and unnecessary compute costs.

While building the Adaptive Geo-Time Orchestrator—an open-source Proof of Concept powered by Spring Boot, Spring AI, and Qwen 2.5 7B (via Ollama)—I ran into a classic disambiguation bottleneck. Here is how moving from a pure chat loop to a Hybrid Neuro-Symbolic Adaptive UI solved it.

1. The Problem with Pure Chat Disambiguation

Initially, when a user searched for an ambiguous city name like "Springfield" or "Franklin," the system responded with a free-text prompt:

"Found 10 matches for Springfield (including Missouri, Illinois, Massachusetts, Ohio, Tennessee, Kentucky). Please specify the U.S. state to resume."

Because the interface relied on a free-text input box, users frequently entered typos, abbreviations, or unexpected phrasing. Every invalid reply triggered additional LLM inference cycles just to parse the correction—frustrating the user and wasting local GPU/CPU cycles on work that a single button click could solve deterministically.

2. The Solution: A 4-Stage Neuro-Symbolic Pipeline

Instead of treating the LLM as an all-purpose hammer, the orchestrator splits responsibilities between deterministic Java code and Qwen 2.5 7B:

4-Stage Hybrid Neuro-Symbolic Architecture
+-----------------------------------------------------------------------------------+

|                        USER INPUT ("Atlanta", "Springfield", "The Big Easy")      |
+-----------------------------------------+-----------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+

| STAGE 1: HYBRID SEMANTIC ROUTER (parseIntent)                                     |
|  * Structured ("Gary, IN")   --> Fast Deterministic String Split (0 LLM tokens)   |
|  * Unstructured (>3 words)   --> Bifrost -> Qwen 2.5 7B Intent Extraction         |
+-----------------------------------------+-----------------------------------------+
                                          |
                                          v
+-----------------------------------------------------------------------------------+

| STAGE 2: DETERMINISTIC TOOL EXECUTION (MCP - Open-Meteo API)                      |
|  * Exact geographic lookup returning strong Java LocationMatch records            |
+-----------------------------------------+-----------------------------------------+
                                          |
                          +---------------+---------------+

                          | Matches Found?                | Empty (Alias/Nickname)
                          v                               v
                          |         +-----------------------------------------------+

                          |         | STAGE 3: AGENTIC RAG FALLBACK (Milvus)        |
                          |         |  * embeddinggemma-2:270m resolves alias       |
                          |         |    ("The Big Easy" -> "New Orleans, LA")      |
                          |         +-----------------------+-----------------------+

                          |                                 |
                          +----------------+----------------+
                                           |
                                           v
+-----------------------------------------------------------------------------------+

| STAGE 4: DYNAMIC CONTROL-FLOW ROUTING & ADAPTIVE UI (routeByAmbiguity)            |
+------------------------+---------------------------------+------------------------+

|       1 MATCH          |           2 - 5 MATCHES         |       > 5 MATCHES      |
|  (Pipeline + Eval)     |   (Java 21 Parallel Fan-Out)    |  (HITL Guardrail)      |
+------------------------+---------------------------------+------------------------+

| * Resolve timezone     | * Resolve all timezones in      | * Save state to        |
|   immediately          |   parallel upfront              |   PostgreSQL Checkpoint|
| * Render green         | * Open Modal with clickable     | * Open Modal with      |
|   Deterministic Card   |   state pills (0 extra calls)   |   dynamic selector     |
+------------------------+---------------------------------+-----------+------------+
                                                                       |
                                                                       v
                                                           +------------------------+

                                                           | DETERMINISTIC RESUME   |
                                                           | User clicks state ->   |
                                                           | /resume (skips LLM) -> |
                                                           | Renders Verified Card  |
                                                           +------------------------+
  • 1 Match (Pipeline): Directly renders a verified Deterministic Result Card—zero extra clicks.
  • 2–5 Matches (Parallel Fan-Out): Uses Java 21 parallel streams to resolve all candidate time zones upfront and presents instant clickable state pills.
  • >5 Matches (Human-in-the-Loop Guardrail): Pauses execution before expensive fan-out calls, saves state in a PostgreSQL checkpoint, and dynamically morphs the UI into a constrained selector (clickable chips or a compact dropdown).

3. Deterministic Resume (Zero-Hallucination UI)

When the backend flags clarificationRequired, the frontend dynamically renders clickable buttons (or a dropdown for 8+ matches like Franklin) bound directly to the Postgres checkpointId.

When the user selects a state and clicks Resume, the browser sends { checkpointId, chosenState } straight to /api/geo-time/resume. Because the selection is already a canonical string from the backend's own candidate list, the controller bypasses LLM normalization completely, resumes the saved Postgres checkpoint, and renders the verified local time card.

4. Why PostgreSQL Checkpoints Beat Over-Engineered Event Streams

When designing disambiguation tracking for a PoC, it is tempting to introduce distributed message brokers like Apache Kafka to publish and track ambiguity events. However, running Kafka alongside local LLM inference adds heavy operational and memory overhead without immediate value.

Because the orchestrator already persists paused workflows in PostgreSQL, the checkpoint table doubles as a built-in audit and observability log—recording every ambiguous query, candidate count, and resolution state out of the box with zero extra infrastructure.

Key Takeaway

Great Agentic UX isn't about making users type more—it's about constraining choices when precision matters and reserving LLM reasoning strictly for the moments human language is truly ambiguous.

Exposing One Autonomous Service as Both an MCP Server and an A2A v1.0 Agent

Exposing One Autonomous Service as Both an MCP Server and an A2A v1.0 Agent
Architecture & Protocol Integration

Exposing One Autonomous Service as Both an MCP Server and an A2A v1.0 Agent

How refactor-agent runs Model Context Protocol (MCP) tools and Agent-to-Agent (A2A) v1.0 JSON-RPC endpoints side by side on a single Starlette ASGI server.

As agentic architectures mature, developers often face a common dilemma: should a service be built as a Model Context Protocol (MCP) tool server or as an Agent-to-Agent (A2A) autonomous agent?

In the refactor-agent repository (htotapally/refactor-agent on branch Add-agent), we solved this by running both protocols side by side inside a single unified Starlette/Uvicorn server. Because the underlying 7-agent phased refactoring pipeline (Scout, Planner, Transformer, Verifier, and Distiller) is completely decoupled from its transport layer, the exact same core service can be invoked synchronously as MCP tools by an IDE or assistant, or discovered and delegated to asynchronously by other agents via the A2A v1.0 protocol and gateways like Bifrost.

Unified Dual-Protocol Architecture

Both protocols share one Starlette ASGI process on port 8095 and converge on the same RefactorAgent orchestrator, TieredLLMRouter, and MemoryClient:

External Clients & Gateways IDE / AI Assistant (MCP Client) Peer Agent / Gateway (Bifrost A2A v1.0) Discovery + JSON-RPC refactor-agent Container (Starlette / Uvicorn :8095) MCP Transport Layer GET /sse & POST /messages/ MCPServer.sse_app() @mcp.tool Handlers refactor, scout, verify, query A2A v1.0 Transport Layer GET /.well-known/agent-card.json config/agent-card.json POST /a2a (JSON-RPC) SendMessage / GetTask _dispatch_skill() Shared Core Engine RefactorAgent Scout → Planner → Transformer → Verifier → Distiller TieredLLMRouter Edge 3B → Heavy 7B → Frontier via Bifrost LLM Gateway MemoryClient Milvus DynamicPolicyStore Workspace RAG & Episodic Hints MCP SSE 1. Discover 2. Delegate
Figure 1: Unified Starlette/Uvicorn server routing both MCP tool calls and A2A v1.0 JSON-RPC tasks into the shared RefactorAgent engine.

Why Support Both MCP and A2A?

MCP and A2A solve complementary problems:

  • MCP connects an LLM host (such as Claude Desktop, Cursor, or an orchestrator) directly to deterministic tools (refactor_repository, scout_repository, verify_repository, and query_knowledge_base) over Server-Sent Events (/sse).
  • A2A enables peer-to-peer interoperability between opaque agents. Instead of exposing low-level tool schemas, A2A publishes an Agent Card describing high-level skills and manages stateful task lifecycles (TASK_STATE_WORKING → TASK_STATE_COMPLETED) over JSON-RPC (/a2a).

By mounting both interfaces on the same ASGI application, you maintain one codebase, one Docker container, and one memory/LLM routing layer while serving both ecosystems.

How We Updated refactor-agent for A2A v1.0

1. Externalizing the A2A v1.0 Agent Card

Rather than hardcoding agent metadata inside Python dictionaries, we externalized the Agent Card into src/refactor_agent/config/agent-card.json and configured pyproject.toml ([tool.setuptools.package-data]) so it bundles cleanly into Docker builds.

To satisfy the A2A v1.0 specification (and strict gateways like Bifrost), the card declares supportedInterfaces with explicit JSONRPC binding and protocolVersion: "1.0":

{
  "name": "refactor-agent",
  "description": "Autonomous 7-agent phased refactoring service with Bifrost tiered LLM routing.",
  "version": "0.2.0",
  "supportedInterfaces": [
    {
      "url": "http://refactor-agent:8095/a2a",
      "protocolBinding": "JSONRPC",
      "protocolVersion": "1.0"
    }
  ],
  "capabilities": {
    "streaming": false,
    "pushNotifications": false,
    "stateTransitionHistory": true
  },
  "defaultInputModes": ["application/json", "text/plain"],
  "defaultOutputModes": ["application/json"],
  "skills": [
    {
      "id": "phased-refactoring",
      "name": "Phased Architectural Refactoring",
      "description": "Runs Scout -> Planner -> Transformer -> Verifier -> Distiller across a target repo.",
      "tags": ["java", "spring-boot", "refactoring", "archunit", "pmd"]
    },
    {
      "id": "repository-scouting",
      "name": "Repository Scouting & Rule Discovery",
      "description": "Extracts architectural boundaries, canonical imports, and indexes workspace chunks.",
      "tags": ["discovery", "milvus", "rag"]
    },
    {
      "id": "build-verification",
      "name": "Deterministic Guardrail & Build Gate Verification",
      "description": "Runs zero-token auto-healing, Milvus DynamicPolicyStore regex rules, and Maven gates.",
      "tags": ["verification", "guardrails", "maven"]
    },
    {
      "id": "knowledge-retrieval",
      "name": "Cross-Project Policy & Episodic Memory Retrieval",
      "description": "Queries active dynamic policy rules, RAG chunks, and historical fix hints.",
      "tags": ["memory", "policy-store", "milvus"]
    }
  ]
}

At runtime, build_agent_card() in src/refactor_agent/a2a_server.py reads this file and dynamically aligns the interface url with the incoming request's Host header (e.g., http://refactor-agent:8095/a2a inside Docker networks), serving it at both /.well-known/agent-card.json and the legacy /.well-known/agent.json endpoint.

2. Implementing the A2A v1.0 JSON-RPC Endpoint (a2a_server.py)

In src/refactor_agent/a2a_server.py, we implemented a lightweight JSON-RPC router supporting SendMessage and GetTask (along with legacy message/send and tasks/get aliases).

A critical lesson when integrating with A2A v1.0 gateways like Bifrost is adhering strictly to the v1.0 wire format rather than v0.3 conventions:

  • Result Envelope: Wrap the returned task object inside "result": { "task": ... } rather than placing task fields directly at the root of result.
  • No "kind" Discriminators: A2A v1.0 infers part and object types from field names (text, data) instead of "kind": "task" or "kind": "text".
  • Standardized Enum Casing & IDs: Use SCREAMING_SNAKE_CASE for states and roles (TASK_STATE_WORKING, TASK_STATE_COMPLETED, TASK_STATE_FAILED, ROLE_AGENT) and include a messageId on status messages.
task_record["status"] = {
    "state": "TASK_STATE_COMPLETED",
    "timestamp": finished_at,
    "message": {
        "messageId": f"msg-{uuid.uuid4().hex[:8]}",
        "role": "ROLE_AGENT",
        "parts": [
            {"text": f"Completed skill '{payload.get('skill', 'phased-refactoring')}'."}
        ],
    },
}
task_record["artifacts"] = [
    {
        "artifactId": f"art-{uuid.uuid4().hex[:8]}",
        "name": "refactoring-result",
        "parts": [{"data": result_data}],
    }
]
return JSONResponse({"jsonrpc": "2.0", "id": rpc_id, "result": {"task": task_record}})

When a SendMessage request arrives, _extract_a2a_payload() parses structured data or JSON/plain-text text parts from the incoming A2A Message, routes the request to _dispatch_skill(), and invokes the exact same RefactorAgent orchestrator used by the MCP tools.

3. Unifying MCP SSE and A2A Routes in cli.py

The wiring that turns a single service into both an MCP server and an A2A agent happens in just a few lines inside src/refactor_agent/cli.py.

MCPServer.sse_app() returns a standard Starlette ASGI application. By calling starlette_app.routes.extend(create_a2a_routes(host=host, port=port)) before starting Uvicorn, a single process on port 8095 handles all traffic cleanly:

@app.command("serve")
def cli_serve(
    host: str = typer.Option(settings.mcp_host, "--host"),
    port: int = typer.Option(settings.mcp_port, "--port"),
):
    """Start unified MCP SSE (:8095/sse) + A2A (/.well-known/agent-card.json & /a2a) server."""
    starlette_app = mcp.sse_app(
        sse_path="/sse",
        host=host,
        transport_security=TransportSecuritySettings(
            enable_dns_rebinding_protection=True,
            allowed_hosts=[
                "localhost:*",
                "127.0.0.1:*",
                "refactor-agent:*",
                f"refactor-agent:{port}",
            ],
            allowed_origins=[
                "http://localhost:*",
                "http://127.0.0.1:*",
                "http://refactor-agent:*",
                "http://mcp-bifrost-gateway:*",
            ],
        ),
    )
    starlette_app.routes.extend(create_a2a_routes(host=host, port=port))
    uvicorn.run(starlette_app, host=host, port=port)

Explicitly allowlisting internal Docker hostnames (refactor-agent:* and http://mcp-bifrost-gateway:*) in TransportSecuritySettings ensures Starlette's DNS rebinding protection permits container-to-container discovery and task execution without throwing 421 Misdirected Request errors.

Endpoint Summary

GET /sse & POST /messages/

Standard MCP Server endpoints for tool-calling IDE assistants and orchestrators.

GET /.well-known/agent-card.json

Dynamic A2A v1.0 Agent Card discovery backed by config/agent-card.json.

POST /a2a

A2A v1.0 JSON-RPC task execution (SendMessage and GetTask) for peer agents and Bifrost.

Repository: https://github.com/htotapally/refactor-agent/tree/Add-agent · Unified MCP + A2A v1.0 Architecture

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