COBOL to Java with AI: How to Ship Clean Code, Not Just Passing Tests

Six AI models matched 41,918-line Medicare COBOL to the penny, yet only one wrote maintainable Java.

Before you spend money migrating COBOL with AI, four findings should shape your plan:

  1. Exact COBOL translation is no longer the hard part. All six matched 41,918-line Medicare COBOL to the cent without a compiler; quality, tests, and cost now decide.
  2. AI extracts complex rules accurately, yet most models skip rule tests. All six recovered Medicare rules, yet only Gemini 4 Neon and agentic Argon tested all 10 policy areas.
  3. AI token bills are tiny compared to testing and review. Raw API costs for 10 million lines scale to roughly $1,540, so human review drives real budgets.
  4. Use two models in sequence, not one. Run GPT-6.1 Sol first for a cheap test baseline, then have Gemini 4 Neon write clean Java.

We tested six models on three US Medicare COBOL programs totaling 50,245 lines. The smallest programs are FQHC at 1,772 lines and Hospice at 6,555 lines. The main stress test is OPPS, a 41,918-line hospital payment calculator.

Our lineup covers Gemini 4 Neon, Argon, and Carbon; Claude Opus 5.5 and Sonnet 5.5; and GPT-6.1 Sol. Every model worked inside an offline container with no access to a COBOL compiler. We checked each Java build against compiled COBOL on 60 hidden claims, requiring an exact $0.00 match.

Your team can run the verification gates inside an offline Docker container in its own CI. The output is standard Java 17 and JUnit 5, with no proprietary runtime.

We tested every model in two modes:

On the large OPPS program, we also checked 119 unseen test claims and external rate updates. Then three rival AI labs scored every passing Java codebase blindly to judge long-term maintainability.

1. Which AI Model Should Your Team Choose?

Most teams expect getting exact outputs from 41,918-line COBOL to be the hardest hurdle. Inside a coding loop, all six models cleared that hurdle and matched 60 of 60 hidden OPPS claims. They also matched at least 118 of 119 unseen test claims without running a COBOL compiler.

Because every model gets the right answer, pass rate hides huge gaps in cost and code quality. Instead, pick each model for a specific job in your migration plan:

Single-prompt conversion works well on small programs under 7,000 lines. Five of six models matched nearly every claim on FQHC and Hospice in one shot. Above 10,000 lines, single-prompt conversion breaks down because models hit token and thinking limits.

On 41,918-line OPPS, five models failed single-shot runs even though they understood COBOL fine. Both Claude models overflowed their context limit, while Neon and Carbon spent their output limits on thinking. Give your models an iterative loop with shell and build tools instead of chasing bigger single prompts.

Recent benchmarks like COBOLEval, COBOLCodeBench, and AlphaTrans confirm that single prompts fail on large legacy code. In those studies, build and test loops fixed most bugs, even when older models struggled to compile. Today's agents match 42,000-line systems without a compiler, shifting your choice from pass rate to quality and cost.

Figure 1. Single-Shot Log-LOC Cliff and Agentic Recovery Across Six Models
True log-LOC exact-cent pass trajectory (1.8K FQHC → 6.6K Hospice → 41.9K OPPS, a 23.7× jump) followed by the agentic compiler-free OPPS recovery slope. Hover any node for run telemetry.
Takeaway: Single-shot breaks between 6.6K and 41.9K lines for five of six models due to output and context budgets, not COBOL comprehension. Agentic mode with zero COBOL compiler access reaches 100% functional saturation (60/60 hidden, 118–119/119 unseen fuzz) on all six models. All 24 raw runs are in the Appendix.

2. Can AI Accurately Extract Business Rules and Verifiable Invariants?

Yes, AI can accurately extract complex legacy rules, with two important catches for production teams. All six coding agents read 41,918 lines of Medicare COBOL and recovered dozens of interacting payment rules. They captured wage floors, outmigration adjustments, 7.1% rural hospital boosts, blood deductibles, device credits, and outlier caps.

