核心用法与用例(1/3)

Set up automated PR reviews using OpenHands and the Software Agent SDK

Check out the complete PR review plugin with ready-to-use code and configuration.

Automated code review helps maintain code quality, catch bugs early, and enforce coding standards consistently across your team. OpenHands provides a GitHub Actions workflow powered by the Software Agent SDK that automatically reviews pull requests and posts inline comments directly on your PRs.

Overview

The OpenHands PR Review workflow is a GitHub Actions workflow that:

  • Triggers automatically when PRs are opened or when you request a review
  • Analyzes code changes in the context of your entire repository
  • Posts inline comments directly on specific lines of code in the PR
  • Provides fast feedback - typically within 2-3 minutes

How It Works

The PR review workflow uses the OpenHands Software Agent SDK to analyze your code changes:

  1. Trigger: The workflow runs when:
  2. A new non-draft PR is opened
  3. A draft PR is marked as ready for review
  4. The review-this label is added to a PR
  5. openhands-agent is requested as a reviewer

  6. Analysis: The agent receives the complete PR diff and uses two skills:

  7. /codereview: Analyzes code for quality, security, data structures, and best practices with a focus on simplicity and pragmatism
  8. /github-pr-review: Posts structured inline comments via the GitHub API

  9. Output: Review comments are posted directly on the PR with:

  10. Priority labels (🔴 Critical, 🟠 Important, 🟡 Suggestion, 🟢 Nit)
  11. Specific line references
  12. Actionable suggestions with code examples

Quick Start

Create `.github/workflows/pr-review-by-openhands.yml` in your repository:
name: PR Review by OpenHands

on:
  pull_request_target:
    types: [opened, ready_for_review, labeled, review_requested]

permissions:
  contents: read
  pull-requests: write
  issues: write

