Why This Matters

Static analysis tools tell you where coverage is missing, then leave the pull request stuck until someone writes the tests by hand. That stalls deployments and pulls developers back into code they wrote weeks ago.

Recommended approach: keep the coverage gate strict, but make the pipeline draft the fix. When coverage drops below 80%, block the merge and have an AI agent open a pull request with the missing tests, with a developer reviewing every one.

In modern software development, moving fast shouldn’t mean breaking things. Yet teams keep hitting the same bottleneck: technical debt from missing unit tests, broken test suites and lagging code coverage.

Static analysis tools like SonarQube do an excellent job of highlighting these gaps, but they are reactive. A developer pushes code, the pipeline flags a coverage failure, and the pull request sits in limbo until someone goes back and writes the missing tests.

Many teams treat a coverage target, such as a strict 80% minimum, as a box to tick right before release. When coverage drops below it, the interruptions cascade:

  • Context Switching

    Developers stop new feature work to re-engage with code they wrote days or weeks ago.

  • Blocked Deployments

    Pull requests stall and create dependencies that delay entire feature trains.

  • Low-Value Reviews

    Engineers spend review time on boilerplate test scaffolding instead of business logic.

The shift is from static reporting to active auto-remediation. A self-healing pipeline shields developers from boilerplate while holding the line on your standards.

The goal is to remove friction while keeping the developer completely in control, so a coverage drop becomes an automation trigger rather than a dead end.

  • Reactive pipeline

    Report the failure and wait

    The gate fails, the pull request stalls, and a developer writes the missing tests by hand days later.

  • Self-healing pipeline

    Report it, then draft the fix

    The gate still blocks the merge, but an AI agent opens a pull request with the missing tests for the developer to review.

Pushing generated code straight into the developer’s working branch would disrupt active work and muddy the git history, so the system isolates the fix. The agent creates a new branch and opens a dependent pull request targeting the developer’s feature branch, never main.

First, the gate decides whether the merge can go ahead:

Then the pipeline heals itself:

Once the developer reviews and merges the automated pull request, the new commit re-triggers the pipeline. With coverage at or above 80%, the quality gate passes and the main pull request is clear for a safe merge.

Here is how to build it with standard enterprise tooling: GitHub Actions (the same pattern works in GitLab CI and Azure DevOps), a SonarQube instance and an LLM orchestration layer.

Step 1: Enforce the Hard Block

Configure branch protection rules so the code quality job must pass before anything merges into main or develop. If coverage sits at 79.9%, the merge button stays locked.

Step 2: Configure the Pipeline

The first job builds, runs your tests with coverage, scans with SonarQube, then reads the pull request’s overall coverage from the SonarQube API (the coverage metric, not new_coverage) and enforces the 80% threshold. Querying by pull request requires SonarQube Developer Edition or above.

.github/workflows/code-quality.yml · part 1
name: Continuous Code Quality & Auto-Remediation

on:
  pull_request:
    branches: [main, develop]

permissions:
  contents: write
  pull-requests: write

jobs:
  code-quality-analysis:
    name: SonarQube analysis and gatekeeper
    runs-on: ubuntu-latest
    outputs:
      below-threshold: ${{ steps.check-threshold.outputs.below-threshold }}
    steps:
      - name: Check out code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Build and run unit tests with coverage
        run: |
          # Replace with your stack, e.g.
          # dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=opencover
          echo "Build and test with coverage enabled"

      - name: SonarQube scan
        uses: SonarSource/sonarqube-scan-action@v5
        continue-on-error: true   # let the threshold step below decide
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        with:
          args: >
            -Dsonar.projectKey=enterprise-application-bff
            -Dsonar.qualitygate.wait=true

      - name: Evaluate coverage against the 80% threshold
        id: check-threshold
        shell: bash
        run: |
          COVERAGE=$(curl -s -u "${{ secrets.SONAR_TOKEN }}:" \
            "${{ secrets.SONAR_HOST_URL }}/api/measures/component?component=enterprise-application-bff&pullRequest=${{ github.event.pull_request.number }}&metricKeys=coverage" \
            | jq -r '.component.measures[0].value // "0"')
          echo "Coverage on this pull request: ${COVERAGE}%"
          if (( $(echo "$COVERAGE < 80.0" | bc -l) )); then
            echo "below-threshold=true" >> "$GITHUB_OUTPUT"
          else
            echo "below-threshold=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Enforce the quality gate
        if: steps.check-threshold.outputs.below-threshold == 'true'
        run: |
          echo "Coverage is below 80%. Blocking merge and starting auto-remediation."
          exit 1

Two details matter. sonar.qualitygate.wait makes the scan wait until SonarQube has processed the report, so the API returns fresh numbers. And the scan step continues on error, so the threshold step still records its result before the final step fails the job and locks the merge.

