Showing posts with label SpringBoot. Show all posts
Showing posts with label SpringBoot. Show all posts

Sunday, November 29, 2026

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