jobs:
  pr-review:
    if: |
      (github.event.action == 'opened' && github.event.pull_request.draft == false) ||
      github.event.action == 'ready_for_review' ||
      github.event.label.name == 'review-this' ||
      github.event.requested_reviewer.login == 'openhands-agent'
    runs-on: ubuntu-latest
    steps:
      - name: Run PR Review
        uses: OpenHands/extensions/plugins/pr-review@main
        with:
          llm-model: anthropic/claude-sonnet-4-5-20250929
          llm-api-key: ${{ secrets.LLM_API_KEY }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
Go to your repository's **Settings → Secrets and variables → Actions** and add:

* **`LLM_API_KEY`**: Your LLM API key (get one from [OpenHands LLM Provider](https://docs.openhands.dev/openhands/usage/llms/openhands-llms))



Create a `review-this` label in your repository:

1. Go to **Issues → Labels**
2. Click **New label**
3. Name: `review-this`
4. Description: `Trigger OpenHands PR review`



Open a PR and either:

* Add the `review-this` label, OR
* Request `openhands-agent` as a reviewer

In a Conversation

You can also trigger a code review manually in any OpenHands conversation. First, install the skill:

/add-skill https://github.com/OpenHands/extensions/tree/main/skills/code-review

Then invoke it:

/codereview

The agent will ask for the PR to review, or you can provide context directly:

/codereview — Please review PR #123 on my-org/my-repo.
Focus on the new authentication middleware.

Composite Action

Action Path Updated: The PR review action has moved to the extensions repository. If your workflow still references the old path, update it:

  • Old: OpenHands/software-agent-sdk/.github/actions/pr-review@main
  • New: OpenHands/extensions/plugins/pr-review@main

The workflow uses a reusable composite action that handles all the setup automatically:

  • Checking out the extensions repository at the specified version
  • Setting up Python and dependencies
  • Running the PR review agent (from extensions repo)
  • Uploading logs as artifacts

Action Inputs

Input Description Required Default
agent-kind Review backend: openhands for the standard SDK agent or acp for an ACP-compatible agent server No openhands
llm-model LLM model(s). Comma-separated to run multiple reviews and compare results (A/B testing). In ACP mode this is passed to the ACP server when supported. No anthropic/claude-sonnet-4-5-20250929
acp-command Command used to start the ACP server. Required when agent-kind is acp. Examples: npx -y @zed-industries/codex-acp@0.12.0, codex-acp, claude-agent-acp, npx -y @agentclientprotocol/claude-agent-acp Yes for ACP mode ''
acp-prompt-timeout Timeout in seconds for one ACP prompt turn No 1800
llm-base-url LLM base URL (for custom endpoints) No ''
review-style [DEPRECATED] Previously chose between standard and roasted. Now ignored — the styles have been merged. No roasted
require-evidence Require the reviewer to enforce an Evidence section in the PR description with end-to-end proof No 'false'
use-sub-agents Enable sub-agent delegation for file-level reviews in openhands mode. Ignored in ACP mode. No 'false'
extensions-repo Extensions repository (owner/repo) No OpenHands/extensions
extensions-version Git ref for extensions (tag, branch, or commit SHA) No main
openhands-sdk-package Package spec passed to uv --with; override only when pinning a specific SDK build for testing or rollout control No openhands-sdk
llm-api-key LLM API key. Required when agent-kind is openhands; ignored in ACP mode. Yes for OpenHands mode -
github-token GitHub token for API access Yes -
lmnr-api-key Laminar API key for observability No ''
enable-uv-cache Enable setup-uv's GitHub Actions cache for Python deps. Default false for security. No 'false'

Use extensions-version to pin to a specific version tag (e.g., v1.0.0) for production stability, or use main to always get the latest features. The extensions repository contains the PR review plugin scripts.

Experimental: ACP Review Backend

The PR review action can run through an ACP-compatible agent server by setting agent-kind: acp. In this mode, OpenHands still loads the review skills and plugin prompt context, but the ACP server owns model access, authentication, and tool execution.

Use ACP mode when your runner already has an authenticated ACP CLI available. The action does not install ACP CLIs for you; install and authenticate the ACP server in workflow steps before invoking the PR review action.

ACP mode is experimental. Use it on trusted self-hosted runners where you control the installed ACP command and the authentication material. Do not expose subscription credentials to workflows that run untrusted pull request code.

Codex ACP Example

To use Codex ACP, first install the Codex CLI and complete device-code login on a trusted machine:

codex login --device-auth
codex login status

Then create a base64-encoded secret from the generated auth file:

# Linux
base64 -w 0 "$HOME/.codex/auth.json"

# macOS
base64 < "$HOME/.codex/auth.json" | tr -d '\n'

Store the printed value as a repository or organization secret named CODEX_AUTH_JSON_B64. The workflow can then restore that file on a self-hosted runner, start Codex ACP with npx, and run the review:

name: PR Review by OpenHands

on:
  pull_request:
    types: [labeled, review_requested]

permissions:
  contents: read
  pull-requests: write
  issues: write

jobs:
  pr-review:
    if: |
      github.event.label.name == 'review-this' ||
      github.event.requested_reviewer.login == 'openhands-agent'
    runs-on: [self-hosted]
    timeout-minutes: 30
    steps:
      - name: Restore Codex auth
        env:
          CODEX_AUTH_JSON_B64: ${{ secrets.CODEX_AUTH_JSON_B64 }}
        run: |
          if [ -z "$CODEX_AUTH_JSON_B64" ]; then
            echo "Error: CODEX_AUTH_JSON_B64 is required for Codex ACP review."
            exit 1
          fi
          mkdir -p "$HOME/.codex"
          if ! printf '%s' "$CODEX_AUTH_JSON_B64" | base64 -d > "$HOME/.codex/auth.json"; then
            echo "Error: Failed to decode CODEX_AUTH_JSON_B64 — check the base64 value."
            exit 1
          fi
          chmod 600 "$HOME/.codex/auth.json"

      - name: Run PR Review
        uses: OpenHands/extensions/plugins/pr-review@main
        with:
          agent-kind: acp
          acp-command: npx -y @zed-industries/codex-acp@0.12.0
          llm-model: o3
          github-token: ${{ secrets.GITHUB_TOKEN }}

      - name: Cleanup Codex auth
        if: always()
        run: rm -f "$HOME/.codex/auth.json"

Customization

Repository-Specific Review Guidelines

Add repo-specific review rules by creating a skill file at .agents/skills/custom-codereview-guide.md:

---
name: custom-codereview-guide
description: Custom code review guidelines for this repository
triggers:
- /codereview
---

# Repository Code Review Guidelines

You are reviewing code for [Your Project Name]. Follow these guidelines:

## Review Decisions

### When to APPROVE
- Configuration changes following existing patterns
- Documentation-only changes
- Test-only changes without production code changes
- Simple additions following established conventions

### When to COMMENT
- Issues that need attention (bugs, security concerns)
- Suggestions for improvement
- Questions about design decisions

## Core Principles

1. **[Your Principle 1]**: Description
2. **[Your Principle 2]**: Description

## What to Check

- **[Category 1]**: What to look for
- **[Category 2]**: What to look for

## Repository Conventions

- Use [your linter] for style checking
- Follow [your style guide]
- Tests should be in [your test directory]

Do not name your skill code-review. The pr-review plugin ships its own code-review skill, and plugin skills override project skills with the same name. Use a different name (e.g. custom-codereview-guide) with the /codereview trigger so both skills are active — the plugin provides the review framework while your skill adds repo-specific rules.

The skill file must use /codereview as the trigger so it activates alongside the default review behavior. See the software-agent-sdk's own custom-codereview-guide for a complete example.

Workflow Configuration

Customize the workflow by modifying the action inputs:

- name: Run PR Review
  uses: OpenHands/extensions/plugins/pr-review@main
  with:
    # Change the LLM model
    llm-model: anthropic/claude-sonnet-4-5-20250929
    # Use a custom LLM endpoint
    llm-base-url: https://your-llm-proxy.example.com
    # Pin to a specific extensions version for stability
    extensions-version: main
    # Secrets
    llm-api-key: ${{ secrets.LLM_API_KEY }}
    github-token: ${{ secrets.GITHUB_TOKEN }}

Trigger Customization

Modify when reviews are triggered by editing the workflow conditions:

# Only trigger on label (disable auto-review on PR open)
if: github.event.label.name == 'review-this'

# Only trigger when specific reviewer is requested
if: github.event.requested_reviewer.login == 'openhands-agent'

# Trigger on all PRs (including drafts)
if: |
  github.event.action == 'opened' ||
  github.event.action == 'synchronize'

Security Considerations

The workflow uses pull_request_target so the code review agent can work properly for PRs from forks. Only users with write access can trigger reviews via labels or reviewer requests.

Potential Risk: A malicious contributor could submit a PR from a fork containing code designed to exfiltrate your LLM_API_KEY when the review agent analyzes their code.

To mitigate this, the PR review workflow passes API keys as SDK secrets rather than environment variables, which prevents the agent from directly accessing these credentials during code execution.

Example Reviews

See real automated reviews in action on the OpenHands Software Agent SDK repository:

PR Description Review Highlights
#1927 Composite GitHub Action refactor Comprehensive review with 🔴 Critical, 🟠 Important, and 🟡 Suggestion labels
#1916 Add example for reconstructing messages Critical issues flagged with clear explanations
#1904 Update code-review skill guidelines APPROVED review highlighting key strengths
#1889 Fix tmux race condition Technical review of concurrency fix with dual-lock strategy analysis

Troubleshooting

<AccordionGroup>

* Ensure the `LLM_API_KEY` secret is set correctly
* Check that the label name matches exactly (`review-this`)
* Verify the workflow file is in `.github/workflows/`
* Check the Actions tab for workflow run errors



* Ensure `GITHUB_TOKEN` has `pull-requests: write` permission
* Check the workflow logs for API errors
* Verify the PR is not from a fork with restricted permissions



* Large PRs may take longer to analyze
* Consider splitting large PRs into smaller ones
* Check if the LLM API is experiencing delays

</AccordionGroup>

Automate This

There are two ways to automate PR reviews with OpenHands: as a GitHub Action (per-repo) or as an OpenHands Automation (org-wide, event-driven). Choose the approach that fits your needs, or use both.

Option A: GitHub Action (Per-Repo)

Use the pr-review plugin as a GitHub Actions workflow. Copy the example workflow into .github/workflows/pr-review.yml in your repository, add your LLM_API_KEY to Settings → Secrets and variables → Actions, and customize the trigger conditions and model as needed.

See the action.yml for all available inputs (llm-model, llm-base-url, use-sub-agents, require-evidence, and more).

When to use this: You want per-repo control, need to integrate with existing CI checks, or want to pin specific action versions per repository.

Option B: OpenHands Automation (Org-Wide)

Before setting up an event-driven automation, complete the one-time prerequisites for GitHub event automations — install the GitHub App, create a team org, and claim your GitHub organization. Without these steps, GitHub events will silently never arrive.

OpenHands Automations is an event-triggered automation system that replaces per-repo GitHub Actions workflows. You define the trigger once and it covers all repositories matching your filter — no per-repo workflow files needed. It also leverages the full OpenHands runtime (browser, tools, sandbox), which GitHub Actions cannot.

When to use this: You want a single configuration that covers all repos in your org, or you need the full OpenHands runtime for more advanced review workflows.

Prerequisites: Bot Account

For org-level automations, you should create a dedicated bot account (a separate GitHub user) and add it to your OpenHands organization. The bot account is the identity that will approve pull requests, request changes, and post review comments — keeping automated actions separate from human activity. Team members can then request this bot as a reviewer to trigger on-demand reviews.

Setup: Create the Automation via Prompt

Log in to OpenHands Cloud as your bot account (or under your team org) and send the following prompt in a new conversation. Replace the placeholders with your values:

  • YOUR_ORG — your GitHub organization name (e.g., mycompany)
  • YOUR_BOT_LOGIN — the GitHub username of your bot account (e.g., mycompany-bot)
Create an OpenHands Cloud automation using the Plugin Preset with the following configuration:

**Name:** PR Review: YOUR_ORG/* (ready for review, review-this, or reviewer requested)

**Plugin:** github:OpenHands/extensions (repo_path: plugins/pr-review)

**Trigger events:**
- pull_request.opened
- pull_request.ready_for_review
- pull_request.review_requested
- pull_request.labeled

**Filter:**
```
glob(repository.full_name, 'YOUR_ORG/*') && (
    label.name == 'review-this'
    || requested_reviewer.login == 'YOUR_BOT_LOGIN'
    || (!label && !requested_reviewer
        && pull_request.author_association != 'FIRST_TIME_CONTRIBUTOR'
        && pull_request.author_association != 'FIRST_TIMER'
        && pull_request.author_association != 'NONE'
        && !pull_request.draft)
)
```

**Timeout:** 600 seconds

**Prompt (use this exactly):**
```
Before starting the code review, complete these steps in order:

Step 1 — Build the session URL.
Run this in terminal:
  SESSION_URL="${AUTOMATION_SESSION_URL:-${AUTOMATION_API_URL:-https://app.all-hands.dev}}"
  echo "SESSION_URL=${SESSION_URL}"

Step 2 — Extract PR info from the event payload:
  PR_NUMBER=$(echo "$AUTOMATION_EVENT_PAYLOAD" | python3 -c "import sys,json; p=json.load(sys.stdin); print(p['pull_request']['number'])")
  REPO=$(echo "$AUTOMATION_EVENT_PAYLOAD" | python3 -c "import sys,json; p=json.load(sys.stdin); print(p['repository']['full_name'])")

Step 3 — Post a progress comment and save the comment ID:
  COMMENT_ID=$(curl -s -X POST \
    -H "Authorization: Bearer $GITHUB_TOKEN" \
    -H "Accept: application/vnd.github+json" \
    "https://api.github.com/repos/$REPO/issues/$PR_NUMBER/comments" \
    -d "{\"body\": \"🔍 **Review in progress…**\\n\\nWe are performing the review through OpenHands Cloud Automation. You can log in and [view the conversation here](${SESSION_URL}).\"}" \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")

Step 4 — /codereview and /github-pr-review
Review the pull request using the pr-review plugin. Post a comprehensive code review on GitHub with inline comments on specific changed lines where appropriate, and a concise overall summary. Avoid duplicating existing unresolved review comments.

When submitting the review, choose the appropriate event type:
- Use "event": "APPROVE" when the PR is ready to merge with no blocking issues (minor suggestions are fine)
- Use "event": "REQUEST_CHANGES" when there are blocking issues that must be fixed before merging
- Use "event": "COMMENT" only when you need more information or are providing an informational review without a clear verdict

At the end of the top-level review body include exactly:
  _This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. [View conversation](${SESSION_URL})_

Step 5 — After the review is posted, update the progress comment:
  curl -s -X PATCH \
    -H "Authorization: Bearer $GITHUB_TOKEN" \
    -H "Accept: application/vnd.github+json" \
    "https://api.github.com/repos/$REPO/issues/comments/$COMMENT_ID" \
    -d "{\"body\": \"✅ **Review complete.**\\n\\nThis review was performed through OpenHands Cloud Automation. You can log in and [view the conversation here](${SESSION_URL}).\"}"
```

Team review requests: The requested_reviewer field is only populated for individual reviewer requests. When a team is requested as reviewer, GitHub uses requested_team instead. To also match team requests, add || requested_team.slug == 'YOUR_TEAM_SLUG' to the filter.

How !label works: JMESPath treats absent fields as null, and !null evaluates to true. This means the third branch fires for opened and ready_for_review events (which have no label or requested_reviewer in the payload), while correctly staying silent for labeled and review_requested events where those fields are set.

What This Produces

When the automation is created and a qualifying PR event occurs, the bot will:

  1. Post a progress comment on the PR: "🔍 Review in progress…" with a link to the live conversation
  2. Run the pr-review plugin which analyzes the diff and posts a structured code review with inline comments — approving clean PRs, requesting changes when there are blocking issues, or leaving an informational comment when the verdict is unclear
  3. Update the progress comment to "✅ Review complete." with the conversation link

The automation triggers on four conditions:

  • opened — when a new non-draft PR is created (for established contributors only)
  • ready_for_review — when a draft PR is marked ready (for established contributors only)
  • review_requested — when your bot account is requested as a reviewer. This is the primary way team members trigger an on-demand review — they simply request the bot from the PR's "Reviewers" sidebar. The bot then posts its review under its own GitHub identity, so approvals and change requests come from a clear, dedicated account.
  • labeled — when the review-this label is added to any PR

The automation does not re-run when new commits are pushed to an existing PR (pull_request.synchronize is intentionally excluded to avoid noisy re-reviews). To request a follow-up review after addressing feedback, re-add the review-this label or re-request the reviewer.

The $AUTOMATION_SESSION_URL variable is injected by the automation runtime and resolves to a direct link to the conversation (e.g., https://app.all-hands.dev/conversations/{uuid}). The prompt includes fallbacks ($AUTOMATION_API_URL, then the default app URL) for environments where the variable is not yet available.

The $AUTOMATION_EVENT_PAYLOAD variable contains the full GitHub webhook event as JSON. The $GITHUB_TOKEN (from the configured GitHub integration) is also automatically available. No additional configuration is needed for any of these variables.

Single-Repo vs Org-Wide

The prompt above uses glob(repository.full_name, 'YOUR_ORG/*') to cover all repos in your org. To target a single repo instead, replace the filter's first condition:

repository.full_name == 'YOUR_ORG/YOUR_REPO' && (
    label.name == 'review-this'
    || requested_reviewer.login == 'YOUR_BOT_LOGIN'
    || (!label && !requested_reviewer
        && pull_request.author_association != 'FIRST_TIME_CONTRIBUTOR'
        && pull_request.author_association != 'FIRST_TIMER'
        && pull_request.author_association != 'NONE'
        && !pull_request.draft)
)

The review-this label and requested_reviewer branches do not exclude draft PRs — labeling a draft or requesting the bot on a draft will still fire the automation. This is intentional: explicit review requests should be honored regardless of draft status.

Testing

After creating the automation:

  1. Add the review-this label to any open PR in a covered repo — this is the most reliable test since it works regardless of author history (you may need to create the label in your repo first if it doesn't exist)
  2. Alternatively, request your bot as a reviewer on any PR, or open a new non-draft PR (note: the auto-trigger on opened requires the PR author to already have contributor history in that specific repo — FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, and NONE associations are excluded)
  3. Watch for the "🔍 Review in progress…" comment — it should appear within a few seconds
  4. The full review will typically follow within a few minutes, depending on PR size

Modernizing legacy COBOL systems with OpenHands

Check out the complete COBOL modernization plugin with ready-to-use code and configuration.

Legacy COBOL systems power critical business operations across banking, insurance, government, and retail. OpenHands can help you understand, document, and modernize these systems while preserving their essential business logic.

This guide is based on our blog post Refactoring COBOL to Java with AI Agents.

The COBOL Modernization Challenge

COBOL modernization is one of the most pressing challenges facing enterprises today. Gartner estimated there were over 200 billion lines of COBOL code in existence, running 80% of the world's business systems. As of 2020, COBOL was still running background processes for 95% of credit and debit card transactions.

The challenge is acute: 47% of organizations struggle to fill COBOL roles, with salaries rising 25% annually. By 2027, 92% of remaining COBOL developers will have retired. Traditional modernization approaches have seen high failure rates, with COBOL's specialized nature requiring a unique skill set that makes it difficult for human teams alone.

Overview

COBOL modernization is a complex undertaking. Every modernization effort is unique and requires careful planning, execution, and validation to ensure the modernized code behaves identically to the original. The migration needs to be driven by an experienced team of developers and domain experts, but even that isn't sufficient to ensure the job is done quickly or cost-effectively. This is where OpenHands comes in.

OpenHands is a powerful agent that assists in modernizing COBOL code along every step of the process:

  1. Understanding: Analyze and document existing COBOL code
  2. Translation: Convert COBOL to modern languages like Java, Python, or C#
  3. Validation: Ensure the modernized code behaves identically to the original

In this document, we will explore the different ways OpenHands contributes to COBOL modernization, with example prompts and techniques to use in your own efforts. While the examples are specific to COBOL, the principles laid out here can help with any legacy system modernization.

Understanding

A significant challenge in modernization is understanding the business function of the code. Developers have practice determining the "how" of the code, even in legacy systems with unfamiliar syntax and keywords, but understanding the "why" is more important to ensure that business logic is preserved accurately. The difficulty then comes from the fact that business function is only implicitly represented in the code and requires external documentation or domain expertise to untangle.

Fortunately, agents like OpenHands are able to understand source code and process-oriented documentation, and this simultaneous view lets them link the two together in a way that makes every downstream process more transparent and predictable. Your COBOL source might already have some structure or comments that make this link clear, but if not OpenHands can help. If your COBOL source is in /src and your process-oriented documentation is in /docs, the following prompt will establish a link between the two and save it for future reference:

For each COBOL program in `/src`, identify which business functions it supports. Search through the documentation in `/docs` to find all relevant sections describing that business function, and generate a summary of how the program supports that function.

Save the results in `business_functions.json` in the following format:

{
  ...,
  "COBIL00C.cbl": {
    "function": "Bill payment -- pay account balance in full and a transaction action for the online payment",
    "references": [
      "docs/billing.md#bill-payment",
      "docs/transactions.md#transaction-action"
    ],
  },
  ...
}

OpenHands uses tools like grep, sed, and awk to navigate files and pull in context. This is natural for source code and also works well for process-oriented documentation, but in some cases exposing the latter using a semantic search engine instead will yield better results. Semantic search engines can understand the meaning behind words and phrases, making it easier to find relevant information.

Translation

With a clear picture of what each program does and why, the next step is translating the COBOL source into your target language. The example prompts in this section target Java, but the same approach works for Python, C#, or any modern language. Just adjust for language-specific idioms and data types as needed.

One thing to watch out for: COBOL keywords and data types do not always match one-to-one with their Java counterparts. For example, COBOL's decimal data type (PIC S9(9)V9(9)), which represents a fixed-point number with a scale of 9 digits, does not have a direct equivalent in Java. Instead, you might use BigDecimal with a scale of 9, but be aware of potential precision issues when converting between the two. A solid test suite will help catch these corner cases but including such known problems in the translation prompt can help prevent such errors from being introduced at all.

An example prompt is below:

Convert the COBOL files in `/src` to Java in `/src/java`.

Requirements:
1. Create a Java class for each COBOL program
2. Preserve the business logic and data structures (see `business_functions.json`)
3. Use appropriate Java naming conventions (camelCase for methods, PascalCase)
4. Convert COBOL data types to appropriate Java types (use BigDecimal for decimal data types)
5. Implement proper error handling with try-catch blocks
6. Add JavaDoc comments explaining the purpose of each class and method
7. In JavaDoc comments, include traceability to the original COBOL source using
   the format: @source <program>:<line numbers> (e.g., @source CBACT01C.cbl:73-77)
8. Create a clean, maintainable object-oriented design
9. Each Java file should be compilable and follow Java best practices

Note the rule that introduces traceability comments to the resulting Java. These comments help agents understand the provenance of the code, but are also helpful for developers attempting to understand the migration process. They can be used, for example, to check how much COBOL code has been translated into Java or to identify areas where business logic has been distributed across multiple Java classes.

Validation

Building confidence in the migrated code is crucial. Ideally, existing end-to-end tests can be reused to validate that business logic has been preserved. If you need to strengthen the testing setup, consider golden file testing. This involves capturing the COBOL program's outputs for a set of known inputs, then verifying the translated code produces identical results. When generating inputs, pay particular attention to decimal precision in monetary calculations (COBOL's fixed-point arithmetic doesn't always map cleanly to Java's BigDecimal) and date handling, where COBOL's conventions can diverge from modern defaults.

Every modernization effort is unique, and developer experience is crucial to ensure the testing strategy covers your organization's requirements. Best practices still apply. A solid test suite will not only ensure the migrated code works as expected, but will also help the translation agent converge to a high-quality solution. Of course, OpenHands can help migrate tests, ensure they run and test the migrated code correctly, and even generate new tests to cover edge cases.

Scaling Up

The largest challenge in scaling modernization efforts is dealing with agents' limited attention span. Asking a single agent to handle the entire migration process in one go will almost certainly lead to errors and low-quality code as the context window is filled and flushed again and again. One way to address this is by tying translation and validation together in an iterative refinement loop.

The idea is straightforward: one agent migrates some amount of code, and another agent critiques the migration. If the quality doesn't meet the standards of the critic, the first agent is given some actionable feedback and the process repeats. Here's what that looks like using the OpenHands SDK:

while current_score < QUALITY_THRESHOLD and iteration < MAX_ITERATIONS:
    # Migrating agent converts COBOL to Java
    migration_conversation.send_message(migration_prompt)
    migration_conversation.run()

    # Critiquing agent evaluates the conversion
    critique_conversation.send_message(critique_prompt)
    critique_conversation.run()

    # Parse the score and decide whether to continue
    current_score = parse_critique_score(critique_file)

By tweaking the critic's prompt and scoring rubric, you can fine-tune the evaluation process to better align with your needs. For example, you might have code quality standards that are difficult to detect with static analysis tools or architectural patterns that are unique to your organization. The following prompt can be easily modified to support a wide range of requirements:

Evaluate the quality of the COBOL to Java migration in `/src`.

For each Java file, assess using the following criteria:
1. Correctness: Does the Java code preserve the original business logic (see `business_functions.json`)?
2. Code Quality: Is the code clean, readable, and following Java 17 conventions?
3. Completeness: Are all COBOL features properly converted?
4. Best Practices: Does it use proper OOP, error handling, and documentation?

For each instance of a criteria not met, deduct a point.

Then generate a report containing actionable feedback for each file. The feedback, if addressed, should improve the score.

Save the results in `critique.json` in the following format:

{
  "total_score": -12,
  "files": [
    {
      "cobol": "COBIL00C.cbl",
      "java": "bill_payment.java",
      "scores": {
        "correctness": 0,
        "code_quality": 0,
        "completeness": -1,
        "best_practices": -2
      },
      "feedback": [
        "Rename single-letter variables to meaningful names.",
        "Ensure all COBOL functionality is translated -- the transaction action for the bill payment is missing.",
      ],
    },
    ...
  ]
}

In future iterations, the migration agent should be given the file critique.json and be prompted to act on the feedback.

This iterative refinement pattern works well for medium-sized projects with a moderate level of complexity. For legacy systems that span hundreds of files, however, the migration and critique processes need to be further decomposed to prevent agents from being overwhelmed. A natural way to do so is to break the system into smaller components, each with its own migration and critique processes. This process can be automated by using the OpenHands large codebase SDK, which combines agentic intelligence with static analysis tools to decompose large projects and orchestrate parallel agents in a dependency-aware manner.

Try It Yourself

The full iterative refinement example is available in the OpenHands SDK:

export LLM_API_KEY="your-api-key"
cd software-agent-sdk
uv run python examples/01_standalone_sdk/31_iterative_refinement.py

For real-world COBOL files, you can use the AWS CardDemo application, which provides a representative mainframe application for testing modernization approaches.