They also recovered nine discount factors and claim validation logic covering error codes 30 through 54. With no compiler, every agent matched 60 of 60 hidden claims to the exact cent. Across claims from 2008 through 2021, every agent matched at least 118 of 119 unseen cases.

Single-shot runs still miss subtle edge rules even on small files. On 1,772-line FQHC, Claude Opus 5.5 missed one Claim 51 day limit, returning the wrong error code.

Ambiguous mainframe rules also require human decisions rather than automated guesses. On bill types '14A' through '149', Neon and Argon kept mainframe intent while four models matched Linux.

When your last COBOL maintainer retires, a slide deck of rules will not protect production. Teams need signed-off business rules and executable tests tied to working Java. This study graded working Java and unit tests rather than a standalone generated rulebook.

Catch 1: Most models fail to write executable tests proving each extracted rule. In healthcare or finance, auditors need executable tests proving every individual business rule. Only Gemini 4 Neon and agentic Argon wrote targeted tests covering all 10 Medicare policy areas:

Catch 2: Extracted rules stay useful only if your team can update rates and logic safely. We raised external Medicare rate files by 10% on disk to verify clean separation from pricing rules. Four of seven passing builds ignored those disk updates because bundled JAR files took priority.

Only Neon, Opus 5.5, and single-shot Argon passed all 60 updated claims. Sol and Sonnet 5.5 buried extracted rules inside roughly 14,500 lines across eight copy-pasted yearly files.

Only Gemini 4 Neon isolated those rules into 21 small classes. Three rival AI labs scored all seven passing builds blindly and agreed almost identically. They gave Neon a unanimous 9 out of 10, though architects must still review its shared fields.

Recent modernization studies like AgentModernize and LegacyModernize-8 confirm this exact split. Multi-agent workflows now reach over 90% rule recall, proving code structure and tests are your real bottleneck. Dual-migration tools like Syzygy and specification-graph pipelines close that gap by generating reviewable rule specs and tests per module.