Why overall coverage: this gate holds the whole codebase at 80%, so every pull request has to keep the total at or above the bar, not just the lines it changes. That is why both jobs read the overall coverage and uncovered_lines metrics and parse the plain .value field. If your team gates on new code only, switch to new_coverage and new_uncovered_lines; SonarQube returns those under a period field rather than .value, so the jq paths change too.

Step 3: Add the Auto-Remediation Engine

When below-threshold is true, a second job lists the files with uncovered lines, asks an LLM to write the missing tests, checks that they compile and pass, then opens the dependent pull request.

.github/workflows/code-quality.yml · part 2
  auto-remediate-coverage:
    name: AI-driven auto-remediation
    needs: code-quality-analysis
    # always(): run even though the gate job failed on purpose
    if: always() && needs.code-quality-analysis.outputs.below-threshold == 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Check out the feature branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.head_ref }}

      - name: List files with uncovered lines
        shell: bash
        run: |
          curl -s -u "${{ secrets.SONAR_TOKEN }}:" \
            "${{ secrets.SONAR_HOST_URL }}/api/measures/component_tree?component=enterprise-application-bff&pullRequest=${{ github.event.pull_request.number }}&metricKeys=uncovered_lines&qualifiers=FIL&ps=500" \
            -o metrics.json
          jq -r '.components[] | select((.measures[0].value // "0" | tonumber) > 0) | .path' \
            metrics.json > low_coverage_files.txt
          echo "Files needing tests:" && cat low_coverage_files.txt

      - name: Generate tests with the AI agent
        env:
          LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
          LLM_MODEL: ${{ vars.LLM_MODEL }}
        run: |
          python3 .github/scripts/generate_ai_tests.py \
            --files low_coverage_files.txt \
            --output-dir ./Tests/Automated \
            --framework NUnit

      - name: Compile and run the generated tests
        run: |
          # Abort here if generated tests fail to build or pass,
          # e.g. dotnet test, npm test or mvn test
          echo "Run your test command"

      - name: Open a dependent pull request
        uses: peter-evans/create-pull-request@v7
        with:
          token: ${{ secrets.AUTOMATION_PAT }}
          commit-message: "chore: AI-generated tests for uncovered lines"
          branch: automation/patch-${{ github.event.pull_request.number }}
          base: ${{ github.head_ref }}   # the developer's branch, never main
          add-paths: Tests/Automated/**   # commit only the generated tests
          delete-branch: true
          title: "AI-generated tests for PR #${{ github.event.pull_request.number }}"
          labels: |
            automated-remediation
            quality-gate
          body: |
            ## Auto-remediation report
            The quality gate failed on your feature branch (coverage below 80%).
            This PR adds generated unit tests for the uncovered lines.

            **Action required:** review the assertions, then merge into your branch.
            Merging re-runs the pipeline scan on your original pull request.

The logic in generate_ai_tests.py is deliberately simple. It reads each uncovered source file, builds a focused prompt with your framework and conventions, and asks the model for compile-ready tests. The endpoint and model are configuration, so you can point it at any OpenAI-compatible API, including a private or enterprise deployment.

.github/scripts/generate_ai_tests.py
import argparse, os, pathlib, requests

API_URL = os.environ.get("LLM_API_URL", "https://api.openai.com/v1/chat/completions")
MODEL = os.environ.get("LLM_MODEL", "gpt-4o")

PROMPT = """You are writing {framework} unit tests.
Cover every public method, boundary condition and exception path in the class below.
Follow the project's existing naming conventions.
Return only compilable source code, with no markdown fences.

{source}"""

def generate(source: str, framework: str) -> str:
    r = requests.post(
        API_URL,
        timeout=120,
        headers={"Authorization": f"Bearer {os.environ['LLM_API_KEY']}"},
        json={
            "model": MODEL,
            "temperature": 0.2,
            "messages": [{"role": "user",
                          "content": PROMPT.format(framework=framework, source=source)}],
        },
    )
    r.raise_for_status()
    return r.json()["choices"][0]["message"]["content"]

def main():
    p = argparse.ArgumentParser()
    p.add_argument("--files", required=True)
    p.add_argument("--output-dir", required=True)
    p.add_argument("--framework", default="NUnit")
    a = p.parse_args()

    out = pathlib.Path(a.output_dir)
    out.mkdir(parents=True, exist_ok=True)
    for path in pathlib.Path(a.files).read_text().split():
        src = pathlib.Path(path)
        if not src.exists():
            continue
        tests = generate(src.read_text(), a.framework)
        (out / f"{src.stem}Tests{src.suffix}").write_text(tests)
        print(f"Generated tests for {path}")

if __name__ == "__main__":
    main()

To move the blueprint into a working system, you need to know where the files live, how the loop re-triggers, and which permissions it needs.

File Placement

GitHub Actions reads workflows from .github/workflows at the repository root. Keep the generator script beside it:

Repository layout
your-repository/
├── .github/
│   ├── workflows/
│   │   └── code-quality.yml
│   └── scripts/
│       └── generate_ai_tests.py
├── src/
└── Tests/
    └── Automated/

How the Loop Re-Triggers

  • First run

    The gate fails, the agent responds

    Coverage is below 80%, the required check blocks the merge, and the remediation job opens a child pull request with the missing tests.

  • After the merge

    The clean re-scan

    The developer merges the child pull request, a new commit lands on the feature branch, the workflow re-runs and the main pull request goes green.

Repository Settings and Secrets

Under Settings › Actions › General › Workflow permissions, select Read and write permissions and tick Allow GitHub Actions to create and approve pull requests. Then add these under Settings › Secrets and variables › Actions:

  • SONAR_HOST_URL. The URL of your SonarQube instance.
  • SONAR_TOKEN. An analysis token from your SonarQube profile.
  • LLM_API_KEY. The key for your approved LLM endpoint. Set LLM_MODEL as a repository variable.
  • AUTOMATION_PAT. A token with repo scope. Pull requests opened with the default GITHUB_TOKEN don’t trigger workflow runs, so without it the child pull request would never get its own checks.

Self-healing automation is powerful, but unchecked AI changes flowing into active developer branches create their own risks. Scale it safely with these rules.

  • Protect Main Branches

    The bot works only on feature branches and its own temporary branches, and should never be able to bypass branch protection.

  • Test Before You Push

    If a generated test fails to build or pass, abort and flag the run instead of opening a broken pull request.

  • Co-Pilot, Not Authority

    Generated tests are structured suggestions that need the same human sign-off as any other code.

  • Protect Code and Data

    In regulated environments, use an enterprise or private model endpoint and keep secrets and customer data out of prompts.

  • Avoid Coverage Theater

    A test that asserts whatever the code returns proves nothing. Review assertions and consider mutation testing.

  • Internal Branches Only

    Pull requests from forks can’t read your secrets, so keep auto-remediation inside your organization.

AI is excellent at repetitive assertions, mocks and boundary cases. It can’t infer the business rules your code doesn’t state. That part stays with your engineers.

Turning a standard gatekeeper into an active, self-healing utility lets engineering teams pay down coverage debt as they go. Developers stop losing hours to boilerplate and context switching. The pipeline becomes a background collaborator that handles compliance and structural upkeep, while people stay focused on features, architecture and the review decisions only they can make.

Green builds, without the busywork.

  • Reporting is not fixing. Static analysis finds coverage gaps; a self-healing pipeline also drafts the fix.
  • Keep the gate strict. Coverage below 80% still blocks the merge through branch protection.
  • Isolate the fix. Generated tests arrive as a child pull request against the feature branch, never pushed into it.
  • Let the merge re-trigger the scan. Merging the tests re-runs the pipeline, so the original pull request unblocks itself.
  • Verify before you push. Compile and run generated tests before any pull request opens.
  • Keep humans in the loop. Every generated test gets reviewed, and sensitive code goes only to approved model endpoints.

The best next step is small: pick one service where coverage keeps slipping, add the gate and the remediation job to its pipeline, and review what the agent proposes for two weeks before rolling it out.

What is a self-healing CI/CD pipeline?
A pipeline that doesn’t stop at reporting a quality failure. When a pull request drops below the coverage threshold, it still blocks the merge, but it also triggers an AI agent to generate the missing unit tests and open a pull request with them for the developer to review.
Why open a separate pull request instead of pushing tests to the developer’s branch?
Pushing generated code directly into an active branch disrupts the developer’s work and muddies the git history. A dependent pull request keeps the fix isolated and reviewable, and merging it is an explicit human decision.
Do AI-generated tests replace code review?
No. They handle repetitive assertions, mocks and boundary cases well, but they can’t infer business rules and can encode current behavior even when it’s wrong. Every generated test should be reviewed like any other code before it merges.
Is it safe to send source code to an LLM?
It depends on your environment and policies. For regulated or sensitive codebases, use an enterprise or privately hosted model endpoint, keep secrets and customer data out of prompts, and log what the pipeline sends.
Does this only work with GitHub Actions and SonarQube?
No. The pattern is tool-agnostic: any CI system that can read a coverage metric, run a script and open a merge request can do it, including GitLab CI and Azure DevOps.
Kamal Kiran Nethala, Senior Software Engineer at Sails Software

Kamal Kiran Nethala

Senior Software Engineer, Cloud Delivery, Sails Software — writes about DevOps, CI/CD and AI-assisted quality engineering, building pipelines that fix what they find while people keep the final say.

Connect on LinkedIn

Ready to make your pipeline fix what it finds?

Sails Software helps engineering teams add governed AI to their CI/CD pipelines, with people reviewing every output.

Talk to Sails Software