This prompt is designed for QA automation engineers and platform teams who need a structured, automated signal about test coverage gaps before a pull request merges. The core job-to-be-done is preventing regressions by surfacing what isn't tested. The ideal user is integrating this into a CI/CD pipeline as a merge gate, using it during manual code review to quickly identify coverage blind spots, or running it as part of a pre-release QA checklist. It assumes you can provide the full code diff, the relevant test files, and optionally a coverage report. It does not execute tests, judge the quality of existing tests, or replace human judgment for critical security and business logic paths.
Prompt
PR Diff Test Coverage Gap Analysis Prompt

When to Use This Prompt
Identify untested code paths in a pull request before merge by analyzing the diff against the existing test suite.
To use this prompt effectively, you must supply three concrete inputs: the [DIFF] of the pull request, the [TEST_SUITE] files that cover the modified areas, and an optional [COVERAGE_REPORT] for additional signal. The prompt works by mapping each changed function, modified branch, and new code path in the diff to the corresponding test cases. It then identifies gaps where a code path has no matching test. The output is a structured gap report with file paths, line ranges, risk scores, and recommended test types. This is not a general-purpose code review prompt; it is specifically for coverage gap analysis. Do not use it for style review, performance analysis, or security auditing unless those are secondary signals in the gap report.
There are clear boundaries for when this prompt should not be used. If the diff is for a configuration change, documentation update, or dependency bump with no code logic changes, the analysis will produce noise. If the test suite is sparse or poorly organized, the gap report will be overwhelmingly large and may not be actionable. In high-risk domains such as authentication, authorization, or financial transaction logic, the prompt's output must be treated as advisory and require mandatory human review. The prompt identifies what is missing; your team decides what to write and what risk to accept. For a complete pre-merge workflow, pair this prompt with the Pre-Merge Test Gap Summary Prompt to synthesize multiple signals into a go/no-go recommendation.
Use Case Fit
Where the PR Diff Test Coverage Gap Analysis Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your workflow before integrating it into a CI/CD pipeline.
Good Fit: Structured PR Review with Existing Test Suites
Use when: you have a code diff, an accessible test suite, and need a systematic gap report before merge. The prompt excels at mapping modified functions and branches to missing unit, integration, and edge-case tests. Guardrail: Provide the full diff context and test file inventory; the harness must validate that every flagged gap references a specific diff hunk and coverage rationale.
Bad Fit: Greenfield Projects Without Existing Tests
Avoid when: there is no existing test suite to compare against. The prompt analyzes gaps relative to current coverage; without a baseline, it cannot distinguish between new code and untested code. Guardrail: Use a test case recommendation prompt instead, and gate this prompt behind a check that the test suite file count is greater than zero.
Required Inputs: Diff, Test Map, and Coverage Data
What to watch: incomplete inputs produce unreliable gap reports. The prompt needs a unified diff, a mapping of source files to their test files, and optionally a coverage report. Missing any of these degrades precision. Guardrail: Build a pre-flight validator that confirms all three input types are present and non-empty before the prompt executes.
Operational Risk: False Confidence in Coverage Completeness
Risk: the prompt may miss gaps that require runtime or integration context, such as race conditions, environment-specific failures, or third-party service contracts. Teams may incorrectly treat a clean gap report as proof of sufficient coverage. Guardrail: Always pair this prompt with integration test analysis and human review for critical paths. Never use it as the sole merge gate.
Pipeline Risk: Latency and Token Costs at Scale
Risk: large diffs with many files can produce high token usage and slow PR checks, frustrating developers. Guardrail: Implement diff size thresholds that route small-to-medium PRs through full analysis and large PRs through a summary mode. Cache test file mappings to avoid resending the full test suite inventory on every run.
Eval Risk: Gap Accuracy Depends on Diff Quality
Risk: if the diff is incomplete, rebased incorrectly, or includes generated code, the prompt will flag gaps that don't exist or miss real ones. Guardrail: Validate that the diff is against the correct base branch and exclude generated files, vendor directories, and lock files before analysis. Log diff metadata for traceability.
Copy-Ready Prompt Template
A ready-to-use prompt that instructs the model to act as a QA automation engineer performing a structured coverage gap analysis on a pull request diff.
The following prompt template is designed to be copied directly into your AI system. It instructs the model to adopt the persona of a QA automation engineer and perform a rigorous, structured analysis of a code diff against an existing test suite. The prompt enforces a strict output schema, requires evidence for every finding, and demands a risk score for each gap. Before using this template, you must replace every square-bracket placeholder with the actual data for your specific pull request and test suite. The prompt is self-contained and can be used independently of the rest of this playbook, though the surrounding sections on validation, failure modes, and evaluation criteria are critical for production use.
textYou are a senior QA automation engineer. Your task is to perform a structured test coverage gap analysis on a pull request diff. ## INPUT - CODE_DIFF:
[CODE_DIFF]
code- EXISTING_TEST_SUITE:
[EXISTING_TEST_SUITE]
code- COVERAGE_REPORT (optional):
[COVERAGE_REPORT]
code## CONSTRAINTS - Every flagged gap MUST map to a specific hunk in the CODE_DIFF. - Every flagged gap MUST include a coverage rationale explaining why existing tests do not cover the change. - Do not flag code that is unreachable, generated, or configuration-only unless it introduces a new execution path. - If the COVERAGE_REPORT is provided, use it to confirm coverage status. If not provided, infer coverage gaps from the EXISTING_TEST_SUITE alone and note the lower confidence. - Do not recommend tests for code that is purely cosmetic (whitespace, comments, formatting). ## OUTPUT_SCHEMA Return a single JSON object with the following structure: { "analysis_summary": { "total_files_changed": <integer>, "total_hunks": <integer>, "gaps_found": <integer>, "critical_gaps": <integer>, "high_gaps": <integer>, "medium_gaps": <integer>, "low_gaps": <integer> }, "gaps": [ { "gap_id": "GAP-<3-digit-integer>", "file_path": "<string>", "line_range": "<start_line>-<end_line>", "diff_hunk_reference": "<brief description of the change>", "risk_score": "critical|high|medium|low", "gap_type": "untested_function|modified_branch|new_code_path|exception_handler|boundary_condition|concurrency_path|other", "coverage_rationale": "<explanation of why existing tests do not cover this change>", "recommended_test_type": "unit|integration|e2e|contract|property|fuzz|manual", "recommended_test_description": "<concrete description of the test case, including suggested inputs and expected outcomes>", "existing_test_reference": "<name of closest existing test or 'none'>" } ], "safe_changes": [ { "file_path": "<string>", "line_range": "<start_line>-<end_line>", "reason": "<why this change is adequately covered or low-risk>" } ] } ## RISK_SCORE DEFINITIONS - critical: Untested change in authentication, authorization, data integrity, payment, or PII handling. - high: Untested change in core business logic, API contract, or error handling with user-facing impact. - medium: Untested change in non-critical logic, logging, or internal helper with indirect impact. - low: Untested change in formatting, comments, or dead code removal with no behavioral impact. ## INSTRUCTIONS 1. Parse the CODE_DIFF and identify every changed function, modified branch, new code path, exception handler, and boundary condition. 2. For each identified change, check the EXISTING_TEST_SUITE for coverage. If a COVERAGE_REPORT is provided, cross-reference it. 3. For any change without adequate coverage, populate a gap entry in the output. 4. Assign a risk_score based on the definitions above. 5. Recommend a specific, actionable test case for each gap. 6. Include a safe_changes entry for any change that is adequately covered or demonstrably low-risk. 7. Return ONLY the JSON object. No markdown fences, no commentary.
To adapt this prompt for your environment, replace [CODE_DIFF] with the unified diff output from your version control system, [EXISTING_TEST_SUITE] with the relevant test files or a summary of test coverage, and [COVERAGE_REPORT] with the output of your coverage tool if available. The OUTPUT_SCHEMA is designed to be machine-readable for downstream automation, but you can add or remove fields to match your ticketing system or CI pipeline. If your model does not reliably produce valid JSON, pair this prompt with a structured output API or a post-generation validation step as described in the implementation harness section. For high-risk repositories, always require human review of critical and high-severity gaps before merging.
Prompt Variables
Every placeholder the PR Diff Test Coverage Gap Analysis Prompt expects, why it matters, and how to validate it before sending. Wire these into your CI harness to prevent malformed requests.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DIFF] | The unified diff or git patch to analyze for coverage gaps. Must include file paths and line ranges. | diff --git a/src/auth/login.ts b/src/auth/login.ts @@ -12,6 +12,14 @@ ... | Parse check: must contain valid diff headers (---/+++/@@). Reject if empty or only whitespace. Strip binary diffs before sending. |
[TEST_SUITE_MAP] | A mapping of source files to their corresponding test files and covered line ranges. Provides the coverage baseline. | {"src/auth/login.ts": {"test_file": "tests/auth/login.test.ts", "covered_lines": [[1,45],[60,85]]}} | Schema check: valid JSON object with string keys. Each value must have test_file (string) and covered_lines (array of [start, end] tuples). Null allowed if no tests exist for a file. |
[COVERAGE_THRESHOLD] | Minimum acceptable line or branch coverage percentage. Gaps below this threshold are flagged as blocking. | 80 | Type check: integer 0-100. Default to 80 if not provided. Reject values outside range. Used to classify gap severity in output. |
[RISK_WEIGHTS] | Optional object to weight risk factors: change_complexity, historical_bug_frequency, caller_impact, and security_surface. Tunes risk scoring. | {"change_complexity": 0.4, "historical_bug_frequency": 0.3, "caller_impact": 0.2, "security_surface": 0.1} | Schema check: valid JSON object with numeric values that sum to 1.0 (±0.05 tolerance). If omitted, use default equal weights. Reject negative values. |
[IGNORE_PATTERNS] | Glob patterns or file paths to exclude from gap analysis. Prevents noise from generated code, vendored deps, or known-safe files. | ["/generated/", "/vendor/", "**/*.pb.go"] | Type check: array of strings. Each string must be a valid glob or literal path. Empty array allowed. Validate patterns compile before sending. |
[OUTPUT_SCHEMA] | The expected JSON schema for the gap report. Defines required fields, types, and constraints for each finding. | {"type": "object", "properties": {"gaps": {"type": "array", "items": {"$ref": "#/definitions/gap"}}}, "required": ["gaps"]} | Schema check: valid JSON Schema draft-07 or later. Must define gap object with file_path, line_range, risk_score, and recommended_test_type fields at minimum. Reject if schema is not parseable. |
[MAX_GAPS] | Upper limit on the number of gaps returned. Prevents token blowout on large diffs with many uncovered paths. | 25 | Type check: positive integer. Default to 50 if not provided. Harness should truncate output to this limit and include a truncated flag. Reject values over 200. |
[CONTEXT_WINDOW] | Number of lines of surrounding code to include with each gap for human readability. Does not affect analysis scope. | 5 | Type check: integer 0-20. Default to 3. Controls output verbosity, not analysis depth. Set to 0 for minimal output. |
Implementation Harness Notes
How to wire the PR Diff Test Coverage Gap Analysis prompt into a CI/CD pipeline or review workflow so it runs reliably at scale.
This prompt is designed to run as a gated step in a CI/CD pipeline, triggered on pull request creation or update. The harness must supply the unified diff, a structured representation of the existing test suite (file paths, function names, covered line ranges), and any relevant coverage report data. The model call should be treated as a non-blocking analysis that enriches the PR with a structured gap report, not as a merge gate by itself. A human reviewer or a downstream validation system must confirm findings before blocking a merge.
The implementation should validate the model's output against the input diff before surfacing results. Every flagged gap must map to a specific diff hunk using file path and line range. The harness should reject any finding that references code outside the diff context or that duplicates an existing test case already present in the test suite input. Use a post-processing validator that cross-references the output's file_path and line_range fields against the diff hunks and the provided test coverage map. If more than 10% of findings fail this cross-reference, the entire output should be discarded and the model retried once with a stricter prompt that includes the validation failure details. Log the raw output, validation results, and retry count for observability.
For model choice, use a model with strong code reasoning capabilities and a large context window sufficient to hold the full diff plus test suite summary. If the diff exceeds the context window, chunk by file or module and run the prompt per chunk, then merge results with deduplication logic. The output schema should be enforced via structured output mode (JSON mode or function calling) to ensure the gaps array, risk_score, and recommended_test_type fields are reliably parseable. Store results as a PR comment or check run annotation, linking each finding to the relevant diff line. Never auto-block a merge based solely on this prompt's output without human review for high-risk repositories or regulated codebases.
For evaluation, maintain a golden dataset of known diffs with manually annotated test gaps. Run this prompt against the golden set on each prompt revision and measure precision (do flagged gaps correspond to real untested code?) and recall (are known gaps found?). Track false positives over time—findings that reference covered code or code outside the diff—and tune the prompt and validator thresholds accordingly. In production, monitor the rate of findings dismissed by reviewers as false positives and use that signal to trigger prompt updates or validator rule adjustments.
Expected Output Contract
Post-process the model response against these fields. Every flagged gap must map to a specific diff hunk and include a coverage rationale. Reject any output that fails required-field or type checks.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
gap_report_id | string (UUID v4) | Must be a valid UUID v4 string. Parse and reject if format is wrong. | |
generated_at | string (ISO 8601 UTC) | Must parse as a valid ISO 8601 datetime in UTC. Reject if missing timezone or unparseable. | |
diff_summary | object | Must contain | |
gaps | array of objects | Must be a non-null array. If empty, confirm that | |
gaps[].file_path | string (relative path) | Must match a file path present in the provided diff. Reject if the path does not appear in the diff hunks. | |
gaps[].line_range | object | Must contain | |
gaps[].risk_score | integer 1-10 | Must be an integer between 1 and 10 inclusive. Reject if out of range or non-integer. | |
gaps[].coverage_rationale | string (non-empty) | Must be a non-empty string explaining why existing tests do not cover this gap. Reject if empty or whitespace-only. | |
gaps[].recommended_test_type | string (enum) | Must be one of: unit, integration, e2e, contract, property, fuzz, manual. Reject if value is not in the allowed enum. | |
gaps[].suggested_test_description | string (non-empty) | Must be a non-empty string describing the test scenario. Reject if empty or whitespace-only. | |
gaps[].existing_test_reference | string or null | If a related test exists, provide the test name or path. If none, must be null. Reject if non-null but not a string. | |
gaps[].requires_human_review | boolean | Must be true or false. Set true for risk_score >= 7, concurrency, auth, or security test types. Reject if not boolean. | |
metadata | object | Must contain |
Common Failure Modes
What breaks first when analyzing a PR diff for test coverage gaps and how to guard against it before you ship.
Diff-to-Code Mismatch
What to watch: The model flags a gap for a function or line that was not actually modified in the diff. This happens when the model infers context from surrounding code and loses track of the change boundary. Guardrail: Require the harness to validate that every flagged gap maps to a specific diff hunk. Reject findings that cannot be traced to a line range present in the provided diff.
Hallucinated Test Existence
What to watch: The model claims a code path is covered by a test that does not actually exist in the provided test suite. This is common when the model assumes standard test naming conventions or infers coverage from similar patterns. Guardrail: Cross-reference every 'covered' assertion against the actual test file list. If a referenced test name or file is absent from the input, flag it as unverified and reclassify the path as a potential gap.
Risk Score Inflation
What to watch: The model assigns high risk scores to every finding, making it impossible to prioritize. This often occurs when the prompt lacks a calibrated risk rubric or when the model defaults to caution. Guardrail: Provide a concrete risk rubric in the prompt (e.g., 'High: untested auth or data mutation; Medium: untested error handling; Low: untested logging'). Validate that the output distribution of scores is not uniform before accepting the report.
Ignoring Indirectly Affected Code
What to watch: The model only analyzes functions directly touched by the diff but misses callers, overrides, or dependent modules whose behavior changes due to the modification. This creates a false sense of security. Guardrail: Include a static call graph or dependency map in the context. Instruct the model to trace one level up (callers) and one level down (callees) from each changed symbol and flag any of those paths that lack tests.
Test Type Mismatch
What to watch: The model recommends a unit test for a gap that requires an integration test (or vice versa), leading to tests that pass locally but fail to catch the actual regression risk. Guardrail: Define explicit test type criteria in the prompt (e.g., 'Unit test: single function, no I/O; Integration test: crosses module boundary or touches external dependency'). Validate that each recommendation's test type matches the scope of the flagged gap.
Duplicate Gap Reporting
What to watch: The same untested code path is reported multiple times with slightly different descriptions, cluttering the report and wasting review time. This happens when the model analyzes the same logic through different lenses (e.g., branch coverage and line coverage). Guardrail: Add a deduplication step in the harness that clusters findings by file and overlapping line ranges. Keep the finding with the highest risk score and merge the descriptions, discarding redundant entries.
Evaluation Rubric
Run these checks on a golden dataset of known diffs with known gaps. Each criterion validates a specific failure mode of the PR Diff Test Coverage Gap Analysis Prompt.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Gap-to-Diff Mapping | Every flagged gap references a specific file path and line range present in the diff hunk | Gap references a file or function not modified in the diff | Parse output JSON; cross-reference each gap location against the input diff hunks using a diff parser |
Coverage Rationale Completeness | Every gap includes a non-empty coverage_rationale field explaining why existing tests do not cover the path | Null, empty, or generic rationale such as 'no test found' without specific reasoning | Schema validation on coverage_rationale field; regex check for minimum 20-character explanation with code-path reference |
Risk Score Calibration | Risk scores for known-critical gaps in the golden dataset are ranked high or critical; low-risk gaps are ranked low or medium | Known injection vulnerability gap scored as low; cosmetic change gap scored as critical | Compare output risk_score against golden dataset expected risk labels; measure rank correlation |
Test Type Recommendation Validity | Recommended test_type matches the gap category: unit for function-level gaps, integration for cross-module gaps, e2e for user-journey gaps | Recommends unit test for a gap spanning three services with database and queue dependencies | Classify each gap in golden dataset by scope; assert recommended test_type matches expected scope classification |
No False Positive Gaps | Zero gaps flagged for code paths already covered by existing tests in the golden dataset | Output flags a function as uncovered when the golden dataset confirms a test exercises that exact path | Diff output against golden dataset expected_gaps list; any gap not in expected_gaps is a false positive |
Existing Test Suite Awareness | Output references specific existing test files or test case names when claiming coverage exists or is missing | States 'no tests exist' without checking the provided test suite context; misses tests present in the input | Inject test suite context with known coverage; verify output acknowledges tests that cover some paths and identifies only genuinely uncovered paths |
Edge Case Enumeration from Conditions | For each conditional branch in the diff, at least one edge case gap is identified when the branch is uncovered | A diff containing five new if/else branches yields only two gaps, missing three conditional paths | Parse diff for conditional statements; count branches; assert gap count per file meets or exceeds uncovered branch count |
Output Schema Compliance | Output is valid JSON matching the required schema with all required fields present and correctly typed | Missing risk_score field; gap_location is a string instead of an object with file and line_range | JSON Schema validation against the output contract; type checks on nested fields |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single diff file and a simplified coverage report. Drop the risk scoring and focus on gap identification only. Accept plain-text output instead of structured JSON.
Prompt modification
- Remove [OUTPUT_SCHEMA] and replace with: "List each untested code path with file path and line range."
- Replace [RISK_THRESHOLD] with a simple instruction: "Flag any path that touches auth, data mutation, or external calls."
- Use a single model call without retry logic.
Watch for
- Missing schema checks will produce inconsistent formatting across runs.
- Overly broad instructions may flag already-tested paths as gaps.
- No coverage rationale means reviewers can't verify findings without manual inspection.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us