Figure 2. Three-Lane Quality Audit: Blind Rubric, Verifiable Invariants, and Inter-Lab Agreement
Left: 5-criterion Harvey-ball rubric (0–2 mean; Math dimmed because all 7 scored 2.0 BigDecimal). Middle: +10% OPPSAPCS rate-override check and JaCoCo line/branch bullet. Right: Concentric zero-drift 3-lab blind scores (Krippendorff's α = 0.935).
Takeaway: Only Gemini 4 Neon earned full 2/2 marks on domain structure, external rate decoupling, fixed-point math, and unit tests simultaneously (unanimous 9/9/9). Four 10/60 rate-override scores occurred because bundled classpath resources took precedence over external filesystem files, not because rates were hard-coded in Java. Full blind verdicts and bias checks are in the Appendix.

Figure 3 scales five passing OPPS builds to exact size so you can see where rules live. Click any row to read the real Java each model wrote.

Figure 3. True-Scale Architectural File Barcode of Five Passing OPPS Migrations
Five Agentic OPPS Repos · Source OPPSCAL.cob = 41,918 LOC. Every bar is scaled 1:1 to exact total Java lines (0 to 16,000); each slice is one .java file. Hover for details or click any row to inspect its source below.
Takeaway: Teal segments (#0f766e) are cohesive modules (<1,500 lines); deep slate segments (#1e293b) are large monolith engines (≥1,500 lines); crimson segments (#c8372d) are duplicated per-year transpiler copies (2014–2021).

Read the Generated Java Yourself



  
  

3. What Will Extraction Actually Cost Your Team?

AI token bills are no longer the main cost of leaving a mainframe. Because prompt caches reused over 93% of input tokens, converting OPPS cost $1.15 on Sol. Getting clean, modular Java from Gemini 4 Neon cost just $5.33 for the entire program.

Combining both models averages about $0.15 per 1,000 lines of COBOL. Scaled linearly to a 10-million-line bank mainframe, raw API bills total roughly $1,540. That estimate covers raw API compute only and excludes engineering, testing, and integration labor.

In practice, raw AI compute now costs less than two days of one senior engineer. Spend your real budget on verification harnesses, domain sign-off, and rollout governance.

Paying more per token does not guarantee better Java. Claude Opus 5.5 cost $12.69 on OPPS, which is 11 times more than GPT-6.1 Sol. With Claude Opus 5.5, you pay more than double Gemini 4 Neon and get worse code. Even Claude Sonnet 5.5 cost more than GPT-6.1 Sol while scoring lowest overall.

Figure 4. Code Quality vs. Total API Cost on OPPS (41,918 Lines)
Higher and further left is better. Every point matched 60 of 60 hidden claims.
Takeaway: Paying more does not buy cleaner code. Gemini 4 Neon ($5.33) scores 9.0 out of 10, while Claude Opus 5.5 costs $12.69 and scores 6.7.

Half of that extra cost comes from how each vendor splits legacy text into tokens. Mainframe COBOL packs files with comment stars and blank spacing. On the exact same OPPS file, Anthropic billed 1.86 times more tokens than OpenAI.

That overhead cuts a 1-million-token window nearly in half, breaking both Claude single-shot runs. The same penalty hits modern code too, where Anthropic billed 1.79 times more tokens on Java. Strip legacy comment banners before sending files to an AI model, or choose a compact tokenizer.

Recent 2024–2026 tokenization studies explain why mainframe formatting inflates your API bills. Standard tokenizers split COBOL verbs, hyphens, and spacing into 1.8 to 3.5 times more tokens than modern code. Those studies show stripping comment banners and sequence numbers cuts token and reasoning overhead by 25% to 50%.

Figure 5. Coupled 1M Context Budget Vessel and COBOL-vs-Java Tokenizer Slopegraph
Left: Exact billed single-shot OPPS prompt + output tokens inside a 1,000K context vessel, showing free headroom versus Anthropic's +48K overflow. Right: Normalized tokenizer inflation (OpenAI = 1.00×) on identical COBOL and Java inputs.
Takeaway: OpenAI leaves 462K tokens free and Google leaves 375K free on single-shot OPPS. Anthropic's 1.86× COBOL tokenization consumes 977.6K tokens before output begins, pushing total demand to 1,048.2K (+48K overflow) and effectively halving usable legacy context.

4. What Is the Best Workflow for Migrating Legacy Code?

Do not ask one AI model to uncover legacy rules and design clean architecture together. From the same prompt, GPT-6.1 Sol acted like a compiler writer and built a fast transpiler. Gemini 4 Neon acted like a senior Java architect and refactored the rules into clean classes.

Recent migration research—including AlphaTrans (call-graph slicing), DARPA TRACTOR / C2Rust (transpile-then-refactor), and Syzygy (dual code-and-test verification)—converges on the six-step workflow in Figure 6. Follow it left to right:

  1. Stage 0 — Slice dependencies and clean inputs (AlphaTrans pattern).
    Purpose: Map program call graphs and copybook dependencies bottom-up, and strip legacy * comment banners before sending files to an AI.
    Why: Real mainframes connect hundreds of programs across CICS, JCL, and DB2. Slicing lets you migrate one module at a time, and stripping comment banners cuts bloated token bills immediately.
  2. Stage 1 — Build a fast throwaway copy (GPT-6.1 Sol, 13 minutes).
    Purpose: Generate a mechanical, runnable Java build whose only job is matching legacy math to the exact cent when live mainframe runs are blocked.
    Why: Mechanical transpiling is fast and captures odd edge cases when live COBOL is unavailable. Treat it strictly as a fallback proxy, never as ground truth.
  3. Freeze a large test baseline (Freeze Baseline).
    Purpose: Run 10,000 or more boundary, synthetic, and historical claims and lock every input and output pair as your reference baseline.
    Why: Most teams start with a few dozen test cases that miss rare branches. Freezing 10,000 pairs gives Stage 2 a fast, automated safety net.

Massive caveat with Stage 1: an AI-built throwaway copy is not ground truth. If GPT-6.1 Sol misreads a rare COBOL branch, rounding rule, or mainframe sort order, freezing 10,000 outputs from Stage 1 alone will lock that bug into Stage 2. Whenever live COBOL, a compiled test runner, or historical batch logs exist, generate your frozen baseline from real COBOL instead of Stage 1. Use Stage 1 as a proxy baseline only when mainframe execution is blocked, and cross-check it against real batch outputs plus human review of edge cases before freezing.

  1. Extract and sign off on business rules (Rule Spec — Human Sign-Off).
    Purpose: Produce a plain-English list of extracted business rules and let domain owners approve ambiguous edge cases before Stage 2 starts.
    Why: Automated tests cannot decide whether production should keep mainframe EBCDIC sort rules (like '14A' through '149') or Linux behavior. Signing off on the spec upfront prevents silent policy bugs.
  2. Stage 2 — Co-generate clean Java and rule tests (Gemini 4 Neon, 23 minutes; Syzygy pattern).
    Purpose: Refactor the logic into small Java classes, load rate tables from external files, and write one executable JUnit test per signed-off business rule.
    Why: Writing code and tests together guarantees every policy area is proven to auditors instead of leaving rules untested.
  3. Run the automated verification loop (Verify → Java 17).
    Purpose: Check every edit against all 10,000 frozen outputs, a 10% external rate-file change, and the full JUnit rule suite, repairing any failure automatically.
    Why: Catching a 1-cent diff or broken rate override immediately prevents billing errors. On OPPS, Stages 1 and 2 finished in about 36 minutes total.
Figure 6. Research-Aligned Multi-Stage Migration Pipeline
Boxes show code and model stages; circles show baseline, human sign-off, and verification gates; dashed lines show preferred inputs and the repair loop.
Stage 0: Slice Call graph & tables Strip * banners AlphaTrans pattern Stage 1: Transpiler GPT-6.1 Sol · 13m Fallback proxy JAR Not ground truth Freeze Baseline 10K+ I/O Real batch logs (preferred) or fuzz inputs + live COBOL Rule Spec Human Sign-Off Approve EBCDIC & edge-case rules Stage 2: Refactor Gemini 4 Neon · 23m Java + JUnit per rule Verify $0.00 diff +10% rates Syzygy-style code + test repair loop until 0 diffs, rate override passes & all rules tested Java 17 Clean code + rule tests Boxes = code & model stages · Circles = baseline, human sign-off & verification gates · Dashed = preferred inputs & repair loop
Takeaway: Anchor behavior on real COBOL or batch logs first (using Stage 1 only as a fallback proxy), approve edge-case rules in a human checkpoint, then refactor cleanly with dual code-and-test verification. See Section 3 for exact API costs.

This workflow mirrors DARPA's TRACTOR program and C2Rust to C2SaferRust pipelines, which lock behavior before refactoring. Our results add a twist: agents now build that Stage 1 transpiler themselves in 13 minutes. For large estates wired with CICS, JCL, and DB2, Stage 0 call-graph slicing keeps each migration step small and safe.

Technique Representative Model Exact Match Blind Score PMD-CPD Relative Cost Best Role
Single-Shot Gemini 4 Argon (1/6 passed) 60/60 5.67 4.5% Low Small programs (<7K LOC) only.
Custom Transpiler GPT-6.1 Sol (port.py) 60/60 5.00 73.7% Lowest Stage 1 fallback proxy synthesis.
Parameterized Engine Opus 5.5 / Argon 60/60 6.33–6.67 4.0–35.7% Moderate–Highest Middle ground; leaves big engine classes.
Modular Refactor Gemini 4 Neon 60/60 9.00 3.3% Moderate Stage 2 maintainable production Java.
Multi-Stage Hybrid Sol → Neon (anchored baseline) 100% locked 9.00 <4% Moderate Recommended production workflow (see Section 3).

Verifying Without Legacy Tests or SMEs

When legacy tests and subject-matter experts are scarce, teams still need to trace every diff to one COBOL rule. Our differential harness checks nine claim fields and seven line fields per record, so a failing field points to one pricing section. Because Stage 1 keeps original COBOL paragraph names as Java methods like p20000ProcessMainNew and p20100Init, engineers can trace state side by side against Stage 2.

Every mismatch falls into one of three buckets:

We evaluated Stage 1 (GPT-6.1 Sol) and Stage 2 (Gemini 4 Neon) separately against compiled GnuCOBOL rather than in one automated chain.

Migration factory vs. generic coding agents: A generic coding agent stops when the code compiles and a few happy-path checks pass. A migration factory enforces repeatable offline gates inside your own environment. Those gates check field-level exact-cent diffs, +10% external rate overrides, duplication and coverage ceilings, and human sign-off on runtime ambiguities.

Four Mainframe Traps That Require Human Sign-Off

Automated tests cannot decide whether your new Java should keep mainframe quirks or match Linux behavior. Before you trust any migration pipeline, watch out for four traps we hit directly:

  1. Open-source COBOL compilers can quietly corrupt your test baseline. GnuCOBOL truncates math at 18 digits under its IBM flag, zeroing all 63 OPPS claims. Add -fno-arithmetic-osvs and audit compiler math flags before trusting any test outputs.
  2. Mainframes and Linux sort letters and digits in opposite orders. A billing rule covering '14A' through '149' caused our only mismatch across 119 unseen claims. Neon and Argon kept mainframe intent while four models matched Linux, proving domain owners must choose.
  3. COBOL record moves can silently shift decimal places. Copying raw text directly into a numeric field turned a $203 deductible into $300. Always wrap incoming text slices in fixed-width record structures before numeric moves.
  4. AI agents will hunt for blocked compilers during evaluations. Claude Opus 5.5 searched disk folders for COBOL tools and tried to download GnuCOBOL from the web. Lock evaluation containers offline with strict root permissions so tests measure real code conversion.

Bottom Line

AI agents now make exact COBOL translation cheap enough that token bills no longer block modernization. To ship Java your team can own next year, run a two-stage workflow and verify rate overrides. Watch for bloated tokenizers, and keep your own architects on final sign-off.

Study Limits

We ran each model once per program across the full benchmark. An earlier 45-minute timeout stopped Gemini 4 Carbon right after it deleted its test file.

Public reference code disclosure: CMS began publishing Java reference source JARs on CMS.gov in Q1 2021, so models may have seen Medicare OPPS code in training. Three forensic checks show the models still translated OPPSCAL.cob directly. First, Sol and Sonnet 5.5 wrote Python COBOL parsers (port.py, cobparse.py) that generated 1,024 paragraph methods. Second, all seven passing builds formatted our custom 72 + 46×N fixed-width output layout and kept COBOL WORKING-STORAGE structure. Third, three of seven builds (Neon, Opus 5.5, and single-shot Argon) parsed raw copybooks at runtime. That let them pass all 60 unseen +10% rate claims, where 50 of the 60 outputs changed.

Scope boundary: This study tested standalone batch COBOL programs up to 41,918 lines, not multi-million-line estates wired across CICS, JCL, DB2, SQL stored procedures, and .NET services. Mixed enterprise estates also require Stage 0 call-graph slicing, stored-procedure extraction, and cross-service integration tests. You can inspect all 24 run logs, blind reviews, and Docker scripts in the Appendix.