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.

No comments:

Post a Comment